TGParser.cpp 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701
  1. //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Implement the Parser for TableGen.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "TGParser.h"
  13. #include "llvm/ADT/None.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallVector.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Config/llvm-config.h"
  19. #include "llvm/Support/Casting.h"
  20. #include "llvm/Support/Compiler.h"
  21. #include "llvm/Support/ErrorHandling.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. #include "llvm/Support/SourceMgr.h"
  24. #include <algorithm>
  25. #include <cassert>
  26. #include <cstdint>
  27. #include <limits>
  28. using namespace llvm;
  29. //===----------------------------------------------------------------------===//
  30. // Support Code for the Semantic Actions.
  31. //===----------------------------------------------------------------------===//
  32. namespace llvm {
  33. struct SubClassReference {
  34. SMRange RefRange;
  35. Record *Rec;
  36. SmallVector<Init*, 4> TemplateArgs;
  37. SubClassReference() : Rec(nullptr) {}
  38. bool isInvalid() const { return Rec == nullptr; }
  39. };
  40. struct SubMultiClassReference {
  41. SMRange RefRange;
  42. MultiClass *MC;
  43. SmallVector<Init*, 4> TemplateArgs;
  44. SubMultiClassReference() : MC(nullptr) {}
  45. bool isInvalid() const { return MC == nullptr; }
  46. void dump() const;
  47. };
  48. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  49. LLVM_DUMP_METHOD void SubMultiClassReference::dump() const {
  50. errs() << "Multiclass:\n";
  51. MC->dump();
  52. errs() << "Template args:\n";
  53. for (Init *TA : TemplateArgs)
  54. TA->dump();
  55. }
  56. #endif
  57. } // end namespace llvm
  58. static bool checkBitsConcrete(Record &R, const RecordVal &RV) {
  59. BitsInit *BV = cast<BitsInit>(RV.getValue());
  60. for (unsigned i = 0, e = BV->getNumBits(); i != e; ++i) {
  61. Init *Bit = BV->getBit(i);
  62. bool IsReference = false;
  63. if (auto VBI = dyn_cast<VarBitInit>(Bit)) {
  64. if (auto VI = dyn_cast<VarInit>(VBI->getBitVar())) {
  65. if (R.getValue(VI->getName()))
  66. IsReference = true;
  67. }
  68. } else if (isa<VarInit>(Bit)) {
  69. IsReference = true;
  70. }
  71. if (!(IsReference || Bit->isConcrete()))
  72. return false;
  73. }
  74. return true;
  75. }
  76. static void checkConcrete(Record &R) {
  77. for (const RecordVal &RV : R.getValues()) {
  78. // HACK: Disable this check for variables declared with 'field'. This is
  79. // done merely because existing targets have legitimate cases of
  80. // non-concrete variables in helper defs. Ideally, we'd introduce a
  81. // 'maybe' or 'optional' modifier instead of this.
  82. if (RV.isNonconcreteOK())
  83. continue;
  84. if (Init *V = RV.getValue()) {
  85. bool Ok = isa<BitsInit>(V) ? checkBitsConcrete(R, RV) : V->isConcrete();
  86. if (!Ok) {
  87. PrintError(R.getLoc(),
  88. Twine("Initializer of '") + RV.getNameInitAsString() +
  89. "' in '" + R.getNameInitAsString() +
  90. "' could not be fully resolved: " +
  91. RV.getValue()->getAsString());
  92. }
  93. }
  94. }
  95. }
  96. /// Return an Init with a qualifier prefix referring
  97. /// to CurRec's name.
  98. static Init *QualifyName(Record &CurRec, MultiClass *CurMultiClass,
  99. Init *Name, StringRef Scoper) {
  100. Init *NewName =
  101. BinOpInit::getStrConcat(CurRec.getNameInit(), StringInit::get(Scoper));
  102. NewName = BinOpInit::getStrConcat(NewName, Name);
  103. if (CurMultiClass && Scoper != "::") {
  104. Init *Prefix = BinOpInit::getStrConcat(CurMultiClass->Rec.getNameInit(),
  105. StringInit::get("::"));
  106. NewName = BinOpInit::getStrConcat(Prefix, NewName);
  107. }
  108. if (BinOpInit *BinOp = dyn_cast<BinOpInit>(NewName))
  109. NewName = BinOp->Fold(&CurRec);
  110. return NewName;
  111. }
  112. /// Return the qualified version of the implicit 'NAME' template argument.
  113. static Init *QualifiedNameOfImplicitName(Record &Rec,
  114. MultiClass *MC = nullptr) {
  115. return QualifyName(Rec, MC, StringInit::get("NAME"), MC ? "::" : ":");
  116. }
  117. static Init *QualifiedNameOfImplicitName(MultiClass *MC) {
  118. return QualifiedNameOfImplicitName(MC->Rec, MC);
  119. }
  120. bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
  121. if (!CurRec)
  122. CurRec = &CurMultiClass->Rec;
  123. if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
  124. // The value already exists in the class, treat this as a set.
  125. if (ERV->setValue(RV.getValue()))
  126. return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
  127. RV.getType()->getAsString() + "' is incompatible with " +
  128. "previous definition of type '" +
  129. ERV->getType()->getAsString() + "'");
  130. } else {
  131. CurRec->addValue(RV);
  132. }
  133. return false;
  134. }
  135. /// SetValue -
  136. /// Return true on error, false on success.
  137. bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
  138. ArrayRef<unsigned> BitList, Init *V,
  139. bool AllowSelfAssignment) {
  140. if (!V) return false;
  141. if (!CurRec) CurRec = &CurMultiClass->Rec;
  142. RecordVal *RV = CurRec->getValue(ValName);
  143. if (!RV)
  144. return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
  145. "' unknown!");
  146. // Do not allow assignments like 'X = X'. This will just cause infinite loops
  147. // in the resolution machinery.
  148. if (BitList.empty())
  149. if (VarInit *VI = dyn_cast<VarInit>(V))
  150. if (VI->getNameInit() == ValName && !AllowSelfAssignment)
  151. return Error(Loc, "Recursion / self-assignment forbidden");
  152. // If we are assigning to a subset of the bits in the value... then we must be
  153. // assigning to a field of BitsRecTy, which must have a BitsInit
  154. // initializer.
  155. //
  156. if (!BitList.empty()) {
  157. BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
  158. if (!CurVal)
  159. return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
  160. "' is not a bits type");
  161. // Convert the incoming value to a bits type of the appropriate size...
  162. Init *BI = V->getCastTo(BitsRecTy::get(BitList.size()));
  163. if (!BI)
  164. return Error(Loc, "Initializer is not compatible with bit range");
  165. SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
  166. // Loop over bits, assigning values as appropriate.
  167. for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
  168. unsigned Bit = BitList[i];
  169. if (NewBits[Bit])
  170. return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
  171. ValName->getAsUnquotedString() + "' more than once");
  172. NewBits[Bit] = BI->getBit(i);
  173. }
  174. for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
  175. if (!NewBits[i])
  176. NewBits[i] = CurVal->getBit(i);
  177. V = BitsInit::get(NewBits);
  178. }
  179. if (RV->setValue(V, Loc)) {
  180. std::string InitType;
  181. if (BitsInit *BI = dyn_cast<BitsInit>(V))
  182. InitType = (Twine("' of type bit initializer with length ") +
  183. Twine(BI->getNumBits())).str();
  184. else if (TypedInit *TI = dyn_cast<TypedInit>(V))
  185. InitType = (Twine("' of type '") + TI->getType()->getAsString()).str();
  186. return Error(Loc, "Field '" + ValName->getAsUnquotedString() +
  187. "' of type '" + RV->getType()->getAsString() +
  188. "' is incompatible with value '" +
  189. V->getAsString() + InitType + "'");
  190. }
  191. return false;
  192. }
  193. /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
  194. /// args as SubClass's template arguments.
  195. bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
  196. Record *SC = SubClass.Rec;
  197. // Add all of the values in the subclass into the current class.
  198. for (const RecordVal &Val : SC->getValues())
  199. if (AddValue(CurRec, SubClass.RefRange.Start, Val))
  200. return true;
  201. ArrayRef<Init *> TArgs = SC->getTemplateArgs();
  202. // Ensure that an appropriate number of template arguments are specified.
  203. if (TArgs.size() < SubClass.TemplateArgs.size())
  204. return Error(SubClass.RefRange.Start,
  205. "More template args specified than expected");
  206. // Loop over all of the template arguments, setting them to the specified
  207. // value or leaving them as the default if necessary.
  208. MapResolver R(CurRec);
  209. for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
  210. if (i < SubClass.TemplateArgs.size()) {
  211. // If a value is specified for this template arg, set it now.
  212. if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
  213. None, SubClass.TemplateArgs[i]))
  214. return true;
  215. } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
  216. return Error(SubClass.RefRange.Start,
  217. "Value not specified for template argument #" +
  218. Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
  219. ") of subclass '" + SC->getNameInitAsString() + "'!");
  220. }
  221. R.set(TArgs[i], CurRec->getValue(TArgs[i])->getValue());
  222. CurRec->removeValue(TArgs[i]);
  223. }
  224. Init *Name;
  225. if (CurRec->isClass())
  226. Name =
  227. VarInit::get(QualifiedNameOfImplicitName(*CurRec), StringRecTy::get());
  228. else
  229. Name = CurRec->getNameInit();
  230. R.set(QualifiedNameOfImplicitName(*SC), Name);
  231. CurRec->resolveReferences(R);
  232. // Since everything went well, we can now set the "superclass" list for the
  233. // current record.
  234. ArrayRef<std::pair<Record *, SMRange>> SCs = SC->getSuperClasses();
  235. for (const auto &SCPair : SCs) {
  236. if (CurRec->isSubClassOf(SCPair.first))
  237. return Error(SubClass.RefRange.Start,
  238. "Already subclass of '" + SCPair.first->getName() + "'!\n");
  239. CurRec->addSuperClass(SCPair.first, SCPair.second);
  240. }
  241. if (CurRec->isSubClassOf(SC))
  242. return Error(SubClass.RefRange.Start,
  243. "Already subclass of '" + SC->getName() + "'!\n");
  244. CurRec->addSuperClass(SC, SubClass.RefRange);
  245. return false;
  246. }
  247. bool TGParser::AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass) {
  248. if (Entry.Rec)
  249. return AddSubClass(Entry.Rec.get(), SubClass);
  250. for (auto &E : Entry.Loop->Entries) {
  251. if (AddSubClass(E, SubClass))
  252. return true;
  253. }
  254. return false;
  255. }
  256. /// AddSubMultiClass - Add SubMultiClass as a subclass to
  257. /// CurMC, resolving its template args as SubMultiClass's
  258. /// template arguments.
  259. bool TGParser::AddSubMultiClass(MultiClass *CurMC,
  260. SubMultiClassReference &SubMultiClass) {
  261. MultiClass *SMC = SubMultiClass.MC;
  262. ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
  263. if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
  264. return Error(SubMultiClass.RefRange.Start,
  265. "More template args specified than expected");
  266. // Prepare the mapping of template argument name to value, filling in default
  267. // values if necessary.
  268. SubstStack TemplateArgs;
  269. for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
  270. if (i < SubMultiClass.TemplateArgs.size()) {
  271. TemplateArgs.emplace_back(SMCTArgs[i], SubMultiClass.TemplateArgs[i]);
  272. } else {
  273. Init *Default = SMC->Rec.getValue(SMCTArgs[i])->getValue();
  274. if (!Default->isComplete()) {
  275. return Error(SubMultiClass.RefRange.Start,
  276. "value not specified for template argument #" + Twine(i) +
  277. " (" + SMCTArgs[i]->getAsUnquotedString() +
  278. ") of multiclass '" + SMC->Rec.getNameInitAsString() +
  279. "'");
  280. }
  281. TemplateArgs.emplace_back(SMCTArgs[i], Default);
  282. }
  283. }
  284. TemplateArgs.emplace_back(
  285. QualifiedNameOfImplicitName(SMC),
  286. VarInit::get(QualifiedNameOfImplicitName(CurMC), StringRecTy::get()));
  287. // Add all of the defs in the subclass into the current multiclass.
  288. return resolve(SMC->Entries, TemplateArgs, false, &CurMC->Entries);
  289. }
  290. /// Add a record or foreach loop to the current context (global record keeper,
  291. /// current inner-most foreach loop, or multiclass).
  292. bool TGParser::addEntry(RecordsEntry E) {
  293. assert(!E.Rec || !E.Loop);
  294. if (!Loops.empty()) {
  295. Loops.back()->Entries.push_back(std::move(E));
  296. return false;
  297. }
  298. if (E.Loop) {
  299. SubstStack Stack;
  300. return resolve(*E.Loop, Stack, CurMultiClass == nullptr,
  301. CurMultiClass ? &CurMultiClass->Entries : nullptr);
  302. }
  303. if (CurMultiClass) {
  304. CurMultiClass->Entries.push_back(std::move(E));
  305. return false;
  306. }
  307. return addDefOne(std::move(E.Rec));
  308. }
  309. /// Resolve the entries in \p Loop, going over inner loops recursively
  310. /// and making the given subsitutions of (name, value) pairs.
  311. ///
  312. /// The resulting records are stored in \p Dest if non-null. Otherwise, they
  313. /// are added to the global record keeper.
  314. bool TGParser::resolve(const ForeachLoop &Loop, SubstStack &Substs,
  315. bool Final, std::vector<RecordsEntry> *Dest,
  316. SMLoc *Loc) {
  317. MapResolver R;
  318. for (const auto &S : Substs)
  319. R.set(S.first, S.second);
  320. Init *List = Loop.ListValue->resolveReferences(R);
  321. auto LI = dyn_cast<ListInit>(List);
  322. if (!LI) {
  323. if (!Final) {
  324. Dest->emplace_back(std::make_unique<ForeachLoop>(Loop.Loc, Loop.IterVar,
  325. List));
  326. return resolve(Loop.Entries, Substs, Final, &Dest->back().Loop->Entries,
  327. Loc);
  328. }
  329. PrintError(Loop.Loc, Twine("attempting to loop over '") +
  330. List->getAsString() + "', expected a list");
  331. return true;
  332. }
  333. bool Error = false;
  334. for (auto Elt : *LI) {
  335. if (Loop.IterVar)
  336. Substs.emplace_back(Loop.IterVar->getNameInit(), Elt);
  337. Error = resolve(Loop.Entries, Substs, Final, Dest);
  338. if (Loop.IterVar)
  339. Substs.pop_back();
  340. if (Error)
  341. break;
  342. }
  343. return Error;
  344. }
  345. /// Resolve the entries in \p Source, going over loops recursively and
  346. /// making the given substitutions of (name, value) pairs.
  347. ///
  348. /// The resulting records are stored in \p Dest if non-null. Otherwise, they
  349. /// are added to the global record keeper.
  350. bool TGParser::resolve(const std::vector<RecordsEntry> &Source,
  351. SubstStack &Substs, bool Final,
  352. std::vector<RecordsEntry> *Dest, SMLoc *Loc) {
  353. bool Error = false;
  354. for (auto &E : Source) {
  355. if (E.Loop) {
  356. Error = resolve(*E.Loop, Substs, Final, Dest);
  357. } else {
  358. auto Rec = std::make_unique<Record>(*E.Rec);
  359. if (Loc)
  360. Rec->appendLoc(*Loc);
  361. MapResolver R(Rec.get());
  362. for (const auto &S : Substs)
  363. R.set(S.first, S.second);
  364. Rec->resolveReferences(R);
  365. if (Dest)
  366. Dest->push_back(std::move(Rec));
  367. else
  368. Error = addDefOne(std::move(Rec));
  369. }
  370. if (Error)
  371. break;
  372. }
  373. return Error;
  374. }
  375. /// Resolve the record fully and add it to the record keeper.
  376. bool TGParser::addDefOne(std::unique_ptr<Record> Rec) {
  377. if (Record *Prev = Records.getDef(Rec->getNameInitAsString())) {
  378. if (!Rec->isAnonymous()) {
  379. PrintError(Rec->getLoc(),
  380. "def already exists: " + Rec->getNameInitAsString());
  381. PrintNote(Prev->getLoc(), "location of previous definition");
  382. return true;
  383. }
  384. Rec->setName(Records.getNewAnonymousName());
  385. }
  386. Rec->resolveReferences();
  387. checkConcrete(*Rec);
  388. CheckRecordAsserts(*Rec);
  389. if (!isa<StringInit>(Rec->getNameInit())) {
  390. PrintError(Rec->getLoc(), Twine("record name '") +
  391. Rec->getNameInit()->getAsString() +
  392. "' could not be fully resolved");
  393. return true;
  394. }
  395. // If ObjectBody has template arguments, it's an error.
  396. assert(Rec->getTemplateArgs().empty() && "How'd this get template args?");
  397. for (DefsetRecord *Defset : Defsets) {
  398. DefInit *I = Rec->getDefInit();
  399. if (!I->getType()->typeIsA(Defset->EltTy)) {
  400. PrintError(Rec->getLoc(), Twine("adding record of incompatible type '") +
  401. I->getType()->getAsString() +
  402. "' to defset");
  403. PrintNote(Defset->Loc, "location of defset declaration");
  404. return true;
  405. }
  406. Defset->Elements.push_back(I);
  407. }
  408. Records.addDef(std::move(Rec));
  409. return false;
  410. }
  411. //===----------------------------------------------------------------------===//
  412. // Parser Code
  413. //===----------------------------------------------------------------------===//
  414. /// isObjectStart - Return true if this is a valid first token for a statement.
  415. static bool isObjectStart(tgtok::TokKind K) {
  416. return K == tgtok::Assert || K == tgtok::Class || K == tgtok::Def ||
  417. K == tgtok::Defm || K == tgtok::Defset || K == tgtok::Defvar ||
  418. K == tgtok::Foreach || K == tgtok::If || K == tgtok::Let ||
  419. K == tgtok::MultiClass;
  420. }
  421. bool TGParser::consume(tgtok::TokKind K) {
  422. if (Lex.getCode() == K) {
  423. Lex.Lex();
  424. return true;
  425. }
  426. return false;
  427. }
  428. /// ParseObjectName - If a valid object name is specified, return it. If no
  429. /// name is specified, return the unset initializer. Return nullptr on parse
  430. /// error.
  431. /// ObjectName ::= Value [ '#' Value ]*
  432. /// ObjectName ::= /*empty*/
  433. ///
  434. Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
  435. switch (Lex.getCode()) {
  436. case tgtok::colon:
  437. case tgtok::semi:
  438. case tgtok::l_brace:
  439. // These are all of the tokens that can begin an object body.
  440. // Some of these can also begin values but we disallow those cases
  441. // because they are unlikely to be useful.
  442. return UnsetInit::get();
  443. default:
  444. break;
  445. }
  446. Record *CurRec = nullptr;
  447. if (CurMultiClass)
  448. CurRec = &CurMultiClass->Rec;
  449. Init *Name = ParseValue(CurRec, StringRecTy::get(), ParseNameMode);
  450. if (!Name)
  451. return nullptr;
  452. if (CurMultiClass) {
  453. Init *NameStr = QualifiedNameOfImplicitName(CurMultiClass);
  454. HasReferenceResolver R(NameStr);
  455. Name->resolveReferences(R);
  456. if (!R.found())
  457. Name = BinOpInit::getStrConcat(VarInit::get(NameStr, StringRecTy::get()),
  458. Name);
  459. }
  460. return Name;
  461. }
  462. /// ParseClassID - Parse and resolve a reference to a class name. This returns
  463. /// null on error.
  464. ///
  465. /// ClassID ::= ID
  466. ///
  467. Record *TGParser::ParseClassID() {
  468. if (Lex.getCode() != tgtok::Id) {
  469. TokError("expected name for ClassID");
  470. return nullptr;
  471. }
  472. Record *Result = Records.getClass(Lex.getCurStrVal());
  473. if (!Result) {
  474. std::string Msg("Couldn't find class '" + Lex.getCurStrVal() + "'");
  475. if (MultiClasses[Lex.getCurStrVal()].get())
  476. TokError(Msg + ". Use 'defm' if you meant to use multiclass '" +
  477. Lex.getCurStrVal() + "'");
  478. else
  479. TokError(Msg);
  480. }
  481. Lex.Lex();
  482. return Result;
  483. }
  484. /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
  485. /// This returns null on error.
  486. ///
  487. /// MultiClassID ::= ID
  488. ///
  489. MultiClass *TGParser::ParseMultiClassID() {
  490. if (Lex.getCode() != tgtok::Id) {
  491. TokError("expected name for MultiClassID");
  492. return nullptr;
  493. }
  494. MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
  495. if (!Result)
  496. TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
  497. Lex.Lex();
  498. return Result;
  499. }
  500. /// ParseSubClassReference - Parse a reference to a subclass or to a templated
  501. /// subclass. This returns a SubClassRefTy with a null Record* on error.
  502. ///
  503. /// SubClassRef ::= ClassID
  504. /// SubClassRef ::= ClassID '<' ValueList '>'
  505. ///
  506. SubClassReference TGParser::
  507. ParseSubClassReference(Record *CurRec, bool isDefm) {
  508. SubClassReference Result;
  509. Result.RefRange.Start = Lex.getLoc();
  510. if (isDefm) {
  511. if (MultiClass *MC = ParseMultiClassID())
  512. Result.Rec = &MC->Rec;
  513. } else {
  514. Result.Rec = ParseClassID();
  515. }
  516. if (!Result.Rec) return Result;
  517. // If there is no template arg list, we're done.
  518. if (!consume(tgtok::less)) {
  519. Result.RefRange.End = Lex.getLoc();
  520. return Result;
  521. }
  522. if (Lex.getCode() == tgtok::greater) {
  523. TokError("subclass reference requires a non-empty list of template values");
  524. Result.Rec = nullptr;
  525. return Result;
  526. }
  527. ParseValueList(Result.TemplateArgs, CurRec, Result.Rec);
  528. if (Result.TemplateArgs.empty()) {
  529. Result.Rec = nullptr; // Error parsing value list.
  530. return Result;
  531. }
  532. if (!consume(tgtok::greater)) {
  533. TokError("expected '>' in template value list");
  534. Result.Rec = nullptr;
  535. return Result;
  536. }
  537. Result.RefRange.End = Lex.getLoc();
  538. return Result;
  539. }
  540. /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
  541. /// templated submulticlass. This returns a SubMultiClassRefTy with a null
  542. /// Record* on error.
  543. ///
  544. /// SubMultiClassRef ::= MultiClassID
  545. /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
  546. ///
  547. SubMultiClassReference TGParser::
  548. ParseSubMultiClassReference(MultiClass *CurMC) {
  549. SubMultiClassReference Result;
  550. Result.RefRange.Start = Lex.getLoc();
  551. Result.MC = ParseMultiClassID();
  552. if (!Result.MC) return Result;
  553. // If there is no template arg list, we're done.
  554. if (!consume(tgtok::less)) {
  555. Result.RefRange.End = Lex.getLoc();
  556. return Result;
  557. }
  558. if (Lex.getCode() == tgtok::greater) {
  559. TokError("subclass reference requires a non-empty list of template values");
  560. Result.MC = nullptr;
  561. return Result;
  562. }
  563. ParseValueList(Result.TemplateArgs, &CurMC->Rec, &Result.MC->Rec);
  564. if (Result.TemplateArgs.empty()) {
  565. Result.MC = nullptr; // Error parsing value list.
  566. return Result;
  567. }
  568. if (!consume(tgtok::greater)) {
  569. TokError("expected '>' in template value list");
  570. Result.MC = nullptr;
  571. return Result;
  572. }
  573. Result.RefRange.End = Lex.getLoc();
  574. return Result;
  575. }
  576. /// ParseRangePiece - Parse a bit/value range.
  577. /// RangePiece ::= INTVAL
  578. /// RangePiece ::= INTVAL '...' INTVAL
  579. /// RangePiece ::= INTVAL '-' INTVAL
  580. /// RangePiece ::= INTVAL INTVAL
  581. // The last two forms are deprecated.
  582. bool TGParser::ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
  583. TypedInit *FirstItem) {
  584. Init *CurVal = FirstItem;
  585. if (!CurVal)
  586. CurVal = ParseValue(nullptr);
  587. IntInit *II = dyn_cast_or_null<IntInit>(CurVal);
  588. if (!II)
  589. return TokError("expected integer or bitrange");
  590. int64_t Start = II->getValue();
  591. int64_t End;
  592. if (Start < 0)
  593. return TokError("invalid range, cannot be negative");
  594. switch (Lex.getCode()) {
  595. default:
  596. Ranges.push_back(Start);
  597. return false;
  598. case tgtok::dotdotdot:
  599. case tgtok::minus: {
  600. Lex.Lex(); // eat
  601. Init *I_End = ParseValue(nullptr);
  602. IntInit *II_End = dyn_cast_or_null<IntInit>(I_End);
  603. if (!II_End) {
  604. TokError("expected integer value as end of range");
  605. return true;
  606. }
  607. End = II_End->getValue();
  608. break;
  609. }
  610. case tgtok::IntVal: {
  611. End = -Lex.getCurIntVal();
  612. Lex.Lex();
  613. break;
  614. }
  615. }
  616. if (End < 0)
  617. return TokError("invalid range, cannot be negative");
  618. // Add to the range.
  619. if (Start < End)
  620. for (; Start <= End; ++Start)
  621. Ranges.push_back(Start);
  622. else
  623. for (; Start >= End; --Start)
  624. Ranges.push_back(Start);
  625. return false;
  626. }
  627. /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
  628. ///
  629. /// RangeList ::= RangePiece (',' RangePiece)*
  630. ///
  631. void TGParser::ParseRangeList(SmallVectorImpl<unsigned> &Result) {
  632. // Parse the first piece.
  633. if (ParseRangePiece(Result)) {
  634. Result.clear();
  635. return;
  636. }
  637. while (consume(tgtok::comma))
  638. // Parse the next range piece.
  639. if (ParseRangePiece(Result)) {
  640. Result.clear();
  641. return;
  642. }
  643. }
  644. /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
  645. /// OptionalRangeList ::= '<' RangeList '>'
  646. /// OptionalRangeList ::= /*empty*/
  647. bool TGParser::ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges) {
  648. SMLoc StartLoc = Lex.getLoc();
  649. if (!consume(tgtok::less))
  650. return false;
  651. // Parse the range list.
  652. ParseRangeList(Ranges);
  653. if (Ranges.empty()) return true;
  654. if (!consume(tgtok::greater)) {
  655. TokError("expected '>' at end of range list");
  656. return Error(StartLoc, "to match this '<'");
  657. }
  658. return false;
  659. }
  660. /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
  661. /// OptionalBitList ::= '{' RangeList '}'
  662. /// OptionalBitList ::= /*empty*/
  663. bool TGParser::ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges) {
  664. SMLoc StartLoc = Lex.getLoc();
  665. if (!consume(tgtok::l_brace))
  666. return false;
  667. // Parse the range list.
  668. ParseRangeList(Ranges);
  669. if (Ranges.empty()) return true;
  670. if (!consume(tgtok::r_brace)) {
  671. TokError("expected '}' at end of bit list");
  672. return Error(StartLoc, "to match this '{'");
  673. }
  674. return false;
  675. }
  676. /// ParseType - Parse and return a tblgen type. This returns null on error.
  677. ///
  678. /// Type ::= STRING // string type
  679. /// Type ::= CODE // code type
  680. /// Type ::= BIT // bit type
  681. /// Type ::= BITS '<' INTVAL '>' // bits<x> type
  682. /// Type ::= INT // int type
  683. /// Type ::= LIST '<' Type '>' // list<x> type
  684. /// Type ::= DAG // dag type
  685. /// Type ::= ClassID // Record Type
  686. ///
  687. RecTy *TGParser::ParseType() {
  688. switch (Lex.getCode()) {
  689. default: TokError("Unknown token when expecting a type"); return nullptr;
  690. case tgtok::String:
  691. case tgtok::Code: Lex.Lex(); return StringRecTy::get();
  692. case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
  693. case tgtok::Int: Lex.Lex(); return IntRecTy::get();
  694. case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
  695. case tgtok::Id:
  696. if (Record *R = ParseClassID()) return RecordRecTy::get(R);
  697. TokError("unknown class name");
  698. return nullptr;
  699. case tgtok::Bits: {
  700. if (Lex.Lex() != tgtok::less) { // Eat 'bits'
  701. TokError("expected '<' after bits type");
  702. return nullptr;
  703. }
  704. if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
  705. TokError("expected integer in bits<n> type");
  706. return nullptr;
  707. }
  708. uint64_t Val = Lex.getCurIntVal();
  709. if (Lex.Lex() != tgtok::greater) { // Eat count.
  710. TokError("expected '>' at end of bits<n> type");
  711. return nullptr;
  712. }
  713. Lex.Lex(); // Eat '>'
  714. return BitsRecTy::get(Val);
  715. }
  716. case tgtok::List: {
  717. if (Lex.Lex() != tgtok::less) { // Eat 'bits'
  718. TokError("expected '<' after list type");
  719. return nullptr;
  720. }
  721. Lex.Lex(); // Eat '<'
  722. RecTy *SubType = ParseType();
  723. if (!SubType) return nullptr;
  724. if (!consume(tgtok::greater)) {
  725. TokError("expected '>' at end of list<ty> type");
  726. return nullptr;
  727. }
  728. return ListRecTy::get(SubType);
  729. }
  730. }
  731. }
  732. /// ParseIDValue
  733. Init *TGParser::ParseIDValue(Record *CurRec, StringInit *Name, SMLoc NameLoc,
  734. IDParseMode Mode) {
  735. if (CurRec) {
  736. if (const RecordVal *RV = CurRec->getValue(Name))
  737. return VarInit::get(Name, RV->getType());
  738. }
  739. if ((CurRec && CurRec->isClass()) || CurMultiClass) {
  740. Init *TemplateArgName;
  741. if (CurMultiClass) {
  742. TemplateArgName =
  743. QualifyName(CurMultiClass->Rec, CurMultiClass, Name, "::");
  744. } else
  745. TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
  746. Record *TemplateRec = CurMultiClass ? &CurMultiClass->Rec : CurRec;
  747. if (TemplateRec->isTemplateArg(TemplateArgName)) {
  748. const RecordVal *RV = TemplateRec->getValue(TemplateArgName);
  749. assert(RV && "Template arg doesn't exist??");
  750. return VarInit::get(TemplateArgName, RV->getType());
  751. } else if (Name->getValue() == "NAME") {
  752. return VarInit::get(TemplateArgName, StringRecTy::get());
  753. }
  754. }
  755. if (CurLocalScope)
  756. if (Init *I = CurLocalScope->getVar(Name->getValue()))
  757. return I;
  758. // If this is in a foreach loop, make sure it's not a loop iterator
  759. for (const auto &L : Loops) {
  760. if (L->IterVar) {
  761. VarInit *IterVar = dyn_cast<VarInit>(L->IterVar);
  762. if (IterVar && IterVar->getNameInit() == Name)
  763. return IterVar;
  764. }
  765. }
  766. if (Mode == ParseNameMode)
  767. return Name;
  768. if (Init *I = Records.getGlobal(Name->getValue()))
  769. return I;
  770. // Allow self-references of concrete defs, but delay the lookup so that we
  771. // get the correct type.
  772. if (CurRec && !CurRec->isClass() && !CurMultiClass &&
  773. CurRec->getNameInit() == Name)
  774. return UnOpInit::get(UnOpInit::CAST, Name, CurRec->getType());
  775. Error(NameLoc, "Variable not defined: '" + Name->getValue() + "'");
  776. return nullptr;
  777. }
  778. /// ParseOperation - Parse an operator. This returns null on error.
  779. ///
  780. /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
  781. ///
  782. Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
  783. switch (Lex.getCode()) {
  784. default:
  785. TokError("unknown bang operator");
  786. return nullptr;
  787. case tgtok::XNOT:
  788. case tgtok::XHead:
  789. case tgtok::XTail:
  790. case tgtok::XSize:
  791. case tgtok::XEmpty:
  792. case tgtok::XCast:
  793. case tgtok::XGetDagOp: { // Value ::= !unop '(' Value ')'
  794. UnOpInit::UnaryOp Code;
  795. RecTy *Type = nullptr;
  796. switch (Lex.getCode()) {
  797. default: llvm_unreachable("Unhandled code!");
  798. case tgtok::XCast:
  799. Lex.Lex(); // eat the operation
  800. Code = UnOpInit::CAST;
  801. Type = ParseOperatorType();
  802. if (!Type) {
  803. TokError("did not get type for unary operator");
  804. return nullptr;
  805. }
  806. break;
  807. case tgtok::XNOT:
  808. Lex.Lex(); // eat the operation
  809. Code = UnOpInit::NOT;
  810. Type = IntRecTy::get();
  811. break;
  812. case tgtok::XHead:
  813. Lex.Lex(); // eat the operation
  814. Code = UnOpInit::HEAD;
  815. break;
  816. case tgtok::XTail:
  817. Lex.Lex(); // eat the operation
  818. Code = UnOpInit::TAIL;
  819. break;
  820. case tgtok::XSize:
  821. Lex.Lex();
  822. Code = UnOpInit::SIZE;
  823. Type = IntRecTy::get();
  824. break;
  825. case tgtok::XEmpty:
  826. Lex.Lex(); // eat the operation
  827. Code = UnOpInit::EMPTY;
  828. Type = IntRecTy::get();
  829. break;
  830. case tgtok::XGetDagOp:
  831. Lex.Lex(); // eat the operation
  832. if (Lex.getCode() == tgtok::less) {
  833. // Parse an optional type suffix, so that you can say
  834. // !getdagop<BaseClass>(someDag) as a shorthand for
  835. // !cast<BaseClass>(!getdagop(someDag)).
  836. Type = ParseOperatorType();
  837. if (!Type) {
  838. TokError("did not get type for unary operator");
  839. return nullptr;
  840. }
  841. if (!isa<RecordRecTy>(Type)) {
  842. TokError("type for !getdagop must be a record type");
  843. // but keep parsing, to consume the operand
  844. }
  845. } else {
  846. Type = RecordRecTy::get({});
  847. }
  848. Code = UnOpInit::GETDAGOP;
  849. break;
  850. }
  851. if (!consume(tgtok::l_paren)) {
  852. TokError("expected '(' after unary operator");
  853. return nullptr;
  854. }
  855. Init *LHS = ParseValue(CurRec);
  856. if (!LHS) return nullptr;
  857. if (Code == UnOpInit::EMPTY || Code == UnOpInit::SIZE) {
  858. ListInit *LHSl = dyn_cast<ListInit>(LHS);
  859. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  860. DagInit *LHSd = dyn_cast<DagInit>(LHS);
  861. TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
  862. if (!LHSl && !LHSs && !LHSd && !LHSt) {
  863. TokError("expected string, list, or dag type argument in unary operator");
  864. return nullptr;
  865. }
  866. if (LHSt) {
  867. ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
  868. StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
  869. DagRecTy *DType = dyn_cast<DagRecTy>(LHSt->getType());
  870. if (!LType && !SType && !DType) {
  871. TokError("expected string, list, or dag type argument in unary operator");
  872. return nullptr;
  873. }
  874. }
  875. }
  876. if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
  877. ListInit *LHSl = dyn_cast<ListInit>(LHS);
  878. TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
  879. if (!LHSl && !LHSt) {
  880. TokError("expected list type argument in unary operator");
  881. return nullptr;
  882. }
  883. if (LHSt) {
  884. ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
  885. if (!LType) {
  886. TokError("expected list type argument in unary operator");
  887. return nullptr;
  888. }
  889. }
  890. if (LHSl && LHSl->empty()) {
  891. TokError("empty list argument in unary operator");
  892. return nullptr;
  893. }
  894. if (LHSl) {
  895. Init *Item = LHSl->getElement(0);
  896. TypedInit *Itemt = dyn_cast<TypedInit>(Item);
  897. if (!Itemt) {
  898. TokError("untyped list element in unary operator");
  899. return nullptr;
  900. }
  901. Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
  902. : ListRecTy::get(Itemt->getType());
  903. } else {
  904. assert(LHSt && "expected list type argument in unary operator");
  905. ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
  906. Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
  907. }
  908. }
  909. if (!consume(tgtok::r_paren)) {
  910. TokError("expected ')' in unary operator");
  911. return nullptr;
  912. }
  913. return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec);
  914. }
  915. case tgtok::XIsA: {
  916. // Value ::= !isa '<' Type '>' '(' Value ')'
  917. Lex.Lex(); // eat the operation
  918. RecTy *Type = ParseOperatorType();
  919. if (!Type)
  920. return nullptr;
  921. if (!consume(tgtok::l_paren)) {
  922. TokError("expected '(' after type of !isa");
  923. return nullptr;
  924. }
  925. Init *LHS = ParseValue(CurRec);
  926. if (!LHS)
  927. return nullptr;
  928. if (!consume(tgtok::r_paren)) {
  929. TokError("expected ')' in !isa");
  930. return nullptr;
  931. }
  932. return (IsAOpInit::get(Type, LHS))->Fold();
  933. }
  934. case tgtok::XConcat:
  935. case tgtok::XADD:
  936. case tgtok::XSUB:
  937. case tgtok::XMUL:
  938. case tgtok::XAND:
  939. case tgtok::XOR:
  940. case tgtok::XXOR:
  941. case tgtok::XSRA:
  942. case tgtok::XSRL:
  943. case tgtok::XSHL:
  944. case tgtok::XEq:
  945. case tgtok::XNe:
  946. case tgtok::XLe:
  947. case tgtok::XLt:
  948. case tgtok::XGe:
  949. case tgtok::XGt:
  950. case tgtok::XListConcat:
  951. case tgtok::XListSplat:
  952. case tgtok::XStrConcat:
  953. case tgtok::XInterleave:
  954. case tgtok::XSetDagOp: { // Value ::= !binop '(' Value ',' Value ')'
  955. tgtok::TokKind OpTok = Lex.getCode();
  956. SMLoc OpLoc = Lex.getLoc();
  957. Lex.Lex(); // eat the operation
  958. BinOpInit::BinaryOp Code;
  959. switch (OpTok) {
  960. default: llvm_unreachable("Unhandled code!");
  961. case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
  962. case tgtok::XADD: Code = BinOpInit::ADD; break;
  963. case tgtok::XSUB: Code = BinOpInit::SUB; break;
  964. case tgtok::XMUL: Code = BinOpInit::MUL; break;
  965. case tgtok::XAND: Code = BinOpInit::AND; break;
  966. case tgtok::XOR: Code = BinOpInit::OR; break;
  967. case tgtok::XXOR: Code = BinOpInit::XOR; break;
  968. case tgtok::XSRA: Code = BinOpInit::SRA; break;
  969. case tgtok::XSRL: Code = BinOpInit::SRL; break;
  970. case tgtok::XSHL: Code = BinOpInit::SHL; break;
  971. case tgtok::XEq: Code = BinOpInit::EQ; break;
  972. case tgtok::XNe: Code = BinOpInit::NE; break;
  973. case tgtok::XLe: Code = BinOpInit::LE; break;
  974. case tgtok::XLt: Code = BinOpInit::LT; break;
  975. case tgtok::XGe: Code = BinOpInit::GE; break;
  976. case tgtok::XGt: Code = BinOpInit::GT; break;
  977. case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
  978. case tgtok::XListSplat: Code = BinOpInit::LISTSPLAT; break;
  979. case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
  980. case tgtok::XInterleave: Code = BinOpInit::INTERLEAVE; break;
  981. case tgtok::XSetDagOp: Code = BinOpInit::SETDAGOP; break;
  982. }
  983. RecTy *Type = nullptr;
  984. RecTy *ArgType = nullptr;
  985. switch (OpTok) {
  986. default:
  987. llvm_unreachable("Unhandled code!");
  988. case tgtok::XConcat:
  989. case tgtok::XSetDagOp:
  990. Type = DagRecTy::get();
  991. ArgType = DagRecTy::get();
  992. break;
  993. case tgtok::XAND:
  994. case tgtok::XOR:
  995. case tgtok::XXOR:
  996. case tgtok::XSRA:
  997. case tgtok::XSRL:
  998. case tgtok::XSHL:
  999. case tgtok::XADD:
  1000. case tgtok::XSUB:
  1001. case tgtok::XMUL:
  1002. Type = IntRecTy::get();
  1003. ArgType = IntRecTy::get();
  1004. break;
  1005. case tgtok::XEq:
  1006. case tgtok::XNe:
  1007. case tgtok::XLe:
  1008. case tgtok::XLt:
  1009. case tgtok::XGe:
  1010. case tgtok::XGt:
  1011. Type = BitRecTy::get();
  1012. // ArgType for the comparison operators is not yet known.
  1013. break;
  1014. case tgtok::XListConcat:
  1015. // We don't know the list type until we parse the first argument
  1016. ArgType = ItemType;
  1017. break;
  1018. case tgtok::XListSplat:
  1019. // Can't do any typechecking until we parse the first argument.
  1020. break;
  1021. case tgtok::XStrConcat:
  1022. Type = StringRecTy::get();
  1023. ArgType = StringRecTy::get();
  1024. break;
  1025. case tgtok::XInterleave:
  1026. Type = StringRecTy::get();
  1027. // The first argument type is not yet known.
  1028. }
  1029. if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
  1030. Error(OpLoc, Twine("expected value of type '") +
  1031. ItemType->getAsString() + "', got '" +
  1032. Type->getAsString() + "'");
  1033. return nullptr;
  1034. }
  1035. if (!consume(tgtok::l_paren)) {
  1036. TokError("expected '(' after binary operator");
  1037. return nullptr;
  1038. }
  1039. SmallVector<Init*, 2> InitList;
  1040. // Note that this loop consumes an arbitrary number of arguments.
  1041. // The actual count is checked later.
  1042. for (;;) {
  1043. SMLoc InitLoc = Lex.getLoc();
  1044. InitList.push_back(ParseValue(CurRec, ArgType));
  1045. if (!InitList.back()) return nullptr;
  1046. TypedInit *InitListBack = dyn_cast<TypedInit>(InitList.back());
  1047. if (!InitListBack) {
  1048. Error(OpLoc, Twine("expected value to be a typed value, got '" +
  1049. InitList.back()->getAsString() + "'"));
  1050. return nullptr;
  1051. }
  1052. RecTy *ListType = InitListBack->getType();
  1053. if (!ArgType) {
  1054. // Argument type must be determined from the argument itself.
  1055. ArgType = ListType;
  1056. switch (Code) {
  1057. case BinOpInit::LISTCONCAT:
  1058. if (!isa<ListRecTy>(ArgType)) {
  1059. Error(InitLoc, Twine("expected a list, got value of type '") +
  1060. ArgType->getAsString() + "'");
  1061. return nullptr;
  1062. }
  1063. break;
  1064. case BinOpInit::LISTSPLAT:
  1065. if (ItemType && InitList.size() == 1) {
  1066. if (!isa<ListRecTy>(ItemType)) {
  1067. Error(OpLoc,
  1068. Twine("expected output type to be a list, got type '") +
  1069. ItemType->getAsString() + "'");
  1070. return nullptr;
  1071. }
  1072. if (!ArgType->getListTy()->typeIsConvertibleTo(ItemType)) {
  1073. Error(OpLoc, Twine("expected first arg type to be '") +
  1074. ArgType->getAsString() +
  1075. "', got value of type '" +
  1076. cast<ListRecTy>(ItemType)
  1077. ->getElementType()
  1078. ->getAsString() +
  1079. "'");
  1080. return nullptr;
  1081. }
  1082. }
  1083. if (InitList.size() == 2 && !isa<IntRecTy>(ArgType)) {
  1084. Error(InitLoc, Twine("expected second parameter to be an int, got "
  1085. "value of type '") +
  1086. ArgType->getAsString() + "'");
  1087. return nullptr;
  1088. }
  1089. ArgType = nullptr; // Broken invariant: types not identical.
  1090. break;
  1091. case BinOpInit::EQ:
  1092. case BinOpInit::NE:
  1093. if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
  1094. !ArgType->typeIsConvertibleTo(StringRecTy::get()) &&
  1095. !ArgType->typeIsConvertibleTo(RecordRecTy::get({}))) {
  1096. Error(InitLoc, Twine("expected bit, bits, int, string, or record; "
  1097. "got value of type '") + ArgType->getAsString() +
  1098. "'");
  1099. return nullptr;
  1100. }
  1101. break;
  1102. case BinOpInit::LE:
  1103. case BinOpInit::LT:
  1104. case BinOpInit::GE:
  1105. case BinOpInit::GT:
  1106. if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
  1107. !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
  1108. Error(InitLoc, Twine("expected bit, bits, int, or string; "
  1109. "got value of type '") + ArgType->getAsString() +
  1110. "'");
  1111. return nullptr;
  1112. }
  1113. break;
  1114. case BinOpInit::INTERLEAVE:
  1115. switch (InitList.size()) {
  1116. case 1: // First argument must be a list of strings or integers.
  1117. if (ArgType != StringRecTy::get()->getListTy() &&
  1118. !ArgType->typeIsConvertibleTo(IntRecTy::get()->getListTy())) {
  1119. Error(InitLoc, Twine("expected list of string, int, bits, or bit; "
  1120. "got value of type '") +
  1121. ArgType->getAsString() + "'");
  1122. return nullptr;
  1123. }
  1124. break;
  1125. case 2: // Second argument must be a string.
  1126. if (!isa<StringRecTy>(ArgType)) {
  1127. Error(InitLoc, Twine("expected second argument to be a string, "
  1128. "got value of type '") +
  1129. ArgType->getAsString() + "'");
  1130. return nullptr;
  1131. }
  1132. break;
  1133. default: ;
  1134. }
  1135. ArgType = nullptr; // Broken invariant: types not identical.
  1136. break;
  1137. default: llvm_unreachable("other ops have fixed argument types");
  1138. }
  1139. } else {
  1140. // Desired argument type is a known and in ArgType.
  1141. RecTy *Resolved = resolveTypes(ArgType, ListType);
  1142. if (!Resolved) {
  1143. Error(InitLoc, Twine("expected value of type '") +
  1144. ArgType->getAsString() + "', got '" +
  1145. ListType->getAsString() + "'");
  1146. return nullptr;
  1147. }
  1148. if (Code != BinOpInit::ADD && Code != BinOpInit::SUB &&
  1149. Code != BinOpInit::AND && Code != BinOpInit::OR &&
  1150. Code != BinOpInit::XOR && Code != BinOpInit::SRA &&
  1151. Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
  1152. Code != BinOpInit::MUL)
  1153. ArgType = Resolved;
  1154. }
  1155. // Deal with BinOps whose arguments have different types, by
  1156. // rewriting ArgType in between them.
  1157. switch (Code) {
  1158. case BinOpInit::SETDAGOP:
  1159. // After parsing the first dag argument, switch to expecting
  1160. // a record, with no restriction on its superclasses.
  1161. ArgType = RecordRecTy::get({});
  1162. break;
  1163. default:
  1164. break;
  1165. }
  1166. if (!consume(tgtok::comma))
  1167. break;
  1168. }
  1169. if (!consume(tgtok::r_paren)) {
  1170. TokError("expected ')' in operator");
  1171. return nullptr;
  1172. }
  1173. // listconcat returns a list with type of the argument.
  1174. if (Code == BinOpInit::LISTCONCAT)
  1175. Type = ArgType;
  1176. // listsplat returns a list of type of the *first* argument.
  1177. if (Code == BinOpInit::LISTSPLAT)
  1178. Type = cast<TypedInit>(InitList.front())->getType()->getListTy();
  1179. // We allow multiple operands to associative operators like !strconcat as
  1180. // shorthand for nesting them.
  1181. if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
  1182. Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
  1183. Code == BinOpInit::AND || Code == BinOpInit::OR ||
  1184. Code == BinOpInit::XOR || Code == BinOpInit::MUL) {
  1185. while (InitList.size() > 2) {
  1186. Init *RHS = InitList.pop_back_val();
  1187. RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
  1188. InitList.back() = RHS;
  1189. }
  1190. }
  1191. if (InitList.size() == 2)
  1192. return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
  1193. ->Fold(CurRec);
  1194. Error(OpLoc, "expected two operands to operator");
  1195. return nullptr;
  1196. }
  1197. case tgtok::XForEach:
  1198. case tgtok::XFilter: {
  1199. return ParseOperationForEachFilter(CurRec, ItemType);
  1200. }
  1201. case tgtok::XDag:
  1202. case tgtok::XIf:
  1203. case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
  1204. TernOpInit::TernaryOp Code;
  1205. RecTy *Type = nullptr;
  1206. tgtok::TokKind LexCode = Lex.getCode();
  1207. Lex.Lex(); // eat the operation
  1208. switch (LexCode) {
  1209. default: llvm_unreachable("Unhandled code!");
  1210. case tgtok::XDag:
  1211. Code = TernOpInit::DAG;
  1212. Type = DagRecTy::get();
  1213. ItemType = nullptr;
  1214. break;
  1215. case tgtok::XIf:
  1216. Code = TernOpInit::IF;
  1217. break;
  1218. case tgtok::XSubst:
  1219. Code = TernOpInit::SUBST;
  1220. break;
  1221. }
  1222. if (!consume(tgtok::l_paren)) {
  1223. TokError("expected '(' after ternary operator");
  1224. return nullptr;
  1225. }
  1226. Init *LHS = ParseValue(CurRec);
  1227. if (!LHS) return nullptr;
  1228. if (!consume(tgtok::comma)) {
  1229. TokError("expected ',' in ternary operator");
  1230. return nullptr;
  1231. }
  1232. SMLoc MHSLoc = Lex.getLoc();
  1233. Init *MHS = ParseValue(CurRec, ItemType);
  1234. if (!MHS)
  1235. return nullptr;
  1236. if (!consume(tgtok::comma)) {
  1237. TokError("expected ',' in ternary operator");
  1238. return nullptr;
  1239. }
  1240. SMLoc RHSLoc = Lex.getLoc();
  1241. Init *RHS = ParseValue(CurRec, ItemType);
  1242. if (!RHS)
  1243. return nullptr;
  1244. if (!consume(tgtok::r_paren)) {
  1245. TokError("expected ')' in binary operator");
  1246. return nullptr;
  1247. }
  1248. switch (LexCode) {
  1249. default: llvm_unreachable("Unhandled code!");
  1250. case tgtok::XDag: {
  1251. TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
  1252. if (!MHSt && !isa<UnsetInit>(MHS)) {
  1253. Error(MHSLoc, "could not determine type of the child list in !dag");
  1254. return nullptr;
  1255. }
  1256. if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
  1257. Error(MHSLoc, Twine("expected list of children, got type '") +
  1258. MHSt->getType()->getAsString() + "'");
  1259. return nullptr;
  1260. }
  1261. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1262. if (!RHSt && !isa<UnsetInit>(RHS)) {
  1263. Error(RHSLoc, "could not determine type of the name list in !dag");
  1264. return nullptr;
  1265. }
  1266. if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
  1267. Error(RHSLoc, Twine("expected list<string>, got type '") +
  1268. RHSt->getType()->getAsString() + "'");
  1269. return nullptr;
  1270. }
  1271. if (!MHSt && !RHSt) {
  1272. Error(MHSLoc,
  1273. "cannot have both unset children and unset names in !dag");
  1274. return nullptr;
  1275. }
  1276. break;
  1277. }
  1278. case tgtok::XIf: {
  1279. RecTy *MHSTy = nullptr;
  1280. RecTy *RHSTy = nullptr;
  1281. if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
  1282. MHSTy = MHSt->getType();
  1283. if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
  1284. MHSTy = BitsRecTy::get(MHSbits->getNumBits());
  1285. if (isa<BitInit>(MHS))
  1286. MHSTy = BitRecTy::get();
  1287. if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
  1288. RHSTy = RHSt->getType();
  1289. if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
  1290. RHSTy = BitsRecTy::get(RHSbits->getNumBits());
  1291. if (isa<BitInit>(RHS))
  1292. RHSTy = BitRecTy::get();
  1293. // For UnsetInit, it's typed from the other hand.
  1294. if (isa<UnsetInit>(MHS))
  1295. MHSTy = RHSTy;
  1296. if (isa<UnsetInit>(RHS))
  1297. RHSTy = MHSTy;
  1298. if (!MHSTy || !RHSTy) {
  1299. TokError("could not get type for !if");
  1300. return nullptr;
  1301. }
  1302. Type = resolveTypes(MHSTy, RHSTy);
  1303. if (!Type) {
  1304. TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
  1305. "' and '" + RHSTy->getAsString() + "' for !if");
  1306. return nullptr;
  1307. }
  1308. break;
  1309. }
  1310. case tgtok::XSubst: {
  1311. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1312. if (!RHSt) {
  1313. TokError("could not get type for !subst");
  1314. return nullptr;
  1315. }
  1316. Type = RHSt->getType();
  1317. break;
  1318. }
  1319. }
  1320. return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
  1321. }
  1322. case tgtok::XSubstr:
  1323. return ParseOperationSubstr(CurRec, ItemType);
  1324. case tgtok::XCond:
  1325. return ParseOperationCond(CurRec, ItemType);
  1326. case tgtok::XFoldl: {
  1327. // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
  1328. Lex.Lex(); // eat the operation
  1329. if (!consume(tgtok::l_paren)) {
  1330. TokError("expected '(' after !foldl");
  1331. return nullptr;
  1332. }
  1333. Init *StartUntyped = ParseValue(CurRec);
  1334. if (!StartUntyped)
  1335. return nullptr;
  1336. TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
  1337. if (!Start) {
  1338. TokError(Twine("could not get type of !foldl start: '") +
  1339. StartUntyped->getAsString() + "'");
  1340. return nullptr;
  1341. }
  1342. if (!consume(tgtok::comma)) {
  1343. TokError("expected ',' in !foldl");
  1344. return nullptr;
  1345. }
  1346. Init *ListUntyped = ParseValue(CurRec);
  1347. if (!ListUntyped)
  1348. return nullptr;
  1349. TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
  1350. if (!List) {
  1351. TokError(Twine("could not get type of !foldl list: '") +
  1352. ListUntyped->getAsString() + "'");
  1353. return nullptr;
  1354. }
  1355. ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
  1356. if (!ListType) {
  1357. TokError(Twine("!foldl list must be a list, but is of type '") +
  1358. List->getType()->getAsString());
  1359. return nullptr;
  1360. }
  1361. if (Lex.getCode() != tgtok::comma) {
  1362. TokError("expected ',' in !foldl");
  1363. return nullptr;
  1364. }
  1365. if (Lex.Lex() != tgtok::Id) { // eat the ','
  1366. TokError("third argument of !foldl must be an identifier");
  1367. return nullptr;
  1368. }
  1369. Init *A = StringInit::get(Lex.getCurStrVal());
  1370. if (CurRec && CurRec->getValue(A)) {
  1371. TokError((Twine("left !foldl variable '") + A->getAsString() +
  1372. "' already defined")
  1373. .str());
  1374. return nullptr;
  1375. }
  1376. if (Lex.Lex() != tgtok::comma) { // eat the id
  1377. TokError("expected ',' in !foldl");
  1378. return nullptr;
  1379. }
  1380. if (Lex.Lex() != tgtok::Id) { // eat the ','
  1381. TokError("fourth argument of !foldl must be an identifier");
  1382. return nullptr;
  1383. }
  1384. Init *B = StringInit::get(Lex.getCurStrVal());
  1385. if (CurRec && CurRec->getValue(B)) {
  1386. TokError((Twine("right !foldl variable '") + B->getAsString() +
  1387. "' already defined")
  1388. .str());
  1389. return nullptr;
  1390. }
  1391. if (Lex.Lex() != tgtok::comma) { // eat the id
  1392. TokError("expected ',' in !foldl");
  1393. return nullptr;
  1394. }
  1395. Lex.Lex(); // eat the ','
  1396. // We need to create a temporary record to provide a scope for the
  1397. // two variables.
  1398. std::unique_ptr<Record> ParseRecTmp;
  1399. Record *ParseRec = CurRec;
  1400. if (!ParseRec) {
  1401. ParseRecTmp = std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
  1402. ParseRec = ParseRecTmp.get();
  1403. }
  1404. ParseRec->addValue(RecordVal(A, Start->getType(), RecordVal::FK_Normal));
  1405. ParseRec->addValue(RecordVal(B, ListType->getElementType(),
  1406. RecordVal::FK_Normal));
  1407. Init *ExprUntyped = ParseValue(ParseRec);
  1408. ParseRec->removeValue(A);
  1409. ParseRec->removeValue(B);
  1410. if (!ExprUntyped)
  1411. return nullptr;
  1412. TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
  1413. if (!Expr) {
  1414. TokError("could not get type of !foldl expression");
  1415. return nullptr;
  1416. }
  1417. if (Expr->getType() != Start->getType()) {
  1418. TokError(Twine("!foldl expression must be of same type as start (") +
  1419. Start->getType()->getAsString() + "), but is of type " +
  1420. Expr->getType()->getAsString());
  1421. return nullptr;
  1422. }
  1423. if (!consume(tgtok::r_paren)) {
  1424. TokError("expected ')' in fold operator");
  1425. return nullptr;
  1426. }
  1427. return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
  1428. ->Fold(CurRec);
  1429. }
  1430. }
  1431. }
  1432. /// ParseOperatorType - Parse a type for an operator. This returns
  1433. /// null on error.
  1434. ///
  1435. /// OperatorType ::= '<' Type '>'
  1436. ///
  1437. RecTy *TGParser::ParseOperatorType() {
  1438. RecTy *Type = nullptr;
  1439. if (!consume(tgtok::less)) {
  1440. TokError("expected type name for operator");
  1441. return nullptr;
  1442. }
  1443. if (Lex.getCode() == tgtok::Code)
  1444. TokError("the 'code' type is not allowed in bang operators; use 'string'");
  1445. Type = ParseType();
  1446. if (!Type) {
  1447. TokError("expected type name for operator");
  1448. return nullptr;
  1449. }
  1450. if (!consume(tgtok::greater)) {
  1451. TokError("expected type name for operator");
  1452. return nullptr;
  1453. }
  1454. return Type;
  1455. }
  1456. /// Parse the !substr operation. Return null on error.
  1457. ///
  1458. /// Substr ::= !substr(string, start-int [, length-int]) => string
  1459. Init *TGParser::ParseOperationSubstr(Record *CurRec, RecTy *ItemType) {
  1460. TernOpInit::TernaryOp Code = TernOpInit::SUBSTR;
  1461. RecTy *Type = StringRecTy::get();
  1462. Lex.Lex(); // eat the operation
  1463. if (!consume(tgtok::l_paren)) {
  1464. TokError("expected '(' after !substr operator");
  1465. return nullptr;
  1466. }
  1467. Init *LHS = ParseValue(CurRec);
  1468. if (!LHS)
  1469. return nullptr;
  1470. if (!consume(tgtok::comma)) {
  1471. TokError("expected ',' in !substr operator");
  1472. return nullptr;
  1473. }
  1474. SMLoc MHSLoc = Lex.getLoc();
  1475. Init *MHS = ParseValue(CurRec);
  1476. if (!MHS)
  1477. return nullptr;
  1478. SMLoc RHSLoc = Lex.getLoc();
  1479. Init *RHS;
  1480. if (consume(tgtok::comma)) {
  1481. RHSLoc = Lex.getLoc();
  1482. RHS = ParseValue(CurRec);
  1483. if (!RHS)
  1484. return nullptr;
  1485. } else {
  1486. RHS = IntInit::get(std::numeric_limits<int64_t>::max());
  1487. }
  1488. if (!consume(tgtok::r_paren)) {
  1489. TokError("expected ')' in !substr operator");
  1490. return nullptr;
  1491. }
  1492. if (ItemType && !Type->typeIsConvertibleTo(ItemType)) {
  1493. Error(RHSLoc, Twine("expected value of type '") +
  1494. ItemType->getAsString() + "', got '" +
  1495. Type->getAsString() + "'");
  1496. }
  1497. TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
  1498. if (!LHSt && !isa<UnsetInit>(LHS)) {
  1499. TokError("could not determine type of the string in !substr");
  1500. return nullptr;
  1501. }
  1502. if (LHSt && !isa<StringRecTy>(LHSt->getType())) {
  1503. TokError(Twine("expected string, got type '") +
  1504. LHSt->getType()->getAsString() + "'");
  1505. return nullptr;
  1506. }
  1507. TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
  1508. if (!MHSt && !isa<UnsetInit>(MHS)) {
  1509. TokError("could not determine type of the start position in !substr");
  1510. return nullptr;
  1511. }
  1512. if (MHSt && !isa<IntRecTy>(MHSt->getType())) {
  1513. Error(MHSLoc, Twine("expected int, got type '") +
  1514. MHSt->getType()->getAsString() + "'");
  1515. return nullptr;
  1516. }
  1517. if (RHS) {
  1518. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1519. if (!RHSt && !isa<UnsetInit>(RHS)) {
  1520. TokError("could not determine type of the length in !substr");
  1521. return nullptr;
  1522. }
  1523. if (RHSt && !isa<IntRecTy>(RHSt->getType())) {
  1524. TokError(Twine("expected int, got type '") +
  1525. RHSt->getType()->getAsString() + "'");
  1526. return nullptr;
  1527. }
  1528. }
  1529. return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
  1530. }
  1531. /// Parse the !foreach and !filter operations. Return null on error.
  1532. ///
  1533. /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
  1534. /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
  1535. Init *TGParser::ParseOperationForEachFilter(Record *CurRec, RecTy *ItemType) {
  1536. SMLoc OpLoc = Lex.getLoc();
  1537. tgtok::TokKind Operation = Lex.getCode();
  1538. Lex.Lex(); // eat the operation
  1539. if (Lex.getCode() != tgtok::l_paren) {
  1540. TokError("expected '(' after !foreach/!filter");
  1541. return nullptr;
  1542. }
  1543. if (Lex.Lex() != tgtok::Id) { // eat the '('
  1544. TokError("first argument of !foreach/!filter must be an identifier");
  1545. return nullptr;
  1546. }
  1547. Init *LHS = StringInit::get(Lex.getCurStrVal());
  1548. Lex.Lex(); // eat the ID.
  1549. if (CurRec && CurRec->getValue(LHS)) {
  1550. TokError((Twine("iteration variable '") + LHS->getAsString() +
  1551. "' is already defined")
  1552. .str());
  1553. return nullptr;
  1554. }
  1555. if (!consume(tgtok::comma)) {
  1556. TokError("expected ',' in !foreach/!filter");
  1557. return nullptr;
  1558. }
  1559. Init *MHS = ParseValue(CurRec);
  1560. if (!MHS)
  1561. return nullptr;
  1562. if (!consume(tgtok::comma)) {
  1563. TokError("expected ',' in !foreach/!filter");
  1564. return nullptr;
  1565. }
  1566. TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
  1567. if (!MHSt) {
  1568. TokError("could not get type of !foreach/!filter list or dag");
  1569. return nullptr;
  1570. }
  1571. RecTy *InEltType = nullptr;
  1572. RecTy *ExprEltType = nullptr;
  1573. bool IsDAG = false;
  1574. if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
  1575. InEltType = InListTy->getElementType();
  1576. if (ItemType) {
  1577. if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
  1578. ExprEltType = (Operation == tgtok::XForEach)
  1579. ? OutListTy->getElementType()
  1580. : IntRecTy::get();
  1581. } else {
  1582. Error(OpLoc,
  1583. "expected value of type '" +
  1584. Twine(ItemType->getAsString()) +
  1585. "', but got list type");
  1586. return nullptr;
  1587. }
  1588. }
  1589. } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
  1590. if (Operation == tgtok::XFilter) {
  1591. TokError("!filter must have a list argument");
  1592. return nullptr;
  1593. }
  1594. InEltType = InDagTy;
  1595. if (ItemType && !isa<DagRecTy>(ItemType)) {
  1596. Error(OpLoc,
  1597. "expected value of type '" + Twine(ItemType->getAsString()) +
  1598. "', but got dag type");
  1599. return nullptr;
  1600. }
  1601. IsDAG = true;
  1602. } else {
  1603. if (Operation == tgtok::XForEach)
  1604. TokError("!foreach must have a list or dag argument");
  1605. else
  1606. TokError("!filter must have a list argument");
  1607. return nullptr;
  1608. }
  1609. // We need to create a temporary record to provide a scope for the
  1610. // iteration variable.
  1611. std::unique_ptr<Record> ParseRecTmp;
  1612. Record *ParseRec = CurRec;
  1613. if (!ParseRec) {
  1614. ParseRecTmp =
  1615. std::make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
  1616. ParseRec = ParseRecTmp.get();
  1617. }
  1618. ParseRec->addValue(RecordVal(LHS, InEltType, RecordVal::FK_Normal));
  1619. Init *RHS = ParseValue(ParseRec, ExprEltType);
  1620. ParseRec->removeValue(LHS);
  1621. if (!RHS)
  1622. return nullptr;
  1623. if (!consume(tgtok::r_paren)) {
  1624. TokError("expected ')' in !foreach/!filter");
  1625. return nullptr;
  1626. }
  1627. RecTy *OutType = InEltType;
  1628. if (Operation == tgtok::XForEach && !IsDAG) {
  1629. TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
  1630. if (!RHSt) {
  1631. TokError("could not get type of !foreach result expression");
  1632. return nullptr;
  1633. }
  1634. OutType = RHSt->getType()->getListTy();
  1635. } else if (Operation == tgtok::XFilter) {
  1636. OutType = InEltType->getListTy();
  1637. }
  1638. return (TernOpInit::get((Operation == tgtok::XForEach) ? TernOpInit::FOREACH
  1639. : TernOpInit::FILTER,
  1640. LHS, MHS, RHS, OutType))
  1641. ->Fold(CurRec);
  1642. }
  1643. Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
  1644. Lex.Lex(); // eat the operation 'cond'
  1645. if (!consume(tgtok::l_paren)) {
  1646. TokError("expected '(' after !cond operator");
  1647. return nullptr;
  1648. }
  1649. // Parse through '[Case: Val,]+'
  1650. SmallVector<Init *, 4> Case;
  1651. SmallVector<Init *, 4> Val;
  1652. while (true) {
  1653. if (consume(tgtok::r_paren))
  1654. break;
  1655. Init *V = ParseValue(CurRec);
  1656. if (!V)
  1657. return nullptr;
  1658. Case.push_back(V);
  1659. if (!consume(tgtok::colon)) {
  1660. TokError("expected ':' following a condition in !cond operator");
  1661. return nullptr;
  1662. }
  1663. V = ParseValue(CurRec, ItemType);
  1664. if (!V)
  1665. return nullptr;
  1666. Val.push_back(V);
  1667. if (consume(tgtok::r_paren))
  1668. break;
  1669. if (!consume(tgtok::comma)) {
  1670. TokError("expected ',' or ')' following a value in !cond operator");
  1671. return nullptr;
  1672. }
  1673. }
  1674. if (Case.size() < 1) {
  1675. TokError("there should be at least 1 'condition : value' in the !cond operator");
  1676. return nullptr;
  1677. }
  1678. // resolve type
  1679. RecTy *Type = nullptr;
  1680. for (Init *V : Val) {
  1681. RecTy *VTy = nullptr;
  1682. if (TypedInit *Vt = dyn_cast<TypedInit>(V))
  1683. VTy = Vt->getType();
  1684. if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
  1685. VTy = BitsRecTy::get(Vbits->getNumBits());
  1686. if (isa<BitInit>(V))
  1687. VTy = BitRecTy::get();
  1688. if (Type == nullptr) {
  1689. if (!isa<UnsetInit>(V))
  1690. Type = VTy;
  1691. } else {
  1692. if (!isa<UnsetInit>(V)) {
  1693. RecTy *RType = resolveTypes(Type, VTy);
  1694. if (!RType) {
  1695. TokError(Twine("inconsistent types '") + Type->getAsString() +
  1696. "' and '" + VTy->getAsString() + "' for !cond");
  1697. return nullptr;
  1698. }
  1699. Type = RType;
  1700. }
  1701. }
  1702. }
  1703. if (!Type) {
  1704. TokError("could not determine type for !cond from its arguments");
  1705. return nullptr;
  1706. }
  1707. return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
  1708. }
  1709. /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
  1710. ///
  1711. /// SimpleValue ::= IDValue
  1712. /// SimpleValue ::= INTVAL
  1713. /// SimpleValue ::= STRVAL+
  1714. /// SimpleValue ::= CODEFRAGMENT
  1715. /// SimpleValue ::= '?'
  1716. /// SimpleValue ::= '{' ValueList '}'
  1717. /// SimpleValue ::= ID '<' ValueListNE '>'
  1718. /// SimpleValue ::= '[' ValueList ']'
  1719. /// SimpleValue ::= '(' IDValue DagArgList ')'
  1720. /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
  1721. /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
  1722. /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
  1723. /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
  1724. /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
  1725. /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
  1726. /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
  1727. /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
  1728. /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
  1729. /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
  1730. ///
  1731. Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
  1732. IDParseMode Mode) {
  1733. Init *R = nullptr;
  1734. switch (Lex.getCode()) {
  1735. default: TokError("Unknown or reserved token when parsing a value"); break;
  1736. case tgtok::TrueVal:
  1737. R = IntInit::get(1);
  1738. Lex.Lex();
  1739. break;
  1740. case tgtok::FalseVal:
  1741. R = IntInit::get(0);
  1742. Lex.Lex();
  1743. break;
  1744. case tgtok::IntVal:
  1745. R = IntInit::get(Lex.getCurIntVal());
  1746. Lex.Lex();
  1747. break;
  1748. case tgtok::BinaryIntVal: {
  1749. auto BinaryVal = Lex.getCurBinaryIntVal();
  1750. SmallVector<Init*, 16> Bits(BinaryVal.second);
  1751. for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
  1752. Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
  1753. R = BitsInit::get(Bits);
  1754. Lex.Lex();
  1755. break;
  1756. }
  1757. case tgtok::StrVal: {
  1758. std::string Val = Lex.getCurStrVal();
  1759. Lex.Lex();
  1760. // Handle multiple consecutive concatenated strings.
  1761. while (Lex.getCode() == tgtok::StrVal) {
  1762. Val += Lex.getCurStrVal();
  1763. Lex.Lex();
  1764. }
  1765. R = StringInit::get(Val);
  1766. break;
  1767. }
  1768. case tgtok::CodeFragment:
  1769. R = StringInit::get(Lex.getCurStrVal(), StringInit::SF_Code);
  1770. Lex.Lex();
  1771. break;
  1772. case tgtok::question:
  1773. R = UnsetInit::get();
  1774. Lex.Lex();
  1775. break;
  1776. case tgtok::Id: {
  1777. SMLoc NameLoc = Lex.getLoc();
  1778. StringInit *Name = StringInit::get(Lex.getCurStrVal());
  1779. if (Lex.Lex() != tgtok::less) // consume the Id.
  1780. return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
  1781. // Value ::= ID '<' ValueListNE '>'
  1782. if (Lex.Lex() == tgtok::greater) {
  1783. TokError("expected non-empty value list");
  1784. return nullptr;
  1785. }
  1786. // This is a CLASS<initvalslist> expression. This is supposed to synthesize
  1787. // a new anonymous definition, deriving from CLASS<initvalslist> with no
  1788. // body.
  1789. Record *Class = Records.getClass(Name->getValue());
  1790. if (!Class) {
  1791. Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
  1792. return nullptr;
  1793. }
  1794. SmallVector<Init *, 8> Args;
  1795. ParseValueList(Args, CurRec, Class);
  1796. if (Args.empty()) return nullptr;
  1797. if (!consume(tgtok::greater)) {
  1798. TokError("expected '>' at end of value list");
  1799. return nullptr;
  1800. }
  1801. // Typecheck the template arguments list
  1802. ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
  1803. if (ExpectedArgs.size() < Args.size()) {
  1804. Error(NameLoc,
  1805. "More template args specified than expected");
  1806. return nullptr;
  1807. }
  1808. for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
  1809. RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
  1810. if (i < Args.size()) {
  1811. if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
  1812. RecTy *ExpectedType = ExpectedArg->getType();
  1813. if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
  1814. Error(NameLoc,
  1815. "Value specified for template argument #" + Twine(i) + " (" +
  1816. ExpectedArg->getNameInitAsString() + ") is of type '" +
  1817. TI->getType()->getAsString() + "', expected '" +
  1818. ExpectedType->getAsString() + "': " + TI->getAsString());
  1819. return nullptr;
  1820. }
  1821. continue;
  1822. }
  1823. } else if (ExpectedArg->getValue()->isComplete())
  1824. continue;
  1825. Error(NameLoc,
  1826. "Value not specified for template argument #" + Twine(i) + " (" +
  1827. ExpectedArgs[i]->getAsUnquotedString() + ")");
  1828. return nullptr;
  1829. }
  1830. return VarDefInit::get(Class, Args)->Fold();
  1831. }
  1832. case tgtok::l_brace: { // Value ::= '{' ValueList '}'
  1833. SMLoc BraceLoc = Lex.getLoc();
  1834. Lex.Lex(); // eat the '{'
  1835. SmallVector<Init*, 16> Vals;
  1836. if (Lex.getCode() != tgtok::r_brace) {
  1837. ParseValueList(Vals, CurRec);
  1838. if (Vals.empty()) return nullptr;
  1839. }
  1840. if (!consume(tgtok::r_brace)) {
  1841. TokError("expected '}' at end of bit list value");
  1842. return nullptr;
  1843. }
  1844. SmallVector<Init *, 16> NewBits;
  1845. // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
  1846. // first. We'll first read everything in to a vector, then we can reverse
  1847. // it to get the bits in the correct order for the BitsInit value.
  1848. for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
  1849. // FIXME: The following two loops would not be duplicated
  1850. // if the API was a little more orthogonal.
  1851. // bits<n> values are allowed to initialize n bits.
  1852. if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
  1853. for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
  1854. NewBits.push_back(BI->getBit((e - i) - 1));
  1855. continue;
  1856. }
  1857. // bits<n> can also come from variable initializers.
  1858. if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
  1859. if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
  1860. for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
  1861. NewBits.push_back(VI->getBit((e - i) - 1));
  1862. continue;
  1863. }
  1864. // Fallthrough to try convert this to a bit.
  1865. }
  1866. // All other values must be convertible to just a single bit.
  1867. Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
  1868. if (!Bit) {
  1869. Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
  1870. ") is not convertable to a bit");
  1871. return nullptr;
  1872. }
  1873. NewBits.push_back(Bit);
  1874. }
  1875. std::reverse(NewBits.begin(), NewBits.end());
  1876. return BitsInit::get(NewBits);
  1877. }
  1878. case tgtok::l_square: { // Value ::= '[' ValueList ']'
  1879. Lex.Lex(); // eat the '['
  1880. SmallVector<Init*, 16> Vals;
  1881. RecTy *DeducedEltTy = nullptr;
  1882. ListRecTy *GivenListTy = nullptr;
  1883. if (ItemType) {
  1884. ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
  1885. if (!ListType) {
  1886. TokError(Twine("Encountered a list when expecting a ") +
  1887. ItemType->getAsString());
  1888. return nullptr;
  1889. }
  1890. GivenListTy = ListType;
  1891. }
  1892. if (Lex.getCode() != tgtok::r_square) {
  1893. ParseValueList(Vals, CurRec, nullptr,
  1894. GivenListTy ? GivenListTy->getElementType() : nullptr);
  1895. if (Vals.empty()) return nullptr;
  1896. }
  1897. if (!consume(tgtok::r_square)) {
  1898. TokError("expected ']' at end of list value");
  1899. return nullptr;
  1900. }
  1901. RecTy *GivenEltTy = nullptr;
  1902. if (consume(tgtok::less)) {
  1903. // Optional list element type
  1904. GivenEltTy = ParseType();
  1905. if (!GivenEltTy) {
  1906. // Couldn't parse element type
  1907. return nullptr;
  1908. }
  1909. if (!consume(tgtok::greater)) {
  1910. TokError("expected '>' at end of list element type");
  1911. return nullptr;
  1912. }
  1913. }
  1914. // Check elements
  1915. RecTy *EltTy = nullptr;
  1916. for (Init *V : Vals) {
  1917. TypedInit *TArg = dyn_cast<TypedInit>(V);
  1918. if (TArg) {
  1919. if (EltTy) {
  1920. EltTy = resolveTypes(EltTy, TArg->getType());
  1921. if (!EltTy) {
  1922. TokError("Incompatible types in list elements");
  1923. return nullptr;
  1924. }
  1925. } else {
  1926. EltTy = TArg->getType();
  1927. }
  1928. }
  1929. }
  1930. if (GivenEltTy) {
  1931. if (EltTy) {
  1932. // Verify consistency
  1933. if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
  1934. TokError("Incompatible types in list elements");
  1935. return nullptr;
  1936. }
  1937. }
  1938. EltTy = GivenEltTy;
  1939. }
  1940. if (!EltTy) {
  1941. if (!ItemType) {
  1942. TokError("No type for list");
  1943. return nullptr;
  1944. }
  1945. DeducedEltTy = GivenListTy->getElementType();
  1946. } else {
  1947. // Make sure the deduced type is compatible with the given type
  1948. if (GivenListTy) {
  1949. if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
  1950. TokError(Twine("Element type mismatch for list: element type '") +
  1951. EltTy->getAsString() + "' not convertible to '" +
  1952. GivenListTy->getElementType()->getAsString());
  1953. return nullptr;
  1954. }
  1955. }
  1956. DeducedEltTy = EltTy;
  1957. }
  1958. return ListInit::get(Vals, DeducedEltTy);
  1959. }
  1960. case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
  1961. Lex.Lex(); // eat the '('
  1962. if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast &&
  1963. Lex.getCode() != tgtok::question && Lex.getCode() != tgtok::XGetDagOp) {
  1964. TokError("expected identifier in dag init");
  1965. return nullptr;
  1966. }
  1967. Init *Operator = ParseValue(CurRec);
  1968. if (!Operator) return nullptr;
  1969. // If the operator name is present, parse it.
  1970. StringInit *OperatorName = nullptr;
  1971. if (consume(tgtok::colon)) {
  1972. if (Lex.getCode() != tgtok::VarName) { // eat the ':'
  1973. TokError("expected variable name in dag operator");
  1974. return nullptr;
  1975. }
  1976. OperatorName = StringInit::get(Lex.getCurStrVal());
  1977. Lex.Lex(); // eat the VarName.
  1978. }
  1979. SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
  1980. if (Lex.getCode() != tgtok::r_paren) {
  1981. ParseDagArgList(DagArgs, CurRec);
  1982. if (DagArgs.empty()) return nullptr;
  1983. }
  1984. if (!consume(tgtok::r_paren)) {
  1985. TokError("expected ')' in dag init");
  1986. return nullptr;
  1987. }
  1988. return DagInit::get(Operator, OperatorName, DagArgs);
  1989. }
  1990. case tgtok::XHead:
  1991. case tgtok::XTail:
  1992. case tgtok::XSize:
  1993. case tgtok::XEmpty:
  1994. case tgtok::XCast:
  1995. case tgtok::XGetDagOp: // Value ::= !unop '(' Value ')'
  1996. case tgtok::XIsA:
  1997. case tgtok::XConcat:
  1998. case tgtok::XDag:
  1999. case tgtok::XADD:
  2000. case tgtok::XSUB:
  2001. case tgtok::XMUL:
  2002. case tgtok::XNOT:
  2003. case tgtok::XAND:
  2004. case tgtok::XOR:
  2005. case tgtok::XXOR:
  2006. case tgtok::XSRA:
  2007. case tgtok::XSRL:
  2008. case tgtok::XSHL:
  2009. case tgtok::XEq:
  2010. case tgtok::XNe:
  2011. case tgtok::XLe:
  2012. case tgtok::XLt:
  2013. case tgtok::XGe:
  2014. case tgtok::XGt:
  2015. case tgtok::XListConcat:
  2016. case tgtok::XListSplat:
  2017. case tgtok::XStrConcat:
  2018. case tgtok::XInterleave:
  2019. case tgtok::XSetDagOp: // Value ::= !binop '(' Value ',' Value ')'
  2020. case tgtok::XIf:
  2021. case tgtok::XCond:
  2022. case tgtok::XFoldl:
  2023. case tgtok::XForEach:
  2024. case tgtok::XFilter:
  2025. case tgtok::XSubst:
  2026. case tgtok::XSubstr: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
  2027. return ParseOperation(CurRec, ItemType);
  2028. }
  2029. }
  2030. return R;
  2031. }
  2032. /// ParseValue - Parse a TableGen value. This returns null on error.
  2033. ///
  2034. /// Value ::= SimpleValue ValueSuffix*
  2035. /// ValueSuffix ::= '{' BitList '}'
  2036. /// ValueSuffix ::= '[' BitList ']'
  2037. /// ValueSuffix ::= '.' ID
  2038. ///
  2039. Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
  2040. Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
  2041. if (!Result) return nullptr;
  2042. // Parse the suffixes now if present.
  2043. while (true) {
  2044. switch (Lex.getCode()) {
  2045. default: return Result;
  2046. case tgtok::l_brace: {
  2047. if (Mode == ParseNameMode)
  2048. // This is the beginning of the object body.
  2049. return Result;
  2050. SMLoc CurlyLoc = Lex.getLoc();
  2051. Lex.Lex(); // eat the '{'
  2052. SmallVector<unsigned, 16> Ranges;
  2053. ParseRangeList(Ranges);
  2054. if (Ranges.empty()) return nullptr;
  2055. // Reverse the bitlist.
  2056. std::reverse(Ranges.begin(), Ranges.end());
  2057. Result = Result->convertInitializerBitRange(Ranges);
  2058. if (!Result) {
  2059. Error(CurlyLoc, "Invalid bit range for value");
  2060. return nullptr;
  2061. }
  2062. // Eat the '}'.
  2063. if (!consume(tgtok::r_brace)) {
  2064. TokError("expected '}' at end of bit range list");
  2065. return nullptr;
  2066. }
  2067. break;
  2068. }
  2069. case tgtok::l_square: {
  2070. SMLoc SquareLoc = Lex.getLoc();
  2071. Lex.Lex(); // eat the '['
  2072. SmallVector<unsigned, 16> Ranges;
  2073. ParseRangeList(Ranges);
  2074. if (Ranges.empty()) return nullptr;
  2075. Result = Result->convertInitListSlice(Ranges);
  2076. if (!Result) {
  2077. Error(SquareLoc, "Invalid range for list slice");
  2078. return nullptr;
  2079. }
  2080. // Eat the ']'.
  2081. if (!consume(tgtok::r_square)) {
  2082. TokError("expected ']' at end of list slice");
  2083. return nullptr;
  2084. }
  2085. break;
  2086. }
  2087. case tgtok::dot: {
  2088. if (Lex.Lex() != tgtok::Id) { // eat the .
  2089. TokError("expected field identifier after '.'");
  2090. return nullptr;
  2091. }
  2092. StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
  2093. if (!Result->getFieldType(FieldName)) {
  2094. TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
  2095. Result->getAsString() + "'");
  2096. return nullptr;
  2097. }
  2098. Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
  2099. Lex.Lex(); // eat field name
  2100. break;
  2101. }
  2102. case tgtok::paste:
  2103. SMLoc PasteLoc = Lex.getLoc();
  2104. TypedInit *LHS = dyn_cast<TypedInit>(Result);
  2105. if (!LHS) {
  2106. Error(PasteLoc, "LHS of paste is not typed!");
  2107. return nullptr;
  2108. }
  2109. // Check if it's a 'listA # listB'
  2110. if (isa<ListRecTy>(LHS->getType())) {
  2111. Lex.Lex(); // Eat the '#'.
  2112. assert(Mode == ParseValueMode && "encountered paste of lists in name");
  2113. switch (Lex.getCode()) {
  2114. case tgtok::colon:
  2115. case tgtok::semi:
  2116. case tgtok::l_brace:
  2117. Result = LHS; // trailing paste, ignore.
  2118. break;
  2119. default:
  2120. Init *RHSResult = ParseValue(CurRec, ItemType, ParseValueMode);
  2121. if (!RHSResult)
  2122. return nullptr;
  2123. Result = BinOpInit::getListConcat(LHS, RHSResult);
  2124. break;
  2125. }
  2126. break;
  2127. }
  2128. // Create a !strconcat() operation, first casting each operand to
  2129. // a string if necessary.
  2130. if (LHS->getType() != StringRecTy::get()) {
  2131. auto CastLHS = dyn_cast<TypedInit>(
  2132. UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
  2133. ->Fold(CurRec));
  2134. if (!CastLHS) {
  2135. Error(PasteLoc,
  2136. Twine("can't cast '") + LHS->getAsString() + "' to string");
  2137. return nullptr;
  2138. }
  2139. LHS = CastLHS;
  2140. }
  2141. TypedInit *RHS = nullptr;
  2142. Lex.Lex(); // Eat the '#'.
  2143. switch (Lex.getCode()) {
  2144. case tgtok::colon:
  2145. case tgtok::semi:
  2146. case tgtok::l_brace:
  2147. // These are all of the tokens that can begin an object body.
  2148. // Some of these can also begin values but we disallow those cases
  2149. // because they are unlikely to be useful.
  2150. // Trailing paste, concat with an empty string.
  2151. RHS = StringInit::get("");
  2152. break;
  2153. default:
  2154. Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
  2155. if (!RHSResult)
  2156. return nullptr;
  2157. RHS = dyn_cast<TypedInit>(RHSResult);
  2158. if (!RHS) {
  2159. Error(PasteLoc, "RHS of paste is not typed!");
  2160. return nullptr;
  2161. }
  2162. if (RHS->getType() != StringRecTy::get()) {
  2163. auto CastRHS = dyn_cast<TypedInit>(
  2164. UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
  2165. ->Fold(CurRec));
  2166. if (!CastRHS) {
  2167. Error(PasteLoc,
  2168. Twine("can't cast '") + RHS->getAsString() + "' to string");
  2169. return nullptr;
  2170. }
  2171. RHS = CastRHS;
  2172. }
  2173. break;
  2174. }
  2175. Result = BinOpInit::getStrConcat(LHS, RHS);
  2176. break;
  2177. }
  2178. }
  2179. }
  2180. /// ParseDagArgList - Parse the argument list for a dag literal expression.
  2181. ///
  2182. /// DagArg ::= Value (':' VARNAME)?
  2183. /// DagArg ::= VARNAME
  2184. /// DagArgList ::= DagArg
  2185. /// DagArgList ::= DagArgList ',' DagArg
  2186. void TGParser::ParseDagArgList(
  2187. SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
  2188. Record *CurRec) {
  2189. while (true) {
  2190. // DagArg ::= VARNAME
  2191. if (Lex.getCode() == tgtok::VarName) {
  2192. // A missing value is treated like '?'.
  2193. StringInit *VarName = StringInit::get(Lex.getCurStrVal());
  2194. Result.emplace_back(UnsetInit::get(), VarName);
  2195. Lex.Lex();
  2196. } else {
  2197. // DagArg ::= Value (':' VARNAME)?
  2198. Init *Val = ParseValue(CurRec);
  2199. if (!Val) {
  2200. Result.clear();
  2201. return;
  2202. }
  2203. // If the variable name is present, add it.
  2204. StringInit *VarName = nullptr;
  2205. if (Lex.getCode() == tgtok::colon) {
  2206. if (Lex.Lex() != tgtok::VarName) { // eat the ':'
  2207. TokError("expected variable name in dag literal");
  2208. Result.clear();
  2209. return;
  2210. }
  2211. VarName = StringInit::get(Lex.getCurStrVal());
  2212. Lex.Lex(); // eat the VarName.
  2213. }
  2214. Result.push_back(std::make_pair(Val, VarName));
  2215. }
  2216. if (!consume(tgtok::comma))
  2217. break;
  2218. }
  2219. }
  2220. /// ParseValueList - Parse a comma separated list of values, returning them as a
  2221. /// vector. Note that this always expects to be able to parse at least one
  2222. /// value. It returns an empty list if this is not possible.
  2223. ///
  2224. /// ValueList ::= Value (',' Value)
  2225. ///
  2226. void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
  2227. Record *ArgsRec, RecTy *EltTy) {
  2228. RecTy *ItemType = EltTy;
  2229. unsigned int ArgN = 0;
  2230. if (ArgsRec && !EltTy) {
  2231. ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
  2232. if (TArgs.empty()) {
  2233. TokError("template argument provided to non-template class");
  2234. Result.clear();
  2235. return;
  2236. }
  2237. const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
  2238. if (!RV) {
  2239. errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
  2240. << ")\n";
  2241. }
  2242. assert(RV && "Template argument record not found??");
  2243. ItemType = RV->getType();
  2244. ++ArgN;
  2245. }
  2246. Result.push_back(ParseValue(CurRec, ItemType));
  2247. if (!Result.back()) {
  2248. Result.clear();
  2249. return;
  2250. }
  2251. while (consume(tgtok::comma)) {
  2252. // ignore trailing comma for lists
  2253. if (Lex.getCode() == tgtok::r_square)
  2254. return;
  2255. if (ArgsRec && !EltTy) {
  2256. ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
  2257. if (ArgN >= TArgs.size()) {
  2258. TokError("too many template arguments");
  2259. Result.clear();
  2260. return;
  2261. }
  2262. const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
  2263. assert(RV && "Template argument record not found??");
  2264. ItemType = RV->getType();
  2265. ++ArgN;
  2266. }
  2267. Result.push_back(ParseValue(CurRec, ItemType));
  2268. if (!Result.back()) {
  2269. Result.clear();
  2270. return;
  2271. }
  2272. }
  2273. }
  2274. /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
  2275. /// empty string on error. This can happen in a number of different context's,
  2276. /// including within a def or in the template args for a def (which which case
  2277. /// CurRec will be non-null) and within the template args for a multiclass (in
  2278. /// which case CurRec will be null, but CurMultiClass will be set). This can
  2279. /// also happen within a def that is within a multiclass, which will set both
  2280. /// CurRec and CurMultiClass.
  2281. ///
  2282. /// Declaration ::= FIELD? Type ID ('=' Value)?
  2283. ///
  2284. Init *TGParser::ParseDeclaration(Record *CurRec,
  2285. bool ParsingTemplateArgs) {
  2286. // Read the field prefix if present.
  2287. bool HasField = consume(tgtok::Field);
  2288. RecTy *Type = ParseType();
  2289. if (!Type) return nullptr;
  2290. if (Lex.getCode() != tgtok::Id) {
  2291. TokError("Expected identifier in declaration");
  2292. return nullptr;
  2293. }
  2294. std::string Str = Lex.getCurStrVal();
  2295. if (Str == "NAME") {
  2296. TokError("'" + Str + "' is a reserved variable name");
  2297. return nullptr;
  2298. }
  2299. SMLoc IdLoc = Lex.getLoc();
  2300. Init *DeclName = StringInit::get(Str);
  2301. Lex.Lex();
  2302. if (ParsingTemplateArgs) {
  2303. if (CurRec)
  2304. DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
  2305. else
  2306. assert(CurMultiClass);
  2307. if (CurMultiClass)
  2308. DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
  2309. "::");
  2310. }
  2311. // Add the field to the record.
  2312. if (AddValue(CurRec, IdLoc, RecordVal(DeclName, IdLoc, Type,
  2313. HasField ? RecordVal::FK_NonconcreteOK
  2314. : RecordVal::FK_Normal)))
  2315. return nullptr;
  2316. // If a value is present, parse it.
  2317. if (consume(tgtok::equal)) {
  2318. SMLoc ValLoc = Lex.getLoc();
  2319. Init *Val = ParseValue(CurRec, Type);
  2320. if (!Val ||
  2321. SetValue(CurRec, ValLoc, DeclName, None, Val))
  2322. // Return the name, even if an error is thrown. This is so that we can
  2323. // continue to make some progress, even without the value having been
  2324. // initialized.
  2325. return DeclName;
  2326. }
  2327. return DeclName;
  2328. }
  2329. /// ParseForeachDeclaration - Read a foreach declaration, returning
  2330. /// the name of the declared object or a NULL Init on error. Return
  2331. /// the name of the parsed initializer list through ForeachListName.
  2332. ///
  2333. /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
  2334. /// ForeachDeclaration ::= ID '=' RangePiece
  2335. /// ForeachDeclaration ::= ID '=' Value
  2336. ///
  2337. VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
  2338. if (Lex.getCode() != tgtok::Id) {
  2339. TokError("Expected identifier in foreach declaration");
  2340. return nullptr;
  2341. }
  2342. Init *DeclName = StringInit::get(Lex.getCurStrVal());
  2343. Lex.Lex();
  2344. // If a value is present, parse it.
  2345. if (!consume(tgtok::equal)) {
  2346. TokError("Expected '=' in foreach declaration");
  2347. return nullptr;
  2348. }
  2349. RecTy *IterType = nullptr;
  2350. SmallVector<unsigned, 16> Ranges;
  2351. switch (Lex.getCode()) {
  2352. case tgtok::l_brace: { // '{' RangeList '}'
  2353. Lex.Lex(); // eat the '{'
  2354. ParseRangeList(Ranges);
  2355. if (!consume(tgtok::r_brace)) {
  2356. TokError("expected '}' at end of bit range list");
  2357. return nullptr;
  2358. }
  2359. break;
  2360. }
  2361. default: {
  2362. SMLoc ValueLoc = Lex.getLoc();
  2363. Init *I = ParseValue(nullptr);
  2364. if (!I)
  2365. return nullptr;
  2366. TypedInit *TI = dyn_cast<TypedInit>(I);
  2367. if (TI && isa<ListRecTy>(TI->getType())) {
  2368. ForeachListValue = I;
  2369. IterType = cast<ListRecTy>(TI->getType())->getElementType();
  2370. break;
  2371. }
  2372. if (TI) {
  2373. if (ParseRangePiece(Ranges, TI))
  2374. return nullptr;
  2375. break;
  2376. }
  2377. std::string Type;
  2378. if (TI)
  2379. Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
  2380. Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
  2381. if (CurMultiClass) {
  2382. PrintNote({}, "references to multiclass template arguments cannot be "
  2383. "resolved at this time");
  2384. }
  2385. return nullptr;
  2386. }
  2387. }
  2388. if (!Ranges.empty()) {
  2389. assert(!IterType && "Type already initialized?");
  2390. IterType = IntRecTy::get();
  2391. std::vector<Init*> Values;
  2392. for (unsigned R : Ranges)
  2393. Values.push_back(IntInit::get(R));
  2394. ForeachListValue = ListInit::get(Values, IterType);
  2395. }
  2396. if (!IterType)
  2397. return nullptr;
  2398. return VarInit::get(DeclName, IterType);
  2399. }
  2400. /// ParseTemplateArgList - Read a template argument list, which is a non-empty
  2401. /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
  2402. /// template args for a def, which may or may not be in a multiclass. If null,
  2403. /// these are the template args for a multiclass.
  2404. ///
  2405. /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
  2406. ///
  2407. bool TGParser::ParseTemplateArgList(Record *CurRec) {
  2408. assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
  2409. Lex.Lex(); // eat the '<'
  2410. Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
  2411. // Read the first declaration.
  2412. Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
  2413. if (!TemplArg)
  2414. return true;
  2415. TheRecToAddTo->addTemplateArg(TemplArg);
  2416. while (consume(tgtok::comma)) {
  2417. // Read the following declarations.
  2418. SMLoc Loc = Lex.getLoc();
  2419. TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
  2420. if (!TemplArg)
  2421. return true;
  2422. if (TheRecToAddTo->isTemplateArg(TemplArg))
  2423. return Error(Loc, "template argument with the same name has already been "
  2424. "defined");
  2425. TheRecToAddTo->addTemplateArg(TemplArg);
  2426. }
  2427. if (!consume(tgtok::greater))
  2428. return TokError("expected '>' at end of template argument list");
  2429. return false;
  2430. }
  2431. /// ParseBodyItem - Parse a single item within the body of a def or class.
  2432. ///
  2433. /// BodyItem ::= Declaration ';'
  2434. /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
  2435. /// BodyItem ::= Defvar
  2436. /// BodyItem ::= Assert
  2437. bool TGParser::ParseBodyItem(Record *CurRec) {
  2438. if (Lex.getCode() == tgtok::Assert)
  2439. return ParseAssert(nullptr, CurRec);
  2440. if (Lex.getCode() == tgtok::Defvar)
  2441. return ParseDefvar();
  2442. if (Lex.getCode() != tgtok::Let) {
  2443. if (!ParseDeclaration(CurRec, false))
  2444. return true;
  2445. if (!consume(tgtok::semi))
  2446. return TokError("expected ';' after declaration");
  2447. return false;
  2448. }
  2449. // LET ID OptionalRangeList '=' Value ';'
  2450. if (Lex.Lex() != tgtok::Id)
  2451. return TokError("expected field identifier after let");
  2452. SMLoc IdLoc = Lex.getLoc();
  2453. StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
  2454. Lex.Lex(); // eat the field name.
  2455. SmallVector<unsigned, 16> BitList;
  2456. if (ParseOptionalBitList(BitList))
  2457. return true;
  2458. std::reverse(BitList.begin(), BitList.end());
  2459. if (!consume(tgtok::equal))
  2460. return TokError("expected '=' in let expression");
  2461. RecordVal *Field = CurRec->getValue(FieldName);
  2462. if (!Field)
  2463. return TokError("Value '" + FieldName->getValue() + "' unknown!");
  2464. RecTy *Type = Field->getType();
  2465. if (!BitList.empty() && isa<BitsRecTy>(Type)) {
  2466. // When assigning to a subset of a 'bits' object, expect the RHS to have
  2467. // the type of that subset instead of the type of the whole object.
  2468. Type = BitsRecTy::get(BitList.size());
  2469. }
  2470. Init *Val = ParseValue(CurRec, Type);
  2471. if (!Val) return true;
  2472. if (!consume(tgtok::semi))
  2473. return TokError("expected ';' after let expression");
  2474. return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
  2475. }
  2476. /// ParseBody - Read the body of a class or def. Return true on error, false on
  2477. /// success.
  2478. ///
  2479. /// Body ::= ';'
  2480. /// Body ::= '{' BodyList '}'
  2481. /// BodyList BodyItem*
  2482. ///
  2483. bool TGParser::ParseBody(Record *CurRec) {
  2484. // If this is a null definition, just eat the semi and return.
  2485. if (consume(tgtok::semi))
  2486. return false;
  2487. if (!consume(tgtok::l_brace))
  2488. return TokError("Expected '{' to start body or ';' for declaration only");
  2489. // An object body introduces a new scope for local variables.
  2490. TGLocalVarScope *BodyScope = PushLocalScope();
  2491. while (Lex.getCode() != tgtok::r_brace)
  2492. if (ParseBodyItem(CurRec))
  2493. return true;
  2494. PopLocalScope(BodyScope);
  2495. // Eat the '}'.
  2496. Lex.Lex();
  2497. // If we have a semicolon, print a gentle error.
  2498. SMLoc SemiLoc = Lex.getLoc();
  2499. if (consume(tgtok::semi)) {
  2500. PrintError(SemiLoc, "A class or def body should not end with a semicolon");
  2501. PrintNote("Semicolon ignored; remove to eliminate this error");
  2502. }
  2503. return false;
  2504. }
  2505. /// Apply the current let bindings to \a CurRec.
  2506. /// \returns true on error, false otherwise.
  2507. bool TGParser::ApplyLetStack(Record *CurRec) {
  2508. for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
  2509. for (LetRecord &LR : LetInfo)
  2510. if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
  2511. return true;
  2512. return false;
  2513. }
  2514. bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
  2515. if (Entry.Rec)
  2516. return ApplyLetStack(Entry.Rec.get());
  2517. for (auto &E : Entry.Loop->Entries) {
  2518. if (ApplyLetStack(E))
  2519. return true;
  2520. }
  2521. return false;
  2522. }
  2523. /// ParseObjectBody - Parse the body of a def or class. This consists of an
  2524. /// optional ClassList followed by a Body. CurRec is the current def or class
  2525. /// that is being parsed.
  2526. ///
  2527. /// ObjectBody ::= BaseClassList Body
  2528. /// BaseClassList ::= /*empty*/
  2529. /// BaseClassList ::= ':' BaseClassListNE
  2530. /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
  2531. ///
  2532. bool TGParser::ParseObjectBody(Record *CurRec) {
  2533. // If there is a baseclass list, read it.
  2534. if (consume(tgtok::colon)) {
  2535. // Read all of the subclasses.
  2536. SubClassReference SubClass = ParseSubClassReference(CurRec, false);
  2537. while (true) {
  2538. // Check for error.
  2539. if (!SubClass.Rec) return true;
  2540. // Add it.
  2541. if (AddSubClass(CurRec, SubClass))
  2542. return true;
  2543. if (!consume(tgtok::comma))
  2544. break;
  2545. SubClass = ParseSubClassReference(CurRec, false);
  2546. }
  2547. }
  2548. if (ApplyLetStack(CurRec))
  2549. return true;
  2550. return ParseBody(CurRec);
  2551. }
  2552. /// ParseDef - Parse and return a top level or multiclass def, return the record
  2553. /// corresponding to it. This returns null on error.
  2554. ///
  2555. /// DefInst ::= DEF ObjectName ObjectBody
  2556. ///
  2557. bool TGParser::ParseDef(MultiClass *CurMultiClass) {
  2558. SMLoc DefLoc = Lex.getLoc();
  2559. assert(Lex.getCode() == tgtok::Def && "Unknown tok");
  2560. Lex.Lex(); // Eat the 'def' token.
  2561. // Parse ObjectName and make a record for it.
  2562. std::unique_ptr<Record> CurRec;
  2563. Init *Name = ParseObjectName(CurMultiClass);
  2564. if (!Name)
  2565. return true;
  2566. if (isa<UnsetInit>(Name))
  2567. CurRec = std::make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
  2568. /*Anonymous=*/true);
  2569. else
  2570. CurRec = std::make_unique<Record>(Name, DefLoc, Records);
  2571. if (ParseObjectBody(CurRec.get()))
  2572. return true;
  2573. return addEntry(std::move(CurRec));
  2574. }
  2575. /// ParseDefset - Parse a defset statement.
  2576. ///
  2577. /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
  2578. ///
  2579. bool TGParser::ParseDefset() {
  2580. assert(Lex.getCode() == tgtok::Defset);
  2581. Lex.Lex(); // Eat the 'defset' token
  2582. DefsetRecord Defset;
  2583. Defset.Loc = Lex.getLoc();
  2584. RecTy *Type = ParseType();
  2585. if (!Type)
  2586. return true;
  2587. if (!isa<ListRecTy>(Type))
  2588. return Error(Defset.Loc, "expected list type");
  2589. Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
  2590. if (Lex.getCode() != tgtok::Id)
  2591. return TokError("expected identifier");
  2592. StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
  2593. if (Records.getGlobal(DeclName->getValue()))
  2594. return TokError("def or global variable of this name already exists");
  2595. if (Lex.Lex() != tgtok::equal) // Eat the identifier
  2596. return TokError("expected '='");
  2597. if (Lex.Lex() != tgtok::l_brace) // Eat the '='
  2598. return TokError("expected '{'");
  2599. SMLoc BraceLoc = Lex.getLoc();
  2600. Lex.Lex(); // Eat the '{'
  2601. Defsets.push_back(&Defset);
  2602. bool Err = ParseObjectList(nullptr);
  2603. Defsets.pop_back();
  2604. if (Err)
  2605. return true;
  2606. if (!consume(tgtok::r_brace)) {
  2607. TokError("expected '}' at end of defset");
  2608. return Error(BraceLoc, "to match this '{'");
  2609. }
  2610. Records.addExtraGlobal(DeclName->getValue(),
  2611. ListInit::get(Defset.Elements, Defset.EltTy));
  2612. return false;
  2613. }
  2614. /// ParseDefvar - Parse a defvar statement.
  2615. ///
  2616. /// Defvar ::= DEFVAR Id '=' Value ';'
  2617. ///
  2618. bool TGParser::ParseDefvar() {
  2619. assert(Lex.getCode() == tgtok::Defvar);
  2620. Lex.Lex(); // Eat the 'defvar' token
  2621. if (Lex.getCode() != tgtok::Id)
  2622. return TokError("expected identifier");
  2623. StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
  2624. if (CurLocalScope) {
  2625. if (CurLocalScope->varAlreadyDefined(DeclName->getValue()))
  2626. return TokError("local variable of this name already exists");
  2627. } else {
  2628. if (Records.getGlobal(DeclName->getValue()))
  2629. return TokError("def or global variable of this name already exists");
  2630. }
  2631. Lex.Lex();
  2632. if (!consume(tgtok::equal))
  2633. return TokError("expected '='");
  2634. Init *Value = ParseValue(nullptr);
  2635. if (!Value)
  2636. return true;
  2637. if (!consume(tgtok::semi))
  2638. return TokError("expected ';'");
  2639. if (CurLocalScope)
  2640. CurLocalScope->addVar(DeclName->getValue(), Value);
  2641. else
  2642. Records.addExtraGlobal(DeclName->getValue(), Value);
  2643. return false;
  2644. }
  2645. /// ParseForeach - Parse a for statement. Return the record corresponding
  2646. /// to it. This returns true on error.
  2647. ///
  2648. /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
  2649. /// Foreach ::= FOREACH Declaration IN Object
  2650. ///
  2651. bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
  2652. SMLoc Loc = Lex.getLoc();
  2653. assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
  2654. Lex.Lex(); // Eat the 'for' token.
  2655. // Make a temporary object to record items associated with the for
  2656. // loop.
  2657. Init *ListValue = nullptr;
  2658. VarInit *IterName = ParseForeachDeclaration(ListValue);
  2659. if (!IterName)
  2660. return TokError("expected declaration in for");
  2661. if (!consume(tgtok::In))
  2662. return TokError("Unknown tok");
  2663. // Create a loop object and remember it.
  2664. Loops.push_back(std::make_unique<ForeachLoop>(Loc, IterName, ListValue));
  2665. // A foreach loop introduces a new scope for local variables.
  2666. TGLocalVarScope *ForeachScope = PushLocalScope();
  2667. if (Lex.getCode() != tgtok::l_brace) {
  2668. // FOREACH Declaration IN Object
  2669. if (ParseObject(CurMultiClass))
  2670. return true;
  2671. } else {
  2672. SMLoc BraceLoc = Lex.getLoc();
  2673. // Otherwise, this is a group foreach.
  2674. Lex.Lex(); // eat the '{'.
  2675. // Parse the object list.
  2676. if (ParseObjectList(CurMultiClass))
  2677. return true;
  2678. if (!consume(tgtok::r_brace)) {
  2679. TokError("expected '}' at end of foreach command");
  2680. return Error(BraceLoc, "to match this '{'");
  2681. }
  2682. }
  2683. PopLocalScope(ForeachScope);
  2684. // Resolve the loop or store it for later resolution.
  2685. std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
  2686. Loops.pop_back();
  2687. return addEntry(std::move(Loop));
  2688. }
  2689. /// ParseIf - Parse an if statement.
  2690. ///
  2691. /// If ::= IF Value THEN IfBody
  2692. /// If ::= IF Value THEN IfBody ELSE IfBody
  2693. ///
  2694. bool TGParser::ParseIf(MultiClass *CurMultiClass) {
  2695. SMLoc Loc = Lex.getLoc();
  2696. assert(Lex.getCode() == tgtok::If && "Unknown tok");
  2697. Lex.Lex(); // Eat the 'if' token.
  2698. // Make a temporary object to record items associated with the for
  2699. // loop.
  2700. Init *Condition = ParseValue(nullptr);
  2701. if (!Condition)
  2702. return true;
  2703. if (!consume(tgtok::Then))
  2704. return TokError("Unknown tok");
  2705. // We have to be able to save if statements to execute later, and they have
  2706. // to live on the same stack as foreach loops. The simplest implementation
  2707. // technique is to convert each 'then' or 'else' clause *into* a foreach
  2708. // loop, over a list of length 0 or 1 depending on the condition, and with no
  2709. // iteration variable being assigned.
  2710. ListInit *EmptyList = ListInit::get({}, BitRecTy::get());
  2711. ListInit *SingletonList = ListInit::get({BitInit::get(1)}, BitRecTy::get());
  2712. RecTy *BitListTy = ListRecTy::get(BitRecTy::get());
  2713. // The foreach containing the then-clause selects SingletonList if
  2714. // the condition is true.
  2715. Init *ThenClauseList =
  2716. TernOpInit::get(TernOpInit::IF, Condition, SingletonList, EmptyList,
  2717. BitListTy)
  2718. ->Fold(nullptr);
  2719. Loops.push_back(std::make_unique<ForeachLoop>(Loc, nullptr, ThenClauseList));
  2720. if (ParseIfBody(CurMultiClass, "then"))
  2721. return true;
  2722. std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
  2723. Loops.pop_back();
  2724. if (addEntry(std::move(Loop)))
  2725. return true;
  2726. // Now look for an optional else clause. The if-else syntax has the usual
  2727. // dangling-else ambiguity, and by greedily matching an else here if we can,
  2728. // we implement the usual resolution of pairing with the innermost unmatched
  2729. // if.
  2730. if (consume(tgtok::ElseKW)) {
  2731. // The foreach containing the else-clause uses the same pair of lists as
  2732. // above, but this time, selects SingletonList if the condition is *false*.
  2733. Init *ElseClauseList =
  2734. TernOpInit::get(TernOpInit::IF, Condition, EmptyList, SingletonList,
  2735. BitListTy)
  2736. ->Fold(nullptr);
  2737. Loops.push_back(
  2738. std::make_unique<ForeachLoop>(Loc, nullptr, ElseClauseList));
  2739. if (ParseIfBody(CurMultiClass, "else"))
  2740. return true;
  2741. Loop = std::move(Loops.back());
  2742. Loops.pop_back();
  2743. if (addEntry(std::move(Loop)))
  2744. return true;
  2745. }
  2746. return false;
  2747. }
  2748. /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
  2749. ///
  2750. /// IfBody ::= Object
  2751. /// IfBody ::= '{' ObjectList '}'
  2752. ///
  2753. bool TGParser::ParseIfBody(MultiClass *CurMultiClass, StringRef Kind) {
  2754. TGLocalVarScope *BodyScope = PushLocalScope();
  2755. if (Lex.getCode() != tgtok::l_brace) {
  2756. // A single object.
  2757. if (ParseObject(CurMultiClass))
  2758. return true;
  2759. } else {
  2760. SMLoc BraceLoc = Lex.getLoc();
  2761. // A braced block.
  2762. Lex.Lex(); // eat the '{'.
  2763. // Parse the object list.
  2764. if (ParseObjectList(CurMultiClass))
  2765. return true;
  2766. if (!consume(tgtok::r_brace)) {
  2767. TokError("expected '}' at end of '" + Kind + "' clause");
  2768. return Error(BraceLoc, "to match this '{'");
  2769. }
  2770. }
  2771. PopLocalScope(BodyScope);
  2772. return false;
  2773. }
  2774. /// ParseAssert - Parse an assert statement.
  2775. ///
  2776. /// Assert ::= ASSERT condition , message ;
  2777. bool TGParser::ParseAssert(MultiClass *CurMultiClass, Record *CurRec) {
  2778. assert(Lex.getCode() == tgtok::Assert && "Unknown tok");
  2779. Lex.Lex(); // Eat the 'assert' token.
  2780. SMLoc ConditionLoc = Lex.getLoc();
  2781. Init *Condition = ParseValue(CurRec);
  2782. if (!Condition)
  2783. return true;
  2784. if (!consume(tgtok::comma)) {
  2785. TokError("expected ',' in assert statement");
  2786. return true;
  2787. }
  2788. Init *Message = ParseValue(CurRec);
  2789. if (!Message)
  2790. return true;
  2791. if (!consume(tgtok::semi))
  2792. return TokError("expected ';'");
  2793. if (CurMultiClass) {
  2794. assert(false && "assert in multiclass not yet supported");
  2795. } else if (CurRec) {
  2796. CurRec->addAssertion(ConditionLoc, Condition, Message);
  2797. } else { // at top level
  2798. CheckAssert(ConditionLoc, Condition, Message);
  2799. }
  2800. return false;
  2801. }
  2802. /// ParseClass - Parse a tblgen class definition.
  2803. ///
  2804. /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
  2805. ///
  2806. bool TGParser::ParseClass() {
  2807. assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
  2808. Lex.Lex();
  2809. if (Lex.getCode() != tgtok::Id)
  2810. return TokError("expected class name after 'class' keyword");
  2811. Record *CurRec = Records.getClass(Lex.getCurStrVal());
  2812. if (CurRec) {
  2813. // If the body was previously defined, this is an error.
  2814. if (!CurRec->getValues().empty() ||
  2815. !CurRec->getSuperClasses().empty() ||
  2816. !CurRec->getTemplateArgs().empty())
  2817. return TokError("Class '" + CurRec->getNameInitAsString() +
  2818. "' already defined");
  2819. } else {
  2820. // If this is the first reference to this class, create and add it.
  2821. auto NewRec =
  2822. std::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
  2823. /*Class=*/true);
  2824. CurRec = NewRec.get();
  2825. Records.addClass(std::move(NewRec));
  2826. }
  2827. Lex.Lex(); // eat the name.
  2828. // If there are template args, parse them.
  2829. if (Lex.getCode() == tgtok::less)
  2830. if (ParseTemplateArgList(CurRec))
  2831. return true;
  2832. return ParseObjectBody(CurRec);
  2833. }
  2834. /// ParseLetList - Parse a non-empty list of assignment expressions into a list
  2835. /// of LetRecords.
  2836. ///
  2837. /// LetList ::= LetItem (',' LetItem)*
  2838. /// LetItem ::= ID OptionalRangeList '=' Value
  2839. ///
  2840. void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
  2841. do {
  2842. if (Lex.getCode() != tgtok::Id) {
  2843. TokError("expected identifier in let definition");
  2844. Result.clear();
  2845. return;
  2846. }
  2847. StringInit *Name = StringInit::get(Lex.getCurStrVal());
  2848. SMLoc NameLoc = Lex.getLoc();
  2849. Lex.Lex(); // Eat the identifier.
  2850. // Check for an optional RangeList.
  2851. SmallVector<unsigned, 16> Bits;
  2852. if (ParseOptionalRangeList(Bits)) {
  2853. Result.clear();
  2854. return;
  2855. }
  2856. std::reverse(Bits.begin(), Bits.end());
  2857. if (!consume(tgtok::equal)) {
  2858. TokError("expected '=' in let expression");
  2859. Result.clear();
  2860. return;
  2861. }
  2862. Init *Val = ParseValue(nullptr);
  2863. if (!Val) {
  2864. Result.clear();
  2865. return;
  2866. }
  2867. // Now that we have everything, add the record.
  2868. Result.emplace_back(Name, Bits, Val, NameLoc);
  2869. } while (consume(tgtok::comma));
  2870. }
  2871. /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
  2872. /// different related productions. This works inside multiclasses too.
  2873. ///
  2874. /// Object ::= LET LetList IN '{' ObjectList '}'
  2875. /// Object ::= LET LetList IN Object
  2876. ///
  2877. bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
  2878. assert(Lex.getCode() == tgtok::Let && "Unexpected token");
  2879. Lex.Lex();
  2880. // Add this entry to the let stack.
  2881. SmallVector<LetRecord, 8> LetInfo;
  2882. ParseLetList(LetInfo);
  2883. if (LetInfo.empty()) return true;
  2884. LetStack.push_back(std::move(LetInfo));
  2885. if (!consume(tgtok::In))
  2886. return TokError("expected 'in' at end of top-level 'let'");
  2887. TGLocalVarScope *LetScope = PushLocalScope();
  2888. // If this is a scalar let, just handle it now
  2889. if (Lex.getCode() != tgtok::l_brace) {
  2890. // LET LetList IN Object
  2891. if (ParseObject(CurMultiClass))
  2892. return true;
  2893. } else { // Object ::= LETCommand '{' ObjectList '}'
  2894. SMLoc BraceLoc = Lex.getLoc();
  2895. // Otherwise, this is a group let.
  2896. Lex.Lex(); // eat the '{'.
  2897. // Parse the object list.
  2898. if (ParseObjectList(CurMultiClass))
  2899. return true;
  2900. if (!consume(tgtok::r_brace)) {
  2901. TokError("expected '}' at end of top level let command");
  2902. return Error(BraceLoc, "to match this '{'");
  2903. }
  2904. }
  2905. PopLocalScope(LetScope);
  2906. // Outside this let scope, this let block is not active.
  2907. LetStack.pop_back();
  2908. return false;
  2909. }
  2910. /// ParseMultiClass - Parse a multiclass definition.
  2911. ///
  2912. /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
  2913. /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
  2914. /// MultiClassObject ::= DefInst
  2915. /// MultiClassObject ::= MultiClassInst
  2916. /// MultiClassObject ::= DefMInst
  2917. /// MultiClassObject ::= LETCommand '{' ObjectList '}'
  2918. /// MultiClassObject ::= LETCommand Object
  2919. ///
  2920. bool TGParser::ParseMultiClass() {
  2921. assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
  2922. Lex.Lex(); // Eat the multiclass token.
  2923. if (Lex.getCode() != tgtok::Id)
  2924. return TokError("expected identifier after multiclass for name");
  2925. std::string Name = Lex.getCurStrVal();
  2926. auto Result =
  2927. MultiClasses.insert(std::make_pair(Name,
  2928. std::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
  2929. if (!Result.second)
  2930. return TokError("multiclass '" + Name + "' already defined");
  2931. CurMultiClass = Result.first->second.get();
  2932. Lex.Lex(); // Eat the identifier.
  2933. // If there are template args, parse them.
  2934. if (Lex.getCode() == tgtok::less)
  2935. if (ParseTemplateArgList(nullptr))
  2936. return true;
  2937. bool inherits = false;
  2938. // If there are submulticlasses, parse them.
  2939. if (consume(tgtok::colon)) {
  2940. inherits = true;
  2941. // Read all of the submulticlasses.
  2942. SubMultiClassReference SubMultiClass =
  2943. ParseSubMultiClassReference(CurMultiClass);
  2944. while (true) {
  2945. // Check for error.
  2946. if (!SubMultiClass.MC) return true;
  2947. // Add it.
  2948. if (AddSubMultiClass(CurMultiClass, SubMultiClass))
  2949. return true;
  2950. if (!consume(tgtok::comma))
  2951. break;
  2952. SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
  2953. }
  2954. }
  2955. if (Lex.getCode() != tgtok::l_brace) {
  2956. if (!inherits)
  2957. return TokError("expected '{' in multiclass definition");
  2958. if (!consume(tgtok::semi))
  2959. return TokError("expected ';' in multiclass definition");
  2960. } else {
  2961. if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
  2962. return TokError("multiclass must contain at least one def");
  2963. // A multiclass body introduces a new scope for local variables.
  2964. TGLocalVarScope *MulticlassScope = PushLocalScope();
  2965. while (Lex.getCode() != tgtok::r_brace) {
  2966. switch (Lex.getCode()) {
  2967. default:
  2968. return TokError("expected 'assert', 'def', 'defm', 'defvar', "
  2969. "'foreach', 'if', or 'let' in multiclass body");
  2970. case tgtok::Assert:
  2971. return TokError("an assert statement in a multiclass is not yet supported");
  2972. case tgtok::Def:
  2973. case tgtok::Defm:
  2974. case tgtok::Defvar:
  2975. case tgtok::Foreach:
  2976. case tgtok::If:
  2977. case tgtok::Let:
  2978. if (ParseObject(CurMultiClass))
  2979. return true;
  2980. break;
  2981. }
  2982. }
  2983. Lex.Lex(); // eat the '}'.
  2984. // If we have a semicolon, print a gentle error.
  2985. SMLoc SemiLoc = Lex.getLoc();
  2986. if (consume(tgtok::semi)) {
  2987. PrintError(SemiLoc, "A multiclass body should not end with a semicolon");
  2988. PrintNote("Semicolon ignored; remove to eliminate this error");
  2989. }
  2990. PopLocalScope(MulticlassScope);
  2991. }
  2992. CurMultiClass = nullptr;
  2993. return false;
  2994. }
  2995. /// ParseDefm - Parse the instantiation of a multiclass.
  2996. ///
  2997. /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
  2998. ///
  2999. bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
  3000. assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
  3001. Lex.Lex(); // eat the defm
  3002. Init *DefmName = ParseObjectName(CurMultiClass);
  3003. if (!DefmName)
  3004. return true;
  3005. if (isa<UnsetInit>(DefmName)) {
  3006. DefmName = Records.getNewAnonymousName();
  3007. if (CurMultiClass)
  3008. DefmName = BinOpInit::getStrConcat(
  3009. VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
  3010. StringRecTy::get()),
  3011. DefmName);
  3012. }
  3013. if (Lex.getCode() != tgtok::colon)
  3014. return TokError("expected ':' after defm identifier");
  3015. // Keep track of the new generated record definitions.
  3016. std::vector<RecordsEntry> NewEntries;
  3017. // This record also inherits from a regular class (non-multiclass)?
  3018. bool InheritFromClass = false;
  3019. // eat the colon.
  3020. Lex.Lex();
  3021. SMLoc SubClassLoc = Lex.getLoc();
  3022. SubClassReference Ref = ParseSubClassReference(nullptr, true);
  3023. while (true) {
  3024. if (!Ref.Rec) return true;
  3025. // To instantiate a multiclass, we need to first get the multiclass, then
  3026. // instantiate each def contained in the multiclass with the SubClassRef
  3027. // template parameters.
  3028. MultiClass *MC = MultiClasses[std::string(Ref.Rec->getName())].get();
  3029. assert(MC && "Didn't lookup multiclass correctly?");
  3030. ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
  3031. // Verify that the correct number of template arguments were specified.
  3032. ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
  3033. if (TArgs.size() < TemplateVals.size())
  3034. return Error(SubClassLoc,
  3035. "more template args specified than multiclass expects");
  3036. SubstStack Substs;
  3037. for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
  3038. if (i < TemplateVals.size()) {
  3039. Substs.emplace_back(TArgs[i], TemplateVals[i]);
  3040. } else {
  3041. Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
  3042. if (!Default->isComplete()) {
  3043. return Error(SubClassLoc,
  3044. "value not specified for template argument #" +
  3045. Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
  3046. ") of multiclass '" + MC->Rec.getNameInitAsString() +
  3047. "'");
  3048. }
  3049. Substs.emplace_back(TArgs[i], Default);
  3050. }
  3051. }
  3052. Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
  3053. if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
  3054. &SubClassLoc))
  3055. return true;
  3056. if (!consume(tgtok::comma))
  3057. break;
  3058. if (Lex.getCode() != tgtok::Id)
  3059. return TokError("expected identifier");
  3060. SubClassLoc = Lex.getLoc();
  3061. // A defm can inherit from regular classes (non-multiclass) as
  3062. // long as they come in the end of the inheritance list.
  3063. InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
  3064. if (InheritFromClass)
  3065. break;
  3066. Ref = ParseSubClassReference(nullptr, true);
  3067. }
  3068. if (InheritFromClass) {
  3069. // Process all the classes to inherit as if they were part of a
  3070. // regular 'def' and inherit all record values.
  3071. SubClassReference SubClass = ParseSubClassReference(nullptr, false);
  3072. while (true) {
  3073. // Check for error.
  3074. if (!SubClass.Rec) return true;
  3075. // Get the expanded definition prototypes and teach them about
  3076. // the record values the current class to inherit has
  3077. for (auto &E : NewEntries) {
  3078. // Add it.
  3079. if (AddSubClass(E, SubClass))
  3080. return true;
  3081. }
  3082. if (!consume(tgtok::comma))
  3083. break;
  3084. SubClass = ParseSubClassReference(nullptr, false);
  3085. }
  3086. }
  3087. for (auto &E : NewEntries) {
  3088. if (ApplyLetStack(E))
  3089. return true;
  3090. addEntry(std::move(E));
  3091. }
  3092. if (!consume(tgtok::semi))
  3093. return TokError("expected ';' at end of defm");
  3094. return false;
  3095. }
  3096. /// ParseObject
  3097. /// Object ::= ClassInst
  3098. /// Object ::= DefInst
  3099. /// Object ::= MultiClassInst
  3100. /// Object ::= DefMInst
  3101. /// Object ::= LETCommand '{' ObjectList '}'
  3102. /// Object ::= LETCommand Object
  3103. /// Object ::= Defset
  3104. /// Object ::= Defvar
  3105. /// Object ::= Assert
  3106. bool TGParser::ParseObject(MultiClass *MC) {
  3107. switch (Lex.getCode()) {
  3108. default:
  3109. return TokError(
  3110. "Expected assert, class, def, defm, defset, foreach, if, or let");
  3111. case tgtok::Assert: return ParseAssert(MC, nullptr);
  3112. case tgtok::Def: return ParseDef(MC);
  3113. case tgtok::Defm: return ParseDefm(MC);
  3114. case tgtok::Defvar: return ParseDefvar();
  3115. case tgtok::Foreach: return ParseForeach(MC);
  3116. case tgtok::If: return ParseIf(MC);
  3117. case tgtok::Let: return ParseTopLevelLet(MC);
  3118. case tgtok::Defset:
  3119. if (MC)
  3120. return TokError("defset is not allowed inside multiclass");
  3121. return ParseDefset();
  3122. case tgtok::Class:
  3123. if (MC)
  3124. return TokError("class is not allowed inside multiclass");
  3125. if (!Loops.empty())
  3126. return TokError("class is not allowed inside foreach loop");
  3127. return ParseClass();
  3128. case tgtok::MultiClass:
  3129. if (!Loops.empty())
  3130. return TokError("multiclass is not allowed inside foreach loop");
  3131. return ParseMultiClass();
  3132. }
  3133. }
  3134. /// ParseObjectList
  3135. /// ObjectList :== Object*
  3136. bool TGParser::ParseObjectList(MultiClass *MC) {
  3137. while (isObjectStart(Lex.getCode())) {
  3138. if (ParseObject(MC))
  3139. return true;
  3140. }
  3141. return false;
  3142. }
  3143. bool TGParser::ParseFile() {
  3144. Lex.Lex(); // Prime the lexer.
  3145. if (ParseObjectList()) return true;
  3146. // If we have unread input at the end of the file, report it.
  3147. if (Lex.getCode() == tgtok::Eof)
  3148. return false;
  3149. return TokError("Unexpected token at top level");
  3150. }
  3151. // Check an assertion: Obtain the condition value and be sure it is true.
  3152. // If not, print a nonfatal error along with the message.
  3153. void TGParser::CheckAssert(SMLoc Loc, Init *Condition, Init *Message) {
  3154. auto *CondValue = dyn_cast_or_null<IntInit>(
  3155. Condition->convertInitializerTo(IntRecTy::get()));
  3156. if (CondValue) {
  3157. if (!CondValue->getValue()) {
  3158. PrintError(Loc, "assertion failed");
  3159. if (auto *MessageInit = dyn_cast<StringInit>(Message))
  3160. PrintNote(MessageInit->getValue());
  3161. else
  3162. PrintNote("(assert message is not a string)");
  3163. }
  3164. } else {
  3165. PrintError(Loc, "assert condition must of type bit, bits, or int.");
  3166. }
  3167. }
  3168. // Check all record assertions: For each one, resolve the condition
  3169. // and message, then call CheckAssert().
  3170. void TGParser::CheckRecordAsserts(Record &Rec) {
  3171. RecordResolver R(Rec);
  3172. R.setFinal(true);
  3173. for (auto Assertion : Rec.getAssertions()) {
  3174. Init *Condition = std::get<1>(Assertion)->resolveReferences(R);
  3175. Init *Message = std::get<2>(Assertion)->resolveReferences(R);
  3176. CheckAssert(std::get<0>(Assertion), Condition, Message);
  3177. }
  3178. }
  3179. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  3180. LLVM_DUMP_METHOD void RecordsEntry::dump() const {
  3181. if (Loop)
  3182. Loop->dump();
  3183. if (Rec)
  3184. Rec->dump();
  3185. }
  3186. LLVM_DUMP_METHOD void ForeachLoop::dump() const {
  3187. errs() << "foreach " << IterVar->getAsString() << " = "
  3188. << ListValue->getAsString() << " in {\n";
  3189. for (const auto &E : Entries)
  3190. E.dump();
  3191. errs() << "}\n";
  3192. }
  3193. LLVM_DUMP_METHOD void MultiClass::dump() const {
  3194. errs() << "Record:\n";
  3195. Rec.dump();
  3196. errs() << "Defs:\n";
  3197. for (const auto &E : Entries)
  3198. E.dump();
  3199. }
  3200. #endif