TGParser.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677
  1. //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
  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. // Implement the Parser for TableGen.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "TGParser.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/Support/CommandLine.h"
  18. #include "llvm/TableGen/Record.h"
  19. #include <algorithm>
  20. #include <sstream>
  21. using namespace llvm;
  22. //===----------------------------------------------------------------------===//
  23. // Support Code for the Semantic Actions.
  24. //===----------------------------------------------------------------------===//
  25. namespace llvm {
  26. struct SubClassReference {
  27. SMRange RefRange;
  28. Record *Rec;
  29. std::vector<Init*> TemplateArgs;
  30. SubClassReference() : Rec(nullptr) {}
  31. bool isInvalid() const { return Rec == nullptr; }
  32. };
  33. struct SubMultiClassReference {
  34. SMRange RefRange;
  35. MultiClass *MC;
  36. std::vector<Init*> TemplateArgs;
  37. SubMultiClassReference() : MC(nullptr) {}
  38. bool isInvalid() const { return MC == nullptr; }
  39. void dump() const;
  40. };
  41. void SubMultiClassReference::dump() const {
  42. errs() << "Multiclass:\n";
  43. MC->dump();
  44. errs() << "Template args:\n";
  45. for (Init *TA : TemplateArgs)
  46. TA->dump();
  47. }
  48. } // end namespace llvm
  49. bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
  50. if (!CurRec)
  51. CurRec = &CurMultiClass->Rec;
  52. if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
  53. // The value already exists in the class, treat this as a set.
  54. if (ERV->setValue(RV.getValue()))
  55. return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
  56. RV.getType()->getAsString() + "' is incompatible with " +
  57. "previous definition of type '" +
  58. ERV->getType()->getAsString() + "'");
  59. } else {
  60. CurRec->addValue(RV);
  61. }
  62. return false;
  63. }
  64. /// SetValue -
  65. /// Return true on error, false on success.
  66. bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
  67. const std::vector<unsigned> &BitList, Init *V) {
  68. if (!V) return false;
  69. if (!CurRec) CurRec = &CurMultiClass->Rec;
  70. RecordVal *RV = CurRec->getValue(ValName);
  71. if (!RV)
  72. return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
  73. "' unknown!");
  74. // Do not allow assignments like 'X = X'. This will just cause infinite loops
  75. // in the resolution machinery.
  76. if (BitList.empty())
  77. if (VarInit *VI = dyn_cast<VarInit>(V))
  78. if (VI->getNameInit() == ValName)
  79. return false;
  80. // If we are assigning to a subset of the bits in the value... then we must be
  81. // assigning to a field of BitsRecTy, which must have a BitsInit
  82. // initializer.
  83. //
  84. if (!BitList.empty()) {
  85. BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
  86. if (!CurVal)
  87. return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
  88. "' is not a bits type");
  89. // Convert the incoming value to a bits type of the appropriate size...
  90. Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
  91. if (!BI)
  92. return Error(Loc, "Initializer is not compatible with bit range");
  93. // We should have a BitsInit type now.
  94. BitsInit *BInit = cast<BitsInit>(BI);
  95. SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
  96. // Loop over bits, assigning values as appropriate.
  97. for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
  98. unsigned Bit = BitList[i];
  99. if (NewBits[Bit])
  100. return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
  101. ValName->getAsUnquotedString() + "' more than once");
  102. NewBits[Bit] = BInit->getBit(i);
  103. }
  104. for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
  105. if (!NewBits[i])
  106. NewBits[i] = CurVal->getBit(i);
  107. V = BitsInit::get(NewBits);
  108. }
  109. if (RV->setValue(V)) {
  110. std::string InitType = "";
  111. if (BitsInit *BI = dyn_cast<BitsInit>(V))
  112. InitType = (Twine("' of type bit initializer with length ") +
  113. Twine(BI->getNumBits())).str();
  114. return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
  115. "' of type '" + RV->getType()->getAsString() +
  116. "' is incompatible with initializer '" + V->getAsString() +
  117. InitType + "'");
  118. }
  119. return false;
  120. }
  121. /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
  122. /// args as SubClass's template arguments.
  123. bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
  124. Record *SC = SubClass.Rec;
  125. // Add all of the values in the subclass into the current class.
  126. for (const RecordVal &Val : SC->getValues())
  127. if (AddValue(CurRec, SubClass.RefRange.Start, Val))
  128. return true;
  129. const std::vector<Init *> &TArgs = SC->getTemplateArgs();
  130. // Ensure that an appropriate number of template arguments are specified.
  131. if (TArgs.size() < SubClass.TemplateArgs.size())
  132. return Error(SubClass.RefRange.Start,
  133. "More template args specified than expected");
  134. // Loop over all of the template arguments, setting them to the specified
  135. // value or leaving them as the default if necessary.
  136. for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
  137. if (i < SubClass.TemplateArgs.size()) {
  138. // If a value is specified for this template arg, set it now.
  139. if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
  140. std::vector<unsigned>(), SubClass.TemplateArgs[i]))
  141. return true;
  142. // Resolve it next.
  143. CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
  144. // Now remove it.
  145. CurRec->removeValue(TArgs[i]);
  146. } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
  147. return Error(SubClass.RefRange.Start,
  148. "Value not specified for template argument #" +
  149. Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
  150. ") of subclass '" + SC->getNameInitAsString() + "'!");
  151. }
  152. }
  153. // Since everything went well, we can now set the "superclass" list for the
  154. // current record.
  155. ArrayRef<Record *> SCs = SC->getSuperClasses();
  156. ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
  157. for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
  158. if (CurRec->isSubClassOf(SCs[i]))
  159. return Error(SubClass.RefRange.Start,
  160. "Already subclass of '" + SCs[i]->getName() + "'!\n");
  161. CurRec->addSuperClass(SCs[i], SCRanges[i]);
  162. }
  163. if (CurRec->isSubClassOf(SC))
  164. return Error(SubClass.RefRange.Start,
  165. "Already subclass of '" + SC->getName() + "'!\n");
  166. CurRec->addSuperClass(SC, SubClass.RefRange);
  167. return false;
  168. }
  169. /// AddSubMultiClass - Add SubMultiClass as a subclass to
  170. /// CurMC, resolving its template args as SubMultiClass's
  171. /// template arguments.
  172. bool TGParser::AddSubMultiClass(MultiClass *CurMC,
  173. SubMultiClassReference &SubMultiClass) {
  174. MultiClass *SMC = SubMultiClass.MC;
  175. Record *CurRec = &CurMC->Rec;
  176. // Add all of the values in the subclass into the current class.
  177. for (const auto &SMCVal : SMC->Rec.getValues())
  178. if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
  179. return true;
  180. unsigned newDefStart = CurMC->DefPrototypes.size();
  181. // Add all of the defs in the subclass into the current multiclass.
  182. for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
  183. // Clone the def and add it to the current multiclass
  184. auto NewDef = make_unique<Record>(*R);
  185. // Add all of the values in the superclass into the current def.
  186. for (const auto &MCVal : CurRec->getValues())
  187. if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
  188. return true;
  189. CurMC->DefPrototypes.push_back(std::move(NewDef));
  190. }
  191. const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
  192. // Ensure that an appropriate number of template arguments are
  193. // specified.
  194. if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
  195. return Error(SubMultiClass.RefRange.Start,
  196. "More template args specified than expected");
  197. // Loop over all of the template arguments, setting them to the specified
  198. // value or leaving them as the default if necessary.
  199. for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
  200. if (i < SubMultiClass.TemplateArgs.size()) {
  201. // If a value is specified for this template arg, set it in the
  202. // superclass now.
  203. if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
  204. std::vector<unsigned>(),
  205. SubMultiClass.TemplateArgs[i]))
  206. return true;
  207. // Resolve it next.
  208. CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
  209. // Now remove it.
  210. CurRec->removeValue(SMCTArgs[i]);
  211. // If a value is specified for this template arg, set it in the
  212. // new defs now.
  213. for (const auto &Def :
  214. makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
  215. if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
  216. std::vector<unsigned>(),
  217. SubMultiClass.TemplateArgs[i]))
  218. return true;
  219. // Resolve it next.
  220. Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
  221. // Now remove it
  222. Def->removeValue(SMCTArgs[i]);
  223. }
  224. } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
  225. return Error(SubMultiClass.RefRange.Start,
  226. "Value not specified for template argument #" +
  227. Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
  228. ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
  229. }
  230. }
  231. return false;
  232. }
  233. /// ProcessForeachDefs - Given a record, apply all of the variable
  234. /// values in all surrounding foreach loops, creating new records for
  235. /// each combination of values.
  236. bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
  237. if (Loops.empty())
  238. return false;
  239. // We want to instantiate a new copy of CurRec for each combination
  240. // of nested loop iterator values. We don't want top instantiate
  241. // any copies until we have values for each loop iterator.
  242. IterSet IterVals;
  243. return ProcessForeachDefs(CurRec, Loc, IterVals);
  244. }
  245. /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
  246. /// apply each of the variable values in this loop and then process
  247. /// subloops.
  248. bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
  249. // Recursively build a tuple of iterator values.
  250. if (IterVals.size() != Loops.size()) {
  251. assert(IterVals.size() < Loops.size());
  252. ForeachLoop &CurLoop = Loops[IterVals.size()];
  253. ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
  254. if (!List) {
  255. Error(Loc, "Loop list is not a list");
  256. return true;
  257. }
  258. // Process each value.
  259. for (unsigned i = 0; i < List->size(); ++i) {
  260. Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
  261. IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
  262. if (ProcessForeachDefs(CurRec, Loc, IterVals))
  263. return true;
  264. IterVals.pop_back();
  265. }
  266. return false;
  267. }
  268. // This is the bottom of the recursion. We have all of the iterator values
  269. // for this point in the iteration space. Instantiate a new record to
  270. // reflect this combination of values.
  271. auto IterRec = make_unique<Record>(*CurRec);
  272. // Set the iterator values now.
  273. for (IterRecord &IR : IterVals) {
  274. VarInit *IterVar = IR.IterVar;
  275. TypedInit *IVal = dyn_cast<TypedInit>(IR.IterValue);
  276. if (!IVal)
  277. return Error(Loc, "foreach iterator value is untyped");
  278. IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
  279. if (SetValue(IterRec.get(), Loc, IterVar->getName(),
  280. std::vector<unsigned>(), IVal))
  281. return Error(Loc, "when instantiating this def");
  282. // Resolve it next.
  283. IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
  284. // Remove it.
  285. IterRec->removeValue(IterVar->getName());
  286. }
  287. if (Records.getDef(IterRec->getNameInitAsString())) {
  288. // If this record is anonymous, it's no problem, just generate a new name
  289. if (!IterRec->isAnonymous())
  290. return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
  291. IterRec->setName(GetNewAnonymousName());
  292. }
  293. Record *IterRecSave = IterRec.get(); // Keep a copy before release.
  294. Records.addDef(std::move(IterRec));
  295. IterRecSave->resolveReferences();
  296. return false;
  297. }
  298. //===----------------------------------------------------------------------===//
  299. // Parser Code
  300. //===----------------------------------------------------------------------===//
  301. /// isObjectStart - Return true if this is a valid first token for an Object.
  302. static bool isObjectStart(tgtok::TokKind K) {
  303. return K == tgtok::Class || K == tgtok::Def ||
  304. K == tgtok::Defm || K == tgtok::Let ||
  305. K == tgtok::MultiClass || K == tgtok::Foreach;
  306. }
  307. /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
  308. /// an identifier.
  309. std::string TGParser::GetNewAnonymousName() {
  310. return "anonymous_" + utostr(AnonCounter++);
  311. }
  312. /// ParseObjectName - If an object name is specified, return it. Otherwise,
  313. /// return 0.
  314. /// ObjectName ::= Value [ '#' Value ]*
  315. /// ObjectName ::= /*empty*/
  316. ///
  317. Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
  318. switch (Lex.getCode()) {
  319. case tgtok::colon:
  320. case tgtok::semi:
  321. case tgtok::l_brace:
  322. // These are all of the tokens that can begin an object body.
  323. // Some of these can also begin values but we disallow those cases
  324. // because they are unlikely to be useful.
  325. return nullptr;
  326. default:
  327. break;
  328. }
  329. Record *CurRec = nullptr;
  330. if (CurMultiClass)
  331. CurRec = &CurMultiClass->Rec;
  332. RecTy *Type = nullptr;
  333. if (CurRec) {
  334. const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
  335. if (!CurRecName) {
  336. TokError("Record name is not typed!");
  337. return nullptr;
  338. }
  339. Type = CurRecName->getType();
  340. }
  341. return ParseValue(CurRec, Type, ParseNameMode);
  342. }
  343. /// ParseClassID - Parse and resolve a reference to a class name. This returns
  344. /// null on error.
  345. ///
  346. /// ClassID ::= ID
  347. ///
  348. Record *TGParser::ParseClassID() {
  349. if (Lex.getCode() != tgtok::Id) {
  350. TokError("expected name for ClassID");
  351. return nullptr;
  352. }
  353. Record *Result = Records.getClass(Lex.getCurStrVal());
  354. if (!Result)
  355. TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
  356. Lex.Lex();
  357. return Result;
  358. }
  359. /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
  360. /// This returns null on error.
  361. ///
  362. /// MultiClassID ::= ID
  363. ///
  364. MultiClass *TGParser::ParseMultiClassID() {
  365. if (Lex.getCode() != tgtok::Id) {
  366. TokError("expected name for MultiClassID");
  367. return nullptr;
  368. }
  369. MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
  370. if (!Result)
  371. TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
  372. Lex.Lex();
  373. return Result;
  374. }
  375. /// ParseSubClassReference - Parse a reference to a subclass or to a templated
  376. /// subclass. This returns a SubClassRefTy with a null Record* on error.
  377. ///
  378. /// SubClassRef ::= ClassID
  379. /// SubClassRef ::= ClassID '<' ValueList '>'
  380. ///
  381. SubClassReference TGParser::
  382. ParseSubClassReference(Record *CurRec, bool isDefm) {
  383. SubClassReference Result;
  384. Result.RefRange.Start = Lex.getLoc();
  385. if (isDefm) {
  386. if (MultiClass *MC = ParseMultiClassID())
  387. Result.Rec = &MC->Rec;
  388. } else {
  389. Result.Rec = ParseClassID();
  390. }
  391. if (!Result.Rec) return Result;
  392. // If there is no template arg list, we're done.
  393. if (Lex.getCode() != tgtok::less) {
  394. Result.RefRange.End = Lex.getLoc();
  395. return Result;
  396. }
  397. Lex.Lex(); // Eat the '<'
  398. if (Lex.getCode() == tgtok::greater) {
  399. TokError("subclass reference requires a non-empty list of template values");
  400. Result.Rec = nullptr;
  401. return Result;
  402. }
  403. Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
  404. if (Result.TemplateArgs.empty()) {
  405. Result.Rec = nullptr; // Error parsing value list.
  406. return Result;
  407. }
  408. if (Lex.getCode() != tgtok::greater) {
  409. TokError("expected '>' in template value list");
  410. Result.Rec = nullptr;
  411. return Result;
  412. }
  413. Lex.Lex();
  414. Result.RefRange.End = Lex.getLoc();
  415. return Result;
  416. }
  417. /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
  418. /// templated submulticlass. This returns a SubMultiClassRefTy with a null
  419. /// Record* on error.
  420. ///
  421. /// SubMultiClassRef ::= MultiClassID
  422. /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
  423. ///
  424. SubMultiClassReference TGParser::
  425. ParseSubMultiClassReference(MultiClass *CurMC) {
  426. SubMultiClassReference Result;
  427. Result.RefRange.Start = Lex.getLoc();
  428. Result.MC = ParseMultiClassID();
  429. if (!Result.MC) return Result;
  430. // If there is no template arg list, we're done.
  431. if (Lex.getCode() != tgtok::less) {
  432. Result.RefRange.End = Lex.getLoc();
  433. return Result;
  434. }
  435. Lex.Lex(); // Eat the '<'
  436. if (Lex.getCode() == tgtok::greater) {
  437. TokError("subclass reference requires a non-empty list of template values");
  438. Result.MC = nullptr;
  439. return Result;
  440. }
  441. Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
  442. if (Result.TemplateArgs.empty()) {
  443. Result.MC = nullptr; // Error parsing value list.
  444. return Result;
  445. }
  446. if (Lex.getCode() != tgtok::greater) {
  447. TokError("expected '>' in template value list");
  448. Result.MC = nullptr;
  449. return Result;
  450. }
  451. Lex.Lex();
  452. Result.RefRange.End = Lex.getLoc();
  453. return Result;
  454. }
  455. /// ParseRangePiece - Parse a bit/value range.
  456. /// RangePiece ::= INTVAL
  457. /// RangePiece ::= INTVAL '-' INTVAL
  458. /// RangePiece ::= INTVAL INTVAL
  459. bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
  460. if (Lex.getCode() != tgtok::IntVal) {
  461. TokError("expected integer or bitrange");
  462. return true;
  463. }
  464. int64_t Start = Lex.getCurIntVal();
  465. int64_t End;
  466. if (Start < 0)
  467. return TokError("invalid range, cannot be negative");
  468. switch (Lex.Lex()) { // eat first character.
  469. default:
  470. Ranges.push_back(Start);
  471. return false;
  472. case tgtok::minus:
  473. if (Lex.Lex() != tgtok::IntVal) {
  474. TokError("expected integer value as end of range");
  475. return true;
  476. }
  477. End = Lex.getCurIntVal();
  478. break;
  479. case tgtok::IntVal:
  480. End = -Lex.getCurIntVal();
  481. break;
  482. }
  483. if (End < 0)
  484. return TokError("invalid range, cannot be negative");
  485. Lex.Lex();
  486. // Add to the range.
  487. if (Start < End)
  488. for (; Start <= End; ++Start)
  489. Ranges.push_back(Start);
  490. else
  491. for (; Start >= End; --Start)
  492. Ranges.push_back(Start);
  493. return false;
  494. }
  495. /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
  496. ///
  497. /// RangeList ::= RangePiece (',' RangePiece)*
  498. ///
  499. std::vector<unsigned> TGParser::ParseRangeList() {
  500. std::vector<unsigned> Result;
  501. // Parse the first piece.
  502. if (ParseRangePiece(Result))
  503. return std::vector<unsigned>();
  504. while (Lex.getCode() == tgtok::comma) {
  505. Lex.Lex(); // Eat the comma.
  506. // Parse the next range piece.
  507. if (ParseRangePiece(Result))
  508. return std::vector<unsigned>();
  509. }
  510. return Result;
  511. }
  512. /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
  513. /// OptionalRangeList ::= '<' RangeList '>'
  514. /// OptionalRangeList ::= /*empty*/
  515. bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
  516. if (Lex.getCode() != tgtok::less)
  517. return false;
  518. SMLoc StartLoc = Lex.getLoc();
  519. Lex.Lex(); // eat the '<'
  520. // Parse the range list.
  521. Ranges = ParseRangeList();
  522. if (Ranges.empty()) return true;
  523. if (Lex.getCode() != tgtok::greater) {
  524. TokError("expected '>' at end of range list");
  525. return Error(StartLoc, "to match this '<'");
  526. }
  527. Lex.Lex(); // eat the '>'.
  528. return false;
  529. }
  530. /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
  531. /// OptionalBitList ::= '{' RangeList '}'
  532. /// OptionalBitList ::= /*empty*/
  533. bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
  534. if (Lex.getCode() != tgtok::l_brace)
  535. return false;
  536. SMLoc StartLoc = Lex.getLoc();
  537. Lex.Lex(); // eat the '{'
  538. // Parse the range list.
  539. Ranges = ParseRangeList();
  540. if (Ranges.empty()) return true;
  541. if (Lex.getCode() != tgtok::r_brace) {
  542. TokError("expected '}' at end of bit list");
  543. return Error(StartLoc, "to match this '{'");
  544. }
  545. Lex.Lex(); // eat the '}'.
  546. return false;
  547. }
  548. /// ParseType - Parse and return a tblgen type. This returns null on error.
  549. ///
  550. /// Type ::= STRING // string type
  551. /// Type ::= CODE // code type
  552. /// Type ::= BIT // bit type
  553. /// Type ::= BITS '<' INTVAL '>' // bits<x> type
  554. /// Type ::= INT // int type
  555. /// Type ::= LIST '<' Type '>' // list<x> type
  556. /// Type ::= DAG // dag type
  557. /// Type ::= ClassID // Record Type
  558. ///
  559. RecTy *TGParser::ParseType() {
  560. switch (Lex.getCode()) {
  561. default: TokError("Unknown token when expecting a type"); return nullptr;
  562. case tgtok::String: Lex.Lex(); return StringRecTy::get();
  563. case tgtok::Code: Lex.Lex(); return StringRecTy::get();
  564. case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
  565. case tgtok::Int: Lex.Lex(); return IntRecTy::get();
  566. case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
  567. case tgtok::Id:
  568. if (Record *R = ParseClassID()) return RecordRecTy::get(R);
  569. return nullptr;
  570. case tgtok::Bits: {
  571. if (Lex.Lex() != tgtok::less) { // Eat 'bits'
  572. TokError("expected '<' after bits type");
  573. return nullptr;
  574. }
  575. if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
  576. TokError("expected integer in bits<n> type");
  577. return nullptr;
  578. }
  579. uint64_t Val = Lex.getCurIntVal();
  580. if (Lex.Lex() != tgtok::greater) { // Eat count.
  581. TokError("expected '>' at end of bits<n> type");
  582. return nullptr;
  583. }
  584. Lex.Lex(); // Eat '>'
  585. return BitsRecTy::get(Val);
  586. }
  587. case tgtok::List: {
  588. if (Lex.Lex() != tgtok::less) { // Eat 'bits'
  589. TokError("expected '<' after list type");
  590. return nullptr;
  591. }
  592. Lex.Lex(); // Eat '<'
  593. RecTy *SubType = ParseType();
  594. if (!SubType) return nullptr;
  595. if (Lex.getCode() != tgtok::greater) {
  596. TokError("expected '>' at end of list<ty> type");
  597. return nullptr;
  598. }
  599. Lex.Lex(); // Eat '>'
  600. return ListRecTy::get(SubType);
  601. }
  602. }
  603. }
  604. /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
  605. /// has already been read.
  606. Init *TGParser::ParseIDValue(Record *CurRec,
  607. const std::string &Name, SMLoc NameLoc,
  608. IDParseMode Mode) {
  609. if (CurRec) {
  610. if (const RecordVal *RV = CurRec->getValue(Name))
  611. return VarInit::get(Name, RV->getType());
  612. Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
  613. if (CurMultiClass)
  614. TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
  615. "::");
  616. if (CurRec->isTemplateArg(TemplateArgName)) {
  617. const RecordVal *RV = CurRec->getValue(TemplateArgName);
  618. assert(RV && "Template arg doesn't exist??");
  619. return VarInit::get(TemplateArgName, RV->getType());
  620. }
  621. }
  622. if (CurMultiClass) {
  623. Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
  624. "::");
  625. if (CurMultiClass->Rec.isTemplateArg(MCName)) {
  626. const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
  627. assert(RV && "Template arg doesn't exist??");
  628. return VarInit::get(MCName, RV->getType());
  629. }
  630. }
  631. // If this is in a foreach loop, make sure it's not a loop iterator
  632. for (const auto &L : Loops) {
  633. VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
  634. if (IterVar && IterVar->getName() == Name)
  635. return IterVar;
  636. }
  637. if (Mode == ParseNameMode)
  638. return StringInit::get(Name);
  639. if (Record *D = Records.getDef(Name))
  640. return DefInit::get(D);
  641. if (Mode == ParseValueMode) {
  642. Error(NameLoc, "Variable not defined: '" + Name + "'");
  643. return nullptr;
  644. }
  645. return StringInit::get(Name);
  646. }
  647. /// ParseOperation - Parse an operator. This returns null on error.
  648. ///
  649. /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
  650. ///
  651. Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
  652. switch (Lex.getCode()) {
  653. default:
  654. TokError("unknown operation");
  655. return nullptr;
  656. case tgtok::XHead:
  657. case tgtok::XTail:
  658. case tgtok::XEmpty:
  659. case tgtok::XCast: { // Value ::= !unop '(' Value ')'
  660. UnOpInit::UnaryOp Code;
  661. RecTy *Type = nullptr;
  662. switch (Lex.getCode()) {
  663. default: llvm_unreachable("Unhandled code!");
  664. case tgtok::XCast:
  665. Lex.Lex(); // eat the operation
  666. Code = UnOpInit::CAST;
  667. Type = ParseOperatorType();
  668. if (!Type) {
  669. TokError("did not get type for unary operator");
  670. return nullptr;
  671. }
  672. break;
  673. case tgtok::XHead:
  674. Lex.Lex(); // eat the operation
  675. Code = UnOpInit::HEAD;
  676. break;
  677. case tgtok::XTail:
  678. Lex.Lex(); // eat the operation
  679. Code = UnOpInit::TAIL;
  680. break;
  681. case tgtok::XEmpty:
  682. Lex.Lex(); // eat the operation
  683. Code = UnOpInit::EMPTY;
  684. Type = IntRecTy::get();
  685. break;
  686. }
  687. if (Lex.getCode() != tgtok::l_paren) {
  688. TokError("expected '(' after unary operator");
  689. return nullptr;
  690. }
  691. Lex.Lex(); // eat the '('
  692. Init *LHS = ParseValue(CurRec);
  693. if (!LHS) return nullptr;
  694. if (Code == UnOpInit::HEAD ||
  695. Code == UnOpInit::TAIL ||
  696. Code == UnOpInit::EMPTY) {
  697. ListInit *LHSl = dyn_cast<ListInit>(LHS);
  698. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  699. TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
  700. if (!LHSl && !LHSs && !LHSt) {
  701. TokError("expected list or string type argument in unary operator");
  702. return nullptr;
  703. }
  704. if (LHSt) {
  705. ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
  706. StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
  707. if (!LType && !SType) {
  708. TokError("expected list or string type argument in unary operator");
  709. return nullptr;
  710. }
  711. }
  712. if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
  713. if (!LHSl && !LHSt) {
  714. TokError("expected list type argument in unary operator");
  715. return nullptr;
  716. }
  717. if (LHSl && LHSl->empty()) {
  718. TokError("empty list argument in unary operator");
  719. return nullptr;
  720. }
  721. if (LHSl) {
  722. Init *Item = LHSl->getElement(0);
  723. TypedInit *Itemt = dyn_cast<TypedInit>(Item);
  724. if (!Itemt) {
  725. TokError("untyped list element in unary operator");
  726. return nullptr;
  727. }
  728. Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
  729. : ListRecTy::get(Itemt->getType());
  730. } else {
  731. assert(LHSt && "expected list type argument in unary operator");
  732. ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
  733. if (!LType) {
  734. TokError("expected list type argument in unary operator");
  735. return nullptr;
  736. }
  737. Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
  738. }
  739. }
  740. }
  741. if (Lex.getCode() != tgtok::r_paren) {
  742. TokError("expected ')' in unary operator");
  743. return nullptr;
  744. }
  745. Lex.Lex(); // eat the ')'
  746. return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
  747. }
  748. case tgtok::XConcat:
  749. case tgtok::XADD:
  750. case tgtok::XAND:
  751. case tgtok::XSRA:
  752. case tgtok::XSRL:
  753. case tgtok::XSHL:
  754. case tgtok::XEq:
  755. case tgtok::XListConcat:
  756. case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
  757. tgtok::TokKind OpTok = Lex.getCode();
  758. SMLoc OpLoc = Lex.getLoc();
  759. Lex.Lex(); // eat the operation
  760. BinOpInit::BinaryOp Code;
  761. RecTy *Type = nullptr;
  762. switch (OpTok) {
  763. default: llvm_unreachable("Unhandled code!");
  764. case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
  765. case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
  766. case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
  767. case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
  768. case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
  769. case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
  770. case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
  771. case tgtok::XListConcat:
  772. Code = BinOpInit::LISTCONCAT;
  773. // We don't know the list type until we parse the first argument
  774. break;
  775. case tgtok::XStrConcat:
  776. Code = BinOpInit::STRCONCAT;
  777. Type = StringRecTy::get();
  778. break;
  779. }
  780. if (Lex.getCode() != tgtok::l_paren) {
  781. TokError("expected '(' after binary operator");
  782. return nullptr;
  783. }
  784. Lex.Lex(); // eat the '('
  785. SmallVector<Init*, 2> InitList;
  786. InitList.push_back(ParseValue(CurRec));
  787. if (!InitList.back()) return nullptr;
  788. while (Lex.getCode() == tgtok::comma) {
  789. Lex.Lex(); // eat the ','
  790. InitList.push_back(ParseValue(CurRec));
  791. if (!InitList.back()) return nullptr;
  792. }
  793. if (Lex.getCode() != tgtok::r_paren) {
  794. TokError("expected ')' in operator");
  795. return nullptr;
  796. }
  797. Lex.Lex(); // eat the ')'
  798. // If we are doing !listconcat, we should know the type by now
  799. if (OpTok == tgtok::XListConcat) {
  800. if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
  801. Type = Arg0->getType();
  802. else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
  803. Type = Arg0->getType();
  804. else {
  805. InitList[0]->dump();
  806. Error(OpLoc, "expected a list");
  807. return nullptr;
  808. }
  809. }
  810. // We allow multiple operands to associative operators like !strconcat as
  811. // shorthand for nesting them.
  812. if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
  813. while (InitList.size() > 2) {
  814. Init *RHS = InitList.pop_back_val();
  815. RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
  816. ->Fold(CurRec, CurMultiClass);
  817. InitList.back() = RHS;
  818. }
  819. }
  820. if (InitList.size() == 2)
  821. return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
  822. ->Fold(CurRec, CurMultiClass);
  823. Error(OpLoc, "expected two operands to operator");
  824. return nullptr;
  825. }
  826. case tgtok::XIf:
  827. case tgtok::XForEach:
  828. case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
  829. TernOpInit::TernaryOp Code;
  830. RecTy *Type = nullptr;
  831. tgtok::TokKind LexCode = Lex.getCode();
  832. Lex.Lex(); // eat the operation
  833. switch (LexCode) {
  834. default: llvm_unreachable("Unhandled code!");
  835. case tgtok::XIf:
  836. Code = TernOpInit::IF;
  837. break;
  838. case tgtok::XForEach:
  839. Code = TernOpInit::FOREACH;
  840. break;
  841. case tgtok::XSubst:
  842. Code = TernOpInit::SUBST;
  843. break;
  844. }
  845. if (Lex.getCode() != tgtok::l_paren) {
  846. TokError("expected '(' after ternary operator");
  847. return nullptr;
  848. }
  849. Lex.Lex(); // eat the '('
  850. Init *LHS = ParseValue(CurRec);
  851. if (!LHS) return nullptr;
  852. if (Lex.getCode() != tgtok::comma) {
  853. TokError("expected ',' in ternary operator");
  854. return nullptr;
  855. }
  856. Lex.Lex(); // eat the ','
  857. Init *MHS = ParseValue(CurRec, ItemType);
  858. if (!MHS)
  859. return nullptr;
  860. if (Lex.getCode() != tgtok::comma) {
  861. TokError("expected ',' in ternary operator");
  862. return nullptr;
  863. }
  864. Lex.Lex(); // eat the ','
  865. Init *RHS = ParseValue(CurRec, ItemType);
  866. if (!RHS)
  867. return nullptr;
  868. if (Lex.getCode() != tgtok::r_paren) {
  869. TokError("expected ')' in binary operator");
  870. return nullptr;
  871. }
  872. Lex.Lex(); // eat the ')'
  873. switch (LexCode) {
  874. default: llvm_unreachable("Unhandled code!");
  875. case tgtok::XIf: {
  876. RecTy *MHSTy = nullptr;
  877. RecTy *RHSTy = nullptr;
  878. if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
  879. MHSTy = MHSt->getType();
  880. if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
  881. MHSTy = BitsRecTy::get(MHSbits->getNumBits());
  882. if (isa<BitInit>(MHS))
  883. MHSTy = BitRecTy::get();
  884. if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
  885. RHSTy = RHSt->getType();
  886. if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
  887. RHSTy = BitsRecTy::get(RHSbits->getNumBits());
  888. if (isa<BitInit>(RHS))
  889. RHSTy = BitRecTy::get();
  890. // For UnsetInit, it's typed from the other hand.
  891. if (isa<UnsetInit>(MHS))
  892. MHSTy = RHSTy;
  893. if (isa<UnsetInit>(RHS))
  894. RHSTy = MHSTy;
  895. if (!MHSTy || !RHSTy) {
  896. TokError("could not get type for !if");
  897. return nullptr;
  898. }
  899. if (MHSTy->typeIsConvertibleTo(RHSTy)) {
  900. Type = RHSTy;
  901. } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
  902. Type = MHSTy;
  903. } else {
  904. TokError("inconsistent types for !if");
  905. return nullptr;
  906. }
  907. break;
  908. }
  909. case tgtok::XForEach: {
  910. TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
  911. if (!MHSt) {
  912. TokError("could not get type for !foreach");
  913. return nullptr;
  914. }
  915. Type = MHSt->getType();
  916. break;
  917. }
  918. case tgtok::XSubst: {
  919. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  920. if (!RHSt) {
  921. TokError("could not get type for !subst");
  922. return nullptr;
  923. }
  924. Type = RHSt->getType();
  925. break;
  926. }
  927. }
  928. return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
  929. CurMultiClass);
  930. }
  931. }
  932. }
  933. /// ParseOperatorType - Parse a type for an operator. This returns
  934. /// null on error.
  935. ///
  936. /// OperatorType ::= '<' Type '>'
  937. ///
  938. RecTy *TGParser::ParseOperatorType() {
  939. RecTy *Type = nullptr;
  940. if (Lex.getCode() != tgtok::less) {
  941. TokError("expected type name for operator");
  942. return nullptr;
  943. }
  944. Lex.Lex(); // eat the <
  945. Type = ParseType();
  946. if (!Type) {
  947. TokError("expected type name for operator");
  948. return nullptr;
  949. }
  950. if (Lex.getCode() != tgtok::greater) {
  951. TokError("expected type name for operator");
  952. return nullptr;
  953. }
  954. Lex.Lex(); // eat the >
  955. return Type;
  956. }
  957. /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
  958. ///
  959. /// SimpleValue ::= IDValue
  960. /// SimpleValue ::= INTVAL
  961. /// SimpleValue ::= STRVAL+
  962. /// SimpleValue ::= CODEFRAGMENT
  963. /// SimpleValue ::= '?'
  964. /// SimpleValue ::= '{' ValueList '}'
  965. /// SimpleValue ::= ID '<' ValueListNE '>'
  966. /// SimpleValue ::= '[' ValueList ']'
  967. /// SimpleValue ::= '(' IDValue DagArgList ')'
  968. /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
  969. /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
  970. /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
  971. /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
  972. /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
  973. /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
  974. /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
  975. ///
  976. Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
  977. IDParseMode Mode) {
  978. Init *R = nullptr;
  979. switch (Lex.getCode()) {
  980. default: TokError("Unknown token when parsing a value"); break;
  981. case tgtok::paste:
  982. // This is a leading paste operation. This is deprecated but
  983. // still exists in some .td files. Ignore it.
  984. Lex.Lex(); // Skip '#'.
  985. return ParseSimpleValue(CurRec, ItemType, Mode);
  986. case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
  987. case tgtok::BinaryIntVal: {
  988. auto BinaryVal = Lex.getCurBinaryIntVal();
  989. SmallVector<Init*, 16> Bits(BinaryVal.second);
  990. for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
  991. Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
  992. R = BitsInit::get(Bits);
  993. Lex.Lex();
  994. break;
  995. }
  996. case tgtok::StrVal: {
  997. std::string Val = Lex.getCurStrVal();
  998. Lex.Lex();
  999. // Handle multiple consecutive concatenated strings.
  1000. while (Lex.getCode() == tgtok::StrVal) {
  1001. Val += Lex.getCurStrVal();
  1002. Lex.Lex();
  1003. }
  1004. R = StringInit::get(Val);
  1005. break;
  1006. }
  1007. case tgtok::CodeFragment:
  1008. R = StringInit::get(Lex.getCurStrVal());
  1009. Lex.Lex();
  1010. break;
  1011. case tgtok::question:
  1012. R = UnsetInit::get();
  1013. Lex.Lex();
  1014. break;
  1015. case tgtok::Id: {
  1016. SMLoc NameLoc = Lex.getLoc();
  1017. std::string Name = Lex.getCurStrVal();
  1018. if (Lex.Lex() != tgtok::less) // consume the Id.
  1019. return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
  1020. // Value ::= ID '<' ValueListNE '>'
  1021. if (Lex.Lex() == tgtok::greater) {
  1022. TokError("expected non-empty value list");
  1023. return nullptr;
  1024. }
  1025. // This is a CLASS<initvalslist> expression. This is supposed to synthesize
  1026. // a new anonymous definition, deriving from CLASS<initvalslist> with no
  1027. // body.
  1028. Record *Class = Records.getClass(Name);
  1029. if (!Class) {
  1030. Error(NameLoc, "Expected a class name, got '" + Name + "'");
  1031. return nullptr;
  1032. }
  1033. std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
  1034. if (ValueList.empty()) return nullptr;
  1035. if (Lex.getCode() != tgtok::greater) {
  1036. TokError("expected '>' at end of value list");
  1037. return nullptr;
  1038. }
  1039. Lex.Lex(); // eat the '>'
  1040. SMLoc EndLoc = Lex.getLoc();
  1041. // Create the new record, set it as CurRec temporarily.
  1042. auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
  1043. Records, /*IsAnonymous=*/true);
  1044. Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
  1045. SubClassReference SCRef;
  1046. SCRef.RefRange = SMRange(NameLoc, EndLoc);
  1047. SCRef.Rec = Class;
  1048. SCRef.TemplateArgs = ValueList;
  1049. // Add info about the subclass to NewRec.
  1050. if (AddSubClass(NewRec, SCRef))
  1051. return nullptr;
  1052. if (!CurMultiClass) {
  1053. NewRec->resolveReferences();
  1054. Records.addDef(std::move(NewRecOwner));
  1055. } else {
  1056. // This needs to get resolved once the multiclass template arguments are
  1057. // known before any use.
  1058. NewRec->setResolveFirst(true);
  1059. // Otherwise, we're inside a multiclass, add it to the multiclass.
  1060. CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
  1061. // Copy the template arguments for the multiclass into the def.
  1062. for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
  1063. const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
  1064. assert(RV && "Template arg doesn't exist?");
  1065. NewRec->addValue(*RV);
  1066. }
  1067. // We can't return the prototype def here, instead return:
  1068. // !cast<ItemType>(!strconcat(NAME, AnonName)).
  1069. const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
  1070. assert(MCNameRV && "multiclass record must have a NAME");
  1071. return UnOpInit::get(UnOpInit::CAST,
  1072. BinOpInit::get(BinOpInit::STRCONCAT,
  1073. VarInit::get(MCNameRV->getName(),
  1074. MCNameRV->getType()),
  1075. NewRec->getNameInit(),
  1076. StringRecTy::get()),
  1077. Class->getDefInit()->getType());
  1078. }
  1079. // The result of the expression is a reference to the new record.
  1080. return DefInit::get(NewRec);
  1081. }
  1082. case tgtok::l_brace: { // Value ::= '{' ValueList '}'
  1083. SMLoc BraceLoc = Lex.getLoc();
  1084. Lex.Lex(); // eat the '{'
  1085. std::vector<Init*> Vals;
  1086. if (Lex.getCode() != tgtok::r_brace) {
  1087. Vals = ParseValueList(CurRec);
  1088. if (Vals.empty()) return nullptr;
  1089. }
  1090. if (Lex.getCode() != tgtok::r_brace) {
  1091. TokError("expected '}' at end of bit list value");
  1092. return nullptr;
  1093. }
  1094. Lex.Lex(); // eat the '}'
  1095. SmallVector<Init *, 16> NewBits;
  1096. // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
  1097. // first. We'll first read everything in to a vector, then we can reverse
  1098. // it to get the bits in the correct order for the BitsInit value.
  1099. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1100. // FIXME: The following two loops would not be duplicated
  1101. // if the API was a little more orthogonal.
  1102. // bits<n> values are allowed to initialize n bits.
  1103. if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
  1104. for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
  1105. NewBits.push_back(BI->getBit((e - i) - 1));
  1106. continue;
  1107. }
  1108. // bits<n> can also come from variable initializers.
  1109. if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
  1110. if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
  1111. for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
  1112. NewBits.push_back(VI->getBit((e - i) - 1));
  1113. continue;
  1114. }
  1115. // Fallthrough to try convert this to a bit.
  1116. }
  1117. // All other values must be convertible to just a single bit.
  1118. Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
  1119. if (!Bit) {
  1120. Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
  1121. ") is not convertable to a bit");
  1122. return nullptr;
  1123. }
  1124. NewBits.push_back(Bit);
  1125. }
  1126. std::reverse(NewBits.begin(), NewBits.end());
  1127. return BitsInit::get(NewBits);
  1128. }
  1129. case tgtok::l_square: { // Value ::= '[' ValueList ']'
  1130. Lex.Lex(); // eat the '['
  1131. std::vector<Init*> Vals;
  1132. RecTy *DeducedEltTy = nullptr;
  1133. ListRecTy *GivenListTy = nullptr;
  1134. if (ItemType) {
  1135. ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
  1136. if (!ListType) {
  1137. TokError(Twine("Type mismatch for list, expected list type, got ") +
  1138. ItemType->getAsString());
  1139. return nullptr;
  1140. }
  1141. GivenListTy = ListType;
  1142. }
  1143. if (Lex.getCode() != tgtok::r_square) {
  1144. Vals = ParseValueList(CurRec, nullptr,
  1145. GivenListTy ? GivenListTy->getElementType() : nullptr);
  1146. if (Vals.empty()) return nullptr;
  1147. }
  1148. if (Lex.getCode() != tgtok::r_square) {
  1149. TokError("expected ']' at end of list value");
  1150. return nullptr;
  1151. }
  1152. Lex.Lex(); // eat the ']'
  1153. RecTy *GivenEltTy = nullptr;
  1154. if (Lex.getCode() == tgtok::less) {
  1155. // Optional list element type
  1156. Lex.Lex(); // eat the '<'
  1157. GivenEltTy = ParseType();
  1158. if (!GivenEltTy) {
  1159. // Couldn't parse element type
  1160. return nullptr;
  1161. }
  1162. if (Lex.getCode() != tgtok::greater) {
  1163. TokError("expected '>' at end of list element type");
  1164. return nullptr;
  1165. }
  1166. Lex.Lex(); // eat the '>'
  1167. }
  1168. // Check elements
  1169. RecTy *EltTy = nullptr;
  1170. for (Init *V : Vals) {
  1171. TypedInit *TArg = dyn_cast<TypedInit>(V);
  1172. if (!TArg) {
  1173. TokError("Untyped list element");
  1174. return nullptr;
  1175. }
  1176. if (EltTy) {
  1177. EltTy = resolveTypes(EltTy, TArg->getType());
  1178. if (!EltTy) {
  1179. TokError("Incompatible types in list elements");
  1180. return nullptr;
  1181. }
  1182. } else {
  1183. EltTy = TArg->getType();
  1184. }
  1185. }
  1186. if (GivenEltTy) {
  1187. if (EltTy) {
  1188. // Verify consistency
  1189. if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
  1190. TokError("Incompatible types in list elements");
  1191. return nullptr;
  1192. }
  1193. }
  1194. EltTy = GivenEltTy;
  1195. }
  1196. if (!EltTy) {
  1197. if (!ItemType) {
  1198. TokError("No type for list");
  1199. return nullptr;
  1200. }
  1201. DeducedEltTy = GivenListTy->getElementType();
  1202. } else {
  1203. // Make sure the deduced type is compatible with the given type
  1204. if (GivenListTy) {
  1205. if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
  1206. TokError("Element type mismatch for list");
  1207. return nullptr;
  1208. }
  1209. }
  1210. DeducedEltTy = EltTy;
  1211. }
  1212. return ListInit::get(Vals, DeducedEltTy);
  1213. }
  1214. case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
  1215. Lex.Lex(); // eat the '('
  1216. if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
  1217. TokError("expected identifier in dag init");
  1218. return nullptr;
  1219. }
  1220. Init *Operator = ParseValue(CurRec);
  1221. if (!Operator) return nullptr;
  1222. // If the operator name is present, parse it.
  1223. std::string OperatorName;
  1224. if (Lex.getCode() == tgtok::colon) {
  1225. if (Lex.Lex() != tgtok::VarName) { // eat the ':'
  1226. TokError("expected variable name in dag operator");
  1227. return nullptr;
  1228. }
  1229. OperatorName = Lex.getCurStrVal();
  1230. Lex.Lex(); // eat the VarName.
  1231. }
  1232. std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
  1233. if (Lex.getCode() != tgtok::r_paren) {
  1234. DagArgs = ParseDagArgList(CurRec);
  1235. if (DagArgs.empty()) return nullptr;
  1236. }
  1237. if (Lex.getCode() != tgtok::r_paren) {
  1238. TokError("expected ')' in dag init");
  1239. return nullptr;
  1240. }
  1241. Lex.Lex(); // eat the ')'
  1242. return DagInit::get(Operator, OperatorName, DagArgs);
  1243. }
  1244. case tgtok::XHead:
  1245. case tgtok::XTail:
  1246. case tgtok::XEmpty:
  1247. case tgtok::XCast: // Value ::= !unop '(' Value ')'
  1248. case tgtok::XConcat:
  1249. case tgtok::XADD:
  1250. case tgtok::XAND:
  1251. case tgtok::XSRA:
  1252. case tgtok::XSRL:
  1253. case tgtok::XSHL:
  1254. case tgtok::XEq:
  1255. case tgtok::XListConcat:
  1256. case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
  1257. case tgtok::XIf:
  1258. case tgtok::XForEach:
  1259. case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
  1260. return ParseOperation(CurRec, ItemType);
  1261. }
  1262. }
  1263. return R;
  1264. }
  1265. /// ParseValue - Parse a tblgen value. This returns null on error.
  1266. ///
  1267. /// Value ::= SimpleValue ValueSuffix*
  1268. /// ValueSuffix ::= '{' BitList '}'
  1269. /// ValueSuffix ::= '[' BitList ']'
  1270. /// ValueSuffix ::= '.' ID
  1271. ///
  1272. Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
  1273. Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
  1274. if (!Result) return nullptr;
  1275. // Parse the suffixes now if present.
  1276. while (1) {
  1277. switch (Lex.getCode()) {
  1278. default: return Result;
  1279. case tgtok::l_brace: {
  1280. if (Mode == ParseNameMode || Mode == ParseForeachMode)
  1281. // This is the beginning of the object body.
  1282. return Result;
  1283. SMLoc CurlyLoc = Lex.getLoc();
  1284. Lex.Lex(); // eat the '{'
  1285. std::vector<unsigned> Ranges = ParseRangeList();
  1286. if (Ranges.empty()) return nullptr;
  1287. // Reverse the bitlist.
  1288. std::reverse(Ranges.begin(), Ranges.end());
  1289. Result = Result->convertInitializerBitRange(Ranges);
  1290. if (!Result) {
  1291. Error(CurlyLoc, "Invalid bit range for value");
  1292. return nullptr;
  1293. }
  1294. // Eat the '}'.
  1295. if (Lex.getCode() != tgtok::r_brace) {
  1296. TokError("expected '}' at end of bit range list");
  1297. return nullptr;
  1298. }
  1299. Lex.Lex();
  1300. break;
  1301. }
  1302. case tgtok::l_square: {
  1303. SMLoc SquareLoc = Lex.getLoc();
  1304. Lex.Lex(); // eat the '['
  1305. std::vector<unsigned> Ranges = ParseRangeList();
  1306. if (Ranges.empty()) return nullptr;
  1307. Result = Result->convertInitListSlice(Ranges);
  1308. if (!Result) {
  1309. Error(SquareLoc, "Invalid range for list slice");
  1310. return nullptr;
  1311. }
  1312. // Eat the ']'.
  1313. if (Lex.getCode() != tgtok::r_square) {
  1314. TokError("expected ']' at end of list slice");
  1315. return nullptr;
  1316. }
  1317. Lex.Lex();
  1318. break;
  1319. }
  1320. case tgtok::period:
  1321. if (Lex.Lex() != tgtok::Id) { // eat the .
  1322. TokError("expected field identifier after '.'");
  1323. return nullptr;
  1324. }
  1325. if (!Result->getFieldType(Lex.getCurStrVal())) {
  1326. TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
  1327. Result->getAsString() + "'");
  1328. return nullptr;
  1329. }
  1330. Result = FieldInit::get(Result, Lex.getCurStrVal());
  1331. Lex.Lex(); // eat field name
  1332. break;
  1333. case tgtok::paste:
  1334. SMLoc PasteLoc = Lex.getLoc();
  1335. // Create a !strconcat() operation, first casting each operand to
  1336. // a string if necessary.
  1337. TypedInit *LHS = dyn_cast<TypedInit>(Result);
  1338. if (!LHS) {
  1339. Error(PasteLoc, "LHS of paste is not typed!");
  1340. return nullptr;
  1341. }
  1342. if (LHS->getType() != StringRecTy::get()) {
  1343. LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
  1344. }
  1345. TypedInit *RHS = nullptr;
  1346. Lex.Lex(); // Eat the '#'.
  1347. switch (Lex.getCode()) {
  1348. case tgtok::colon:
  1349. case tgtok::semi:
  1350. case tgtok::l_brace:
  1351. // These are all of the tokens that can begin an object body.
  1352. // Some of these can also begin values but we disallow those cases
  1353. // because they are unlikely to be useful.
  1354. // Trailing paste, concat with an empty string.
  1355. RHS = StringInit::get("");
  1356. break;
  1357. default:
  1358. Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
  1359. RHS = dyn_cast<TypedInit>(RHSResult);
  1360. if (!RHS) {
  1361. Error(PasteLoc, "RHS of paste is not typed!");
  1362. return nullptr;
  1363. }
  1364. if (RHS->getType() != StringRecTy::get()) {
  1365. RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
  1366. }
  1367. break;
  1368. }
  1369. Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
  1370. StringRecTy::get())->Fold(CurRec, CurMultiClass);
  1371. break;
  1372. }
  1373. }
  1374. }
  1375. /// ParseDagArgList - Parse the argument list for a dag literal expression.
  1376. ///
  1377. /// DagArg ::= Value (':' VARNAME)?
  1378. /// DagArg ::= VARNAME
  1379. /// DagArgList ::= DagArg
  1380. /// DagArgList ::= DagArgList ',' DagArg
  1381. std::vector<std::pair<llvm::Init*, std::string> >
  1382. TGParser::ParseDagArgList(Record *CurRec) {
  1383. std::vector<std::pair<llvm::Init*, std::string> > Result;
  1384. while (1) {
  1385. // DagArg ::= VARNAME
  1386. if (Lex.getCode() == tgtok::VarName) {
  1387. // A missing value is treated like '?'.
  1388. Result.emplace_back(UnsetInit::get(), Lex.getCurStrVal());
  1389. Lex.Lex();
  1390. } else {
  1391. // DagArg ::= Value (':' VARNAME)?
  1392. Init *Val = ParseValue(CurRec);
  1393. if (!Val)
  1394. return std::vector<std::pair<llvm::Init*, std::string> >();
  1395. // If the variable name is present, add it.
  1396. std::string VarName;
  1397. if (Lex.getCode() == tgtok::colon) {
  1398. if (Lex.Lex() != tgtok::VarName) { // eat the ':'
  1399. TokError("expected variable name in dag literal");
  1400. return std::vector<std::pair<llvm::Init*, std::string> >();
  1401. }
  1402. VarName = Lex.getCurStrVal();
  1403. Lex.Lex(); // eat the VarName.
  1404. }
  1405. Result.push_back(std::make_pair(Val, VarName));
  1406. }
  1407. if (Lex.getCode() != tgtok::comma) break;
  1408. Lex.Lex(); // eat the ','
  1409. }
  1410. return Result;
  1411. }
  1412. /// ParseValueList - Parse a comma separated list of values, returning them as a
  1413. /// vector. Note that this always expects to be able to parse at least one
  1414. /// value. It returns an empty list if this is not possible.
  1415. ///
  1416. /// ValueList ::= Value (',' Value)
  1417. ///
  1418. std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
  1419. RecTy *EltTy) {
  1420. std::vector<Init*> Result;
  1421. RecTy *ItemType = EltTy;
  1422. unsigned int ArgN = 0;
  1423. if (ArgsRec && !EltTy) {
  1424. const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
  1425. if (TArgs.empty()) {
  1426. TokError("template argument provided to non-template class");
  1427. return std::vector<Init*>();
  1428. }
  1429. const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
  1430. if (!RV) {
  1431. errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
  1432. << ")\n";
  1433. }
  1434. assert(RV && "Template argument record not found??");
  1435. ItemType = RV->getType();
  1436. ++ArgN;
  1437. }
  1438. Result.push_back(ParseValue(CurRec, ItemType));
  1439. if (!Result.back()) return std::vector<Init*>();
  1440. while (Lex.getCode() == tgtok::comma) {
  1441. Lex.Lex(); // Eat the comma
  1442. if (ArgsRec && !EltTy) {
  1443. const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
  1444. if (ArgN >= TArgs.size()) {
  1445. TokError("too many template arguments");
  1446. return std::vector<Init*>();
  1447. }
  1448. const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
  1449. assert(RV && "Template argument record not found??");
  1450. ItemType = RV->getType();
  1451. ++ArgN;
  1452. }
  1453. Result.push_back(ParseValue(CurRec, ItemType));
  1454. if (!Result.back()) return std::vector<Init*>();
  1455. }
  1456. return Result;
  1457. }
  1458. /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
  1459. /// empty string on error. This can happen in a number of different context's,
  1460. /// including within a def or in the template args for a def (which which case
  1461. /// CurRec will be non-null) and within the template args for a multiclass (in
  1462. /// which case CurRec will be null, but CurMultiClass will be set). This can
  1463. /// also happen within a def that is within a multiclass, which will set both
  1464. /// CurRec and CurMultiClass.
  1465. ///
  1466. /// Declaration ::= FIELD? Type ID ('=' Value)?
  1467. ///
  1468. Init *TGParser::ParseDeclaration(Record *CurRec,
  1469. bool ParsingTemplateArgs) {
  1470. // Read the field prefix if present.
  1471. bool HasField = Lex.getCode() == tgtok::Field;
  1472. if (HasField) Lex.Lex();
  1473. RecTy *Type = ParseType();
  1474. if (!Type) return nullptr;
  1475. if (Lex.getCode() != tgtok::Id) {
  1476. TokError("Expected identifier in declaration");
  1477. return nullptr;
  1478. }
  1479. SMLoc IdLoc = Lex.getLoc();
  1480. Init *DeclName = StringInit::get(Lex.getCurStrVal());
  1481. Lex.Lex();
  1482. if (ParsingTemplateArgs) {
  1483. if (CurRec)
  1484. DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
  1485. else
  1486. assert(CurMultiClass);
  1487. if (CurMultiClass)
  1488. DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
  1489. "::");
  1490. }
  1491. // Add the value.
  1492. if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
  1493. return nullptr;
  1494. // If a value is present, parse it.
  1495. if (Lex.getCode() == tgtok::equal) {
  1496. Lex.Lex();
  1497. SMLoc ValLoc = Lex.getLoc();
  1498. Init *Val = ParseValue(CurRec, Type);
  1499. if (!Val ||
  1500. SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
  1501. // Return the name, even if an error is thrown. This is so that we can
  1502. // continue to make some progress, even without the value having been
  1503. // initialized.
  1504. return DeclName;
  1505. }
  1506. return DeclName;
  1507. }
  1508. /// ParseForeachDeclaration - Read a foreach declaration, returning
  1509. /// the name of the declared object or a NULL Init on error. Return
  1510. /// the name of the parsed initializer list through ForeachListName.
  1511. ///
  1512. /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
  1513. /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
  1514. /// ForeachDeclaration ::= ID '=' RangePiece
  1515. ///
  1516. VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
  1517. if (Lex.getCode() != tgtok::Id) {
  1518. TokError("Expected identifier in foreach declaration");
  1519. return nullptr;
  1520. }
  1521. Init *DeclName = StringInit::get(Lex.getCurStrVal());
  1522. Lex.Lex();
  1523. // If a value is present, parse it.
  1524. if (Lex.getCode() != tgtok::equal) {
  1525. TokError("Expected '=' in foreach declaration");
  1526. return nullptr;
  1527. }
  1528. Lex.Lex(); // Eat the '='
  1529. RecTy *IterType = nullptr;
  1530. std::vector<unsigned> Ranges;
  1531. switch (Lex.getCode()) {
  1532. default: TokError("Unknown token when expecting a range list"); return nullptr;
  1533. case tgtok::l_square: { // '[' ValueList ']'
  1534. Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
  1535. ForeachListValue = dyn_cast<ListInit>(List);
  1536. if (!ForeachListValue) {
  1537. TokError("Expected a Value list");
  1538. return nullptr;
  1539. }
  1540. RecTy *ValueType = ForeachListValue->getType();
  1541. ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
  1542. if (!ListType) {
  1543. TokError("Value list is not of list type");
  1544. return nullptr;
  1545. }
  1546. IterType = ListType->getElementType();
  1547. break;
  1548. }
  1549. case tgtok::IntVal: { // RangePiece.
  1550. if (ParseRangePiece(Ranges))
  1551. return nullptr;
  1552. break;
  1553. }
  1554. case tgtok::l_brace: { // '{' RangeList '}'
  1555. Lex.Lex(); // eat the '{'
  1556. Ranges = ParseRangeList();
  1557. if (Lex.getCode() != tgtok::r_brace) {
  1558. TokError("expected '}' at end of bit range list");
  1559. return nullptr;
  1560. }
  1561. Lex.Lex();
  1562. break;
  1563. }
  1564. }
  1565. if (!Ranges.empty()) {
  1566. assert(!IterType && "Type already initialized?");
  1567. IterType = IntRecTy::get();
  1568. std::vector<Init*> Values;
  1569. for (unsigned R : Ranges)
  1570. Values.push_back(IntInit::get(R));
  1571. ForeachListValue = ListInit::get(Values, IterType);
  1572. }
  1573. if (!IterType)
  1574. return nullptr;
  1575. return VarInit::get(DeclName, IterType);
  1576. }
  1577. /// ParseTemplateArgList - Read a template argument list, which is a non-empty
  1578. /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
  1579. /// template args for a def, which may or may not be in a multiclass. If null,
  1580. /// these are the template args for a multiclass.
  1581. ///
  1582. /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
  1583. ///
  1584. bool TGParser::ParseTemplateArgList(Record *CurRec) {
  1585. assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
  1586. Lex.Lex(); // eat the '<'
  1587. Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
  1588. // Read the first declaration.
  1589. Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
  1590. if (!TemplArg)
  1591. return true;
  1592. TheRecToAddTo->addTemplateArg(TemplArg);
  1593. while (Lex.getCode() == tgtok::comma) {
  1594. Lex.Lex(); // eat the ','
  1595. // Read the following declarations.
  1596. TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
  1597. if (!TemplArg)
  1598. return true;
  1599. TheRecToAddTo->addTemplateArg(TemplArg);
  1600. }
  1601. if (Lex.getCode() != tgtok::greater)
  1602. return TokError("expected '>' at end of template argument list");
  1603. Lex.Lex(); // eat the '>'.
  1604. return false;
  1605. }
  1606. /// ParseBodyItem - Parse a single item at within the body of a def or class.
  1607. ///
  1608. /// BodyItem ::= Declaration ';'
  1609. /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
  1610. bool TGParser::ParseBodyItem(Record *CurRec) {
  1611. if (Lex.getCode() != tgtok::Let) {
  1612. if (!ParseDeclaration(CurRec, false))
  1613. return true;
  1614. if (Lex.getCode() != tgtok::semi)
  1615. return TokError("expected ';' after declaration");
  1616. Lex.Lex();
  1617. return false;
  1618. }
  1619. // LET ID OptionalRangeList '=' Value ';'
  1620. if (Lex.Lex() != tgtok::Id)
  1621. return TokError("expected field identifier after let");
  1622. SMLoc IdLoc = Lex.getLoc();
  1623. std::string FieldName = Lex.getCurStrVal();
  1624. Lex.Lex(); // eat the field name.
  1625. std::vector<unsigned> BitList;
  1626. if (ParseOptionalBitList(BitList))
  1627. return true;
  1628. std::reverse(BitList.begin(), BitList.end());
  1629. if (Lex.getCode() != tgtok::equal)
  1630. return TokError("expected '=' in let expression");
  1631. Lex.Lex(); // eat the '='.
  1632. RecordVal *Field = CurRec->getValue(FieldName);
  1633. if (!Field)
  1634. return TokError("Value '" + FieldName + "' unknown!");
  1635. RecTy *Type = Field->getType();
  1636. Init *Val = ParseValue(CurRec, Type);
  1637. if (!Val) return true;
  1638. if (Lex.getCode() != tgtok::semi)
  1639. return TokError("expected ';' after let expression");
  1640. Lex.Lex();
  1641. return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
  1642. }
  1643. /// ParseBody - Read the body of a class or def. Return true on error, false on
  1644. /// success.
  1645. ///
  1646. /// Body ::= ';'
  1647. /// Body ::= '{' BodyList '}'
  1648. /// BodyList BodyItem*
  1649. ///
  1650. bool TGParser::ParseBody(Record *CurRec) {
  1651. // If this is a null definition, just eat the semi and return.
  1652. if (Lex.getCode() == tgtok::semi) {
  1653. Lex.Lex();
  1654. return false;
  1655. }
  1656. if (Lex.getCode() != tgtok::l_brace)
  1657. return TokError("Expected ';' or '{' to start body");
  1658. // Eat the '{'.
  1659. Lex.Lex();
  1660. while (Lex.getCode() != tgtok::r_brace)
  1661. if (ParseBodyItem(CurRec))
  1662. return true;
  1663. // Eat the '}'.
  1664. Lex.Lex();
  1665. return false;
  1666. }
  1667. /// \brief Apply the current let bindings to \a CurRec.
  1668. /// \returns true on error, false otherwise.
  1669. bool TGParser::ApplyLetStack(Record *CurRec) {
  1670. for (std::vector<LetRecord> &LetInfo : LetStack)
  1671. for (LetRecord &LR : LetInfo)
  1672. if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
  1673. return true;
  1674. return false;
  1675. }
  1676. /// ParseObjectBody - Parse the body of a def or class. This consists of an
  1677. /// optional ClassList followed by a Body. CurRec is the current def or class
  1678. /// that is being parsed.
  1679. ///
  1680. /// ObjectBody ::= BaseClassList Body
  1681. /// BaseClassList ::= /*empty*/
  1682. /// BaseClassList ::= ':' BaseClassListNE
  1683. /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
  1684. ///
  1685. bool TGParser::ParseObjectBody(Record *CurRec) {
  1686. // If there is a baseclass list, read it.
  1687. if (Lex.getCode() == tgtok::colon) {
  1688. Lex.Lex();
  1689. // Read all of the subclasses.
  1690. SubClassReference SubClass = ParseSubClassReference(CurRec, false);
  1691. while (1) {
  1692. // Check for error.
  1693. if (!SubClass.Rec) return true;
  1694. // Add it.
  1695. if (AddSubClass(CurRec, SubClass))
  1696. return true;
  1697. if (Lex.getCode() != tgtok::comma) break;
  1698. Lex.Lex(); // eat ','.
  1699. SubClass = ParseSubClassReference(CurRec, false);
  1700. }
  1701. }
  1702. if (ApplyLetStack(CurRec))
  1703. return true;
  1704. return ParseBody(CurRec);
  1705. }
  1706. /// ParseDef - Parse and return a top level or multiclass def, return the record
  1707. /// corresponding to it. This returns null on error.
  1708. ///
  1709. /// DefInst ::= DEF ObjectName ObjectBody
  1710. ///
  1711. bool TGParser::ParseDef(MultiClass *CurMultiClass) {
  1712. SMLoc DefLoc = Lex.getLoc();
  1713. assert(Lex.getCode() == tgtok::Def && "Unknown tok");
  1714. Lex.Lex(); // Eat the 'def' token.
  1715. // Parse ObjectName and make a record for it.
  1716. std::unique_ptr<Record> CurRecOwner;
  1717. Init *Name = ParseObjectName(CurMultiClass);
  1718. if (Name)
  1719. CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
  1720. else
  1721. CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
  1722. Records, /*IsAnonymous=*/true);
  1723. Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
  1724. if (!CurMultiClass && Loops.empty()) {
  1725. // Top-level def definition.
  1726. // Ensure redefinition doesn't happen.
  1727. if (Records.getDef(CurRec->getNameInitAsString()))
  1728. return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
  1729. "' already defined");
  1730. Records.addDef(std::move(CurRecOwner));
  1731. if (ParseObjectBody(CurRec))
  1732. return true;
  1733. } else if (CurMultiClass) {
  1734. // Parse the body before adding this prototype to the DefPrototypes vector.
  1735. // That way implicit definitions will be added to the DefPrototypes vector
  1736. // before this object, instantiated prior to defs derived from this object,
  1737. // and this available for indirect name resolution when defs derived from
  1738. // this object are instantiated.
  1739. if (ParseObjectBody(CurRec))
  1740. return true;
  1741. // Otherwise, a def inside a multiclass, add it to the multiclass.
  1742. for (const auto &Proto : CurMultiClass->DefPrototypes)
  1743. if (Proto->getNameInit() == CurRec->getNameInit())
  1744. return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
  1745. "' already defined in this multiclass!");
  1746. CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
  1747. } else if (ParseObjectBody(CurRec)) {
  1748. return true;
  1749. }
  1750. if (!CurMultiClass) // Def's in multiclasses aren't really defs.
  1751. // See Record::setName(). This resolve step will see any new name
  1752. // for the def that might have been created when resolving
  1753. // inheritance, values and arguments above.
  1754. CurRec->resolveReferences();
  1755. // If ObjectBody has template arguments, it's an error.
  1756. assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
  1757. if (CurMultiClass) {
  1758. // Copy the template arguments for the multiclass into the def.
  1759. for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
  1760. const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
  1761. assert(RV && "Template arg doesn't exist?");
  1762. CurRec->addValue(*RV);
  1763. }
  1764. }
  1765. if (ProcessForeachDefs(CurRec, DefLoc))
  1766. return Error(DefLoc, "Could not process loops for def" +
  1767. CurRec->getNameInitAsString());
  1768. return false;
  1769. }
  1770. /// ParseForeach - Parse a for statement. Return the record corresponding
  1771. /// to it. This returns true on error.
  1772. ///
  1773. /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
  1774. /// Foreach ::= FOREACH Declaration IN Object
  1775. ///
  1776. bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
  1777. assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
  1778. Lex.Lex(); // Eat the 'for' token.
  1779. // Make a temporary object to record items associated with the for
  1780. // loop.
  1781. ListInit *ListValue = nullptr;
  1782. VarInit *IterName = ParseForeachDeclaration(ListValue);
  1783. if (!IterName)
  1784. return TokError("expected declaration in for");
  1785. if (Lex.getCode() != tgtok::In)
  1786. return TokError("Unknown tok");
  1787. Lex.Lex(); // Eat the in
  1788. // Create a loop object and remember it.
  1789. Loops.push_back(ForeachLoop(IterName, ListValue));
  1790. if (Lex.getCode() != tgtok::l_brace) {
  1791. // FOREACH Declaration IN Object
  1792. if (ParseObject(CurMultiClass))
  1793. return true;
  1794. } else {
  1795. SMLoc BraceLoc = Lex.getLoc();
  1796. // Otherwise, this is a group foreach.
  1797. Lex.Lex(); // eat the '{'.
  1798. // Parse the object list.
  1799. if (ParseObjectList(CurMultiClass))
  1800. return true;
  1801. if (Lex.getCode() != tgtok::r_brace) {
  1802. TokError("expected '}' at end of foreach command");
  1803. return Error(BraceLoc, "to match this '{'");
  1804. }
  1805. Lex.Lex(); // Eat the }
  1806. }
  1807. // We've processed everything in this loop.
  1808. Loops.pop_back();
  1809. return false;
  1810. }
  1811. /// ParseClass - Parse a tblgen class definition.
  1812. ///
  1813. /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
  1814. ///
  1815. bool TGParser::ParseClass() {
  1816. assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
  1817. Lex.Lex();
  1818. if (Lex.getCode() != tgtok::Id)
  1819. return TokError("expected class name after 'class' keyword");
  1820. Record *CurRec = Records.getClass(Lex.getCurStrVal());
  1821. if (CurRec) {
  1822. // If the body was previously defined, this is an error.
  1823. if (CurRec->getValues().size() > 1 || // Account for NAME.
  1824. !CurRec->getSuperClasses().empty() ||
  1825. !CurRec->getTemplateArgs().empty())
  1826. return TokError("Class '" + CurRec->getNameInitAsString() +
  1827. "' already defined");
  1828. } else {
  1829. // If this is the first reference to this class, create and add it.
  1830. auto NewRec =
  1831. llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
  1832. CurRec = NewRec.get();
  1833. Records.addClass(std::move(NewRec));
  1834. }
  1835. Lex.Lex(); // eat the name.
  1836. // If there are template args, parse them.
  1837. if (Lex.getCode() == tgtok::less)
  1838. if (ParseTemplateArgList(CurRec))
  1839. return true;
  1840. // Finally, parse the object body.
  1841. return ParseObjectBody(CurRec);
  1842. }
  1843. /// ParseLetList - Parse a non-empty list of assignment expressions into a list
  1844. /// of LetRecords.
  1845. ///
  1846. /// LetList ::= LetItem (',' LetItem)*
  1847. /// LetItem ::= ID OptionalRangeList '=' Value
  1848. ///
  1849. std::vector<LetRecord> TGParser::ParseLetList() {
  1850. std::vector<LetRecord> Result;
  1851. while (1) {
  1852. if (Lex.getCode() != tgtok::Id) {
  1853. TokError("expected identifier in let definition");
  1854. return std::vector<LetRecord>();
  1855. }
  1856. std::string Name = Lex.getCurStrVal();
  1857. SMLoc NameLoc = Lex.getLoc();
  1858. Lex.Lex(); // Eat the identifier.
  1859. // Check for an optional RangeList.
  1860. std::vector<unsigned> Bits;
  1861. if (ParseOptionalRangeList(Bits))
  1862. return std::vector<LetRecord>();
  1863. std::reverse(Bits.begin(), Bits.end());
  1864. if (Lex.getCode() != tgtok::equal) {
  1865. TokError("expected '=' in let expression");
  1866. return std::vector<LetRecord>();
  1867. }
  1868. Lex.Lex(); // eat the '='.
  1869. Init *Val = ParseValue(nullptr);
  1870. if (!Val) return std::vector<LetRecord>();
  1871. // Now that we have everything, add the record.
  1872. Result.emplace_back(std::move(Name), std::move(Bits), Val, NameLoc);
  1873. if (Lex.getCode() != tgtok::comma)
  1874. return Result;
  1875. Lex.Lex(); // eat the comma.
  1876. }
  1877. }
  1878. /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
  1879. /// different related productions. This works inside multiclasses too.
  1880. ///
  1881. /// Object ::= LET LetList IN '{' ObjectList '}'
  1882. /// Object ::= LET LetList IN Object
  1883. ///
  1884. bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
  1885. assert(Lex.getCode() == tgtok::Let && "Unexpected token");
  1886. Lex.Lex();
  1887. // Add this entry to the let stack.
  1888. std::vector<LetRecord> LetInfo = ParseLetList();
  1889. if (LetInfo.empty()) return true;
  1890. LetStack.push_back(std::move(LetInfo));
  1891. if (Lex.getCode() != tgtok::In)
  1892. return TokError("expected 'in' at end of top-level 'let'");
  1893. Lex.Lex();
  1894. // If this is a scalar let, just handle it now
  1895. if (Lex.getCode() != tgtok::l_brace) {
  1896. // LET LetList IN Object
  1897. if (ParseObject(CurMultiClass))
  1898. return true;
  1899. } else { // Object ::= LETCommand '{' ObjectList '}'
  1900. SMLoc BraceLoc = Lex.getLoc();
  1901. // Otherwise, this is a group let.
  1902. Lex.Lex(); // eat the '{'.
  1903. // Parse the object list.
  1904. if (ParseObjectList(CurMultiClass))
  1905. return true;
  1906. if (Lex.getCode() != tgtok::r_brace) {
  1907. TokError("expected '}' at end of top level let command");
  1908. return Error(BraceLoc, "to match this '{'");
  1909. }
  1910. Lex.Lex();
  1911. }
  1912. // Outside this let scope, this let block is not active.
  1913. LetStack.pop_back();
  1914. return false;
  1915. }
  1916. /// ParseMultiClass - Parse a multiclass definition.
  1917. ///
  1918. /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
  1919. /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
  1920. /// MultiClassObject ::= DefInst
  1921. /// MultiClassObject ::= MultiClassInst
  1922. /// MultiClassObject ::= DefMInst
  1923. /// MultiClassObject ::= LETCommand '{' ObjectList '}'
  1924. /// MultiClassObject ::= LETCommand Object
  1925. ///
  1926. bool TGParser::ParseMultiClass() {
  1927. assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
  1928. Lex.Lex(); // Eat the multiclass token.
  1929. if (Lex.getCode() != tgtok::Id)
  1930. return TokError("expected identifier after multiclass for name");
  1931. std::string Name = Lex.getCurStrVal();
  1932. auto Result =
  1933. MultiClasses.insert(std::make_pair(Name,
  1934. llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
  1935. if (!Result.second)
  1936. return TokError("multiclass '" + Name + "' already defined");
  1937. CurMultiClass = Result.first->second.get();
  1938. Lex.Lex(); // Eat the identifier.
  1939. // If there are template args, parse them.
  1940. if (Lex.getCode() == tgtok::less)
  1941. if (ParseTemplateArgList(nullptr))
  1942. return true;
  1943. bool inherits = false;
  1944. // If there are submulticlasses, parse them.
  1945. if (Lex.getCode() == tgtok::colon) {
  1946. inherits = true;
  1947. Lex.Lex();
  1948. // Read all of the submulticlasses.
  1949. SubMultiClassReference SubMultiClass =
  1950. ParseSubMultiClassReference(CurMultiClass);
  1951. while (1) {
  1952. // Check for error.
  1953. if (!SubMultiClass.MC) return true;
  1954. // Add it.
  1955. if (AddSubMultiClass(CurMultiClass, SubMultiClass))
  1956. return true;
  1957. if (Lex.getCode() != tgtok::comma) break;
  1958. Lex.Lex(); // eat ','.
  1959. SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
  1960. }
  1961. }
  1962. if (Lex.getCode() != tgtok::l_brace) {
  1963. if (!inherits)
  1964. return TokError("expected '{' in multiclass definition");
  1965. if (Lex.getCode() != tgtok::semi)
  1966. return TokError("expected ';' in multiclass definition");
  1967. Lex.Lex(); // eat the ';'.
  1968. } else {
  1969. if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
  1970. return TokError("multiclass must contain at least one def");
  1971. while (Lex.getCode() != tgtok::r_brace) {
  1972. switch (Lex.getCode()) {
  1973. default:
  1974. return TokError("expected 'let', 'def' or 'defm' in multiclass body");
  1975. case tgtok::Let:
  1976. case tgtok::Def:
  1977. case tgtok::Defm:
  1978. case tgtok::Foreach:
  1979. if (ParseObject(CurMultiClass))
  1980. return true;
  1981. break;
  1982. }
  1983. }
  1984. Lex.Lex(); // eat the '}'.
  1985. }
  1986. CurMultiClass = nullptr;
  1987. return false;
  1988. }
  1989. Record *TGParser::
  1990. InstantiateMulticlassDef(MultiClass &MC,
  1991. Record *DefProto,
  1992. Init *&DefmPrefix,
  1993. SMRange DefmPrefixRange,
  1994. const std::vector<Init *> &TArgs,
  1995. std::vector<Init *> &TemplateVals) {
  1996. // We need to preserve DefProto so it can be reused for later
  1997. // instantiations, so create a new Record to inherit from it.
  1998. // Add in the defm name. If the defm prefix is empty, give each
  1999. // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
  2000. // name, substitute the prefix for #NAME#. Otherwise, use the defm name
  2001. // as a prefix.
  2002. bool IsAnonymous = false;
  2003. if (!DefmPrefix) {
  2004. DefmPrefix = StringInit::get(GetNewAnonymousName());
  2005. IsAnonymous = true;
  2006. }
  2007. Init *DefName = DefProto->getNameInit();
  2008. StringInit *DefNameString = dyn_cast<StringInit>(DefName);
  2009. if (DefNameString) {
  2010. // We have a fully expanded string so there are no operators to
  2011. // resolve. We should concatenate the given prefix and name.
  2012. DefName =
  2013. BinOpInit::get(BinOpInit::STRCONCAT,
  2014. UnOpInit::get(UnOpInit::CAST, DefmPrefix,
  2015. StringRecTy::get())->Fold(DefProto, &MC),
  2016. DefName, StringRecTy::get())->Fold(DefProto, &MC);
  2017. }
  2018. // Make a trail of SMLocs from the multiclass instantiations.
  2019. SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
  2020. Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
  2021. auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
  2022. SubClassReference Ref;
  2023. Ref.RefRange = DefmPrefixRange;
  2024. Ref.Rec = DefProto;
  2025. AddSubClass(CurRec.get(), Ref);
  2026. // Set the value for NAME. We don't resolve references to it 'til later,
  2027. // though, so that uses in nested multiclass names don't get
  2028. // confused.
  2029. if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
  2030. std::vector<unsigned>(), DefmPrefix)) {
  2031. Error(DefmPrefixRange.Start, "Could not resolve " +
  2032. CurRec->getNameInitAsString() + ":NAME to '" +
  2033. DefmPrefix->getAsUnquotedString() + "'");
  2034. return nullptr;
  2035. }
  2036. // If the DefNameString didn't resolve, we probably have a reference to
  2037. // NAME and need to replace it. We need to do at least this much greedily,
  2038. // otherwise nested multiclasses will end up with incorrect NAME expansions.
  2039. if (!DefNameString) {
  2040. RecordVal *DefNameRV = CurRec->getValue("NAME");
  2041. CurRec->resolveReferencesTo(DefNameRV);
  2042. }
  2043. if (!CurMultiClass) {
  2044. // Now that we're at the top level, resolve all NAME references
  2045. // in the resultant defs that weren't in the def names themselves.
  2046. RecordVal *DefNameRV = CurRec->getValue("NAME");
  2047. CurRec->resolveReferencesTo(DefNameRV);
  2048. // Check if the name is a complex pattern.
  2049. // If so, resolve it.
  2050. DefName = CurRec->getNameInit();
  2051. DefNameString = dyn_cast<StringInit>(DefName);
  2052. // OK the pattern is more complex than simply using NAME.
  2053. // Let's use the heavy weaponery.
  2054. if (!DefNameString) {
  2055. ResolveMulticlassDefArgs(MC, CurRec.get(), DefmPrefixRange.Start,
  2056. Lex.getLoc(), TArgs, TemplateVals,
  2057. false/*Delete args*/);
  2058. DefName = CurRec->getNameInit();
  2059. DefNameString = dyn_cast<StringInit>(DefName);
  2060. if (!DefNameString)
  2061. DefName = DefName->convertInitializerTo(StringRecTy::get());
  2062. // We ran out of options here...
  2063. DefNameString = dyn_cast<StringInit>(DefName);
  2064. if (!DefNameString) {
  2065. PrintFatalError(CurRec->getLoc()[CurRec->getLoc().size() - 1],
  2066. DefName->getAsUnquotedString() + " is not a string.");
  2067. return nullptr;
  2068. }
  2069. CurRec->setName(DefName);
  2070. }
  2071. // Now that NAME references are resolved and we're at the top level of
  2072. // any multiclass expansions, add the record to the RecordKeeper. If we are
  2073. // currently in a multiclass, it means this defm appears inside a
  2074. // multiclass and its name won't be fully resolvable until we see
  2075. // the top-level defm. Therefore, we don't add this to the
  2076. // RecordKeeper at this point. If we did we could get duplicate
  2077. // defs as more than one probably refers to NAME or some other
  2078. // common internal placeholder.
  2079. // Ensure redefinition doesn't happen.
  2080. if (Records.getDef(CurRec->getNameInitAsString())) {
  2081. Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
  2082. "' already defined, instantiating defm with subdef '" +
  2083. DefProto->getNameInitAsString() + "'");
  2084. return nullptr;
  2085. }
  2086. Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
  2087. Records.addDef(std::move(CurRec));
  2088. return CurRecSave;
  2089. }
  2090. // FIXME This is bad but the ownership transfer to caller is pretty messy.
  2091. // The unique_ptr in this function at least protects the exits above.
  2092. return CurRec.release();
  2093. }
  2094. bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
  2095. Record *CurRec,
  2096. SMLoc DefmPrefixLoc,
  2097. SMLoc SubClassLoc,
  2098. const std::vector<Init *> &TArgs,
  2099. std::vector<Init *> &TemplateVals,
  2100. bool DeleteArgs) {
  2101. // Loop over all of the template arguments, setting them to the specified
  2102. // value or leaving them as the default if necessary.
  2103. for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
  2104. // Check if a value is specified for this temp-arg.
  2105. if (i < TemplateVals.size()) {
  2106. // Set it now.
  2107. if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
  2108. TemplateVals[i]))
  2109. return true;
  2110. // Resolve it next.
  2111. CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
  2112. if (DeleteArgs)
  2113. // Now remove it.
  2114. CurRec->removeValue(TArgs[i]);
  2115. } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
  2116. return Error(SubClassLoc, "value not specified for template argument #" +
  2117. Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
  2118. ") of multiclassclass '" + MC.Rec.getNameInitAsString() +
  2119. "'");
  2120. }
  2121. }
  2122. return false;
  2123. }
  2124. bool TGParser::ResolveMulticlassDef(MultiClass &MC,
  2125. Record *CurRec,
  2126. Record *DefProto,
  2127. SMLoc DefmPrefixLoc) {
  2128. // If the mdef is inside a 'let' expression, add to each def.
  2129. if (ApplyLetStack(CurRec))
  2130. return Error(DefmPrefixLoc, "when instantiating this defm");
  2131. // Don't create a top level definition for defm inside multiclasses,
  2132. // instead, only update the prototypes and bind the template args
  2133. // with the new created definition.
  2134. if (!CurMultiClass)
  2135. return false;
  2136. for (const auto &Proto : CurMultiClass->DefPrototypes)
  2137. if (Proto->getNameInit() == CurRec->getNameInit())
  2138. return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
  2139. "' already defined in this multiclass!");
  2140. CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
  2141. // Copy the template arguments for the multiclass into the new def.
  2142. for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
  2143. const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
  2144. assert(RV && "Template arg doesn't exist?");
  2145. CurRec->addValue(*RV);
  2146. }
  2147. return false;
  2148. }
  2149. /// ParseDefm - Parse the instantiation of a multiclass.
  2150. ///
  2151. /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
  2152. ///
  2153. bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
  2154. assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
  2155. SMLoc DefmLoc = Lex.getLoc();
  2156. Init *DefmPrefix = nullptr;
  2157. if (Lex.Lex() == tgtok::Id) { // eat the defm.
  2158. DefmPrefix = ParseObjectName(CurMultiClass);
  2159. }
  2160. SMLoc DefmPrefixEndLoc = Lex.getLoc();
  2161. if (Lex.getCode() != tgtok::colon)
  2162. return TokError("expected ':' after defm identifier");
  2163. // Keep track of the new generated record definitions.
  2164. std::vector<Record*> NewRecDefs;
  2165. // This record also inherits from a regular class (non-multiclass)?
  2166. bool InheritFromClass = false;
  2167. // eat the colon.
  2168. Lex.Lex();
  2169. SMLoc SubClassLoc = Lex.getLoc();
  2170. SubClassReference Ref = ParseSubClassReference(nullptr, true);
  2171. while (1) {
  2172. if (!Ref.Rec) return true;
  2173. // To instantiate a multiclass, we need to first get the multiclass, then
  2174. // instantiate each def contained in the multiclass with the SubClassRef
  2175. // template parameters.
  2176. MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
  2177. assert(MC && "Didn't lookup multiclass correctly?");
  2178. std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
  2179. // Verify that the correct number of template arguments were specified.
  2180. const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
  2181. if (TArgs.size() < TemplateVals.size())
  2182. return Error(SubClassLoc,
  2183. "more template args specified than multiclass expects");
  2184. // Loop over all the def's in the multiclass, instantiating each one.
  2185. for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
  2186. // The record name construction goes as follow:
  2187. // - If the def name is a string, prepend the prefix.
  2188. // - If the def name is a more complex pattern, use that pattern.
  2189. // As a result, the record is instanciated before resolving
  2190. // arguments, as it would make its name a string.
  2191. Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
  2192. SMRange(DefmLoc,
  2193. DefmPrefixEndLoc),
  2194. TArgs, TemplateVals);
  2195. if (!CurRec)
  2196. return true;
  2197. // Now that the record is instanciated, we can resolve arguments.
  2198. if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
  2199. TArgs, TemplateVals, true/*Delete args*/))
  2200. return Error(SubClassLoc, "could not instantiate def");
  2201. if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
  2202. return Error(SubClassLoc, "could not instantiate def");
  2203. // Defs that can be used by other definitions should be fully resolved
  2204. // before any use.
  2205. if (DefProto->isResolveFirst() && !CurMultiClass) {
  2206. CurRec->resolveReferences();
  2207. CurRec->setResolveFirst(false);
  2208. }
  2209. NewRecDefs.push_back(CurRec);
  2210. }
  2211. if (Lex.getCode() != tgtok::comma) break;
  2212. Lex.Lex(); // eat ','.
  2213. if (Lex.getCode() != tgtok::Id)
  2214. return TokError("expected identifier");
  2215. SubClassLoc = Lex.getLoc();
  2216. // A defm can inherit from regular classes (non-multiclass) as
  2217. // long as they come in the end of the inheritance list.
  2218. InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
  2219. if (InheritFromClass)
  2220. break;
  2221. Ref = ParseSubClassReference(nullptr, true);
  2222. }
  2223. if (InheritFromClass) {
  2224. // Process all the classes to inherit as if they were part of a
  2225. // regular 'def' and inherit all record values.
  2226. SubClassReference SubClass = ParseSubClassReference(nullptr, false);
  2227. while (1) {
  2228. // Check for error.
  2229. if (!SubClass.Rec) return true;
  2230. // Get the expanded definition prototypes and teach them about
  2231. // the record values the current class to inherit has
  2232. for (Record *CurRec : NewRecDefs) {
  2233. // Add it.
  2234. if (AddSubClass(CurRec, SubClass))
  2235. return true;
  2236. if (ApplyLetStack(CurRec))
  2237. return true;
  2238. }
  2239. if (Lex.getCode() != tgtok::comma) break;
  2240. Lex.Lex(); // eat ','.
  2241. SubClass = ParseSubClassReference(nullptr, false);
  2242. }
  2243. }
  2244. if (!CurMultiClass)
  2245. for (Record *CurRec : NewRecDefs)
  2246. // See Record::setName(). This resolve step will see any new
  2247. // name for the def that might have been created when resolving
  2248. // inheritance, values and arguments above.
  2249. CurRec->resolveReferences();
  2250. if (Lex.getCode() != tgtok::semi)
  2251. return TokError("expected ';' at end of defm");
  2252. Lex.Lex();
  2253. return false;
  2254. }
  2255. /// ParseObject
  2256. /// Object ::= ClassInst
  2257. /// Object ::= DefInst
  2258. /// Object ::= MultiClassInst
  2259. /// Object ::= DefMInst
  2260. /// Object ::= LETCommand '{' ObjectList '}'
  2261. /// Object ::= LETCommand Object
  2262. bool TGParser::ParseObject(MultiClass *MC) {
  2263. switch (Lex.getCode()) {
  2264. default:
  2265. return TokError("Expected class, def, defm, multiclass or let definition");
  2266. case tgtok::Let: return ParseTopLevelLet(MC);
  2267. case tgtok::Def: return ParseDef(MC);
  2268. case tgtok::Foreach: return ParseForeach(MC);
  2269. case tgtok::Defm: return ParseDefm(MC);
  2270. case tgtok::Class: return ParseClass();
  2271. case tgtok::MultiClass: return ParseMultiClass();
  2272. }
  2273. }
  2274. /// ParseObjectList
  2275. /// ObjectList :== Object*
  2276. bool TGParser::ParseObjectList(MultiClass *MC) {
  2277. while (isObjectStart(Lex.getCode())) {
  2278. if (ParseObject(MC))
  2279. return true;
  2280. }
  2281. return false;
  2282. }
  2283. bool TGParser::ParseFile() {
  2284. Lex.Lex(); // Prime the lexer.
  2285. if (ParseObjectList()) return true;
  2286. // If we have unread input at the end of the file, report it.
  2287. if (Lex.getCode() == tgtok::Eof)
  2288. return false;
  2289. return TokError("Unexpected input at top level");
  2290. }