CodeGenDAGPatterns.cpp 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511
  1. //===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the CodeGenDAGPatterns class, which is used to read and
  11. // represent the patterns present in a .td file for instructions.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CodeGenDAGPatterns.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Support/Debug.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include "llvm/TableGen/Error.h"
  21. #include "llvm/TableGen/Record.h"
  22. #include <algorithm>
  23. #include <cstdio>
  24. #include <set>
  25. using namespace llvm;
  26. //===----------------------------------------------------------------------===//
  27. // EEVT::TypeSet Implementation
  28. //===----------------------------------------------------------------------===//
  29. static inline bool isInteger(MVT::SimpleValueType VT) {
  30. return EVT(VT).isInteger();
  31. }
  32. static inline bool isFloatingPoint(MVT::SimpleValueType VT) {
  33. return EVT(VT).isFloatingPoint();
  34. }
  35. static inline bool isVector(MVT::SimpleValueType VT) {
  36. return EVT(VT).isVector();
  37. }
  38. static inline bool isScalar(MVT::SimpleValueType VT) {
  39. return !EVT(VT).isVector();
  40. }
  41. EEVT::TypeSet::TypeSet(MVT::SimpleValueType VT, TreePattern &TP) {
  42. if (VT == MVT::iAny)
  43. EnforceInteger(TP);
  44. else if (VT == MVT::fAny)
  45. EnforceFloatingPoint(TP);
  46. else if (VT == MVT::vAny)
  47. EnforceVector(TP);
  48. else {
  49. assert((VT < MVT::LAST_VALUETYPE || VT == MVT::iPTR ||
  50. VT == MVT::iPTRAny) && "Not a concrete type!");
  51. TypeVec.push_back(VT);
  52. }
  53. }
  54. EEVT::TypeSet::TypeSet(const std::vector<MVT::SimpleValueType> &VTList) {
  55. assert(!VTList.empty() && "empty list?");
  56. TypeVec.append(VTList.begin(), VTList.end());
  57. if (!VTList.empty())
  58. assert(VTList[0] != MVT::iAny && VTList[0] != MVT::vAny &&
  59. VTList[0] != MVT::fAny);
  60. // Verify no duplicates.
  61. array_pod_sort(TypeVec.begin(), TypeVec.end());
  62. assert(std::unique(TypeVec.begin(), TypeVec.end()) == TypeVec.end());
  63. }
  64. /// FillWithPossibleTypes - Set to all legal types and return true, only valid
  65. /// on completely unknown type sets.
  66. bool EEVT::TypeSet::FillWithPossibleTypes(TreePattern &TP,
  67. bool (*Pred)(MVT::SimpleValueType),
  68. const char *PredicateName) {
  69. assert(isCompletelyUnknown());
  70. const std::vector<MVT::SimpleValueType> &LegalTypes =
  71. TP.getDAGPatterns().getTargetInfo().getLegalValueTypes();
  72. if (TP.hasError())
  73. return false;
  74. for (unsigned i = 0, e = LegalTypes.size(); i != e; ++i)
  75. if (Pred == 0 || Pred(LegalTypes[i]))
  76. TypeVec.push_back(LegalTypes[i]);
  77. // If we have nothing that matches the predicate, bail out.
  78. if (TypeVec.empty()) {
  79. TP.error("Type inference contradiction found, no " +
  80. std::string(PredicateName) + " types found");
  81. return false;
  82. }
  83. // No need to sort with one element.
  84. if (TypeVec.size() == 1) return true;
  85. // Remove duplicates.
  86. array_pod_sort(TypeVec.begin(), TypeVec.end());
  87. TypeVec.erase(std::unique(TypeVec.begin(), TypeVec.end()), TypeVec.end());
  88. return true;
  89. }
  90. /// hasIntegerTypes - Return true if this TypeSet contains iAny or an
  91. /// integer value type.
  92. bool EEVT::TypeSet::hasIntegerTypes() const {
  93. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  94. if (isInteger(TypeVec[i]))
  95. return true;
  96. return false;
  97. }
  98. /// hasFloatingPointTypes - Return true if this TypeSet contains an fAny or
  99. /// a floating point value type.
  100. bool EEVT::TypeSet::hasFloatingPointTypes() const {
  101. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  102. if (isFloatingPoint(TypeVec[i]))
  103. return true;
  104. return false;
  105. }
  106. /// hasVectorTypes - Return true if this TypeSet contains a vAny or a vector
  107. /// value type.
  108. bool EEVT::TypeSet::hasVectorTypes() const {
  109. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  110. if (isVector(TypeVec[i]))
  111. return true;
  112. return false;
  113. }
  114. std::string EEVT::TypeSet::getName() const {
  115. if (TypeVec.empty()) return "<empty>";
  116. std::string Result;
  117. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i) {
  118. std::string VTName = llvm::getEnumName(TypeVec[i]);
  119. // Strip off MVT:: prefix if present.
  120. if (VTName.substr(0,5) == "MVT::")
  121. VTName = VTName.substr(5);
  122. if (i) Result += ':';
  123. Result += VTName;
  124. }
  125. if (TypeVec.size() == 1)
  126. return Result;
  127. return "{" + Result + "}";
  128. }
  129. /// MergeInTypeInfo - This merges in type information from the specified
  130. /// argument. If 'this' changes, it returns true. If the two types are
  131. /// contradictory (e.g. merge f32 into i32) then this flags an error.
  132. bool EEVT::TypeSet::MergeInTypeInfo(const EEVT::TypeSet &InVT, TreePattern &TP){
  133. if (InVT.isCompletelyUnknown() || *this == InVT || TP.hasError())
  134. return false;
  135. if (isCompletelyUnknown()) {
  136. *this = InVT;
  137. return true;
  138. }
  139. assert(TypeVec.size() >= 1 && InVT.TypeVec.size() >= 1 && "No unknowns");
  140. // Handle the abstract cases, seeing if we can resolve them better.
  141. switch (TypeVec[0]) {
  142. default: break;
  143. case MVT::iPTR:
  144. case MVT::iPTRAny:
  145. if (InVT.hasIntegerTypes()) {
  146. EEVT::TypeSet InCopy(InVT);
  147. InCopy.EnforceInteger(TP);
  148. InCopy.EnforceScalar(TP);
  149. if (InCopy.isConcrete()) {
  150. // If the RHS has one integer type, upgrade iPTR to i32.
  151. TypeVec[0] = InVT.TypeVec[0];
  152. return true;
  153. }
  154. // If the input has multiple scalar integers, this doesn't add any info.
  155. if (!InCopy.isCompletelyUnknown())
  156. return false;
  157. }
  158. break;
  159. }
  160. // If the input constraint is iAny/iPTR and this is an integer type list,
  161. // remove non-integer types from the list.
  162. if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
  163. hasIntegerTypes()) {
  164. bool MadeChange = EnforceInteger(TP);
  165. // If we're merging in iPTR/iPTRAny and the node currently has a list of
  166. // multiple different integer types, replace them with a single iPTR.
  167. if ((InVT.TypeVec[0] == MVT::iPTR || InVT.TypeVec[0] == MVT::iPTRAny) &&
  168. TypeVec.size() != 1) {
  169. TypeVec.resize(1);
  170. TypeVec[0] = InVT.TypeVec[0];
  171. MadeChange = true;
  172. }
  173. return MadeChange;
  174. }
  175. // If this is a type list and the RHS is a typelist as well, eliminate entries
  176. // from this list that aren't in the other one.
  177. bool MadeChange = false;
  178. TypeSet InputSet(*this);
  179. for (unsigned i = 0; i != TypeVec.size(); ++i) {
  180. bool InInVT = false;
  181. for (unsigned j = 0, e = InVT.TypeVec.size(); j != e; ++j)
  182. if (TypeVec[i] == InVT.TypeVec[j]) {
  183. InInVT = true;
  184. break;
  185. }
  186. if (InInVT) continue;
  187. TypeVec.erase(TypeVec.begin()+i--);
  188. MadeChange = true;
  189. }
  190. // If we removed all of our types, we have a type contradiction.
  191. if (!TypeVec.empty())
  192. return MadeChange;
  193. // FIXME: Really want an SMLoc here!
  194. TP.error("Type inference contradiction found, merging '" +
  195. InVT.getName() + "' into '" + InputSet.getName() + "'");
  196. return false;
  197. }
  198. /// EnforceInteger - Remove all non-integer types from this set.
  199. bool EEVT::TypeSet::EnforceInteger(TreePattern &TP) {
  200. if (TP.hasError())
  201. return false;
  202. // If we know nothing, then get the full set.
  203. if (TypeVec.empty())
  204. return FillWithPossibleTypes(TP, isInteger, "integer");
  205. if (!hasFloatingPointTypes())
  206. return false;
  207. TypeSet InputSet(*this);
  208. // Filter out all the fp types.
  209. for (unsigned i = 0; i != TypeVec.size(); ++i)
  210. if (!isInteger(TypeVec[i]))
  211. TypeVec.erase(TypeVec.begin()+i--);
  212. if (TypeVec.empty()) {
  213. TP.error("Type inference contradiction found, '" +
  214. InputSet.getName() + "' needs to be integer");
  215. return false;
  216. }
  217. return true;
  218. }
  219. /// EnforceFloatingPoint - Remove all integer types from this set.
  220. bool EEVT::TypeSet::EnforceFloatingPoint(TreePattern &TP) {
  221. if (TP.hasError())
  222. return false;
  223. // If we know nothing, then get the full set.
  224. if (TypeVec.empty())
  225. return FillWithPossibleTypes(TP, isFloatingPoint, "floating point");
  226. if (!hasIntegerTypes())
  227. return false;
  228. TypeSet InputSet(*this);
  229. // Filter out all the fp types.
  230. for (unsigned i = 0; i != TypeVec.size(); ++i)
  231. if (!isFloatingPoint(TypeVec[i]))
  232. TypeVec.erase(TypeVec.begin()+i--);
  233. if (TypeVec.empty()) {
  234. TP.error("Type inference contradiction found, '" +
  235. InputSet.getName() + "' needs to be floating point");
  236. return false;
  237. }
  238. return true;
  239. }
  240. /// EnforceScalar - Remove all vector types from this.
  241. bool EEVT::TypeSet::EnforceScalar(TreePattern &TP) {
  242. if (TP.hasError())
  243. return false;
  244. // If we know nothing, then get the full set.
  245. if (TypeVec.empty())
  246. return FillWithPossibleTypes(TP, isScalar, "scalar");
  247. if (!hasVectorTypes())
  248. return false;
  249. TypeSet InputSet(*this);
  250. // Filter out all the vector types.
  251. for (unsigned i = 0; i != TypeVec.size(); ++i)
  252. if (!isScalar(TypeVec[i]))
  253. TypeVec.erase(TypeVec.begin()+i--);
  254. if (TypeVec.empty()) {
  255. TP.error("Type inference contradiction found, '" +
  256. InputSet.getName() + "' needs to be scalar");
  257. return false;
  258. }
  259. return true;
  260. }
  261. /// EnforceVector - Remove all vector types from this.
  262. bool EEVT::TypeSet::EnforceVector(TreePattern &TP) {
  263. if (TP.hasError())
  264. return false;
  265. // If we know nothing, then get the full set.
  266. if (TypeVec.empty())
  267. return FillWithPossibleTypes(TP, isVector, "vector");
  268. TypeSet InputSet(*this);
  269. bool MadeChange = false;
  270. // Filter out all the scalar types.
  271. for (unsigned i = 0; i != TypeVec.size(); ++i)
  272. if (!isVector(TypeVec[i])) {
  273. TypeVec.erase(TypeVec.begin()+i--);
  274. MadeChange = true;
  275. }
  276. if (TypeVec.empty()) {
  277. TP.error("Type inference contradiction found, '" +
  278. InputSet.getName() + "' needs to be a vector");
  279. return false;
  280. }
  281. return MadeChange;
  282. }
  283. /// EnforceSmallerThan - 'this' must be a smaller VT than Other. Update
  284. /// this an other based on this information.
  285. bool EEVT::TypeSet::EnforceSmallerThan(EEVT::TypeSet &Other, TreePattern &TP) {
  286. if (TP.hasError())
  287. return false;
  288. // Both operands must be integer or FP, but we don't care which.
  289. bool MadeChange = false;
  290. if (isCompletelyUnknown())
  291. MadeChange = FillWithPossibleTypes(TP);
  292. if (Other.isCompletelyUnknown())
  293. MadeChange = Other.FillWithPossibleTypes(TP);
  294. // If one side is known to be integer or known to be FP but the other side has
  295. // no information, get at least the type integrality info in there.
  296. if (!hasFloatingPointTypes())
  297. MadeChange |= Other.EnforceInteger(TP);
  298. else if (!hasIntegerTypes())
  299. MadeChange |= Other.EnforceFloatingPoint(TP);
  300. if (!Other.hasFloatingPointTypes())
  301. MadeChange |= EnforceInteger(TP);
  302. else if (!Other.hasIntegerTypes())
  303. MadeChange |= EnforceFloatingPoint(TP);
  304. assert(!isCompletelyUnknown() && !Other.isCompletelyUnknown() &&
  305. "Should have a type list now");
  306. // If one contains vectors but the other doesn't pull vectors out.
  307. if (!hasVectorTypes())
  308. MadeChange |= Other.EnforceScalar(TP);
  309. if (!hasVectorTypes())
  310. MadeChange |= EnforceScalar(TP);
  311. if (TypeVec.size() == 1 && Other.TypeVec.size() == 1) {
  312. // If we are down to concrete types, this code does not currently
  313. // handle nodes which have multiple types, where some types are
  314. // integer, and some are fp. Assert that this is not the case.
  315. assert(!(hasIntegerTypes() && hasFloatingPointTypes()) &&
  316. !(Other.hasIntegerTypes() && Other.hasFloatingPointTypes()) &&
  317. "SDTCisOpSmallerThanOp does not handle mixed int/fp types!");
  318. // Otherwise, if these are both vector types, either this vector
  319. // must have a larger bitsize than the other, or this element type
  320. // must be larger than the other.
  321. EVT Type(TypeVec[0]);
  322. EVT OtherType(Other.TypeVec[0]);
  323. if (hasVectorTypes() && Other.hasVectorTypes()) {
  324. if (Type.getSizeInBits() >= OtherType.getSizeInBits())
  325. if (Type.getVectorElementType().getSizeInBits()
  326. >= OtherType.getVectorElementType().getSizeInBits()) {
  327. TP.error("Type inference contradiction found, '" +
  328. getName() + "' element type not smaller than '" +
  329. Other.getName() +"'!");
  330. return false;
  331. }
  332. }
  333. else
  334. // For scalar types, the bitsize of this type must be larger
  335. // than that of the other.
  336. if (Type.getSizeInBits() >= OtherType.getSizeInBits()) {
  337. TP.error("Type inference contradiction found, '" +
  338. getName() + "' is not smaller than '" +
  339. Other.getName() +"'!");
  340. return false;
  341. }
  342. }
  343. // Handle int and fp as disjoint sets. This won't work for patterns
  344. // that have mixed fp/int types but those are likely rare and would
  345. // not have been accepted by this code previously.
  346. // Okay, find the smallest type from the current set and remove it from the
  347. // largest set.
  348. MVT::SimpleValueType SmallestInt = MVT::LAST_VALUETYPE;
  349. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  350. if (isInteger(TypeVec[i])) {
  351. SmallestInt = TypeVec[i];
  352. break;
  353. }
  354. for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
  355. if (isInteger(TypeVec[i]) && TypeVec[i] < SmallestInt)
  356. SmallestInt = TypeVec[i];
  357. MVT::SimpleValueType SmallestFP = MVT::LAST_VALUETYPE;
  358. for (unsigned i = 0, e = TypeVec.size(); i != e; ++i)
  359. if (isFloatingPoint(TypeVec[i])) {
  360. SmallestFP = TypeVec[i];
  361. break;
  362. }
  363. for (unsigned i = 1, e = TypeVec.size(); i != e; ++i)
  364. if (isFloatingPoint(TypeVec[i]) && TypeVec[i] < SmallestFP)
  365. SmallestFP = TypeVec[i];
  366. int OtherIntSize = 0;
  367. int OtherFPSize = 0;
  368. for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
  369. Other.TypeVec.begin();
  370. TVI != Other.TypeVec.end();
  371. /* NULL */) {
  372. if (isInteger(*TVI)) {
  373. ++OtherIntSize;
  374. if (*TVI == SmallestInt) {
  375. TVI = Other.TypeVec.erase(TVI);
  376. --OtherIntSize;
  377. MadeChange = true;
  378. continue;
  379. }
  380. }
  381. else if (isFloatingPoint(*TVI)) {
  382. ++OtherFPSize;
  383. if (*TVI == SmallestFP) {
  384. TVI = Other.TypeVec.erase(TVI);
  385. --OtherFPSize;
  386. MadeChange = true;
  387. continue;
  388. }
  389. }
  390. ++TVI;
  391. }
  392. // If this is the only type in the large set, the constraint can never be
  393. // satisfied.
  394. if ((Other.hasIntegerTypes() && OtherIntSize == 0)
  395. || (Other.hasFloatingPointTypes() && OtherFPSize == 0)) {
  396. TP.error("Type inference contradiction found, '" +
  397. Other.getName() + "' has nothing larger than '" + getName() +"'!");
  398. return false;
  399. }
  400. // Okay, find the largest type in the Other set and remove it from the
  401. // current set.
  402. MVT::SimpleValueType LargestInt = MVT::Other;
  403. for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
  404. if (isInteger(Other.TypeVec[i])) {
  405. LargestInt = Other.TypeVec[i];
  406. break;
  407. }
  408. for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
  409. if (isInteger(Other.TypeVec[i]) && Other.TypeVec[i] > LargestInt)
  410. LargestInt = Other.TypeVec[i];
  411. MVT::SimpleValueType LargestFP = MVT::Other;
  412. for (unsigned i = 0, e = Other.TypeVec.size(); i != e; ++i)
  413. if (isFloatingPoint(Other.TypeVec[i])) {
  414. LargestFP = Other.TypeVec[i];
  415. break;
  416. }
  417. for (unsigned i = 1, e = Other.TypeVec.size(); i != e; ++i)
  418. if (isFloatingPoint(Other.TypeVec[i]) && Other.TypeVec[i] > LargestFP)
  419. LargestFP = Other.TypeVec[i];
  420. int IntSize = 0;
  421. int FPSize = 0;
  422. for (SmallVector<MVT::SimpleValueType, 2>::iterator TVI =
  423. TypeVec.begin();
  424. TVI != TypeVec.end();
  425. /* NULL */) {
  426. if (isInteger(*TVI)) {
  427. ++IntSize;
  428. if (*TVI == LargestInt) {
  429. TVI = TypeVec.erase(TVI);
  430. --IntSize;
  431. MadeChange = true;
  432. continue;
  433. }
  434. }
  435. else if (isFloatingPoint(*TVI)) {
  436. ++FPSize;
  437. if (*TVI == LargestFP) {
  438. TVI = TypeVec.erase(TVI);
  439. --FPSize;
  440. MadeChange = true;
  441. continue;
  442. }
  443. }
  444. ++TVI;
  445. }
  446. // If this is the only type in the small set, the constraint can never be
  447. // satisfied.
  448. if ((hasIntegerTypes() && IntSize == 0)
  449. || (hasFloatingPointTypes() && FPSize == 0)) {
  450. TP.error("Type inference contradiction found, '" +
  451. getName() + "' has nothing smaller than '" + Other.getName()+"'!");
  452. return false;
  453. }
  454. return MadeChange;
  455. }
  456. /// EnforceVectorEltTypeIs - 'this' is now constrainted to be a vector type
  457. /// whose element is specified by VTOperand.
  458. bool EEVT::TypeSet::EnforceVectorEltTypeIs(EEVT::TypeSet &VTOperand,
  459. TreePattern &TP) {
  460. if (TP.hasError())
  461. return false;
  462. // "This" must be a vector and "VTOperand" must be a scalar.
  463. bool MadeChange = false;
  464. MadeChange |= EnforceVector(TP);
  465. MadeChange |= VTOperand.EnforceScalar(TP);
  466. // If we know the vector type, it forces the scalar to agree.
  467. if (isConcrete()) {
  468. EVT IVT = getConcrete();
  469. IVT = IVT.getVectorElementType();
  470. return MadeChange |
  471. VTOperand.MergeInTypeInfo(IVT.getSimpleVT().SimpleTy, TP);
  472. }
  473. // If the scalar type is known, filter out vector types whose element types
  474. // disagree.
  475. if (!VTOperand.isConcrete())
  476. return MadeChange;
  477. MVT::SimpleValueType VT = VTOperand.getConcrete();
  478. TypeSet InputSet(*this);
  479. // Filter out all the types which don't have the right element type.
  480. for (unsigned i = 0; i != TypeVec.size(); ++i) {
  481. assert(isVector(TypeVec[i]) && "EnforceVector didn't work");
  482. if (EVT(TypeVec[i]).getVectorElementType().getSimpleVT().SimpleTy != VT) {
  483. TypeVec.erase(TypeVec.begin()+i--);
  484. MadeChange = true;
  485. }
  486. }
  487. if (TypeVec.empty()) { // FIXME: Really want an SMLoc here!
  488. TP.error("Type inference contradiction found, forcing '" +
  489. InputSet.getName() + "' to have a vector element");
  490. return false;
  491. }
  492. return MadeChange;
  493. }
  494. /// EnforceVectorSubVectorTypeIs - 'this' is now constrainted to be a
  495. /// vector type specified by VTOperand.
  496. bool EEVT::TypeSet::EnforceVectorSubVectorTypeIs(EEVT::TypeSet &VTOperand,
  497. TreePattern &TP) {
  498. // "This" must be a vector and "VTOperand" must be a vector.
  499. bool MadeChange = false;
  500. MadeChange |= EnforceVector(TP);
  501. MadeChange |= VTOperand.EnforceVector(TP);
  502. // "This" must be larger than "VTOperand."
  503. MadeChange |= VTOperand.EnforceSmallerThan(*this, TP);
  504. // If we know the vector type, it forces the scalar types to agree.
  505. if (isConcrete()) {
  506. EVT IVT = getConcrete();
  507. IVT = IVT.getVectorElementType();
  508. EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
  509. MadeChange |= VTOperand.EnforceVectorEltTypeIs(EltTypeSet, TP);
  510. } else if (VTOperand.isConcrete()) {
  511. EVT IVT = VTOperand.getConcrete();
  512. IVT = IVT.getVectorElementType();
  513. EEVT::TypeSet EltTypeSet(IVT.getSimpleVT().SimpleTy, TP);
  514. MadeChange |= EnforceVectorEltTypeIs(EltTypeSet, TP);
  515. }
  516. return MadeChange;
  517. }
  518. //===----------------------------------------------------------------------===//
  519. // Helpers for working with extended types.
  520. /// Dependent variable map for CodeGenDAGPattern variant generation
  521. typedef std::map<std::string, int> DepVarMap;
  522. /// Const iterator shorthand for DepVarMap
  523. typedef DepVarMap::const_iterator DepVarMap_citer;
  524. static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
  525. if (N->isLeaf()) {
  526. if (isa<DefInit>(N->getLeafValue()))
  527. DepMap[N->getName()]++;
  528. } else {
  529. for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
  530. FindDepVarsOf(N->getChild(i), DepMap);
  531. }
  532. }
  533. /// Find dependent variables within child patterns
  534. static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
  535. DepVarMap depcounts;
  536. FindDepVarsOf(N, depcounts);
  537. for (DepVarMap_citer i = depcounts.begin(); i != depcounts.end(); ++i) {
  538. if (i->second > 1) // std::pair<std::string, int>
  539. DepVars.insert(i->first);
  540. }
  541. }
  542. #ifndef NDEBUG
  543. /// Dump the dependent variable set:
  544. static void DumpDepVars(MultipleUseVarSet &DepVars) {
  545. if (DepVars.empty()) {
  546. DEBUG(errs() << "<empty set>");
  547. } else {
  548. DEBUG(errs() << "[ ");
  549. for (MultipleUseVarSet::const_iterator i = DepVars.begin(),
  550. e = DepVars.end(); i != e; ++i) {
  551. DEBUG(errs() << (*i) << " ");
  552. }
  553. DEBUG(errs() << "]");
  554. }
  555. }
  556. #endif
  557. //===----------------------------------------------------------------------===//
  558. // TreePredicateFn Implementation
  559. //===----------------------------------------------------------------------===//
  560. /// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
  561. TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
  562. assert((getPredCode().empty() || getImmCode().empty()) &&
  563. ".td file corrupt: can't have a node predicate *and* an imm predicate");
  564. }
  565. std::string TreePredicateFn::getPredCode() const {
  566. return PatFragRec->getRecord()->getValueAsString("PredicateCode");
  567. }
  568. std::string TreePredicateFn::getImmCode() const {
  569. return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
  570. }
  571. /// isAlwaysTrue - Return true if this is a noop predicate.
  572. bool TreePredicateFn::isAlwaysTrue() const {
  573. return getPredCode().empty() && getImmCode().empty();
  574. }
  575. /// Return the name to use in the generated code to reference this, this is
  576. /// "Predicate_foo" if from a pattern fragment "foo".
  577. std::string TreePredicateFn::getFnName() const {
  578. return "Predicate_" + PatFragRec->getRecord()->getName();
  579. }
  580. /// getCodeToRunOnSDNode - Return the code for the function body that
  581. /// evaluates this predicate. The argument is expected to be in "Node",
  582. /// not N. This handles casting and conversion to a concrete node type as
  583. /// appropriate.
  584. std::string TreePredicateFn::getCodeToRunOnSDNode() const {
  585. // Handle immediate predicates first.
  586. std::string ImmCode = getImmCode();
  587. if (!ImmCode.empty()) {
  588. std::string Result =
  589. " int64_t Imm = cast<ConstantSDNode>(Node)->getSExtValue();\n";
  590. return Result + ImmCode;
  591. }
  592. // Handle arbitrary node predicates.
  593. assert(!getPredCode().empty() && "Don't have any predicate code!");
  594. std::string ClassName;
  595. if (PatFragRec->getOnlyTree()->isLeaf())
  596. ClassName = "SDNode";
  597. else {
  598. Record *Op = PatFragRec->getOnlyTree()->getOperator();
  599. ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
  600. }
  601. std::string Result;
  602. if (ClassName == "SDNode")
  603. Result = " SDNode *N = Node;\n";
  604. else
  605. Result = " " + ClassName + "*N = cast<" + ClassName + ">(Node);\n";
  606. return Result + getPredCode();
  607. }
  608. //===----------------------------------------------------------------------===//
  609. // PatternToMatch implementation
  610. //
  611. /// getPatternSize - Return the 'size' of this pattern. We want to match large
  612. /// patterns before small ones. This is used to determine the size of a
  613. /// pattern.
  614. static unsigned getPatternSize(const TreePatternNode *P,
  615. const CodeGenDAGPatterns &CGP) {
  616. unsigned Size = 3; // The node itself.
  617. // If the root node is a ConstantSDNode, increases its size.
  618. // e.g. (set R32:$dst, 0).
  619. if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
  620. Size += 2;
  621. // FIXME: This is a hack to statically increase the priority of patterns
  622. // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
  623. // Later we can allow complexity / cost for each pattern to be (optionally)
  624. // specified. To get best possible pattern match we'll need to dynamically
  625. // calculate the complexity of all patterns a dag can potentially map to.
  626. const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
  627. if (AM)
  628. Size += AM->getNumOperands() * 3;
  629. // If this node has some predicate function that must match, it adds to the
  630. // complexity of this node.
  631. if (!P->getPredicateFns().empty())
  632. ++Size;
  633. // Count children in the count if they are also nodes.
  634. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
  635. TreePatternNode *Child = P->getChild(i);
  636. if (!Child->isLeaf() && Child->getNumTypes() &&
  637. Child->getType(0) != MVT::Other)
  638. Size += getPatternSize(Child, CGP);
  639. else if (Child->isLeaf()) {
  640. if (isa<IntInit>(Child->getLeafValue()))
  641. Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
  642. else if (Child->getComplexPatternInfo(CGP))
  643. Size += getPatternSize(Child, CGP);
  644. else if (!Child->getPredicateFns().empty())
  645. ++Size;
  646. }
  647. }
  648. return Size;
  649. }
  650. /// Compute the complexity metric for the input pattern. This roughly
  651. /// corresponds to the number of nodes that are covered.
  652. unsigned PatternToMatch::
  653. getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
  654. return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
  655. }
  656. /// getPredicateCheck - Return a single string containing all of this
  657. /// pattern's predicates concatenated with "&&" operators.
  658. ///
  659. std::string PatternToMatch::getPredicateCheck() const {
  660. std::string PredicateCheck;
  661. for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
  662. if (DefInit *Pred = dyn_cast<DefInit>(Predicates->getElement(i))) {
  663. Record *Def = Pred->getDef();
  664. if (!Def->isSubClassOf("Predicate")) {
  665. #ifndef NDEBUG
  666. Def->dump();
  667. #endif
  668. llvm_unreachable("Unknown predicate type!");
  669. }
  670. if (!PredicateCheck.empty())
  671. PredicateCheck += " && ";
  672. PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
  673. }
  674. }
  675. return PredicateCheck;
  676. }
  677. //===----------------------------------------------------------------------===//
  678. // SDTypeConstraint implementation
  679. //
  680. SDTypeConstraint::SDTypeConstraint(Record *R) {
  681. OperandNo = R->getValueAsInt("OperandNum");
  682. if (R->isSubClassOf("SDTCisVT")) {
  683. ConstraintType = SDTCisVT;
  684. x.SDTCisVT_Info.VT = getValueType(R->getValueAsDef("VT"));
  685. if (x.SDTCisVT_Info.VT == MVT::isVoid)
  686. PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
  687. } else if (R->isSubClassOf("SDTCisPtrTy")) {
  688. ConstraintType = SDTCisPtrTy;
  689. } else if (R->isSubClassOf("SDTCisInt")) {
  690. ConstraintType = SDTCisInt;
  691. } else if (R->isSubClassOf("SDTCisFP")) {
  692. ConstraintType = SDTCisFP;
  693. } else if (R->isSubClassOf("SDTCisVec")) {
  694. ConstraintType = SDTCisVec;
  695. } else if (R->isSubClassOf("SDTCisSameAs")) {
  696. ConstraintType = SDTCisSameAs;
  697. x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
  698. } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
  699. ConstraintType = SDTCisVTSmallerThanOp;
  700. x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
  701. R->getValueAsInt("OtherOperandNum");
  702. } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
  703. ConstraintType = SDTCisOpSmallerThanOp;
  704. x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
  705. R->getValueAsInt("BigOperandNum");
  706. } else if (R->isSubClassOf("SDTCisEltOfVec")) {
  707. ConstraintType = SDTCisEltOfVec;
  708. x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
  709. } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
  710. ConstraintType = SDTCisSubVecOfVec;
  711. x.SDTCisSubVecOfVec_Info.OtherOperandNum =
  712. R->getValueAsInt("OtherOpNum");
  713. } else {
  714. errs() << "Unrecognized SDTypeConstraint '" << R->getName() << "'!\n";
  715. exit(1);
  716. }
  717. }
  718. /// getOperandNum - Return the node corresponding to operand #OpNo in tree
  719. /// N, and the result number in ResNo.
  720. static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
  721. const SDNodeInfo &NodeInfo,
  722. unsigned &ResNo) {
  723. unsigned NumResults = NodeInfo.getNumResults();
  724. if (OpNo < NumResults) {
  725. ResNo = OpNo;
  726. return N;
  727. }
  728. OpNo -= NumResults;
  729. if (OpNo >= N->getNumChildren()) {
  730. errs() << "Invalid operand number in type constraint "
  731. << (OpNo+NumResults) << " ";
  732. N->dump();
  733. errs() << '\n';
  734. exit(1);
  735. }
  736. return N->getChild(OpNo);
  737. }
  738. /// ApplyTypeConstraint - Given a node in a pattern, apply this type
  739. /// constraint to the nodes operands. This returns true if it makes a
  740. /// change, false otherwise. If a type contradiction is found, flag an error.
  741. bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
  742. const SDNodeInfo &NodeInfo,
  743. TreePattern &TP) const {
  744. if (TP.hasError())
  745. return false;
  746. unsigned ResNo = 0; // The result number being referenced.
  747. TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
  748. switch (ConstraintType) {
  749. case SDTCisVT:
  750. // Operand must be a particular type.
  751. return NodeToApply->UpdateNodeType(ResNo, x.SDTCisVT_Info.VT, TP);
  752. case SDTCisPtrTy:
  753. // Operand must be same as target pointer type.
  754. return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
  755. case SDTCisInt:
  756. // Require it to be one of the legal integer VTs.
  757. return NodeToApply->getExtType(ResNo).EnforceInteger(TP);
  758. case SDTCisFP:
  759. // Require it to be one of the legal fp VTs.
  760. return NodeToApply->getExtType(ResNo).EnforceFloatingPoint(TP);
  761. case SDTCisVec:
  762. // Require it to be one of the legal vector VTs.
  763. return NodeToApply->getExtType(ResNo).EnforceVector(TP);
  764. case SDTCisSameAs: {
  765. unsigned OResNo = 0;
  766. TreePatternNode *OtherNode =
  767. getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
  768. return NodeToApply->UpdateNodeType(OResNo, OtherNode->getExtType(ResNo),TP)|
  769. OtherNode->UpdateNodeType(ResNo,NodeToApply->getExtType(OResNo),TP);
  770. }
  771. case SDTCisVTSmallerThanOp: {
  772. // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
  773. // have an integer type that is smaller than the VT.
  774. if (!NodeToApply->isLeaf() ||
  775. !isa<DefInit>(NodeToApply->getLeafValue()) ||
  776. !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
  777. ->isSubClassOf("ValueType")) {
  778. TP.error(N->getOperator()->getName() + " expects a VT operand!");
  779. return false;
  780. }
  781. MVT::SimpleValueType VT =
  782. getValueType(static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef());
  783. EEVT::TypeSet TypeListTmp(VT, TP);
  784. unsigned OResNo = 0;
  785. TreePatternNode *OtherNode =
  786. getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
  787. OResNo);
  788. return TypeListTmp.EnforceSmallerThan(OtherNode->getExtType(OResNo), TP);
  789. }
  790. case SDTCisOpSmallerThanOp: {
  791. unsigned BResNo = 0;
  792. TreePatternNode *BigOperand =
  793. getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
  794. BResNo);
  795. return NodeToApply->getExtType(ResNo).
  796. EnforceSmallerThan(BigOperand->getExtType(BResNo), TP);
  797. }
  798. case SDTCisEltOfVec: {
  799. unsigned VResNo = 0;
  800. TreePatternNode *VecOperand =
  801. getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
  802. VResNo);
  803. // Filter vector types out of VecOperand that don't have the right element
  804. // type.
  805. return VecOperand->getExtType(VResNo).
  806. EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), TP);
  807. }
  808. case SDTCisSubVecOfVec: {
  809. unsigned VResNo = 0;
  810. TreePatternNode *BigVecOperand =
  811. getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
  812. VResNo);
  813. // Filter vector types out of BigVecOperand that don't have the
  814. // right subvector type.
  815. return BigVecOperand->getExtType(VResNo).
  816. EnforceVectorSubVectorTypeIs(NodeToApply->getExtType(ResNo), TP);
  817. }
  818. }
  819. llvm_unreachable("Invalid ConstraintType!");
  820. }
  821. //===----------------------------------------------------------------------===//
  822. // SDNodeInfo implementation
  823. //
  824. SDNodeInfo::SDNodeInfo(Record *R) : Def(R) {
  825. EnumName = R->getValueAsString("Opcode");
  826. SDClassName = R->getValueAsString("SDClass");
  827. Record *TypeProfile = R->getValueAsDef("TypeProfile");
  828. NumResults = TypeProfile->getValueAsInt("NumResults");
  829. NumOperands = TypeProfile->getValueAsInt("NumOperands");
  830. // Parse the properties.
  831. Properties = 0;
  832. std::vector<Record*> PropList = R->getValueAsListOfDefs("Properties");
  833. for (unsigned i = 0, e = PropList.size(); i != e; ++i) {
  834. if (PropList[i]->getName() == "SDNPCommutative") {
  835. Properties |= 1 << SDNPCommutative;
  836. } else if (PropList[i]->getName() == "SDNPAssociative") {
  837. Properties |= 1 << SDNPAssociative;
  838. } else if (PropList[i]->getName() == "SDNPHasChain") {
  839. Properties |= 1 << SDNPHasChain;
  840. } else if (PropList[i]->getName() == "SDNPOutGlue") {
  841. Properties |= 1 << SDNPOutGlue;
  842. } else if (PropList[i]->getName() == "SDNPInGlue") {
  843. Properties |= 1 << SDNPInGlue;
  844. } else if (PropList[i]->getName() == "SDNPOptInGlue") {
  845. Properties |= 1 << SDNPOptInGlue;
  846. } else if (PropList[i]->getName() == "SDNPMayStore") {
  847. Properties |= 1 << SDNPMayStore;
  848. } else if (PropList[i]->getName() == "SDNPMayLoad") {
  849. Properties |= 1 << SDNPMayLoad;
  850. } else if (PropList[i]->getName() == "SDNPSideEffect") {
  851. Properties |= 1 << SDNPSideEffect;
  852. } else if (PropList[i]->getName() == "SDNPMemOperand") {
  853. Properties |= 1 << SDNPMemOperand;
  854. } else if (PropList[i]->getName() == "SDNPVariadic") {
  855. Properties |= 1 << SDNPVariadic;
  856. } else {
  857. errs() << "Unknown SD Node property '" << PropList[i]->getName()
  858. << "' on node '" << R->getName() << "'!\n";
  859. exit(1);
  860. }
  861. }
  862. // Parse the type constraints.
  863. std::vector<Record*> ConstraintList =
  864. TypeProfile->getValueAsListOfDefs("Constraints");
  865. TypeConstraints.assign(ConstraintList.begin(), ConstraintList.end());
  866. }
  867. /// getKnownType - If the type constraints on this node imply a fixed type
  868. /// (e.g. all stores return void, etc), then return it as an
  869. /// MVT::SimpleValueType. Otherwise, return EEVT::Other.
  870. MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
  871. unsigned NumResults = getNumResults();
  872. assert(NumResults <= 1 &&
  873. "We only work with nodes with zero or one result so far!");
  874. assert(ResNo == 0 && "Only handles single result nodes so far");
  875. for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i) {
  876. // Make sure that this applies to the correct node result.
  877. if (TypeConstraints[i].OperandNo >= NumResults) // FIXME: need value #
  878. continue;
  879. switch (TypeConstraints[i].ConstraintType) {
  880. default: break;
  881. case SDTypeConstraint::SDTCisVT:
  882. return TypeConstraints[i].x.SDTCisVT_Info.VT;
  883. case SDTypeConstraint::SDTCisPtrTy:
  884. return MVT::iPTR;
  885. }
  886. }
  887. return MVT::Other;
  888. }
  889. //===----------------------------------------------------------------------===//
  890. // TreePatternNode implementation
  891. //
  892. TreePatternNode::~TreePatternNode() {
  893. #if 0 // FIXME: implement refcounted tree nodes!
  894. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  895. delete getChild(i);
  896. #endif
  897. }
  898. static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
  899. if (Operator->getName() == "set" ||
  900. Operator->getName() == "implicit")
  901. return 0; // All return nothing.
  902. if (Operator->isSubClassOf("Intrinsic"))
  903. return CDP.getIntrinsic(Operator).IS.RetVTs.size();
  904. if (Operator->isSubClassOf("SDNode"))
  905. return CDP.getSDNodeInfo(Operator).getNumResults();
  906. if (Operator->isSubClassOf("PatFrag")) {
  907. // If we've already parsed this pattern fragment, get it. Otherwise, handle
  908. // the forward reference case where one pattern fragment references another
  909. // before it is processed.
  910. if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator))
  911. return PFRec->getOnlyTree()->getNumTypes();
  912. // Get the result tree.
  913. DagInit *Tree = Operator->getValueAsDag("Fragment");
  914. Record *Op = 0;
  915. if (Tree)
  916. if (DefInit *DI = dyn_cast<DefInit>(Tree->getOperator()))
  917. Op = DI->getDef();
  918. assert(Op && "Invalid Fragment");
  919. return GetNumNodeResults(Op, CDP);
  920. }
  921. if (Operator->isSubClassOf("Instruction")) {
  922. CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
  923. // FIXME: Should allow access to all the results here.
  924. unsigned NumDefsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
  925. // Add on one implicit def if it has a resolvable type.
  926. if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
  927. ++NumDefsToAdd;
  928. return NumDefsToAdd;
  929. }
  930. if (Operator->isSubClassOf("SDNodeXForm"))
  931. return 1; // FIXME: Generalize SDNodeXForm
  932. Operator->dump();
  933. errs() << "Unhandled node in GetNumNodeResults\n";
  934. exit(1);
  935. }
  936. void TreePatternNode::print(raw_ostream &OS) const {
  937. if (isLeaf())
  938. OS << *getLeafValue();
  939. else
  940. OS << '(' << getOperator()->getName();
  941. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  942. OS << ':' << getExtType(i).getName();
  943. if (!isLeaf()) {
  944. if (getNumChildren() != 0) {
  945. OS << " ";
  946. getChild(0)->print(OS);
  947. for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
  948. OS << ", ";
  949. getChild(i)->print(OS);
  950. }
  951. }
  952. OS << ")";
  953. }
  954. for (unsigned i = 0, e = PredicateFns.size(); i != e; ++i)
  955. OS << "<<P:" << PredicateFns[i].getFnName() << ">>";
  956. if (TransformFn)
  957. OS << "<<X:" << TransformFn->getName() << ">>";
  958. if (!getName().empty())
  959. OS << ":$" << getName();
  960. }
  961. void TreePatternNode::dump() const {
  962. print(errs());
  963. }
  964. /// isIsomorphicTo - Return true if this node is recursively
  965. /// isomorphic to the specified node. For this comparison, the node's
  966. /// entire state is considered. The assigned name is ignored, since
  967. /// nodes with differing names are considered isomorphic. However, if
  968. /// the assigned name is present in the dependent variable set, then
  969. /// the assigned name is considered significant and the node is
  970. /// isomorphic if the names match.
  971. bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
  972. const MultipleUseVarSet &DepVars) const {
  973. if (N == this) return true;
  974. if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
  975. getPredicateFns() != N->getPredicateFns() ||
  976. getTransformFn() != N->getTransformFn())
  977. return false;
  978. if (isLeaf()) {
  979. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  980. if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
  981. return ((DI->getDef() == NDI->getDef())
  982. && (DepVars.find(getName()) == DepVars.end()
  983. || getName() == N->getName()));
  984. }
  985. }
  986. return getLeafValue() == N->getLeafValue();
  987. }
  988. if (N->getOperator() != getOperator() ||
  989. N->getNumChildren() != getNumChildren()) return false;
  990. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  991. if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
  992. return false;
  993. return true;
  994. }
  995. /// clone - Make a copy of this tree and all of its children.
  996. ///
  997. TreePatternNode *TreePatternNode::clone() const {
  998. TreePatternNode *New;
  999. if (isLeaf()) {
  1000. New = new TreePatternNode(getLeafValue(), getNumTypes());
  1001. } else {
  1002. std::vector<TreePatternNode*> CChildren;
  1003. CChildren.reserve(Children.size());
  1004. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1005. CChildren.push_back(getChild(i)->clone());
  1006. New = new TreePatternNode(getOperator(), CChildren, getNumTypes());
  1007. }
  1008. New->setName(getName());
  1009. New->Types = Types;
  1010. New->setPredicateFns(getPredicateFns());
  1011. New->setTransformFn(getTransformFn());
  1012. return New;
  1013. }
  1014. /// RemoveAllTypes - Recursively strip all the types of this tree.
  1015. void TreePatternNode::RemoveAllTypes() {
  1016. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1017. Types[i] = EEVT::TypeSet(); // Reset to unknown type.
  1018. if (isLeaf()) return;
  1019. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1020. getChild(i)->RemoveAllTypes();
  1021. }
  1022. /// SubstituteFormalArguments - Replace the formal arguments in this tree
  1023. /// with actual values specified by ArgMap.
  1024. void TreePatternNode::
  1025. SubstituteFormalArguments(std::map<std::string, TreePatternNode*> &ArgMap) {
  1026. if (isLeaf()) return;
  1027. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1028. TreePatternNode *Child = getChild(i);
  1029. if (Child->isLeaf()) {
  1030. Init *Val = Child->getLeafValue();
  1031. if (isa<DefInit>(Val) &&
  1032. cast<DefInit>(Val)->getDef()->getName() == "node") {
  1033. // We found a use of a formal argument, replace it with its value.
  1034. TreePatternNode *NewChild = ArgMap[Child->getName()];
  1035. assert(NewChild && "Couldn't find formal argument!");
  1036. assert((Child->getPredicateFns().empty() ||
  1037. NewChild->getPredicateFns() == Child->getPredicateFns()) &&
  1038. "Non-empty child predicate clobbered!");
  1039. setChild(i, NewChild);
  1040. }
  1041. } else {
  1042. getChild(i)->SubstituteFormalArguments(ArgMap);
  1043. }
  1044. }
  1045. }
  1046. /// InlinePatternFragments - If this pattern refers to any pattern
  1047. /// fragments, inline them into place, giving us a pattern without any
  1048. /// PatFrag references.
  1049. TreePatternNode *TreePatternNode::InlinePatternFragments(TreePattern &TP) {
  1050. if (TP.hasError())
  1051. return 0;
  1052. if (isLeaf())
  1053. return this; // nothing to do.
  1054. Record *Op = getOperator();
  1055. if (!Op->isSubClassOf("PatFrag")) {
  1056. // Just recursively inline children nodes.
  1057. for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
  1058. TreePatternNode *Child = getChild(i);
  1059. TreePatternNode *NewChild = Child->InlinePatternFragments(TP);
  1060. assert((Child->getPredicateFns().empty() ||
  1061. NewChild->getPredicateFns() == Child->getPredicateFns()) &&
  1062. "Non-empty child predicate clobbered!");
  1063. setChild(i, NewChild);
  1064. }
  1065. return this;
  1066. }
  1067. // Otherwise, we found a reference to a fragment. First, look up its
  1068. // TreePattern record.
  1069. TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
  1070. // Verify that we are passing the right number of operands.
  1071. if (Frag->getNumArgs() != Children.size()) {
  1072. TP.error("'" + Op->getName() + "' fragment requires " +
  1073. utostr(Frag->getNumArgs()) + " operands!");
  1074. return 0;
  1075. }
  1076. TreePatternNode *FragTree = Frag->getOnlyTree()->clone();
  1077. TreePredicateFn PredFn(Frag);
  1078. if (!PredFn.isAlwaysTrue())
  1079. FragTree->addPredicateFn(PredFn);
  1080. // Resolve formal arguments to their actual value.
  1081. if (Frag->getNumArgs()) {
  1082. // Compute the map of formal to actual arguments.
  1083. std::map<std::string, TreePatternNode*> ArgMap;
  1084. for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i)
  1085. ArgMap[Frag->getArgName(i)] = getChild(i)->InlinePatternFragments(TP);
  1086. FragTree->SubstituteFormalArguments(ArgMap);
  1087. }
  1088. FragTree->setName(getName());
  1089. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1090. FragTree->UpdateNodeType(i, getExtType(i), TP);
  1091. // Transfer in the old predicates.
  1092. for (unsigned i = 0, e = getPredicateFns().size(); i != e; ++i)
  1093. FragTree->addPredicateFn(getPredicateFns()[i]);
  1094. // Get a new copy of this fragment to stitch into here.
  1095. //delete this; // FIXME: implement refcounting!
  1096. // The fragment we inlined could have recursive inlining that is needed. See
  1097. // if there are any pattern fragments in it and inline them as needed.
  1098. return FragTree->InlinePatternFragments(TP);
  1099. }
  1100. /// getImplicitType - Check to see if the specified record has an implicit
  1101. /// type which should be applied to it. This will infer the type of register
  1102. /// references from the register file information, for example.
  1103. ///
  1104. static EEVT::TypeSet getImplicitType(Record *R, unsigned ResNo,
  1105. bool NotRegisters, TreePattern &TP) {
  1106. // Check to see if this is a register operand.
  1107. if (R->isSubClassOf("RegisterOperand")) {
  1108. assert(ResNo == 0 && "Regoperand ref only has one result!");
  1109. if (NotRegisters)
  1110. return EEVT::TypeSet(); // Unknown.
  1111. Record *RegClass = R->getValueAsDef("RegClass");
  1112. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1113. return EEVT::TypeSet(T.getRegisterClass(RegClass).getValueTypes());
  1114. }
  1115. // Check to see if this is a register or a register class.
  1116. if (R->isSubClassOf("RegisterClass")) {
  1117. assert(ResNo == 0 && "Regclass ref only has one result!");
  1118. if (NotRegisters)
  1119. return EEVT::TypeSet(); // Unknown.
  1120. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1121. return EEVT::TypeSet(T.getRegisterClass(R).getValueTypes());
  1122. }
  1123. if (R->isSubClassOf("PatFrag")) {
  1124. assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
  1125. // Pattern fragment types will be resolved when they are inlined.
  1126. return EEVT::TypeSet(); // Unknown.
  1127. }
  1128. if (R->isSubClassOf("Register")) {
  1129. assert(ResNo == 0 && "Registers only produce one result!");
  1130. if (NotRegisters)
  1131. return EEVT::TypeSet(); // Unknown.
  1132. const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
  1133. return EEVT::TypeSet(T.getRegisterVTs(R));
  1134. }
  1135. if (R->isSubClassOf("SubRegIndex")) {
  1136. assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
  1137. return EEVT::TypeSet();
  1138. }
  1139. if (R->isSubClassOf("ValueType") || R->isSubClassOf("CondCode")) {
  1140. assert(ResNo == 0 && "This node only has one result!");
  1141. // Using a VTSDNode or CondCodeSDNode.
  1142. return EEVT::TypeSet(MVT::Other, TP);
  1143. }
  1144. if (R->isSubClassOf("ComplexPattern")) {
  1145. assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
  1146. if (NotRegisters)
  1147. return EEVT::TypeSet(); // Unknown.
  1148. return EEVT::TypeSet(TP.getDAGPatterns().getComplexPattern(R).getValueType(),
  1149. TP);
  1150. }
  1151. if (R->isSubClassOf("PointerLikeRegClass")) {
  1152. assert(ResNo == 0 && "Regclass can only have one result!");
  1153. return EEVT::TypeSet(MVT::iPTR, TP);
  1154. }
  1155. if (R->getName() == "node" || R->getName() == "srcvalue" ||
  1156. R->getName() == "zero_reg") {
  1157. // Placeholder.
  1158. return EEVT::TypeSet(); // Unknown.
  1159. }
  1160. TP.error("Unknown node flavor used in pattern: " + R->getName());
  1161. return EEVT::TypeSet(MVT::Other, TP);
  1162. }
  1163. /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
  1164. /// CodeGenIntrinsic information for it, otherwise return a null pointer.
  1165. const CodeGenIntrinsic *TreePatternNode::
  1166. getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
  1167. if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
  1168. getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
  1169. getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
  1170. return 0;
  1171. unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
  1172. return &CDP.getIntrinsicInfo(IID);
  1173. }
  1174. /// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
  1175. /// return the ComplexPattern information, otherwise return null.
  1176. const ComplexPattern *
  1177. TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
  1178. if (!isLeaf()) return 0;
  1179. DefInit *DI = dyn_cast<DefInit>(getLeafValue());
  1180. if (DI && DI->getDef()->isSubClassOf("ComplexPattern"))
  1181. return &CGP.getComplexPattern(DI->getDef());
  1182. return 0;
  1183. }
  1184. /// NodeHasProperty - Return true if this node has the specified property.
  1185. bool TreePatternNode::NodeHasProperty(SDNP Property,
  1186. const CodeGenDAGPatterns &CGP) const {
  1187. if (isLeaf()) {
  1188. if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
  1189. return CP->hasProperty(Property);
  1190. return false;
  1191. }
  1192. Record *Operator = getOperator();
  1193. if (!Operator->isSubClassOf("SDNode")) return false;
  1194. return CGP.getSDNodeInfo(Operator).hasProperty(Property);
  1195. }
  1196. /// TreeHasProperty - Return true if any node in this tree has the specified
  1197. /// property.
  1198. bool TreePatternNode::TreeHasProperty(SDNP Property,
  1199. const CodeGenDAGPatterns &CGP) const {
  1200. if (NodeHasProperty(Property, CGP))
  1201. return true;
  1202. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1203. if (getChild(i)->TreeHasProperty(Property, CGP))
  1204. return true;
  1205. return false;
  1206. }
  1207. /// isCommutativeIntrinsic - Return true if the node corresponds to a
  1208. /// commutative intrinsic.
  1209. bool
  1210. TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
  1211. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
  1212. return Int->isCommutative;
  1213. return false;
  1214. }
  1215. /// ApplyTypeConstraints - Apply all of the type constraints relevant to
  1216. /// this node and its children in the tree. This returns true if it makes a
  1217. /// change, false otherwise. If a type contradiction is found, flag an error.
  1218. bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
  1219. if (TP.hasError())
  1220. return false;
  1221. CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
  1222. if (isLeaf()) {
  1223. if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
  1224. // If it's a regclass or something else known, include the type.
  1225. bool MadeChange = false;
  1226. for (unsigned i = 0, e = Types.size(); i != e; ++i)
  1227. MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
  1228. NotRegisters, TP), TP);
  1229. return MadeChange;
  1230. }
  1231. if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
  1232. assert(Types.size() == 1 && "Invalid IntInit");
  1233. // Int inits are always integers. :)
  1234. bool MadeChange = Types[0].EnforceInteger(TP);
  1235. if (!Types[0].isConcrete())
  1236. return MadeChange;
  1237. MVT::SimpleValueType VT = getType(0);
  1238. if (VT == MVT::iPTR || VT == MVT::iPTRAny)
  1239. return MadeChange;
  1240. unsigned Size = EVT(VT).getSizeInBits();
  1241. // Make sure that the value is representable for this type.
  1242. if (Size >= 32) return MadeChange;
  1243. // Check that the value doesn't use more bits than we have. It must either
  1244. // be a sign- or zero-extended equivalent of the original.
  1245. int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
  1246. if (SignBitAndAbove == -1 || SignBitAndAbove == 0 || SignBitAndAbove == 1)
  1247. return MadeChange;
  1248. TP.error("Integer value '" + itostr(II->getValue()) +
  1249. "' is out of range for type '" + getEnumName(getType(0)) + "'!");
  1250. return false;
  1251. }
  1252. return false;
  1253. }
  1254. // special handling for set, which isn't really an SDNode.
  1255. if (getOperator()->getName() == "set") {
  1256. assert(getNumTypes() == 0 && "Set doesn't produce a value");
  1257. assert(getNumChildren() >= 2 && "Missing RHS of a set?");
  1258. unsigned NC = getNumChildren();
  1259. TreePatternNode *SetVal = getChild(NC-1);
  1260. bool MadeChange = SetVal->ApplyTypeConstraints(TP, NotRegisters);
  1261. for (unsigned i = 0; i < NC-1; ++i) {
  1262. TreePatternNode *Child = getChild(i);
  1263. MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
  1264. // Types of operands must match.
  1265. MadeChange |= Child->UpdateNodeType(0, SetVal->getExtType(i), TP);
  1266. MadeChange |= SetVal->UpdateNodeType(i, Child->getExtType(0), TP);
  1267. }
  1268. return MadeChange;
  1269. }
  1270. if (getOperator()->getName() == "implicit") {
  1271. assert(getNumTypes() == 0 && "Node doesn't produce a value");
  1272. bool MadeChange = false;
  1273. for (unsigned i = 0; i < getNumChildren(); ++i)
  1274. MadeChange = getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  1275. return MadeChange;
  1276. }
  1277. if (getOperator()->getName() == "COPY_TO_REGCLASS") {
  1278. bool MadeChange = false;
  1279. MadeChange |= getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
  1280. MadeChange |= getChild(1)->ApplyTypeConstraints(TP, NotRegisters);
  1281. assert(getChild(0)->getNumTypes() == 1 &&
  1282. getChild(1)->getNumTypes() == 1 && "Unhandled case");
  1283. // child #1 of COPY_TO_REGCLASS should be a register class. We don't care
  1284. // what type it gets, so if it didn't get a concrete type just give it the
  1285. // first viable type from the reg class.
  1286. if (!getChild(1)->hasTypeSet(0) &&
  1287. !getChild(1)->getExtType(0).isCompletelyUnknown()) {
  1288. MVT::SimpleValueType RCVT = getChild(1)->getExtType(0).getTypeList()[0];
  1289. MadeChange |= getChild(1)->UpdateNodeType(0, RCVT, TP);
  1290. }
  1291. return MadeChange;
  1292. }
  1293. if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
  1294. bool MadeChange = false;
  1295. // Apply the result type to the node.
  1296. unsigned NumRetVTs = Int->IS.RetVTs.size();
  1297. unsigned NumParamVTs = Int->IS.ParamVTs.size();
  1298. for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
  1299. MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
  1300. if (getNumChildren() != NumParamVTs + 1) {
  1301. TP.error("Intrinsic '" + Int->Name + "' expects " +
  1302. utostr(NumParamVTs) + " operands, not " +
  1303. utostr(getNumChildren() - 1) + " operands!");
  1304. return false;
  1305. }
  1306. // Apply type info to the intrinsic ID.
  1307. MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
  1308. for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
  1309. MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
  1310. MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
  1311. assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
  1312. MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
  1313. }
  1314. return MadeChange;
  1315. }
  1316. if (getOperator()->isSubClassOf("SDNode")) {
  1317. const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
  1318. // Check that the number of operands is sane. Negative operands -> varargs.
  1319. if (NI.getNumOperands() >= 0 &&
  1320. getNumChildren() != (unsigned)NI.getNumOperands()) {
  1321. TP.error(getOperator()->getName() + " node requires exactly " +
  1322. itostr(NI.getNumOperands()) + " operands!");
  1323. return false;
  1324. }
  1325. bool MadeChange = NI.ApplyTypeConstraints(this, TP);
  1326. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1327. MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
  1328. return MadeChange;
  1329. }
  1330. if (getOperator()->isSubClassOf("Instruction")) {
  1331. const DAGInstruction &Inst = CDP.getInstruction(getOperator());
  1332. CodeGenInstruction &InstInfo =
  1333. CDP.getTargetInfo().getInstruction(getOperator());
  1334. bool MadeChange = false;
  1335. // Apply the result types to the node, these come from the things in the
  1336. // (outs) list of the instruction.
  1337. // FIXME: Cap at one result so far.
  1338. unsigned NumResultsToAdd = InstInfo.Operands.NumDefs ? 1 : 0;
  1339. for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo) {
  1340. Record *ResultNode = Inst.getResult(ResNo);
  1341. if (ResultNode->isSubClassOf("PointerLikeRegClass")) {
  1342. MadeChange |= UpdateNodeType(ResNo, MVT::iPTR, TP);
  1343. } else if (ResultNode->isSubClassOf("RegisterOperand")) {
  1344. Record *RegClass = ResultNode->getValueAsDef("RegClass");
  1345. const CodeGenRegisterClass &RC =
  1346. CDP.getTargetInfo().getRegisterClass(RegClass);
  1347. MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
  1348. } else if (ResultNode->isSubClassOf("unknown_class")) {
  1349. // Nothing to do.
  1350. } else {
  1351. assert(ResultNode->isSubClassOf("RegisterClass") &&
  1352. "Operands should be register classes!");
  1353. const CodeGenRegisterClass &RC =
  1354. CDP.getTargetInfo().getRegisterClass(ResultNode);
  1355. MadeChange |= UpdateNodeType(ResNo, RC.getValueTypes(), TP);
  1356. }
  1357. }
  1358. // If the instruction has implicit defs, we apply the first one as a result.
  1359. // FIXME: This sucks, it should apply all implicit defs.
  1360. if (!InstInfo.ImplicitDefs.empty()) {
  1361. unsigned ResNo = NumResultsToAdd;
  1362. // FIXME: Generalize to multiple possible types and multiple possible
  1363. // ImplicitDefs.
  1364. MVT::SimpleValueType VT =
  1365. InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
  1366. if (VT != MVT::Other)
  1367. MadeChange |= UpdateNodeType(ResNo, VT, TP);
  1368. }
  1369. // If this is an INSERT_SUBREG, constrain the source and destination VTs to
  1370. // be the same.
  1371. if (getOperator()->getName() == "INSERT_SUBREG") {
  1372. assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
  1373. MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
  1374. MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
  1375. }
  1376. unsigned ChildNo = 0;
  1377. for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
  1378. Record *OperandNode = Inst.getOperand(i);
  1379. // If the instruction expects a predicate or optional def operand, we
  1380. // codegen this by setting the operand to it's default value if it has a
  1381. // non-empty DefaultOps field.
  1382. if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
  1383. !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
  1384. continue;
  1385. // Verify that we didn't run out of provided operands.
  1386. if (ChildNo >= getNumChildren()) {
  1387. TP.error("Instruction '" + getOperator()->getName() +
  1388. "' expects more operands than were provided.");
  1389. return false;
  1390. }
  1391. MVT::SimpleValueType VT;
  1392. TreePatternNode *Child = getChild(ChildNo++);
  1393. unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
  1394. if (OperandNode->isSubClassOf("RegisterClass")) {
  1395. const CodeGenRegisterClass &RC =
  1396. CDP.getTargetInfo().getRegisterClass(OperandNode);
  1397. MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
  1398. } else if (OperandNode->isSubClassOf("RegisterOperand")) {
  1399. Record *RegClass = OperandNode->getValueAsDef("RegClass");
  1400. const CodeGenRegisterClass &RC =
  1401. CDP.getTargetInfo().getRegisterClass(RegClass);
  1402. MadeChange |= Child->UpdateNodeType(ChildResNo, RC.getValueTypes(), TP);
  1403. } else if (OperandNode->isSubClassOf("Operand")) {
  1404. VT = getValueType(OperandNode->getValueAsDef("Type"));
  1405. MadeChange |= Child->UpdateNodeType(ChildResNo, VT, TP);
  1406. } else if (OperandNode->isSubClassOf("PointerLikeRegClass")) {
  1407. MadeChange |= Child->UpdateNodeType(ChildResNo, MVT::iPTR, TP);
  1408. } else if (OperandNode->isSubClassOf("unknown_class")) {
  1409. // Nothing to do.
  1410. } else
  1411. llvm_unreachable("Unknown operand type!");
  1412. MadeChange |= Child->ApplyTypeConstraints(TP, NotRegisters);
  1413. }
  1414. if (ChildNo != getNumChildren()) {
  1415. TP.error("Instruction '" + getOperator()->getName() +
  1416. "' was provided too many operands!");
  1417. return false;
  1418. }
  1419. return MadeChange;
  1420. }
  1421. assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
  1422. // Node transforms always take one operand.
  1423. if (getNumChildren() != 1) {
  1424. TP.error("Node transform '" + getOperator()->getName() +
  1425. "' requires one operand!");
  1426. return false;
  1427. }
  1428. bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
  1429. // If either the output or input of the xform does not have exact
  1430. // type info. We assume they must be the same. Otherwise, it is perfectly
  1431. // legal to transform from one type to a completely different type.
  1432. #if 0
  1433. if (!hasTypeSet() || !getChild(0)->hasTypeSet()) {
  1434. bool MadeChange = UpdateNodeType(getChild(0)->getExtType(), TP);
  1435. MadeChange |= getChild(0)->UpdateNodeType(getExtType(), TP);
  1436. return MadeChange;
  1437. }
  1438. #endif
  1439. return MadeChange;
  1440. }
  1441. /// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
  1442. /// RHS of a commutative operation, not the on LHS.
  1443. static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
  1444. if (!N->isLeaf() && N->getOperator()->getName() == "imm")
  1445. return true;
  1446. if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
  1447. return true;
  1448. return false;
  1449. }
  1450. /// canPatternMatch - If it is impossible for this pattern to match on this
  1451. /// target, fill in Reason and return false. Otherwise, return true. This is
  1452. /// used as a sanity check for .td files (to prevent people from writing stuff
  1453. /// that can never possibly work), and to prevent the pattern permuter from
  1454. /// generating stuff that is useless.
  1455. bool TreePatternNode::canPatternMatch(std::string &Reason,
  1456. const CodeGenDAGPatterns &CDP) {
  1457. if (isLeaf()) return true;
  1458. for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
  1459. if (!getChild(i)->canPatternMatch(Reason, CDP))
  1460. return false;
  1461. // If this is an intrinsic, handle cases that would make it not match. For
  1462. // example, if an operand is required to be an immediate.
  1463. if (getOperator()->isSubClassOf("Intrinsic")) {
  1464. // TODO:
  1465. return true;
  1466. }
  1467. // If this node is a commutative operator, check that the LHS isn't an
  1468. // immediate.
  1469. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
  1470. bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
  1471. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  1472. // Scan all of the operands of the node and make sure that only the last one
  1473. // is a constant node, unless the RHS also is.
  1474. if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
  1475. bool Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
  1476. for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
  1477. if (OnlyOnRHSOfCommutative(getChild(i))) {
  1478. Reason="Immediate value must be on the RHS of commutative operators!";
  1479. return false;
  1480. }
  1481. }
  1482. }
  1483. return true;
  1484. }
  1485. //===----------------------------------------------------------------------===//
  1486. // TreePattern implementation
  1487. //
  1488. TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
  1489. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  1490. isInputPattern(isInput), HasError(false) {
  1491. for (unsigned i = 0, e = RawPat->getSize(); i != e; ++i)
  1492. Trees.push_back(ParseTreePattern(RawPat->getElement(i), ""));
  1493. }
  1494. TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
  1495. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  1496. isInputPattern(isInput), HasError(false) {
  1497. Trees.push_back(ParseTreePattern(Pat, ""));
  1498. }
  1499. TreePattern::TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
  1500. CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
  1501. isInputPattern(isInput), HasError(false) {
  1502. Trees.push_back(Pat);
  1503. }
  1504. void TreePattern::error(const std::string &Msg) {
  1505. if (HasError)
  1506. return;
  1507. dump();
  1508. PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
  1509. HasError = true;
  1510. }
  1511. void TreePattern::ComputeNamedNodes() {
  1512. for (unsigned i = 0, e = Trees.size(); i != e; ++i)
  1513. ComputeNamedNodes(Trees[i]);
  1514. }
  1515. void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
  1516. if (!N->getName().empty())
  1517. NamedNodes[N->getName()].push_back(N);
  1518. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  1519. ComputeNamedNodes(N->getChild(i));
  1520. }
  1521. TreePatternNode *TreePattern::ParseTreePattern(Init *TheInit, StringRef OpName){
  1522. if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
  1523. Record *R = DI->getDef();
  1524. // Direct reference to a leaf DagNode or PatFrag? Turn it into a
  1525. // TreePatternNode of its own. For example:
  1526. /// (foo GPR, imm) -> (foo GPR, (imm))
  1527. if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrag"))
  1528. return ParseTreePattern(
  1529. DagInit::get(DI, "",
  1530. std::vector<std::pair<Init*, std::string> >()),
  1531. OpName);
  1532. // Input argument?
  1533. TreePatternNode *Res = new TreePatternNode(DI, 1);
  1534. if (R->getName() == "node" && !OpName.empty()) {
  1535. if (OpName.empty())
  1536. error("'node' argument requires a name to match with operand list");
  1537. Args.push_back(OpName);
  1538. }
  1539. Res->setName(OpName);
  1540. return Res;
  1541. }
  1542. if (IntInit *II = dyn_cast<IntInit>(TheInit)) {
  1543. if (!OpName.empty())
  1544. error("Constant int argument should not have a name!");
  1545. return new TreePatternNode(II, 1);
  1546. }
  1547. if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
  1548. // Turn this into an IntInit.
  1549. Init *II = BI->convertInitializerTo(IntRecTy::get());
  1550. if (II == 0 || !isa<IntInit>(II))
  1551. error("Bits value must be constants!");
  1552. return ParseTreePattern(II, OpName);
  1553. }
  1554. DagInit *Dag = dyn_cast<DagInit>(TheInit);
  1555. if (!Dag) {
  1556. TheInit->dump();
  1557. error("Pattern has unexpected init kind!");
  1558. }
  1559. DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
  1560. if (!OpDef) error("Pattern has unexpected operator type!");
  1561. Record *Operator = OpDef->getDef();
  1562. if (Operator->isSubClassOf("ValueType")) {
  1563. // If the operator is a ValueType, then this must be "type cast" of a leaf
  1564. // node.
  1565. if (Dag->getNumArgs() != 1)
  1566. error("Type cast only takes one operand!");
  1567. TreePatternNode *New = ParseTreePattern(Dag->getArg(0), Dag->getArgName(0));
  1568. // Apply the type cast.
  1569. assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
  1570. New->UpdateNodeType(0, getValueType(Operator), *this);
  1571. if (!OpName.empty())
  1572. error("ValueType cast should not have a name!");
  1573. return New;
  1574. }
  1575. // Verify that this is something that makes sense for an operator.
  1576. if (!Operator->isSubClassOf("PatFrag") &&
  1577. !Operator->isSubClassOf("SDNode") &&
  1578. !Operator->isSubClassOf("Instruction") &&
  1579. !Operator->isSubClassOf("SDNodeXForm") &&
  1580. !Operator->isSubClassOf("Intrinsic") &&
  1581. Operator->getName() != "set" &&
  1582. Operator->getName() != "implicit")
  1583. error("Unrecognized node '" + Operator->getName() + "'!");
  1584. // Check to see if this is something that is illegal in an input pattern.
  1585. if (isInputPattern) {
  1586. if (Operator->isSubClassOf("Instruction") ||
  1587. Operator->isSubClassOf("SDNodeXForm"))
  1588. error("Cannot use '" + Operator->getName() + "' in an input pattern!");
  1589. } else {
  1590. if (Operator->isSubClassOf("Intrinsic"))
  1591. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  1592. if (Operator->isSubClassOf("SDNode") &&
  1593. Operator->getName() != "imm" &&
  1594. Operator->getName() != "fpimm" &&
  1595. Operator->getName() != "tglobaltlsaddr" &&
  1596. Operator->getName() != "tconstpool" &&
  1597. Operator->getName() != "tjumptable" &&
  1598. Operator->getName() != "tframeindex" &&
  1599. Operator->getName() != "texternalsym" &&
  1600. Operator->getName() != "tblockaddress" &&
  1601. Operator->getName() != "tglobaladdr" &&
  1602. Operator->getName() != "bb" &&
  1603. Operator->getName() != "vt")
  1604. error("Cannot use '" + Operator->getName() + "' in an output pattern!");
  1605. }
  1606. std::vector<TreePatternNode*> Children;
  1607. // Parse all the operands.
  1608. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
  1609. Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgName(i)));
  1610. // If the operator is an intrinsic, then this is just syntactic sugar for for
  1611. // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
  1612. // convert the intrinsic name to a number.
  1613. if (Operator->isSubClassOf("Intrinsic")) {
  1614. const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
  1615. unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
  1616. // If this intrinsic returns void, it must have side-effects and thus a
  1617. // chain.
  1618. if (Int.IS.RetVTs.empty())
  1619. Operator = getDAGPatterns().get_intrinsic_void_sdnode();
  1620. else if (Int.ModRef != CodeGenIntrinsic::NoMem)
  1621. // Has side-effects, requires chain.
  1622. Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
  1623. else // Otherwise, no chain.
  1624. Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
  1625. TreePatternNode *IIDNode = new TreePatternNode(IntInit::get(IID), 1);
  1626. Children.insert(Children.begin(), IIDNode);
  1627. }
  1628. unsigned NumResults = GetNumNodeResults(Operator, CDP);
  1629. TreePatternNode *Result = new TreePatternNode(Operator, Children, NumResults);
  1630. Result->setName(OpName);
  1631. if (!Dag->getName().empty()) {
  1632. assert(Result->getName().empty());
  1633. Result->setName(Dag->getName());
  1634. }
  1635. return Result;
  1636. }
  1637. /// SimplifyTree - See if we can simplify this tree to eliminate something that
  1638. /// will never match in favor of something obvious that will. This is here
  1639. /// strictly as a convenience to target authors because it allows them to write
  1640. /// more type generic things and have useless type casts fold away.
  1641. ///
  1642. /// This returns true if any change is made.
  1643. static bool SimplifyTree(TreePatternNode *&N) {
  1644. if (N->isLeaf())
  1645. return false;
  1646. // If we have a bitconvert with a resolved type and if the source and
  1647. // destination types are the same, then the bitconvert is useless, remove it.
  1648. if (N->getOperator()->getName() == "bitconvert" &&
  1649. N->getExtType(0).isConcrete() &&
  1650. N->getExtType(0) == N->getChild(0)->getExtType(0) &&
  1651. N->getName().empty()) {
  1652. N = N->getChild(0);
  1653. SimplifyTree(N);
  1654. return true;
  1655. }
  1656. // Walk all children.
  1657. bool MadeChange = false;
  1658. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  1659. TreePatternNode *Child = N->getChild(i);
  1660. MadeChange |= SimplifyTree(Child);
  1661. N->setChild(i, Child);
  1662. }
  1663. return MadeChange;
  1664. }
  1665. /// InferAllTypes - Infer/propagate as many types throughout the expression
  1666. /// patterns as possible. Return true if all types are inferred, false
  1667. /// otherwise. Flags an error if a type contradiction is found.
  1668. bool TreePattern::
  1669. InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
  1670. if (NamedNodes.empty())
  1671. ComputeNamedNodes();
  1672. bool MadeChange = true;
  1673. while (MadeChange) {
  1674. MadeChange = false;
  1675. for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
  1676. MadeChange |= Trees[i]->ApplyTypeConstraints(*this, false);
  1677. MadeChange |= SimplifyTree(Trees[i]);
  1678. }
  1679. // If there are constraints on our named nodes, apply them.
  1680. for (StringMap<SmallVector<TreePatternNode*,1> >::iterator
  1681. I = NamedNodes.begin(), E = NamedNodes.end(); I != E; ++I) {
  1682. SmallVectorImpl<TreePatternNode*> &Nodes = I->second;
  1683. // If we have input named node types, propagate their types to the named
  1684. // values here.
  1685. if (InNamedTypes) {
  1686. // FIXME: Should be error?
  1687. assert(InNamedTypes->count(I->getKey()) &&
  1688. "Named node in output pattern but not input pattern?");
  1689. const SmallVectorImpl<TreePatternNode*> &InNodes =
  1690. InNamedTypes->find(I->getKey())->second;
  1691. // The input types should be fully resolved by now.
  1692. for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
  1693. // If this node is a register class, and it is the root of the pattern
  1694. // then we're mapping something onto an input register. We allow
  1695. // changing the type of the input register in this case. This allows
  1696. // us to match things like:
  1697. // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
  1698. if (Nodes[i] == Trees[0] && Nodes[i]->isLeaf()) {
  1699. DefInit *DI = dyn_cast<DefInit>(Nodes[i]->getLeafValue());
  1700. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  1701. DI->getDef()->isSubClassOf("RegisterOperand")))
  1702. continue;
  1703. }
  1704. assert(Nodes[i]->getNumTypes() == 1 &&
  1705. InNodes[0]->getNumTypes() == 1 &&
  1706. "FIXME: cannot name multiple result nodes yet");
  1707. MadeChange |= Nodes[i]->UpdateNodeType(0, InNodes[0]->getExtType(0),
  1708. *this);
  1709. }
  1710. }
  1711. // If there are multiple nodes with the same name, they must all have the
  1712. // same type.
  1713. if (I->second.size() > 1) {
  1714. for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
  1715. TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
  1716. assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
  1717. "FIXME: cannot name multiple result nodes yet");
  1718. MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
  1719. MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
  1720. }
  1721. }
  1722. }
  1723. }
  1724. bool HasUnresolvedTypes = false;
  1725. for (unsigned i = 0, e = Trees.size(); i != e; ++i)
  1726. HasUnresolvedTypes |= Trees[i]->ContainsUnresolvedType();
  1727. return !HasUnresolvedTypes;
  1728. }
  1729. void TreePattern::print(raw_ostream &OS) const {
  1730. OS << getRecord()->getName();
  1731. if (!Args.empty()) {
  1732. OS << "(" << Args[0];
  1733. for (unsigned i = 1, e = Args.size(); i != e; ++i)
  1734. OS << ", " << Args[i];
  1735. OS << ")";
  1736. }
  1737. OS << ": ";
  1738. if (Trees.size() > 1)
  1739. OS << "[\n";
  1740. for (unsigned i = 0, e = Trees.size(); i != e; ++i) {
  1741. OS << "\t";
  1742. Trees[i]->print(OS);
  1743. OS << "\n";
  1744. }
  1745. if (Trees.size() > 1)
  1746. OS << "]\n";
  1747. }
  1748. void TreePattern::dump() const { print(errs()); }
  1749. //===----------------------------------------------------------------------===//
  1750. // CodeGenDAGPatterns implementation
  1751. //
  1752. CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R) :
  1753. Records(R), Target(R) {
  1754. Intrinsics = LoadIntrinsics(Records, false);
  1755. TgtIntrinsics = LoadIntrinsics(Records, true);
  1756. ParseNodeInfo();
  1757. ParseNodeTransforms();
  1758. ParseComplexPatterns();
  1759. ParsePatternFragments();
  1760. ParseDefaultOperands();
  1761. ParseInstructions();
  1762. ParsePatterns();
  1763. // Generate variants. For example, commutative patterns can match
  1764. // multiple ways. Add them to PatternsToMatch as well.
  1765. GenerateVariants();
  1766. // Infer instruction flags. For example, we can detect loads,
  1767. // stores, and side effects in many cases by examining an
  1768. // instruction's pattern.
  1769. InferInstructionFlags();
  1770. // Verify that instruction flags match the patterns.
  1771. VerifyInstructionFlags();
  1772. }
  1773. CodeGenDAGPatterns::~CodeGenDAGPatterns() {
  1774. for (pf_iterator I = PatternFragments.begin(),
  1775. E = PatternFragments.end(); I != E; ++I)
  1776. delete I->second;
  1777. }
  1778. Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
  1779. Record *N = Records.getDef(Name);
  1780. if (!N || !N->isSubClassOf("SDNode")) {
  1781. errs() << "Error getting SDNode '" << Name << "'!\n";
  1782. exit(1);
  1783. }
  1784. return N;
  1785. }
  1786. // Parse all of the SDNode definitions for the target, populating SDNodes.
  1787. void CodeGenDAGPatterns::ParseNodeInfo() {
  1788. std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
  1789. while (!Nodes.empty()) {
  1790. SDNodes.insert(std::make_pair(Nodes.back(), Nodes.back()));
  1791. Nodes.pop_back();
  1792. }
  1793. // Get the builtin intrinsic nodes.
  1794. intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
  1795. intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
  1796. intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
  1797. }
  1798. /// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
  1799. /// map, and emit them to the file as functions.
  1800. void CodeGenDAGPatterns::ParseNodeTransforms() {
  1801. std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
  1802. while (!Xforms.empty()) {
  1803. Record *XFormNode = Xforms.back();
  1804. Record *SDNode = XFormNode->getValueAsDef("Opcode");
  1805. std::string Code = XFormNode->getValueAsString("XFormFunction");
  1806. SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
  1807. Xforms.pop_back();
  1808. }
  1809. }
  1810. void CodeGenDAGPatterns::ParseComplexPatterns() {
  1811. std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
  1812. while (!AMs.empty()) {
  1813. ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
  1814. AMs.pop_back();
  1815. }
  1816. }
  1817. /// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
  1818. /// file, building up the PatternFragments map. After we've collected them all,
  1819. /// inline fragments together as necessary, so that there are no references left
  1820. /// inside a pattern fragment to a pattern fragment.
  1821. ///
  1822. void CodeGenDAGPatterns::ParsePatternFragments() {
  1823. std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrag");
  1824. // First step, parse all of the fragments.
  1825. for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
  1826. DagInit *Tree = Fragments[i]->getValueAsDag("Fragment");
  1827. TreePattern *P = new TreePattern(Fragments[i], Tree, true, *this);
  1828. PatternFragments[Fragments[i]] = P;
  1829. // Validate the argument list, converting it to set, to discard duplicates.
  1830. std::vector<std::string> &Args = P->getArgList();
  1831. std::set<std::string> OperandsSet(Args.begin(), Args.end());
  1832. if (OperandsSet.count(""))
  1833. P->error("Cannot have unnamed 'node' values in pattern fragment!");
  1834. // Parse the operands list.
  1835. DagInit *OpsList = Fragments[i]->getValueAsDag("Operands");
  1836. DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
  1837. // Special cases: ops == outs == ins. Different names are used to
  1838. // improve readability.
  1839. if (!OpsOp ||
  1840. (OpsOp->getDef()->getName() != "ops" &&
  1841. OpsOp->getDef()->getName() != "outs" &&
  1842. OpsOp->getDef()->getName() != "ins"))
  1843. P->error("Operands list should start with '(ops ... '!");
  1844. // Copy over the arguments.
  1845. Args.clear();
  1846. for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
  1847. if (!isa<DefInit>(OpsList->getArg(j)) ||
  1848. cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
  1849. P->error("Operands list should all be 'node' values.");
  1850. if (OpsList->getArgName(j).empty())
  1851. P->error("Operands list should have names for each operand!");
  1852. if (!OperandsSet.count(OpsList->getArgName(j)))
  1853. P->error("'" + OpsList->getArgName(j) +
  1854. "' does not occur in pattern or was multiply specified!");
  1855. OperandsSet.erase(OpsList->getArgName(j));
  1856. Args.push_back(OpsList->getArgName(j));
  1857. }
  1858. if (!OperandsSet.empty())
  1859. P->error("Operands list does not contain an entry for operand '" +
  1860. *OperandsSet.begin() + "'!");
  1861. // If there is a code init for this fragment, keep track of the fact that
  1862. // this fragment uses it.
  1863. TreePredicateFn PredFn(P);
  1864. if (!PredFn.isAlwaysTrue())
  1865. P->getOnlyTree()->addPredicateFn(PredFn);
  1866. // If there is a node transformation corresponding to this, keep track of
  1867. // it.
  1868. Record *Transform = Fragments[i]->getValueAsDef("OperandTransform");
  1869. if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
  1870. P->getOnlyTree()->setTransformFn(Transform);
  1871. }
  1872. // Now that we've parsed all of the tree fragments, do a closure on them so
  1873. // that there are not references to PatFrags left inside of them.
  1874. for (unsigned i = 0, e = Fragments.size(); i != e; ++i) {
  1875. TreePattern *ThePat = PatternFragments[Fragments[i]];
  1876. ThePat->InlinePatternFragments();
  1877. // Infer as many types as possible. Don't worry about it if we don't infer
  1878. // all of them, some may depend on the inputs of the pattern.
  1879. ThePat->InferAllTypes();
  1880. ThePat->resetError();
  1881. // If debugging, print out the pattern fragment result.
  1882. DEBUG(ThePat->dump());
  1883. }
  1884. }
  1885. void CodeGenDAGPatterns::ParseDefaultOperands() {
  1886. std::vector<Record*> DefaultOps;
  1887. DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
  1888. // Find some SDNode.
  1889. assert(!SDNodes.empty() && "No SDNodes parsed?");
  1890. Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
  1891. for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
  1892. DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
  1893. // Clone the DefaultInfo dag node, changing the operator from 'ops' to
  1894. // SomeSDnode so that we can parse this.
  1895. std::vector<std::pair<Init*, std::string> > Ops;
  1896. for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
  1897. Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
  1898. DefaultInfo->getArgName(op)));
  1899. DagInit *DI = DagInit::get(SomeSDNode, "", Ops);
  1900. // Create a TreePattern to parse this.
  1901. TreePattern P(DefaultOps[i], DI, false, *this);
  1902. assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
  1903. // Copy the operands over into a DAGDefaultOperand.
  1904. DAGDefaultOperand DefaultOpInfo;
  1905. TreePatternNode *T = P.getTree(0);
  1906. for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
  1907. TreePatternNode *TPN = T->getChild(op);
  1908. while (TPN->ApplyTypeConstraints(P, false))
  1909. /* Resolve all types */;
  1910. if (TPN->ContainsUnresolvedType()) {
  1911. PrintFatalError("Value #" + utostr(i) + " of OperandWithDefaultOps '" +
  1912. DefaultOps[i]->getName() +"' doesn't have a concrete type!");
  1913. }
  1914. DefaultOpInfo.DefaultOps.push_back(TPN);
  1915. }
  1916. // Insert it into the DefaultOperands map so we can find it later.
  1917. DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
  1918. }
  1919. }
  1920. /// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
  1921. /// instruction input. Return true if this is a real use.
  1922. static bool HandleUse(TreePattern *I, TreePatternNode *Pat,
  1923. std::map<std::string, TreePatternNode*> &InstInputs) {
  1924. // No name -> not interesting.
  1925. if (Pat->getName().empty()) {
  1926. if (Pat->isLeaf()) {
  1927. DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
  1928. if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
  1929. DI->getDef()->isSubClassOf("RegisterOperand")))
  1930. I->error("Input " + DI->getDef()->getName() + " must be named!");
  1931. }
  1932. return false;
  1933. }
  1934. Record *Rec;
  1935. if (Pat->isLeaf()) {
  1936. DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
  1937. if (!DI) I->error("Input $" + Pat->getName() + " must be an identifier!");
  1938. Rec = DI->getDef();
  1939. } else {
  1940. Rec = Pat->getOperator();
  1941. }
  1942. // SRCVALUE nodes are ignored.
  1943. if (Rec->getName() == "srcvalue")
  1944. return false;
  1945. TreePatternNode *&Slot = InstInputs[Pat->getName()];
  1946. if (!Slot) {
  1947. Slot = Pat;
  1948. return true;
  1949. }
  1950. Record *SlotRec;
  1951. if (Slot->isLeaf()) {
  1952. SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
  1953. } else {
  1954. assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
  1955. SlotRec = Slot->getOperator();
  1956. }
  1957. // Ensure that the inputs agree if we've already seen this input.
  1958. if (Rec != SlotRec)
  1959. I->error("All $" + Pat->getName() + " inputs must agree with each other");
  1960. if (Slot->getExtTypes() != Pat->getExtTypes())
  1961. I->error("All $" + Pat->getName() + " inputs must agree with each other");
  1962. return true;
  1963. }
  1964. /// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
  1965. /// part of "I", the instruction), computing the set of inputs and outputs of
  1966. /// the pattern. Report errors if we see anything naughty.
  1967. void CodeGenDAGPatterns::
  1968. FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
  1969. std::map<std::string, TreePatternNode*> &InstInputs,
  1970. std::map<std::string, TreePatternNode*>&InstResults,
  1971. std::vector<Record*> &InstImpResults) {
  1972. if (Pat->isLeaf()) {
  1973. bool isUse = HandleUse(I, Pat, InstInputs);
  1974. if (!isUse && Pat->getTransformFn())
  1975. I->error("Cannot specify a transform function for a non-input value!");
  1976. return;
  1977. }
  1978. if (Pat->getOperator()->getName() == "implicit") {
  1979. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  1980. TreePatternNode *Dest = Pat->getChild(i);
  1981. if (!Dest->isLeaf())
  1982. I->error("implicitly defined value should be a register!");
  1983. DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
  1984. if (!Val || !Val->getDef()->isSubClassOf("Register"))
  1985. I->error("implicitly defined value should be a register!");
  1986. InstImpResults.push_back(Val->getDef());
  1987. }
  1988. return;
  1989. }
  1990. if (Pat->getOperator()->getName() != "set") {
  1991. // If this is not a set, verify that the children nodes are not void typed,
  1992. // and recurse.
  1993. for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
  1994. if (Pat->getChild(i)->getNumTypes() == 0)
  1995. I->error("Cannot have void nodes inside of patterns!");
  1996. FindPatternInputsAndOutputs(I, Pat->getChild(i), InstInputs, InstResults,
  1997. InstImpResults);
  1998. }
  1999. // If this is a non-leaf node with no children, treat it basically as if
  2000. // it were a leaf. This handles nodes like (imm).
  2001. bool isUse = HandleUse(I, Pat, InstInputs);
  2002. if (!isUse && Pat->getTransformFn())
  2003. I->error("Cannot specify a transform function for a non-input value!");
  2004. return;
  2005. }
  2006. // Otherwise, this is a set, validate and collect instruction results.
  2007. if (Pat->getNumChildren() == 0)
  2008. I->error("set requires operands!");
  2009. if (Pat->getTransformFn())
  2010. I->error("Cannot specify a transform function on a set node!");
  2011. // Check the set destinations.
  2012. unsigned NumDests = Pat->getNumChildren()-1;
  2013. for (unsigned i = 0; i != NumDests; ++i) {
  2014. TreePatternNode *Dest = Pat->getChild(i);
  2015. if (!Dest->isLeaf())
  2016. I->error("set destination should be a register!");
  2017. DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
  2018. if (!Val)
  2019. I->error("set destination should be a register!");
  2020. if (Val->getDef()->isSubClassOf("RegisterClass") ||
  2021. Val->getDef()->isSubClassOf("RegisterOperand") ||
  2022. Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
  2023. if (Dest->getName().empty())
  2024. I->error("set destination must have a name!");
  2025. if (InstResults.count(Dest->getName()))
  2026. I->error("cannot set '" + Dest->getName() +"' multiple times");
  2027. InstResults[Dest->getName()] = Dest;
  2028. } else if (Val->getDef()->isSubClassOf("Register")) {
  2029. InstImpResults.push_back(Val->getDef());
  2030. } else {
  2031. I->error("set destination should be a register!");
  2032. }
  2033. }
  2034. // Verify and collect info from the computation.
  2035. FindPatternInputsAndOutputs(I, Pat->getChild(NumDests),
  2036. InstInputs, InstResults, InstImpResults);
  2037. }
  2038. //===----------------------------------------------------------------------===//
  2039. // Instruction Analysis
  2040. //===----------------------------------------------------------------------===//
  2041. class InstAnalyzer {
  2042. const CodeGenDAGPatterns &CDP;
  2043. public:
  2044. bool hasSideEffects;
  2045. bool mayStore;
  2046. bool mayLoad;
  2047. bool isBitcast;
  2048. bool isVariadic;
  2049. InstAnalyzer(const CodeGenDAGPatterns &cdp)
  2050. : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
  2051. isBitcast(false), isVariadic(false) {}
  2052. void Analyze(const TreePattern *Pat) {
  2053. // Assume only the first tree is the pattern. The others are clobber nodes.
  2054. AnalyzeNode(Pat->getTree(0));
  2055. }
  2056. void Analyze(const PatternToMatch *Pat) {
  2057. AnalyzeNode(Pat->getSrcPattern());
  2058. }
  2059. private:
  2060. bool IsNodeBitcast(const TreePatternNode *N) const {
  2061. if (hasSideEffects || mayLoad || mayStore || isVariadic)
  2062. return false;
  2063. if (N->getNumChildren() != 2)
  2064. return false;
  2065. const TreePatternNode *N0 = N->getChild(0);
  2066. if (!N0->isLeaf() || !isa<DefInit>(N0->getLeafValue()))
  2067. return false;
  2068. const TreePatternNode *N1 = N->getChild(1);
  2069. if (N1->isLeaf())
  2070. return false;
  2071. if (N1->getNumChildren() != 1 || !N1->getChild(0)->isLeaf())
  2072. return false;
  2073. const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N1->getOperator());
  2074. if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
  2075. return false;
  2076. return OpInfo.getEnumName() == "ISD::BITCAST";
  2077. }
  2078. public:
  2079. void AnalyzeNode(const TreePatternNode *N) {
  2080. if (N->isLeaf()) {
  2081. if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
  2082. Record *LeafRec = DI->getDef();
  2083. // Handle ComplexPattern leaves.
  2084. if (LeafRec->isSubClassOf("ComplexPattern")) {
  2085. const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
  2086. if (CP.hasProperty(SDNPMayStore)) mayStore = true;
  2087. if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
  2088. if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
  2089. }
  2090. }
  2091. return;
  2092. }
  2093. // Analyze children.
  2094. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2095. AnalyzeNode(N->getChild(i));
  2096. // Ignore set nodes, which are not SDNodes.
  2097. if (N->getOperator()->getName() == "set") {
  2098. isBitcast = IsNodeBitcast(N);
  2099. return;
  2100. }
  2101. // Get information about the SDNode for the operator.
  2102. const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
  2103. // Notice properties of the node.
  2104. if (OpInfo.hasProperty(SDNPMayStore)) mayStore = true;
  2105. if (OpInfo.hasProperty(SDNPMayLoad)) mayLoad = true;
  2106. if (OpInfo.hasProperty(SDNPSideEffect)) hasSideEffects = true;
  2107. if (OpInfo.hasProperty(SDNPVariadic)) isVariadic = true;
  2108. if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
  2109. // If this is an intrinsic, analyze it.
  2110. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadArgMem)
  2111. mayLoad = true;// These may load memory.
  2112. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteArgMem)
  2113. mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
  2114. if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem)
  2115. // WriteMem intrinsics can have other strange effects.
  2116. hasSideEffects = true;
  2117. }
  2118. }
  2119. };
  2120. static bool InferFromPattern(CodeGenInstruction &InstInfo,
  2121. const InstAnalyzer &PatInfo,
  2122. Record *PatDef) {
  2123. bool Error = false;
  2124. // Remember where InstInfo got its flags.
  2125. if (InstInfo.hasUndefFlags())
  2126. InstInfo.InferredFrom = PatDef;
  2127. // Check explicitly set flags for consistency.
  2128. if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
  2129. !InstInfo.hasSideEffects_Unset) {
  2130. // Allow explicitly setting hasSideEffects = 1 on instructions, even when
  2131. // the pattern has no side effects. That could be useful for div/rem
  2132. // instructions that may trap.
  2133. if (!InstInfo.hasSideEffects) {
  2134. Error = true;
  2135. PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
  2136. Twine(InstInfo.hasSideEffects));
  2137. }
  2138. }
  2139. if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
  2140. Error = true;
  2141. PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
  2142. Twine(InstInfo.mayStore));
  2143. }
  2144. if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
  2145. // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
  2146. // Some targets translate imediates to loads.
  2147. if (!InstInfo.mayLoad) {
  2148. Error = true;
  2149. PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
  2150. Twine(InstInfo.mayLoad));
  2151. }
  2152. }
  2153. // Transfer inferred flags.
  2154. InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
  2155. InstInfo.mayStore |= PatInfo.mayStore;
  2156. InstInfo.mayLoad |= PatInfo.mayLoad;
  2157. // These flags are silently added without any verification.
  2158. InstInfo.isBitcast |= PatInfo.isBitcast;
  2159. // Don't infer isVariadic. This flag means something different on SDNodes and
  2160. // instructions. For example, a CALL SDNode is variadic because it has the
  2161. // call arguments as operands, but a CALL instruction is not variadic - it
  2162. // has argument registers as implicit, not explicit uses.
  2163. return Error;
  2164. }
  2165. /// hasNullFragReference - Return true if the DAG has any reference to the
  2166. /// null_frag operator.
  2167. static bool hasNullFragReference(DagInit *DI) {
  2168. DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
  2169. if (!OpDef) return false;
  2170. Record *Operator = OpDef->getDef();
  2171. // If this is the null fragment, return true.
  2172. if (Operator->getName() == "null_frag") return true;
  2173. // If any of the arguments reference the null fragment, return true.
  2174. for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
  2175. DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
  2176. if (Arg && hasNullFragReference(Arg))
  2177. return true;
  2178. }
  2179. return false;
  2180. }
  2181. /// hasNullFragReference - Return true if any DAG in the list references
  2182. /// the null_frag operator.
  2183. static bool hasNullFragReference(ListInit *LI) {
  2184. for (unsigned i = 0, e = LI->getSize(); i != e; ++i) {
  2185. DagInit *DI = dyn_cast<DagInit>(LI->getElement(i));
  2186. assert(DI && "non-dag in an instruction Pattern list?!");
  2187. if (hasNullFragReference(DI))
  2188. return true;
  2189. }
  2190. return false;
  2191. }
  2192. /// Get all the instructions in a tree.
  2193. static void
  2194. getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
  2195. if (Tree->isLeaf())
  2196. return;
  2197. if (Tree->getOperator()->isSubClassOf("Instruction"))
  2198. Instrs.push_back(Tree->getOperator());
  2199. for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
  2200. getInstructionsInTree(Tree->getChild(i), Instrs);
  2201. }
  2202. /// ParseInstructions - Parse all of the instructions, inlining and resolving
  2203. /// any fragments involved. This populates the Instructions list with fully
  2204. /// resolved instructions.
  2205. void CodeGenDAGPatterns::ParseInstructions() {
  2206. std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
  2207. for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
  2208. ListInit *LI = 0;
  2209. if (isa<ListInit>(Instrs[i]->getValueInit("Pattern")))
  2210. LI = Instrs[i]->getValueAsListInit("Pattern");
  2211. // If there is no pattern, only collect minimal information about the
  2212. // instruction for its operand list. We have to assume that there is one
  2213. // result, as we have no detailed info. A pattern which references the
  2214. // null_frag operator is as-if no pattern were specified. Normally this
  2215. // is from a multiclass expansion w/ a SDPatternOperator passed in as
  2216. // null_frag.
  2217. if (!LI || LI->getSize() == 0 || hasNullFragReference(LI)) {
  2218. std::vector<Record*> Results;
  2219. std::vector<Record*> Operands;
  2220. CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
  2221. if (InstInfo.Operands.size() != 0) {
  2222. if (InstInfo.Operands.NumDefs == 0) {
  2223. // These produce no results
  2224. for (unsigned j = 0, e = InstInfo.Operands.size(); j < e; ++j)
  2225. Operands.push_back(InstInfo.Operands[j].Rec);
  2226. } else {
  2227. // Assume the first operand is the result.
  2228. Results.push_back(InstInfo.Operands[0].Rec);
  2229. // The rest are inputs.
  2230. for (unsigned j = 1, e = InstInfo.Operands.size(); j < e; ++j)
  2231. Operands.push_back(InstInfo.Operands[j].Rec);
  2232. }
  2233. }
  2234. // Create and insert the instruction.
  2235. std::vector<Record*> ImpResults;
  2236. Instructions.insert(std::make_pair(Instrs[i],
  2237. DAGInstruction(0, Results, Operands, ImpResults)));
  2238. continue; // no pattern.
  2239. }
  2240. // Parse the instruction.
  2241. TreePattern *I = new TreePattern(Instrs[i], LI, true, *this);
  2242. // Inline pattern fragments into it.
  2243. I->InlinePatternFragments();
  2244. // Infer as many types as possible. If we cannot infer all of them, we can
  2245. // never do anything with this instruction pattern: report it to the user.
  2246. if (!I->InferAllTypes())
  2247. I->error("Could not infer all types in pattern!");
  2248. // InstInputs - Keep track of all of the inputs of the instruction, along
  2249. // with the record they are declared as.
  2250. std::map<std::string, TreePatternNode*> InstInputs;
  2251. // InstResults - Keep track of all the virtual registers that are 'set'
  2252. // in the instruction, including what reg class they are.
  2253. std::map<std::string, TreePatternNode*> InstResults;
  2254. std::vector<Record*> InstImpResults;
  2255. // Verify that the top-level forms in the instruction are of void type, and
  2256. // fill in the InstResults map.
  2257. for (unsigned j = 0, e = I->getNumTrees(); j != e; ++j) {
  2258. TreePatternNode *Pat = I->getTree(j);
  2259. if (Pat->getNumTypes() != 0)
  2260. I->error("Top-level forms in instruction pattern should have"
  2261. " void types");
  2262. // Find inputs and outputs, and verify the structure of the uses/defs.
  2263. FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
  2264. InstImpResults);
  2265. }
  2266. // Now that we have inputs and outputs of the pattern, inspect the operands
  2267. // list for the instruction. This determines the order that operands are
  2268. // added to the machine instruction the node corresponds to.
  2269. unsigned NumResults = InstResults.size();
  2270. // Parse the operands list from the (ops) list, validating it.
  2271. assert(I->getArgList().empty() && "Args list should still be empty here!");
  2272. CodeGenInstruction &CGI = Target.getInstruction(Instrs[i]);
  2273. // Check that all of the results occur first in the list.
  2274. std::vector<Record*> Results;
  2275. TreePatternNode *Res0Node = 0;
  2276. for (unsigned i = 0; i != NumResults; ++i) {
  2277. if (i == CGI.Operands.size())
  2278. I->error("'" + InstResults.begin()->first +
  2279. "' set but does not appear in operand list!");
  2280. const std::string &OpName = CGI.Operands[i].Name;
  2281. // Check that it exists in InstResults.
  2282. TreePatternNode *RNode = InstResults[OpName];
  2283. if (RNode == 0)
  2284. I->error("Operand $" + OpName + " does not exist in operand list!");
  2285. if (i == 0)
  2286. Res0Node = RNode;
  2287. Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
  2288. if (R == 0)
  2289. I->error("Operand $" + OpName + " should be a set destination: all "
  2290. "outputs must occur before inputs in operand list!");
  2291. if (CGI.Operands[i].Rec != R)
  2292. I->error("Operand $" + OpName + " class mismatch!");
  2293. // Remember the return type.
  2294. Results.push_back(CGI.Operands[i].Rec);
  2295. // Okay, this one checks out.
  2296. InstResults.erase(OpName);
  2297. }
  2298. // Loop over the inputs next. Make a copy of InstInputs so we can destroy
  2299. // the copy while we're checking the inputs.
  2300. std::map<std::string, TreePatternNode*> InstInputsCheck(InstInputs);
  2301. std::vector<TreePatternNode*> ResultNodeOperands;
  2302. std::vector<Record*> Operands;
  2303. for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
  2304. CGIOperandList::OperandInfo &Op = CGI.Operands[i];
  2305. const std::string &OpName = Op.Name;
  2306. if (OpName.empty())
  2307. I->error("Operand #" + utostr(i) + " in operands list has no name!");
  2308. if (!InstInputsCheck.count(OpName)) {
  2309. // If this is an operand with a DefaultOps set filled in, we can ignore
  2310. // this. When we codegen it, we will do so as always executed.
  2311. if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
  2312. // Does it have a non-empty DefaultOps field? If so, ignore this
  2313. // operand.
  2314. if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
  2315. continue;
  2316. }
  2317. I->error("Operand $" + OpName +
  2318. " does not appear in the instruction pattern");
  2319. }
  2320. TreePatternNode *InVal = InstInputsCheck[OpName];
  2321. InstInputsCheck.erase(OpName); // It occurred, remove from map.
  2322. if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
  2323. Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
  2324. if (Op.Rec != InRec && !InRec->isSubClassOf("ComplexPattern"))
  2325. I->error("Operand $" + OpName + "'s register class disagrees"
  2326. " between the operand and pattern");
  2327. }
  2328. Operands.push_back(Op.Rec);
  2329. // Construct the result for the dest-pattern operand list.
  2330. TreePatternNode *OpNode = InVal->clone();
  2331. // No predicate is useful on the result.
  2332. OpNode->clearPredicateFns();
  2333. // Promote the xform function to be an explicit node if set.
  2334. if (Record *Xform = OpNode->getTransformFn()) {
  2335. OpNode->setTransformFn(0);
  2336. std::vector<TreePatternNode*> Children;
  2337. Children.push_back(OpNode);
  2338. OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
  2339. }
  2340. ResultNodeOperands.push_back(OpNode);
  2341. }
  2342. if (!InstInputsCheck.empty())
  2343. I->error("Input operand $" + InstInputsCheck.begin()->first +
  2344. " occurs in pattern but not in operands list!");
  2345. TreePatternNode *ResultPattern =
  2346. new TreePatternNode(I->getRecord(), ResultNodeOperands,
  2347. GetNumNodeResults(I->getRecord(), *this));
  2348. // Copy fully inferred output node type to instruction result pattern.
  2349. for (unsigned i = 0; i != NumResults; ++i)
  2350. ResultPattern->setType(i, Res0Node->getExtType(i));
  2351. // Create and insert the instruction.
  2352. // FIXME: InstImpResults should not be part of DAGInstruction.
  2353. DAGInstruction TheInst(I, Results, Operands, InstImpResults);
  2354. Instructions.insert(std::make_pair(I->getRecord(), TheInst));
  2355. // Use a temporary tree pattern to infer all types and make sure that the
  2356. // constructed result is correct. This depends on the instruction already
  2357. // being inserted into the Instructions map.
  2358. TreePattern Temp(I->getRecord(), ResultPattern, false, *this);
  2359. Temp.InferAllTypes(&I->getNamedNodesMap());
  2360. DAGInstruction &TheInsertedInst = Instructions.find(I->getRecord())->second;
  2361. TheInsertedInst.setResultPattern(Temp.getOnlyTree());
  2362. DEBUG(I->dump());
  2363. }
  2364. // If we can, convert the instructions to be patterns that are matched!
  2365. for (std::map<Record*, DAGInstruction, LessRecordByID>::iterator II =
  2366. Instructions.begin(),
  2367. E = Instructions.end(); II != E; ++II) {
  2368. DAGInstruction &TheInst = II->second;
  2369. TreePattern *I = TheInst.getPattern();
  2370. if (I == 0) continue; // No pattern.
  2371. // FIXME: Assume only the first tree is the pattern. The others are clobber
  2372. // nodes.
  2373. TreePatternNode *Pattern = I->getTree(0);
  2374. TreePatternNode *SrcPattern;
  2375. if (Pattern->getOperator()->getName() == "set") {
  2376. SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
  2377. } else{
  2378. // Not a set (store or something?)
  2379. SrcPattern = Pattern;
  2380. }
  2381. Record *Instr = II->first;
  2382. AddPatternToMatch(I,
  2383. PatternToMatch(Instr,
  2384. Instr->getValueAsListInit("Predicates"),
  2385. SrcPattern,
  2386. TheInst.getResultPattern(),
  2387. TheInst.getImpResults(),
  2388. Instr->getValueAsInt("AddedComplexity"),
  2389. Instr->getID()));
  2390. }
  2391. }
  2392. typedef std::pair<const TreePatternNode*, unsigned> NameRecord;
  2393. static void FindNames(const TreePatternNode *P,
  2394. std::map<std::string, NameRecord> &Names,
  2395. TreePattern *PatternTop) {
  2396. if (!P->getName().empty()) {
  2397. NameRecord &Rec = Names[P->getName()];
  2398. // If this is the first instance of the name, remember the node.
  2399. if (Rec.second++ == 0)
  2400. Rec.first = P;
  2401. else if (Rec.first->getExtTypes() != P->getExtTypes())
  2402. PatternTop->error("repetition of value: $" + P->getName() +
  2403. " where different uses have different types!");
  2404. }
  2405. if (!P->isLeaf()) {
  2406. for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
  2407. FindNames(P->getChild(i), Names, PatternTop);
  2408. }
  2409. }
  2410. void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
  2411. const PatternToMatch &PTM) {
  2412. // Do some sanity checking on the pattern we're about to match.
  2413. std::string Reason;
  2414. if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
  2415. PrintWarning(Pattern->getRecord()->getLoc(),
  2416. Twine("Pattern can never match: ") + Reason);
  2417. return;
  2418. }
  2419. // If the source pattern's root is a complex pattern, that complex pattern
  2420. // must specify the nodes it can potentially match.
  2421. if (const ComplexPattern *CP =
  2422. PTM.getSrcPattern()->getComplexPatternInfo(*this))
  2423. if (CP->getRootNodes().empty())
  2424. Pattern->error("ComplexPattern at root must specify list of opcodes it"
  2425. " could match");
  2426. // Find all of the named values in the input and output, ensure they have the
  2427. // same type.
  2428. std::map<std::string, NameRecord> SrcNames, DstNames;
  2429. FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
  2430. FindNames(PTM.getDstPattern(), DstNames, Pattern);
  2431. // Scan all of the named values in the destination pattern, rejecting them if
  2432. // they don't exist in the input pattern.
  2433. for (std::map<std::string, NameRecord>::iterator
  2434. I = DstNames.begin(), E = DstNames.end(); I != E; ++I) {
  2435. if (SrcNames[I->first].first == 0)
  2436. Pattern->error("Pattern has input without matching name in output: $" +
  2437. I->first);
  2438. }
  2439. // Scan all of the named values in the source pattern, rejecting them if the
  2440. // name isn't used in the dest, and isn't used to tie two values together.
  2441. for (std::map<std::string, NameRecord>::iterator
  2442. I = SrcNames.begin(), E = SrcNames.end(); I != E; ++I)
  2443. if (DstNames[I->first].first == 0 && SrcNames[I->first].second == 1)
  2444. Pattern->error("Pattern has dead named input: $" + I->first);
  2445. PatternsToMatch.push_back(PTM);
  2446. }
  2447. void CodeGenDAGPatterns::InferInstructionFlags() {
  2448. const std::vector<const CodeGenInstruction*> &Instructions =
  2449. Target.getInstructionsByEnumValue();
  2450. // First try to infer flags from the primary instruction pattern, if any.
  2451. SmallVector<CodeGenInstruction*, 8> Revisit;
  2452. unsigned Errors = 0;
  2453. for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
  2454. CodeGenInstruction &InstInfo =
  2455. const_cast<CodeGenInstruction &>(*Instructions[i]);
  2456. // Treat neverHasSideEffects = 1 as the equivalent of hasSideEffects = 0.
  2457. // This flag is obsolete and will be removed.
  2458. if (InstInfo.neverHasSideEffects) {
  2459. assert(!InstInfo.hasSideEffects);
  2460. InstInfo.hasSideEffects_Unset = false;
  2461. }
  2462. // Get the primary instruction pattern.
  2463. const TreePattern *Pattern = getInstruction(InstInfo.TheDef).getPattern();
  2464. if (!Pattern) {
  2465. if (InstInfo.hasUndefFlags())
  2466. Revisit.push_back(&InstInfo);
  2467. continue;
  2468. }
  2469. InstAnalyzer PatInfo(*this);
  2470. PatInfo.Analyze(Pattern);
  2471. Errors += InferFromPattern(InstInfo, PatInfo, InstInfo.TheDef);
  2472. }
  2473. // Second, look for single-instruction patterns defined outside the
  2474. // instruction.
  2475. for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
  2476. const PatternToMatch &PTM = *I;
  2477. // We can only infer from single-instruction patterns, otherwise we won't
  2478. // know which instruction should get the flags.
  2479. SmallVector<Record*, 8> PatInstrs;
  2480. getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
  2481. if (PatInstrs.size() != 1)
  2482. continue;
  2483. // Get the single instruction.
  2484. CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
  2485. // Only infer properties from the first pattern. We'll verify the others.
  2486. if (InstInfo.InferredFrom)
  2487. continue;
  2488. InstAnalyzer PatInfo(*this);
  2489. PatInfo.Analyze(&PTM);
  2490. Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
  2491. }
  2492. if (Errors)
  2493. PrintFatalError("pattern conflicts");
  2494. // Revisit instructions with undefined flags and no pattern.
  2495. if (Target.guessInstructionProperties()) {
  2496. for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
  2497. CodeGenInstruction &InstInfo = *Revisit[i];
  2498. if (InstInfo.InferredFrom)
  2499. continue;
  2500. // The mayLoad and mayStore flags default to false.
  2501. // Conservatively assume hasSideEffects if it wasn't explicit.
  2502. if (InstInfo.hasSideEffects_Unset)
  2503. InstInfo.hasSideEffects = true;
  2504. }
  2505. return;
  2506. }
  2507. // Complain about any flags that are still undefined.
  2508. for (unsigned i = 0, e = Revisit.size(); i != e; ++i) {
  2509. CodeGenInstruction &InstInfo = *Revisit[i];
  2510. if (InstInfo.InferredFrom)
  2511. continue;
  2512. if (InstInfo.hasSideEffects_Unset)
  2513. PrintError(InstInfo.TheDef->getLoc(),
  2514. "Can't infer hasSideEffects from patterns");
  2515. if (InstInfo.mayStore_Unset)
  2516. PrintError(InstInfo.TheDef->getLoc(),
  2517. "Can't infer mayStore from patterns");
  2518. if (InstInfo.mayLoad_Unset)
  2519. PrintError(InstInfo.TheDef->getLoc(),
  2520. "Can't infer mayLoad from patterns");
  2521. }
  2522. }
  2523. /// Verify instruction flags against pattern node properties.
  2524. void CodeGenDAGPatterns::VerifyInstructionFlags() {
  2525. unsigned Errors = 0;
  2526. for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
  2527. const PatternToMatch &PTM = *I;
  2528. SmallVector<Record*, 8> Instrs;
  2529. getInstructionsInTree(PTM.getDstPattern(), Instrs);
  2530. if (Instrs.empty())
  2531. continue;
  2532. // Count the number of instructions with each flag set.
  2533. unsigned NumSideEffects = 0;
  2534. unsigned NumStores = 0;
  2535. unsigned NumLoads = 0;
  2536. for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
  2537. const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
  2538. NumSideEffects += InstInfo.hasSideEffects;
  2539. NumStores += InstInfo.mayStore;
  2540. NumLoads += InstInfo.mayLoad;
  2541. }
  2542. // Analyze the source pattern.
  2543. InstAnalyzer PatInfo(*this);
  2544. PatInfo.Analyze(&PTM);
  2545. // Collect error messages.
  2546. SmallVector<std::string, 4> Msgs;
  2547. // Check for missing flags in the output.
  2548. // Permit extra flags for now at least.
  2549. if (PatInfo.hasSideEffects && !NumSideEffects)
  2550. Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
  2551. // Don't verify store flags on instructions with side effects. At least for
  2552. // intrinsics, side effects implies mayStore.
  2553. if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
  2554. Msgs.push_back("pattern may store, but mayStore isn't set");
  2555. // Similarly, mayStore implies mayLoad on intrinsics.
  2556. if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
  2557. Msgs.push_back("pattern may load, but mayLoad isn't set");
  2558. // Print error messages.
  2559. if (Msgs.empty())
  2560. continue;
  2561. ++Errors;
  2562. for (unsigned i = 0, e = Msgs.size(); i != e; ++i)
  2563. PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msgs[i]) + " on the " +
  2564. (Instrs.size() == 1 ?
  2565. "instruction" : "output instructions"));
  2566. // Provide the location of the relevant instruction definitions.
  2567. for (unsigned i = 0, e = Instrs.size(); i != e; ++i) {
  2568. if (Instrs[i] != PTM.getSrcRecord())
  2569. PrintError(Instrs[i]->getLoc(), "defined here");
  2570. const CodeGenInstruction &InstInfo = Target.getInstruction(Instrs[i]);
  2571. if (InstInfo.InferredFrom &&
  2572. InstInfo.InferredFrom != InstInfo.TheDef &&
  2573. InstInfo.InferredFrom != PTM.getSrcRecord())
  2574. PrintError(InstInfo.InferredFrom->getLoc(), "inferred from patttern");
  2575. }
  2576. }
  2577. if (Errors)
  2578. PrintFatalError("Errors in DAG patterns");
  2579. }
  2580. /// Given a pattern result with an unresolved type, see if we can find one
  2581. /// instruction with an unresolved result type. Force this result type to an
  2582. /// arbitrary element if it's possible types to converge results.
  2583. static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
  2584. if (N->isLeaf())
  2585. return false;
  2586. // Analyze children.
  2587. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2588. if (ForceArbitraryInstResultType(N->getChild(i), TP))
  2589. return true;
  2590. if (!N->getOperator()->isSubClassOf("Instruction"))
  2591. return false;
  2592. // If this type is already concrete or completely unknown we can't do
  2593. // anything.
  2594. for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
  2595. if (N->getExtType(i).isCompletelyUnknown() || N->getExtType(i).isConcrete())
  2596. continue;
  2597. // Otherwise, force its type to the first possibility (an arbitrary choice).
  2598. if (N->getExtType(i).MergeInTypeInfo(N->getExtType(i).getTypeList()[0], TP))
  2599. return true;
  2600. }
  2601. return false;
  2602. }
  2603. void CodeGenDAGPatterns::ParsePatterns() {
  2604. std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
  2605. for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
  2606. Record *CurPattern = Patterns[i];
  2607. DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
  2608. // If the pattern references the null_frag, there's nothing to do.
  2609. if (hasNullFragReference(Tree))
  2610. continue;
  2611. TreePattern *Pattern = new TreePattern(CurPattern, Tree, true, *this);
  2612. // Inline pattern fragments into it.
  2613. Pattern->InlinePatternFragments();
  2614. ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
  2615. if (LI->getSize() == 0) continue; // no pattern.
  2616. // Parse the instruction.
  2617. TreePattern *Result = new TreePattern(CurPattern, LI, false, *this);
  2618. // Inline pattern fragments into it.
  2619. Result->InlinePatternFragments();
  2620. if (Result->getNumTrees() != 1)
  2621. Result->error("Cannot handle instructions producing instructions "
  2622. "with temporaries yet!");
  2623. bool IterateInference;
  2624. bool InferredAllPatternTypes, InferredAllResultTypes;
  2625. do {
  2626. // Infer as many types as possible. If we cannot infer all of them, we
  2627. // can never do anything with this pattern: report it to the user.
  2628. InferredAllPatternTypes =
  2629. Pattern->InferAllTypes(&Pattern->getNamedNodesMap());
  2630. // Infer as many types as possible. If we cannot infer all of them, we
  2631. // can never do anything with this pattern: report it to the user.
  2632. InferredAllResultTypes =
  2633. Result->InferAllTypes(&Pattern->getNamedNodesMap());
  2634. IterateInference = false;
  2635. // Apply the type of the result to the source pattern. This helps us
  2636. // resolve cases where the input type is known to be a pointer type (which
  2637. // is considered resolved), but the result knows it needs to be 32- or
  2638. // 64-bits. Infer the other way for good measure.
  2639. for (unsigned i = 0, e = std::min(Result->getTree(0)->getNumTypes(),
  2640. Pattern->getTree(0)->getNumTypes());
  2641. i != e; ++i) {
  2642. IterateInference = Pattern->getTree(0)->
  2643. UpdateNodeType(i, Result->getTree(0)->getExtType(i), *Result);
  2644. IterateInference |= Result->getTree(0)->
  2645. UpdateNodeType(i, Pattern->getTree(0)->getExtType(i), *Result);
  2646. }
  2647. // If our iteration has converged and the input pattern's types are fully
  2648. // resolved but the result pattern is not fully resolved, we may have a
  2649. // situation where we have two instructions in the result pattern and
  2650. // the instructions require a common register class, but don't care about
  2651. // what actual MVT is used. This is actually a bug in our modelling:
  2652. // output patterns should have register classes, not MVTs.
  2653. //
  2654. // In any case, to handle this, we just go through and disambiguate some
  2655. // arbitrary types to the result pattern's nodes.
  2656. if (!IterateInference && InferredAllPatternTypes &&
  2657. !InferredAllResultTypes)
  2658. IterateInference = ForceArbitraryInstResultType(Result->getTree(0),
  2659. *Result);
  2660. } while (IterateInference);
  2661. // Verify that we inferred enough types that we can do something with the
  2662. // pattern and result. If these fire the user has to add type casts.
  2663. if (!InferredAllPatternTypes)
  2664. Pattern->error("Could not infer all types in pattern!");
  2665. if (!InferredAllResultTypes) {
  2666. Pattern->dump();
  2667. Result->error("Could not infer all types in pattern result!");
  2668. }
  2669. // Validate that the input pattern is correct.
  2670. std::map<std::string, TreePatternNode*> InstInputs;
  2671. std::map<std::string, TreePatternNode*> InstResults;
  2672. std::vector<Record*> InstImpResults;
  2673. for (unsigned j = 0, ee = Pattern->getNumTrees(); j != ee; ++j)
  2674. FindPatternInputsAndOutputs(Pattern, Pattern->getTree(j),
  2675. InstInputs, InstResults,
  2676. InstImpResults);
  2677. // Promote the xform function to be an explicit node if set.
  2678. TreePatternNode *DstPattern = Result->getOnlyTree();
  2679. std::vector<TreePatternNode*> ResultNodeOperands;
  2680. for (unsigned ii = 0, ee = DstPattern->getNumChildren(); ii != ee; ++ii) {
  2681. TreePatternNode *OpNode = DstPattern->getChild(ii);
  2682. if (Record *Xform = OpNode->getTransformFn()) {
  2683. OpNode->setTransformFn(0);
  2684. std::vector<TreePatternNode*> Children;
  2685. Children.push_back(OpNode);
  2686. OpNode = new TreePatternNode(Xform, Children, OpNode->getNumTypes());
  2687. }
  2688. ResultNodeOperands.push_back(OpNode);
  2689. }
  2690. DstPattern = Result->getOnlyTree();
  2691. if (!DstPattern->isLeaf())
  2692. DstPattern = new TreePatternNode(DstPattern->getOperator(),
  2693. ResultNodeOperands,
  2694. DstPattern->getNumTypes());
  2695. for (unsigned i = 0, e = Result->getOnlyTree()->getNumTypes(); i != e; ++i)
  2696. DstPattern->setType(i, Result->getOnlyTree()->getExtType(i));
  2697. TreePattern Temp(Result->getRecord(), DstPattern, false, *this);
  2698. Temp.InferAllTypes();
  2699. AddPatternToMatch(Pattern,
  2700. PatternToMatch(CurPattern,
  2701. CurPattern->getValueAsListInit("Predicates"),
  2702. Pattern->getTree(0),
  2703. Temp.getOnlyTree(), InstImpResults,
  2704. CurPattern->getValueAsInt("AddedComplexity"),
  2705. CurPattern->getID()));
  2706. }
  2707. }
  2708. /// CombineChildVariants - Given a bunch of permutations of each child of the
  2709. /// 'operator' node, put them together in all possible ways.
  2710. static void CombineChildVariants(TreePatternNode *Orig,
  2711. const std::vector<std::vector<TreePatternNode*> > &ChildVariants,
  2712. std::vector<TreePatternNode*> &OutVariants,
  2713. CodeGenDAGPatterns &CDP,
  2714. const MultipleUseVarSet &DepVars) {
  2715. // Make sure that each operand has at least one variant to choose from.
  2716. for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
  2717. if (ChildVariants[i].empty())
  2718. return;
  2719. // The end result is an all-pairs construction of the resultant pattern.
  2720. std::vector<unsigned> Idxs;
  2721. Idxs.resize(ChildVariants.size());
  2722. bool NotDone;
  2723. do {
  2724. #ifndef NDEBUG
  2725. DEBUG(if (!Idxs.empty()) {
  2726. errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
  2727. for (unsigned i = 0; i < Idxs.size(); ++i) {
  2728. errs() << Idxs[i] << " ";
  2729. }
  2730. errs() << "]\n";
  2731. });
  2732. #endif
  2733. // Create the variant and add it to the output list.
  2734. std::vector<TreePatternNode*> NewChildren;
  2735. for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
  2736. NewChildren.push_back(ChildVariants[i][Idxs[i]]);
  2737. TreePatternNode *R = new TreePatternNode(Orig->getOperator(), NewChildren,
  2738. Orig->getNumTypes());
  2739. // Copy over properties.
  2740. R->setName(Orig->getName());
  2741. R->setPredicateFns(Orig->getPredicateFns());
  2742. R->setTransformFn(Orig->getTransformFn());
  2743. for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
  2744. R->setType(i, Orig->getExtType(i));
  2745. // If this pattern cannot match, do not include it as a variant.
  2746. std::string ErrString;
  2747. if (!R->canPatternMatch(ErrString, CDP)) {
  2748. delete R;
  2749. } else {
  2750. bool AlreadyExists = false;
  2751. // Scan to see if this pattern has already been emitted. We can get
  2752. // duplication due to things like commuting:
  2753. // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
  2754. // which are the same pattern. Ignore the dups.
  2755. for (unsigned i = 0, e = OutVariants.size(); i != e; ++i)
  2756. if (R->isIsomorphicTo(OutVariants[i], DepVars)) {
  2757. AlreadyExists = true;
  2758. break;
  2759. }
  2760. if (AlreadyExists)
  2761. delete R;
  2762. else
  2763. OutVariants.push_back(R);
  2764. }
  2765. // Increment indices to the next permutation by incrementing the
  2766. // indicies from last index backward, e.g., generate the sequence
  2767. // [0, 0], [0, 1], [1, 0], [1, 1].
  2768. int IdxsIdx;
  2769. for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
  2770. if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
  2771. Idxs[IdxsIdx] = 0;
  2772. else
  2773. break;
  2774. }
  2775. NotDone = (IdxsIdx >= 0);
  2776. } while (NotDone);
  2777. }
  2778. /// CombineChildVariants - A helper function for binary operators.
  2779. ///
  2780. static void CombineChildVariants(TreePatternNode *Orig,
  2781. const std::vector<TreePatternNode*> &LHS,
  2782. const std::vector<TreePatternNode*> &RHS,
  2783. std::vector<TreePatternNode*> &OutVariants,
  2784. CodeGenDAGPatterns &CDP,
  2785. const MultipleUseVarSet &DepVars) {
  2786. std::vector<std::vector<TreePatternNode*> > ChildVariants;
  2787. ChildVariants.push_back(LHS);
  2788. ChildVariants.push_back(RHS);
  2789. CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
  2790. }
  2791. static void GatherChildrenOfAssociativeOpcode(TreePatternNode *N,
  2792. std::vector<TreePatternNode *> &Children) {
  2793. assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
  2794. Record *Operator = N->getOperator();
  2795. // Only permit raw nodes.
  2796. if (!N->getName().empty() || !N->getPredicateFns().empty() ||
  2797. N->getTransformFn()) {
  2798. Children.push_back(N);
  2799. return;
  2800. }
  2801. if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
  2802. Children.push_back(N->getChild(0));
  2803. else
  2804. GatherChildrenOfAssociativeOpcode(N->getChild(0), Children);
  2805. if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
  2806. Children.push_back(N->getChild(1));
  2807. else
  2808. GatherChildrenOfAssociativeOpcode(N->getChild(1), Children);
  2809. }
  2810. /// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
  2811. /// the (potentially recursive) pattern by using algebraic laws.
  2812. ///
  2813. static void GenerateVariantsOf(TreePatternNode *N,
  2814. std::vector<TreePatternNode*> &OutVariants,
  2815. CodeGenDAGPatterns &CDP,
  2816. const MultipleUseVarSet &DepVars) {
  2817. // We cannot permute leaves.
  2818. if (N->isLeaf()) {
  2819. OutVariants.push_back(N);
  2820. return;
  2821. }
  2822. // Look up interesting info about the node.
  2823. const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
  2824. // If this node is associative, re-associate.
  2825. if (NodeInfo.hasProperty(SDNPAssociative)) {
  2826. // Re-associate by pulling together all of the linked operators
  2827. std::vector<TreePatternNode*> MaximalChildren;
  2828. GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
  2829. // Only handle child sizes of 3. Otherwise we'll end up trying too many
  2830. // permutations.
  2831. if (MaximalChildren.size() == 3) {
  2832. // Find the variants of all of our maximal children.
  2833. std::vector<TreePatternNode*> AVariants, BVariants, CVariants;
  2834. GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
  2835. GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
  2836. GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
  2837. // There are only two ways we can permute the tree:
  2838. // (A op B) op C and A op (B op C)
  2839. // Within these forms, we can also permute A/B/C.
  2840. // Generate legal pair permutations of A/B/C.
  2841. std::vector<TreePatternNode*> ABVariants;
  2842. std::vector<TreePatternNode*> BAVariants;
  2843. std::vector<TreePatternNode*> ACVariants;
  2844. std::vector<TreePatternNode*> CAVariants;
  2845. std::vector<TreePatternNode*> BCVariants;
  2846. std::vector<TreePatternNode*> CBVariants;
  2847. CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
  2848. CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
  2849. CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
  2850. CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
  2851. CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
  2852. CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
  2853. // Combine those into the result: (x op x) op x
  2854. CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
  2855. CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
  2856. CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
  2857. CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
  2858. CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
  2859. CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
  2860. // Combine those into the result: x op (x op x)
  2861. CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
  2862. CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
  2863. CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
  2864. CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
  2865. CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
  2866. CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
  2867. return;
  2868. }
  2869. }
  2870. // Compute permutations of all children.
  2871. std::vector<std::vector<TreePatternNode*> > ChildVariants;
  2872. ChildVariants.resize(N->getNumChildren());
  2873. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
  2874. GenerateVariantsOf(N->getChild(i), ChildVariants[i], CDP, DepVars);
  2875. // Build all permutations based on how the children were formed.
  2876. CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
  2877. // If this node is commutative, consider the commuted order.
  2878. bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
  2879. if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
  2880. assert((N->getNumChildren()==2 || isCommIntrinsic) &&
  2881. "Commutative but doesn't have 2 children!");
  2882. // Don't count children which are actually register references.
  2883. unsigned NC = 0;
  2884. for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
  2885. TreePatternNode *Child = N->getChild(i);
  2886. if (Child->isLeaf())
  2887. if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
  2888. Record *RR = DI->getDef();
  2889. if (RR->isSubClassOf("Register"))
  2890. continue;
  2891. }
  2892. NC++;
  2893. }
  2894. // Consider the commuted order.
  2895. if (isCommIntrinsic) {
  2896. // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
  2897. // operands are the commutative operands, and there might be more operands
  2898. // after those.
  2899. assert(NC >= 3 &&
  2900. "Commutative intrinsic should have at least 3 childrean!");
  2901. std::vector<std::vector<TreePatternNode*> > Variants;
  2902. Variants.push_back(ChildVariants[0]); // Intrinsic id.
  2903. Variants.push_back(ChildVariants[2]);
  2904. Variants.push_back(ChildVariants[1]);
  2905. for (unsigned i = 3; i != NC; ++i)
  2906. Variants.push_back(ChildVariants[i]);
  2907. CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
  2908. } else if (NC == 2)
  2909. CombineChildVariants(N, ChildVariants[1], ChildVariants[0],
  2910. OutVariants, CDP, DepVars);
  2911. }
  2912. }
  2913. // GenerateVariants - Generate variants. For example, commutative patterns can
  2914. // match multiple ways. Add them to PatternsToMatch as well.
  2915. void CodeGenDAGPatterns::GenerateVariants() {
  2916. DEBUG(errs() << "Generating instruction variants.\n");
  2917. // Loop over all of the patterns we've collected, checking to see if we can
  2918. // generate variants of the instruction, through the exploitation of
  2919. // identities. This permits the target to provide aggressive matching without
  2920. // the .td file having to contain tons of variants of instructions.
  2921. //
  2922. // Note that this loop adds new patterns to the PatternsToMatch list, but we
  2923. // intentionally do not reconsider these. Any variants of added patterns have
  2924. // already been added.
  2925. //
  2926. for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
  2927. MultipleUseVarSet DepVars;
  2928. std::vector<TreePatternNode*> Variants;
  2929. FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
  2930. DEBUG(errs() << "Dependent/multiply used variables: ");
  2931. DEBUG(DumpDepVars(DepVars));
  2932. DEBUG(errs() << "\n");
  2933. GenerateVariantsOf(PatternsToMatch[i].getSrcPattern(), Variants, *this,
  2934. DepVars);
  2935. assert(!Variants.empty() && "Must create at least original variant!");
  2936. Variants.erase(Variants.begin()); // Remove the original pattern.
  2937. if (Variants.empty()) // No variants for this pattern.
  2938. continue;
  2939. DEBUG(errs() << "FOUND VARIANTS OF: ";
  2940. PatternsToMatch[i].getSrcPattern()->dump();
  2941. errs() << "\n");
  2942. for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
  2943. TreePatternNode *Variant = Variants[v];
  2944. DEBUG(errs() << " VAR#" << v << ": ";
  2945. Variant->dump();
  2946. errs() << "\n");
  2947. // Scan to see if an instruction or explicit pattern already matches this.
  2948. bool AlreadyExists = false;
  2949. for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
  2950. // Skip if the top level predicates do not match.
  2951. if (PatternsToMatch[i].getPredicates() !=
  2952. PatternsToMatch[p].getPredicates())
  2953. continue;
  2954. // Check to see if this variant already exists.
  2955. if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
  2956. DepVars)) {
  2957. DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
  2958. AlreadyExists = true;
  2959. break;
  2960. }
  2961. }
  2962. // If we already have it, ignore the variant.
  2963. if (AlreadyExists) continue;
  2964. // Otherwise, add it to the list of patterns we have.
  2965. PatternsToMatch.
  2966. push_back(PatternToMatch(PatternsToMatch[i].getSrcRecord(),
  2967. PatternsToMatch[i].getPredicates(),
  2968. Variant, PatternsToMatch[i].getDstPattern(),
  2969. PatternsToMatch[i].getDstRegs(),
  2970. PatternsToMatch[i].getAddedComplexity(),
  2971. Record::getNewUID()));
  2972. }
  2973. DEBUG(errs() << "\n");
  2974. }
  2975. }