Record.cpp 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069
  1. //===- Record.cpp - Record implementation ---------------------------------===//
  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 tablegen record classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/TableGen/Record.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/FoldingSet.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/StringMap.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/Config/llvm-config.h"
  22. #include "llvm/Support/Allocator.h"
  23. #include "llvm/Support/Casting.h"
  24. #include "llvm/Support/Compiler.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/SMLoc.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. #include "llvm/TableGen/Error.h"
  30. #include <cassert>
  31. #include <cstdint>
  32. #include <map>
  33. #include <memory>
  34. #include <string>
  35. #include <utility>
  36. #include <vector>
  37. using namespace llvm;
  38. #define DEBUG_TYPE "tblgen-records"
  39. //===----------------------------------------------------------------------===//
  40. // Context
  41. //===----------------------------------------------------------------------===//
  42. namespace llvm {
  43. namespace detail {
  44. /// This class represents the internal implementation of the RecordKeeper.
  45. /// It contains all of the contextual static state of the Record classes. It is
  46. /// kept out-of-line to simplify dependencies, and also make it easier for
  47. /// internal classes to access the uniquer state of the keeper.
  48. struct RecordKeeperImpl {
  49. RecordKeeperImpl(RecordKeeper &RK)
  50. : SharedBitRecTy(RK), SharedIntRecTy(RK), SharedStringRecTy(RK),
  51. SharedDagRecTy(RK), AnyRecord(RK, 0), TheUnsetInit(RK),
  52. TrueBitInit(true, &SharedBitRecTy),
  53. FalseBitInit(false, &SharedBitRecTy), StringInitStringPool(Allocator),
  54. StringInitCodePool(Allocator), AnonCounter(0), LastRecordID(0) {}
  55. BumpPtrAllocator Allocator;
  56. std::vector<BitsRecTy *> SharedBitsRecTys;
  57. BitRecTy SharedBitRecTy;
  58. IntRecTy SharedIntRecTy;
  59. StringRecTy SharedStringRecTy;
  60. DagRecTy SharedDagRecTy;
  61. RecordRecTy AnyRecord;
  62. UnsetInit TheUnsetInit;
  63. BitInit TrueBitInit;
  64. BitInit FalseBitInit;
  65. FoldingSet<BitsInit> TheBitsInitPool;
  66. std::map<int64_t, IntInit *> TheIntInitPool;
  67. StringMap<StringInit *, BumpPtrAllocator &> StringInitStringPool;
  68. StringMap<StringInit *, BumpPtrAllocator &> StringInitCodePool;
  69. FoldingSet<ListInit> TheListInitPool;
  70. FoldingSet<UnOpInit> TheUnOpInitPool;
  71. FoldingSet<BinOpInit> TheBinOpInitPool;
  72. FoldingSet<TernOpInit> TheTernOpInitPool;
  73. FoldingSet<FoldOpInit> TheFoldOpInitPool;
  74. FoldingSet<IsAOpInit> TheIsAOpInitPool;
  75. FoldingSet<ExistsOpInit> TheExistsOpInitPool;
  76. DenseMap<std::pair<RecTy *, Init *>, VarInit *> TheVarInitPool;
  77. DenseMap<std::pair<TypedInit *, unsigned>, VarBitInit *> TheVarBitInitPool;
  78. DenseMap<std::pair<TypedInit *, unsigned>, VarListElementInit *>
  79. TheVarListElementInitPool;
  80. FoldingSet<VarDefInit> TheVarDefInitPool;
  81. DenseMap<std::pair<Init *, StringInit *>, FieldInit *> TheFieldInitPool;
  82. FoldingSet<CondOpInit> TheCondOpInitPool;
  83. FoldingSet<DagInit> TheDagInitPool;
  84. FoldingSet<RecordRecTy> RecordTypePool;
  85. unsigned AnonCounter;
  86. unsigned LastRecordID;
  87. };
  88. } // namespace detail
  89. } // namespace llvm
  90. //===----------------------------------------------------------------------===//
  91. // Type implementations
  92. //===----------------------------------------------------------------------===//
  93. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  94. LLVM_DUMP_METHOD void RecTy::dump() const { print(errs()); }
  95. #endif
  96. ListRecTy *RecTy::getListTy() {
  97. if (!ListTy)
  98. ListTy = new (RK.getImpl().Allocator) ListRecTy(this);
  99. return ListTy;
  100. }
  101. bool RecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  102. assert(RHS && "NULL pointer");
  103. return Kind == RHS->getRecTyKind();
  104. }
  105. bool RecTy::typeIsA(const RecTy *RHS) const { return this == RHS; }
  106. BitRecTy *BitRecTy::get(RecordKeeper &RK) {
  107. return &RK.getImpl().SharedBitRecTy;
  108. }
  109. bool BitRecTy::typeIsConvertibleTo(const RecTy *RHS) const{
  110. if (RecTy::typeIsConvertibleTo(RHS) || RHS->getRecTyKind() == IntRecTyKind)
  111. return true;
  112. if (const BitsRecTy *BitsTy = dyn_cast<BitsRecTy>(RHS))
  113. return BitsTy->getNumBits() == 1;
  114. return false;
  115. }
  116. BitsRecTy *BitsRecTy::get(RecordKeeper &RK, unsigned Sz) {
  117. detail::RecordKeeperImpl &RKImpl = RK.getImpl();
  118. if (Sz >= RKImpl.SharedBitsRecTys.size())
  119. RKImpl.SharedBitsRecTys.resize(Sz + 1);
  120. BitsRecTy *&Ty = RKImpl.SharedBitsRecTys[Sz];
  121. if (!Ty)
  122. Ty = new (RKImpl.Allocator) BitsRecTy(RK, Sz);
  123. return Ty;
  124. }
  125. std::string BitsRecTy::getAsString() const {
  126. return "bits<" + utostr(Size) + ">";
  127. }
  128. bool BitsRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  129. if (RecTy::typeIsConvertibleTo(RHS)) //argument and the sender are same type
  130. return cast<BitsRecTy>(RHS)->Size == Size;
  131. RecTyKind kind = RHS->getRecTyKind();
  132. return (kind == BitRecTyKind && Size == 1) || (kind == IntRecTyKind);
  133. }
  134. bool BitsRecTy::typeIsA(const RecTy *RHS) const {
  135. if (const BitsRecTy *RHSb = dyn_cast<BitsRecTy>(RHS))
  136. return RHSb->Size == Size;
  137. return false;
  138. }
  139. IntRecTy *IntRecTy::get(RecordKeeper &RK) {
  140. return &RK.getImpl().SharedIntRecTy;
  141. }
  142. bool IntRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  143. RecTyKind kind = RHS->getRecTyKind();
  144. return kind==BitRecTyKind || kind==BitsRecTyKind || kind==IntRecTyKind;
  145. }
  146. StringRecTy *StringRecTy::get(RecordKeeper &RK) {
  147. return &RK.getImpl().SharedStringRecTy;
  148. }
  149. std::string StringRecTy::getAsString() const {
  150. return "string";
  151. }
  152. bool StringRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  153. RecTyKind Kind = RHS->getRecTyKind();
  154. return Kind == StringRecTyKind;
  155. }
  156. std::string ListRecTy::getAsString() const {
  157. return "list<" + ElementTy->getAsString() + ">";
  158. }
  159. bool ListRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  160. if (const auto *ListTy = dyn_cast<ListRecTy>(RHS))
  161. return ElementTy->typeIsConvertibleTo(ListTy->getElementType());
  162. return false;
  163. }
  164. bool ListRecTy::typeIsA(const RecTy *RHS) const {
  165. if (const ListRecTy *RHSl = dyn_cast<ListRecTy>(RHS))
  166. return getElementType()->typeIsA(RHSl->getElementType());
  167. return false;
  168. }
  169. DagRecTy *DagRecTy::get(RecordKeeper &RK) {
  170. return &RK.getImpl().SharedDagRecTy;
  171. }
  172. std::string DagRecTy::getAsString() const {
  173. return "dag";
  174. }
  175. static void ProfileRecordRecTy(FoldingSetNodeID &ID,
  176. ArrayRef<Record *> Classes) {
  177. ID.AddInteger(Classes.size());
  178. for (Record *R : Classes)
  179. ID.AddPointer(R);
  180. }
  181. RecordRecTy *RecordRecTy::get(RecordKeeper &RK,
  182. ArrayRef<Record *> UnsortedClasses) {
  183. detail::RecordKeeperImpl &RKImpl = RK.getImpl();
  184. if (UnsortedClasses.empty())
  185. return &RKImpl.AnyRecord;
  186. FoldingSet<RecordRecTy> &ThePool = RKImpl.RecordTypePool;
  187. SmallVector<Record *, 4> Classes(UnsortedClasses.begin(),
  188. UnsortedClasses.end());
  189. llvm::sort(Classes, [](Record *LHS, Record *RHS) {
  190. return LHS->getNameInitAsString() < RHS->getNameInitAsString();
  191. });
  192. FoldingSetNodeID ID;
  193. ProfileRecordRecTy(ID, Classes);
  194. void *IP = nullptr;
  195. if (RecordRecTy *Ty = ThePool.FindNodeOrInsertPos(ID, IP))
  196. return Ty;
  197. #ifndef NDEBUG
  198. // Check for redundancy.
  199. for (unsigned i = 0; i < Classes.size(); ++i) {
  200. for (unsigned j = 0; j < Classes.size(); ++j) {
  201. assert(i == j || !Classes[i]->isSubClassOf(Classes[j]));
  202. }
  203. assert(&Classes[0]->getRecords() == &Classes[i]->getRecords());
  204. }
  205. #endif
  206. void *Mem = RKImpl.Allocator.Allocate(
  207. totalSizeToAlloc<Record *>(Classes.size()), alignof(RecordRecTy));
  208. RecordRecTy *Ty = new (Mem) RecordRecTy(RK, Classes.size());
  209. std::uninitialized_copy(Classes.begin(), Classes.end(),
  210. Ty->getTrailingObjects<Record *>());
  211. ThePool.InsertNode(Ty, IP);
  212. return Ty;
  213. }
  214. RecordRecTy *RecordRecTy::get(Record *Class) {
  215. assert(Class && "unexpected null class");
  216. return get(Class->getRecords(), Class);
  217. }
  218. void RecordRecTy::Profile(FoldingSetNodeID &ID) const {
  219. ProfileRecordRecTy(ID, getClasses());
  220. }
  221. std::string RecordRecTy::getAsString() const {
  222. if (NumClasses == 1)
  223. return getClasses()[0]->getNameInitAsString();
  224. std::string Str = "{";
  225. bool First = true;
  226. for (Record *R : getClasses()) {
  227. if (!First)
  228. Str += ", ";
  229. First = false;
  230. Str += R->getNameInitAsString();
  231. }
  232. Str += "}";
  233. return Str;
  234. }
  235. bool RecordRecTy::isSubClassOf(Record *Class) const {
  236. return llvm::any_of(getClasses(), [Class](Record *MySuperClass) {
  237. return MySuperClass == Class ||
  238. MySuperClass->isSubClassOf(Class);
  239. });
  240. }
  241. bool RecordRecTy::typeIsConvertibleTo(const RecTy *RHS) const {
  242. if (this == RHS)
  243. return true;
  244. const RecordRecTy *RTy = dyn_cast<RecordRecTy>(RHS);
  245. if (!RTy)
  246. return false;
  247. return llvm::all_of(RTy->getClasses(), [this](Record *TargetClass) {
  248. return isSubClassOf(TargetClass);
  249. });
  250. }
  251. bool RecordRecTy::typeIsA(const RecTy *RHS) const {
  252. return typeIsConvertibleTo(RHS);
  253. }
  254. static RecordRecTy *resolveRecordTypes(RecordRecTy *T1, RecordRecTy *T2) {
  255. SmallVector<Record *, 4> CommonSuperClasses;
  256. SmallVector<Record *, 4> Stack(T1->classes_begin(), T1->classes_end());
  257. while (!Stack.empty()) {
  258. Record *R = Stack.pop_back_val();
  259. if (T2->isSubClassOf(R)) {
  260. CommonSuperClasses.push_back(R);
  261. } else {
  262. R->getDirectSuperClasses(Stack);
  263. }
  264. }
  265. return RecordRecTy::get(T1->getRecordKeeper(), CommonSuperClasses);
  266. }
  267. RecTy *llvm::resolveTypes(RecTy *T1, RecTy *T2) {
  268. if (T1 == T2)
  269. return T1;
  270. if (RecordRecTy *RecTy1 = dyn_cast<RecordRecTy>(T1)) {
  271. if (RecordRecTy *RecTy2 = dyn_cast<RecordRecTy>(T2))
  272. return resolveRecordTypes(RecTy1, RecTy2);
  273. }
  274. if (T1->typeIsConvertibleTo(T2))
  275. return T2;
  276. if (T2->typeIsConvertibleTo(T1))
  277. return T1;
  278. if (ListRecTy *ListTy1 = dyn_cast<ListRecTy>(T1)) {
  279. if (ListRecTy *ListTy2 = dyn_cast<ListRecTy>(T2)) {
  280. RecTy* NewType = resolveTypes(ListTy1->getElementType(),
  281. ListTy2->getElementType());
  282. if (NewType)
  283. return NewType->getListTy();
  284. }
  285. }
  286. return nullptr;
  287. }
  288. //===----------------------------------------------------------------------===//
  289. // Initializer implementations
  290. //===----------------------------------------------------------------------===//
  291. void Init::anchor() {}
  292. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  293. LLVM_DUMP_METHOD void Init::dump() const { return print(errs()); }
  294. #endif
  295. RecordKeeper &Init::getRecordKeeper() const {
  296. if (auto *TyInit = dyn_cast<TypedInit>(this))
  297. return TyInit->getType()->getRecordKeeper();
  298. return cast<UnsetInit>(this)->getRecordKeeper();
  299. }
  300. UnsetInit *UnsetInit::get(RecordKeeper &RK) {
  301. return &RK.getImpl().TheUnsetInit;
  302. }
  303. Init *UnsetInit::getCastTo(RecTy *Ty) const {
  304. return const_cast<UnsetInit *>(this);
  305. }
  306. Init *UnsetInit::convertInitializerTo(RecTy *Ty) const {
  307. return const_cast<UnsetInit *>(this);
  308. }
  309. BitInit *BitInit::get(RecordKeeper &RK, bool V) {
  310. return V ? &RK.getImpl().TrueBitInit : &RK.getImpl().FalseBitInit;
  311. }
  312. Init *BitInit::convertInitializerTo(RecTy *Ty) const {
  313. if (isa<BitRecTy>(Ty))
  314. return const_cast<BitInit *>(this);
  315. if (isa<IntRecTy>(Ty))
  316. return IntInit::get(getRecordKeeper(), getValue());
  317. if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
  318. // Can only convert single bit.
  319. if (BRT->getNumBits() == 1)
  320. return BitsInit::get(getRecordKeeper(), const_cast<BitInit *>(this));
  321. }
  322. return nullptr;
  323. }
  324. static void
  325. ProfileBitsInit(FoldingSetNodeID &ID, ArrayRef<Init *> Range) {
  326. ID.AddInteger(Range.size());
  327. for (Init *I : Range)
  328. ID.AddPointer(I);
  329. }
  330. BitsInit *BitsInit::get(RecordKeeper &RK, ArrayRef<Init *> Range) {
  331. FoldingSetNodeID ID;
  332. ProfileBitsInit(ID, Range);
  333. detail::RecordKeeperImpl &RKImpl = RK.getImpl();
  334. void *IP = nullptr;
  335. if (BitsInit *I = RKImpl.TheBitsInitPool.FindNodeOrInsertPos(ID, IP))
  336. return I;
  337. void *Mem = RKImpl.Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
  338. alignof(BitsInit));
  339. BitsInit *I = new (Mem) BitsInit(RK, Range.size());
  340. std::uninitialized_copy(Range.begin(), Range.end(),
  341. I->getTrailingObjects<Init *>());
  342. RKImpl.TheBitsInitPool.InsertNode(I, IP);
  343. return I;
  344. }
  345. void BitsInit::Profile(FoldingSetNodeID &ID) const {
  346. ProfileBitsInit(ID, ArrayRef(getTrailingObjects<Init *>(), NumBits));
  347. }
  348. Init *BitsInit::convertInitializerTo(RecTy *Ty) const {
  349. if (isa<BitRecTy>(Ty)) {
  350. if (getNumBits() != 1) return nullptr; // Only accept if just one bit!
  351. return getBit(0);
  352. }
  353. if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
  354. // If the number of bits is right, return it. Otherwise we need to expand
  355. // or truncate.
  356. if (getNumBits() != BRT->getNumBits()) return nullptr;
  357. return const_cast<BitsInit *>(this);
  358. }
  359. if (isa<IntRecTy>(Ty)) {
  360. int64_t Result = 0;
  361. for (unsigned i = 0, e = getNumBits(); i != e; ++i)
  362. if (auto *Bit = dyn_cast<BitInit>(getBit(i)))
  363. Result |= static_cast<int64_t>(Bit->getValue()) << i;
  364. else
  365. return nullptr;
  366. return IntInit::get(getRecordKeeper(), Result);
  367. }
  368. return nullptr;
  369. }
  370. Init *
  371. BitsInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
  372. SmallVector<Init *, 16> NewBits(Bits.size());
  373. for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
  374. if (Bits[i] >= getNumBits())
  375. return nullptr;
  376. NewBits[i] = getBit(Bits[i]);
  377. }
  378. return BitsInit::get(getRecordKeeper(), NewBits);
  379. }
  380. bool BitsInit::isConcrete() const {
  381. for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
  382. if (!getBit(i)->isConcrete())
  383. return false;
  384. }
  385. return true;
  386. }
  387. std::string BitsInit::getAsString() const {
  388. std::string Result = "{ ";
  389. for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
  390. if (i) Result += ", ";
  391. if (Init *Bit = getBit(e-i-1))
  392. Result += Bit->getAsString();
  393. else
  394. Result += "*";
  395. }
  396. return Result + " }";
  397. }
  398. // resolveReferences - If there are any field references that refer to fields
  399. // that have been filled in, we can propagate the values now.
  400. Init *BitsInit::resolveReferences(Resolver &R) const {
  401. bool Changed = false;
  402. SmallVector<Init *, 16> NewBits(getNumBits());
  403. Init *CachedBitVarRef = nullptr;
  404. Init *CachedBitVarResolved = nullptr;
  405. for (unsigned i = 0, e = getNumBits(); i != e; ++i) {
  406. Init *CurBit = getBit(i);
  407. Init *NewBit = CurBit;
  408. if (VarBitInit *CurBitVar = dyn_cast<VarBitInit>(CurBit)) {
  409. if (CurBitVar->getBitVar() != CachedBitVarRef) {
  410. CachedBitVarRef = CurBitVar->getBitVar();
  411. CachedBitVarResolved = CachedBitVarRef->resolveReferences(R);
  412. }
  413. assert(CachedBitVarResolved && "Unresolved bitvar reference");
  414. NewBit = CachedBitVarResolved->getBit(CurBitVar->getBitNum());
  415. } else {
  416. // getBit(0) implicitly converts int and bits<1> values to bit.
  417. NewBit = CurBit->resolveReferences(R)->getBit(0);
  418. }
  419. if (isa<UnsetInit>(NewBit) && R.keepUnsetBits())
  420. NewBit = CurBit;
  421. NewBits[i] = NewBit;
  422. Changed |= CurBit != NewBit;
  423. }
  424. if (Changed)
  425. return BitsInit::get(getRecordKeeper(), NewBits);
  426. return const_cast<BitsInit *>(this);
  427. }
  428. IntInit *IntInit::get(RecordKeeper &RK, int64_t V) {
  429. IntInit *&I = RK.getImpl().TheIntInitPool[V];
  430. if (!I)
  431. I = new (RK.getImpl().Allocator) IntInit(RK, V);
  432. return I;
  433. }
  434. std::string IntInit::getAsString() const {
  435. return itostr(Value);
  436. }
  437. static bool canFitInBitfield(int64_t Value, unsigned NumBits) {
  438. // For example, with NumBits == 4, we permit Values from [-7 .. 15].
  439. return (NumBits >= sizeof(Value) * 8) ||
  440. (Value >> NumBits == 0) || (Value >> (NumBits-1) == -1);
  441. }
  442. Init *IntInit::convertInitializerTo(RecTy *Ty) const {
  443. if (isa<IntRecTy>(Ty))
  444. return const_cast<IntInit *>(this);
  445. if (isa<BitRecTy>(Ty)) {
  446. int64_t Val = getValue();
  447. if (Val != 0 && Val != 1) return nullptr; // Only accept 0 or 1 for a bit!
  448. return BitInit::get(getRecordKeeper(), Val != 0);
  449. }
  450. if (auto *BRT = dyn_cast<BitsRecTy>(Ty)) {
  451. int64_t Value = getValue();
  452. // Make sure this bitfield is large enough to hold the integer value.
  453. if (!canFitInBitfield(Value, BRT->getNumBits()))
  454. return nullptr;
  455. SmallVector<Init *, 16> NewBits(BRT->getNumBits());
  456. for (unsigned i = 0; i != BRT->getNumBits(); ++i)
  457. NewBits[i] =
  458. BitInit::get(getRecordKeeper(), Value & ((i < 64) ? (1LL << i) : 0));
  459. return BitsInit::get(getRecordKeeper(), NewBits);
  460. }
  461. return nullptr;
  462. }
  463. Init *
  464. IntInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
  465. SmallVector<Init *, 16> NewBits(Bits.size());
  466. for (unsigned i = 0, e = Bits.size(); i != e; ++i) {
  467. if (Bits[i] >= 64)
  468. return nullptr;
  469. NewBits[i] =
  470. BitInit::get(getRecordKeeper(), Value & (INT64_C(1) << Bits[i]));
  471. }
  472. return BitsInit::get(getRecordKeeper(), NewBits);
  473. }
  474. AnonymousNameInit *AnonymousNameInit::get(RecordKeeper &RK, unsigned V) {
  475. return new (RK.getImpl().Allocator) AnonymousNameInit(RK, V);
  476. }
  477. StringInit *AnonymousNameInit::getNameInit() const {
  478. return StringInit::get(getRecordKeeper(), getAsString());
  479. }
  480. std::string AnonymousNameInit::getAsString() const {
  481. return "anonymous_" + utostr(Value);
  482. }
  483. Init *AnonymousNameInit::resolveReferences(Resolver &R) const {
  484. auto *Old = const_cast<Init *>(static_cast<const Init *>(this));
  485. auto *New = R.resolve(Old);
  486. New = New ? New : Old;
  487. if (R.isFinal())
  488. if (auto *Anonymous = dyn_cast<AnonymousNameInit>(New))
  489. return Anonymous->getNameInit();
  490. return New;
  491. }
  492. StringInit *StringInit::get(RecordKeeper &RK, StringRef V, StringFormat Fmt) {
  493. detail::RecordKeeperImpl &RKImpl = RK.getImpl();
  494. auto &InitMap = Fmt == SF_String ? RKImpl.StringInitStringPool
  495. : RKImpl.StringInitCodePool;
  496. auto &Entry = *InitMap.insert(std::make_pair(V, nullptr)).first;
  497. if (!Entry.second)
  498. Entry.second = new (RKImpl.Allocator) StringInit(RK, Entry.getKey(), Fmt);
  499. return Entry.second;
  500. }
  501. Init *StringInit::convertInitializerTo(RecTy *Ty) const {
  502. if (isa<StringRecTy>(Ty))
  503. return const_cast<StringInit *>(this);
  504. return nullptr;
  505. }
  506. static void ProfileListInit(FoldingSetNodeID &ID,
  507. ArrayRef<Init *> Range,
  508. RecTy *EltTy) {
  509. ID.AddInteger(Range.size());
  510. ID.AddPointer(EltTy);
  511. for (Init *I : Range)
  512. ID.AddPointer(I);
  513. }
  514. ListInit *ListInit::get(ArrayRef<Init *> Range, RecTy *EltTy) {
  515. FoldingSetNodeID ID;
  516. ProfileListInit(ID, Range, EltTy);
  517. detail::RecordKeeperImpl &RK = EltTy->getRecordKeeper().getImpl();
  518. void *IP = nullptr;
  519. if (ListInit *I = RK.TheListInitPool.FindNodeOrInsertPos(ID, IP))
  520. return I;
  521. assert(Range.empty() || !isa<TypedInit>(Range[0]) ||
  522. cast<TypedInit>(Range[0])->getType()->typeIsConvertibleTo(EltTy));
  523. void *Mem = RK.Allocator.Allocate(totalSizeToAlloc<Init *>(Range.size()),
  524. alignof(ListInit));
  525. ListInit *I = new (Mem) ListInit(Range.size(), EltTy);
  526. std::uninitialized_copy(Range.begin(), Range.end(),
  527. I->getTrailingObjects<Init *>());
  528. RK.TheListInitPool.InsertNode(I, IP);
  529. return I;
  530. }
  531. void ListInit::Profile(FoldingSetNodeID &ID) const {
  532. RecTy *EltTy = cast<ListRecTy>(getType())->getElementType();
  533. ProfileListInit(ID, getValues(), EltTy);
  534. }
  535. Init *ListInit::convertInitializerTo(RecTy *Ty) const {
  536. if (getType() == Ty)
  537. return const_cast<ListInit*>(this);
  538. if (auto *LRT = dyn_cast<ListRecTy>(Ty)) {
  539. SmallVector<Init*, 8> Elements;
  540. Elements.reserve(getValues().size());
  541. // Verify that all of the elements of the list are subclasses of the
  542. // appropriate class!
  543. bool Changed = false;
  544. RecTy *ElementType = LRT->getElementType();
  545. for (Init *I : getValues())
  546. if (Init *CI = I->convertInitializerTo(ElementType)) {
  547. Elements.push_back(CI);
  548. if (CI != I)
  549. Changed = true;
  550. } else
  551. return nullptr;
  552. if (!Changed)
  553. return const_cast<ListInit*>(this);
  554. return ListInit::get(Elements, ElementType);
  555. }
  556. return nullptr;
  557. }
  558. Init *ListInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
  559. if (Elements.size() == 1) {
  560. if (Elements[0] >= size())
  561. return nullptr;
  562. return getElement(Elements[0]);
  563. }
  564. SmallVector<Init*, 8> Vals;
  565. Vals.reserve(Elements.size());
  566. for (unsigned Element : Elements) {
  567. if (Element >= size())
  568. return nullptr;
  569. Vals.push_back(getElement(Element));
  570. }
  571. return ListInit::get(Vals, getElementType());
  572. }
  573. Record *ListInit::getElementAsRecord(unsigned i) const {
  574. assert(i < NumValues && "List element index out of range!");
  575. DefInit *DI = dyn_cast<DefInit>(getElement(i));
  576. if (!DI)
  577. PrintFatalError("Expected record in list!");
  578. return DI->getDef();
  579. }
  580. Init *ListInit::resolveReferences(Resolver &R) const {
  581. SmallVector<Init*, 8> Resolved;
  582. Resolved.reserve(size());
  583. bool Changed = false;
  584. for (Init *CurElt : getValues()) {
  585. Init *E = CurElt->resolveReferences(R);
  586. Changed |= E != CurElt;
  587. Resolved.push_back(E);
  588. }
  589. if (Changed)
  590. return ListInit::get(Resolved, getElementType());
  591. return const_cast<ListInit *>(this);
  592. }
  593. bool ListInit::isComplete() const {
  594. for (Init *Element : *this) {
  595. if (!Element->isComplete())
  596. return false;
  597. }
  598. return true;
  599. }
  600. bool ListInit::isConcrete() const {
  601. for (Init *Element : *this) {
  602. if (!Element->isConcrete())
  603. return false;
  604. }
  605. return true;
  606. }
  607. std::string ListInit::getAsString() const {
  608. std::string Result = "[";
  609. const char *sep = "";
  610. for (Init *Element : *this) {
  611. Result += sep;
  612. sep = ", ";
  613. Result += Element->getAsString();
  614. }
  615. return Result + "]";
  616. }
  617. Init *OpInit::getBit(unsigned Bit) const {
  618. if (getType() == BitRecTy::get(getRecordKeeper()))
  619. return const_cast<OpInit*>(this);
  620. return VarBitInit::get(const_cast<OpInit*>(this), Bit);
  621. }
  622. static void
  623. ProfileUnOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *Op, RecTy *Type) {
  624. ID.AddInteger(Opcode);
  625. ID.AddPointer(Op);
  626. ID.AddPointer(Type);
  627. }
  628. UnOpInit *UnOpInit::get(UnaryOp Opc, Init *LHS, RecTy *Type) {
  629. FoldingSetNodeID ID;
  630. ProfileUnOpInit(ID, Opc, LHS, Type);
  631. detail::RecordKeeperImpl &RK = Type->getRecordKeeper().getImpl();
  632. void *IP = nullptr;
  633. if (UnOpInit *I = RK.TheUnOpInitPool.FindNodeOrInsertPos(ID, IP))
  634. return I;
  635. UnOpInit *I = new (RK.Allocator) UnOpInit(Opc, LHS, Type);
  636. RK.TheUnOpInitPool.InsertNode(I, IP);
  637. return I;
  638. }
  639. void UnOpInit::Profile(FoldingSetNodeID &ID) const {
  640. ProfileUnOpInit(ID, getOpcode(), getOperand(), getType());
  641. }
  642. Init *UnOpInit::Fold(Record *CurRec, bool IsFinal) const {
  643. RecordKeeper &RK = getRecordKeeper();
  644. switch (getOpcode()) {
  645. case CAST:
  646. if (isa<StringRecTy>(getType())) {
  647. if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
  648. return LHSs;
  649. if (DefInit *LHSd = dyn_cast<DefInit>(LHS))
  650. return StringInit::get(RK, LHSd->getAsString());
  651. if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
  652. LHS->convertInitializerTo(IntRecTy::get(RK))))
  653. return StringInit::get(RK, LHSi->getAsString());
  654. } else if (isa<RecordRecTy>(getType())) {
  655. if (StringInit *Name = dyn_cast<StringInit>(LHS)) {
  656. if (!CurRec && !IsFinal)
  657. break;
  658. assert(CurRec && "NULL pointer");
  659. Record *D;
  660. // Self-references are allowed, but their resolution is delayed until
  661. // the final resolve to ensure that we get the correct type for them.
  662. auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
  663. if (Name == CurRec->getNameInit() ||
  664. (Anonymous && Name == Anonymous->getNameInit())) {
  665. if (!IsFinal)
  666. break;
  667. D = CurRec;
  668. } else {
  669. D = CurRec->getRecords().getDef(Name->getValue());
  670. if (!D) {
  671. if (IsFinal)
  672. PrintFatalError(CurRec->getLoc(),
  673. Twine("Undefined reference to record: '") +
  674. Name->getValue() + "'\n");
  675. break;
  676. }
  677. }
  678. DefInit *DI = DefInit::get(D);
  679. if (!DI->getType()->typeIsA(getType())) {
  680. PrintFatalError(CurRec->getLoc(),
  681. Twine("Expected type '") +
  682. getType()->getAsString() + "', got '" +
  683. DI->getType()->getAsString() + "' in: " +
  684. getAsString() + "\n");
  685. }
  686. return DI;
  687. }
  688. }
  689. if (Init *NewInit = LHS->convertInitializerTo(getType()))
  690. return NewInit;
  691. break;
  692. case NOT:
  693. if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
  694. LHS->convertInitializerTo(IntRecTy::get(RK))))
  695. return IntInit::get(RK, LHSi->getValue() ? 0 : 1);
  696. break;
  697. case HEAD:
  698. if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
  699. assert(!LHSl->empty() && "Empty list in head");
  700. return LHSl->getElement(0);
  701. }
  702. break;
  703. case TAIL:
  704. if (ListInit *LHSl = dyn_cast<ListInit>(LHS)) {
  705. assert(!LHSl->empty() && "Empty list in tail");
  706. // Note the +1. We can't just pass the result of getValues()
  707. // directly.
  708. return ListInit::get(LHSl->getValues().slice(1), LHSl->getElementType());
  709. }
  710. break;
  711. case SIZE:
  712. if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
  713. return IntInit::get(RK, LHSl->size());
  714. if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
  715. return IntInit::get(RK, LHSd->arg_size());
  716. if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
  717. return IntInit::get(RK, LHSs->getValue().size());
  718. break;
  719. case EMPTY:
  720. if (ListInit *LHSl = dyn_cast<ListInit>(LHS))
  721. return IntInit::get(RK, LHSl->empty());
  722. if (DagInit *LHSd = dyn_cast<DagInit>(LHS))
  723. return IntInit::get(RK, LHSd->arg_empty());
  724. if (StringInit *LHSs = dyn_cast<StringInit>(LHS))
  725. return IntInit::get(RK, LHSs->getValue().empty());
  726. break;
  727. case GETDAGOP:
  728. if (DagInit *Dag = dyn_cast<DagInit>(LHS)) {
  729. DefInit *DI = DefInit::get(Dag->getOperatorAsDef({}));
  730. if (!DI->getType()->typeIsA(getType())) {
  731. PrintFatalError(CurRec->getLoc(),
  732. Twine("Expected type '") +
  733. getType()->getAsString() + "', got '" +
  734. DI->getType()->getAsString() + "' in: " +
  735. getAsString() + "\n");
  736. } else {
  737. return DI;
  738. }
  739. }
  740. break;
  741. case LOG2:
  742. if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
  743. LHS->convertInitializerTo(IntRecTy::get(RK)))) {
  744. int64_t LHSv = LHSi->getValue();
  745. if (LHSv <= 0) {
  746. PrintFatalError(CurRec->getLoc(),
  747. "Illegal operation: logtwo is undefined "
  748. "on arguments less than or equal to 0");
  749. } else {
  750. uint64_t Log = Log2_64(LHSv);
  751. assert(Log <= INT64_MAX &&
  752. "Log of an int64_t must be smaller than INT64_MAX");
  753. return IntInit::get(RK, static_cast<int64_t>(Log));
  754. }
  755. }
  756. break;
  757. }
  758. return const_cast<UnOpInit *>(this);
  759. }
  760. Init *UnOpInit::resolveReferences(Resolver &R) const {
  761. Init *lhs = LHS->resolveReferences(R);
  762. if (LHS != lhs || (R.isFinal() && getOpcode() == CAST))
  763. return (UnOpInit::get(getOpcode(), lhs, getType()))
  764. ->Fold(R.getCurrentRecord(), R.isFinal());
  765. return const_cast<UnOpInit *>(this);
  766. }
  767. std::string UnOpInit::getAsString() const {
  768. std::string Result;
  769. switch (getOpcode()) {
  770. case CAST: Result = "!cast<" + getType()->getAsString() + ">"; break;
  771. case NOT: Result = "!not"; break;
  772. case HEAD: Result = "!head"; break;
  773. case TAIL: Result = "!tail"; break;
  774. case SIZE: Result = "!size"; break;
  775. case EMPTY: Result = "!empty"; break;
  776. case GETDAGOP: Result = "!getdagop"; break;
  777. case LOG2 : Result = "!logtwo"; break;
  778. }
  779. return Result + "(" + LHS->getAsString() + ")";
  780. }
  781. static void
  782. ProfileBinOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *RHS,
  783. RecTy *Type) {
  784. ID.AddInteger(Opcode);
  785. ID.AddPointer(LHS);
  786. ID.AddPointer(RHS);
  787. ID.AddPointer(Type);
  788. }
  789. BinOpInit *BinOpInit::get(BinaryOp Opc, Init *LHS, Init *RHS, RecTy *Type) {
  790. FoldingSetNodeID ID;
  791. ProfileBinOpInit(ID, Opc, LHS, RHS, Type);
  792. detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
  793. void *IP = nullptr;
  794. if (BinOpInit *I = RK.TheBinOpInitPool.FindNodeOrInsertPos(ID, IP))
  795. return I;
  796. BinOpInit *I = new (RK.Allocator) BinOpInit(Opc, LHS, RHS, Type);
  797. RK.TheBinOpInitPool.InsertNode(I, IP);
  798. return I;
  799. }
  800. void BinOpInit::Profile(FoldingSetNodeID &ID) const {
  801. ProfileBinOpInit(ID, getOpcode(), getLHS(), getRHS(), getType());
  802. }
  803. static StringInit *ConcatStringInits(const StringInit *I0,
  804. const StringInit *I1) {
  805. SmallString<80> Concat(I0->getValue());
  806. Concat.append(I1->getValue());
  807. return StringInit::get(
  808. I0->getRecordKeeper(), Concat,
  809. StringInit::determineFormat(I0->getFormat(), I1->getFormat()));
  810. }
  811. static StringInit *interleaveStringList(const ListInit *List,
  812. const StringInit *Delim) {
  813. if (List->size() == 0)
  814. return StringInit::get(List->getRecordKeeper(), "");
  815. StringInit *Element = dyn_cast<StringInit>(List->getElement(0));
  816. if (!Element)
  817. return nullptr;
  818. SmallString<80> Result(Element->getValue());
  819. StringInit::StringFormat Fmt = StringInit::SF_String;
  820. for (unsigned I = 1, E = List->size(); I < E; ++I) {
  821. Result.append(Delim->getValue());
  822. StringInit *Element = dyn_cast<StringInit>(List->getElement(I));
  823. if (!Element)
  824. return nullptr;
  825. Result.append(Element->getValue());
  826. Fmt = StringInit::determineFormat(Fmt, Element->getFormat());
  827. }
  828. return StringInit::get(List->getRecordKeeper(), Result, Fmt);
  829. }
  830. static StringInit *interleaveIntList(const ListInit *List,
  831. const StringInit *Delim) {
  832. RecordKeeper &RK = List->getRecordKeeper();
  833. if (List->size() == 0)
  834. return StringInit::get(RK, "");
  835. IntInit *Element = dyn_cast_or_null<IntInit>(
  836. List->getElement(0)->convertInitializerTo(IntRecTy::get(RK)));
  837. if (!Element)
  838. return nullptr;
  839. SmallString<80> Result(Element->getAsString());
  840. for (unsigned I = 1, E = List->size(); I < E; ++I) {
  841. Result.append(Delim->getValue());
  842. IntInit *Element = dyn_cast_or_null<IntInit>(
  843. List->getElement(I)->convertInitializerTo(IntRecTy::get(RK)));
  844. if (!Element)
  845. return nullptr;
  846. Result.append(Element->getAsString());
  847. }
  848. return StringInit::get(RK, Result);
  849. }
  850. Init *BinOpInit::getStrConcat(Init *I0, Init *I1) {
  851. // Shortcut for the common case of concatenating two strings.
  852. if (const StringInit *I0s = dyn_cast<StringInit>(I0))
  853. if (const StringInit *I1s = dyn_cast<StringInit>(I1))
  854. return ConcatStringInits(I0s, I1s);
  855. return BinOpInit::get(BinOpInit::STRCONCAT, I0, I1,
  856. StringRecTy::get(I0->getRecordKeeper()));
  857. }
  858. static ListInit *ConcatListInits(const ListInit *LHS,
  859. const ListInit *RHS) {
  860. SmallVector<Init *, 8> Args;
  861. llvm::append_range(Args, *LHS);
  862. llvm::append_range(Args, *RHS);
  863. return ListInit::get(Args, LHS->getElementType());
  864. }
  865. Init *BinOpInit::getListConcat(TypedInit *LHS, Init *RHS) {
  866. assert(isa<ListRecTy>(LHS->getType()) && "First arg must be a list");
  867. // Shortcut for the common case of concatenating two lists.
  868. if (const ListInit *LHSList = dyn_cast<ListInit>(LHS))
  869. if (const ListInit *RHSList = dyn_cast<ListInit>(RHS))
  870. return ConcatListInits(LHSList, RHSList);
  871. return BinOpInit::get(BinOpInit::LISTCONCAT, LHS, RHS, LHS->getType());
  872. }
  873. std::optional<bool> BinOpInit::CompareInit(unsigned Opc, Init *LHS, Init *RHS) const {
  874. // First see if we have two bit, bits, or int.
  875. IntInit *LHSi = dyn_cast_or_null<IntInit>(
  876. LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
  877. IntInit *RHSi = dyn_cast_or_null<IntInit>(
  878. RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
  879. if (LHSi && RHSi) {
  880. bool Result;
  881. switch (Opc) {
  882. case EQ:
  883. Result = LHSi->getValue() == RHSi->getValue();
  884. break;
  885. case NE:
  886. Result = LHSi->getValue() != RHSi->getValue();
  887. break;
  888. case LE:
  889. Result = LHSi->getValue() <= RHSi->getValue();
  890. break;
  891. case LT:
  892. Result = LHSi->getValue() < RHSi->getValue();
  893. break;
  894. case GE:
  895. Result = LHSi->getValue() >= RHSi->getValue();
  896. break;
  897. case GT:
  898. Result = LHSi->getValue() > RHSi->getValue();
  899. break;
  900. default:
  901. llvm_unreachable("unhandled comparison");
  902. }
  903. return Result;
  904. }
  905. // Next try strings.
  906. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  907. StringInit *RHSs = dyn_cast<StringInit>(RHS);
  908. if (LHSs && RHSs) {
  909. bool Result;
  910. switch (Opc) {
  911. case EQ:
  912. Result = LHSs->getValue() == RHSs->getValue();
  913. break;
  914. case NE:
  915. Result = LHSs->getValue() != RHSs->getValue();
  916. break;
  917. case LE:
  918. Result = LHSs->getValue() <= RHSs->getValue();
  919. break;
  920. case LT:
  921. Result = LHSs->getValue() < RHSs->getValue();
  922. break;
  923. case GE:
  924. Result = LHSs->getValue() >= RHSs->getValue();
  925. break;
  926. case GT:
  927. Result = LHSs->getValue() > RHSs->getValue();
  928. break;
  929. default:
  930. llvm_unreachable("unhandled comparison");
  931. }
  932. return Result;
  933. }
  934. // Finally, !eq and !ne can be used with records.
  935. if (Opc == EQ || Opc == NE) {
  936. DefInit *LHSd = dyn_cast<DefInit>(LHS);
  937. DefInit *RHSd = dyn_cast<DefInit>(RHS);
  938. if (LHSd && RHSd)
  939. return (Opc == EQ) ? LHSd == RHSd : LHSd != RHSd;
  940. }
  941. return std::nullopt;
  942. }
  943. Init *BinOpInit::Fold(Record *CurRec) const {
  944. switch (getOpcode()) {
  945. case CONCAT: {
  946. DagInit *LHSs = dyn_cast<DagInit>(LHS);
  947. DagInit *RHSs = dyn_cast<DagInit>(RHS);
  948. if (LHSs && RHSs) {
  949. DefInit *LOp = dyn_cast<DefInit>(LHSs->getOperator());
  950. DefInit *ROp = dyn_cast<DefInit>(RHSs->getOperator());
  951. if ((!LOp && !isa<UnsetInit>(LHSs->getOperator())) ||
  952. (!ROp && !isa<UnsetInit>(RHSs->getOperator())))
  953. break;
  954. if (LOp && ROp && LOp->getDef() != ROp->getDef()) {
  955. PrintFatalError(Twine("Concatenated Dag operators do not match: '") +
  956. LHSs->getAsString() + "' vs. '" + RHSs->getAsString() +
  957. "'");
  958. }
  959. Init *Op = LOp ? LOp : ROp;
  960. if (!Op)
  961. Op = UnsetInit::get(getRecordKeeper());
  962. SmallVector<Init*, 8> Args;
  963. SmallVector<StringInit*, 8> ArgNames;
  964. for (unsigned i = 0, e = LHSs->getNumArgs(); i != e; ++i) {
  965. Args.push_back(LHSs->getArg(i));
  966. ArgNames.push_back(LHSs->getArgName(i));
  967. }
  968. for (unsigned i = 0, e = RHSs->getNumArgs(); i != e; ++i) {
  969. Args.push_back(RHSs->getArg(i));
  970. ArgNames.push_back(RHSs->getArgName(i));
  971. }
  972. return DagInit::get(Op, nullptr, Args, ArgNames);
  973. }
  974. break;
  975. }
  976. case LISTCONCAT: {
  977. ListInit *LHSs = dyn_cast<ListInit>(LHS);
  978. ListInit *RHSs = dyn_cast<ListInit>(RHS);
  979. if (LHSs && RHSs) {
  980. SmallVector<Init *, 8> Args;
  981. llvm::append_range(Args, *LHSs);
  982. llvm::append_range(Args, *RHSs);
  983. return ListInit::get(Args, LHSs->getElementType());
  984. }
  985. break;
  986. }
  987. case LISTSPLAT: {
  988. TypedInit *Value = dyn_cast<TypedInit>(LHS);
  989. IntInit *Size = dyn_cast<IntInit>(RHS);
  990. if (Value && Size) {
  991. SmallVector<Init *, 8> Args(Size->getValue(), Value);
  992. return ListInit::get(Args, Value->getType());
  993. }
  994. break;
  995. }
  996. case LISTREMOVE: {
  997. ListInit *LHSs = dyn_cast<ListInit>(LHS);
  998. ListInit *RHSs = dyn_cast<ListInit>(RHS);
  999. if (LHSs && RHSs) {
  1000. SmallVector<Init *, 8> Args;
  1001. for (Init *EltLHS : *LHSs) {
  1002. bool Found = false;
  1003. for (Init *EltRHS : *RHSs) {
  1004. if (std::optional<bool> Result = CompareInit(EQ, EltLHS, EltRHS)) {
  1005. if (*Result) {
  1006. Found = true;
  1007. break;
  1008. }
  1009. }
  1010. }
  1011. if (!Found)
  1012. Args.push_back(EltLHS);
  1013. }
  1014. return ListInit::get(Args, LHSs->getElementType());
  1015. }
  1016. break;
  1017. }
  1018. case STRCONCAT: {
  1019. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  1020. StringInit *RHSs = dyn_cast<StringInit>(RHS);
  1021. if (LHSs && RHSs)
  1022. return ConcatStringInits(LHSs, RHSs);
  1023. break;
  1024. }
  1025. case INTERLEAVE: {
  1026. ListInit *List = dyn_cast<ListInit>(LHS);
  1027. StringInit *Delim = dyn_cast<StringInit>(RHS);
  1028. if (List && Delim) {
  1029. StringInit *Result;
  1030. if (isa<StringRecTy>(List->getElementType()))
  1031. Result = interleaveStringList(List, Delim);
  1032. else
  1033. Result = interleaveIntList(List, Delim);
  1034. if (Result)
  1035. return Result;
  1036. }
  1037. break;
  1038. }
  1039. case EQ:
  1040. case NE:
  1041. case LE:
  1042. case LT:
  1043. case GE:
  1044. case GT: {
  1045. if (std::optional<bool> Result = CompareInit(getOpcode(), LHS, RHS))
  1046. return BitInit::get(getRecordKeeper(), *Result);
  1047. break;
  1048. }
  1049. case SETDAGOP: {
  1050. DagInit *Dag = dyn_cast<DagInit>(LHS);
  1051. DefInit *Op = dyn_cast<DefInit>(RHS);
  1052. if (Dag && Op) {
  1053. SmallVector<Init*, 8> Args;
  1054. SmallVector<StringInit*, 8> ArgNames;
  1055. for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
  1056. Args.push_back(Dag->getArg(i));
  1057. ArgNames.push_back(Dag->getArgName(i));
  1058. }
  1059. return DagInit::get(Op, nullptr, Args, ArgNames);
  1060. }
  1061. break;
  1062. }
  1063. case ADD:
  1064. case SUB:
  1065. case MUL:
  1066. case DIV:
  1067. case AND:
  1068. case OR:
  1069. case XOR:
  1070. case SHL:
  1071. case SRA:
  1072. case SRL: {
  1073. IntInit *LHSi = dyn_cast_or_null<IntInit>(
  1074. LHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
  1075. IntInit *RHSi = dyn_cast_or_null<IntInit>(
  1076. RHS->convertInitializerTo(IntRecTy::get(getRecordKeeper())));
  1077. if (LHSi && RHSi) {
  1078. int64_t LHSv = LHSi->getValue(), RHSv = RHSi->getValue();
  1079. int64_t Result;
  1080. switch (getOpcode()) {
  1081. default: llvm_unreachable("Bad opcode!");
  1082. case ADD: Result = LHSv + RHSv; break;
  1083. case SUB: Result = LHSv - RHSv; break;
  1084. case MUL: Result = LHSv * RHSv; break;
  1085. case DIV:
  1086. if (RHSv == 0)
  1087. PrintFatalError(CurRec->getLoc(),
  1088. "Illegal operation: division by zero");
  1089. else if (LHSv == INT64_MIN && RHSv == -1)
  1090. PrintFatalError(CurRec->getLoc(),
  1091. "Illegal operation: INT64_MIN / -1");
  1092. else
  1093. Result = LHSv / RHSv;
  1094. break;
  1095. case AND: Result = LHSv & RHSv; break;
  1096. case OR: Result = LHSv | RHSv; break;
  1097. case XOR: Result = LHSv ^ RHSv; break;
  1098. case SHL: Result = (uint64_t)LHSv << (uint64_t)RHSv; break;
  1099. case SRA: Result = LHSv >> RHSv; break;
  1100. case SRL: Result = (uint64_t)LHSv >> (uint64_t)RHSv; break;
  1101. }
  1102. return IntInit::get(getRecordKeeper(), Result);
  1103. }
  1104. break;
  1105. }
  1106. }
  1107. return const_cast<BinOpInit *>(this);
  1108. }
  1109. Init *BinOpInit::resolveReferences(Resolver &R) const {
  1110. Init *lhs = LHS->resolveReferences(R);
  1111. Init *rhs = RHS->resolveReferences(R);
  1112. if (LHS != lhs || RHS != rhs)
  1113. return (BinOpInit::get(getOpcode(), lhs, rhs, getType()))
  1114. ->Fold(R.getCurrentRecord());
  1115. return const_cast<BinOpInit *>(this);
  1116. }
  1117. std::string BinOpInit::getAsString() const {
  1118. std::string Result;
  1119. switch (getOpcode()) {
  1120. case CONCAT: Result = "!con"; break;
  1121. case ADD: Result = "!add"; break;
  1122. case SUB: Result = "!sub"; break;
  1123. case MUL: Result = "!mul"; break;
  1124. case DIV: Result = "!div"; break;
  1125. case AND: Result = "!and"; break;
  1126. case OR: Result = "!or"; break;
  1127. case XOR: Result = "!xor"; break;
  1128. case SHL: Result = "!shl"; break;
  1129. case SRA: Result = "!sra"; break;
  1130. case SRL: Result = "!srl"; break;
  1131. case EQ: Result = "!eq"; break;
  1132. case NE: Result = "!ne"; break;
  1133. case LE: Result = "!le"; break;
  1134. case LT: Result = "!lt"; break;
  1135. case GE: Result = "!ge"; break;
  1136. case GT: Result = "!gt"; break;
  1137. case LISTCONCAT: Result = "!listconcat"; break;
  1138. case LISTSPLAT: Result = "!listsplat"; break;
  1139. case LISTREMOVE: Result = "!listremove"; break;
  1140. case STRCONCAT: Result = "!strconcat"; break;
  1141. case INTERLEAVE: Result = "!interleave"; break;
  1142. case SETDAGOP: Result = "!setdagop"; break;
  1143. }
  1144. return Result + "(" + LHS->getAsString() + ", " + RHS->getAsString() + ")";
  1145. }
  1146. static void
  1147. ProfileTernOpInit(FoldingSetNodeID &ID, unsigned Opcode, Init *LHS, Init *MHS,
  1148. Init *RHS, RecTy *Type) {
  1149. ID.AddInteger(Opcode);
  1150. ID.AddPointer(LHS);
  1151. ID.AddPointer(MHS);
  1152. ID.AddPointer(RHS);
  1153. ID.AddPointer(Type);
  1154. }
  1155. TernOpInit *TernOpInit::get(TernaryOp Opc, Init *LHS, Init *MHS, Init *RHS,
  1156. RecTy *Type) {
  1157. FoldingSetNodeID ID;
  1158. ProfileTernOpInit(ID, Opc, LHS, MHS, RHS, Type);
  1159. detail::RecordKeeperImpl &RK = LHS->getRecordKeeper().getImpl();
  1160. void *IP = nullptr;
  1161. if (TernOpInit *I = RK.TheTernOpInitPool.FindNodeOrInsertPos(ID, IP))
  1162. return I;
  1163. TernOpInit *I = new (RK.Allocator) TernOpInit(Opc, LHS, MHS, RHS, Type);
  1164. RK.TheTernOpInitPool.InsertNode(I, IP);
  1165. return I;
  1166. }
  1167. void TernOpInit::Profile(FoldingSetNodeID &ID) const {
  1168. ProfileTernOpInit(ID, getOpcode(), getLHS(), getMHS(), getRHS(), getType());
  1169. }
  1170. static Init *ItemApply(Init *LHS, Init *MHSe, Init *RHS, Record *CurRec) {
  1171. MapResolver R(CurRec);
  1172. R.set(LHS, MHSe);
  1173. return RHS->resolveReferences(R);
  1174. }
  1175. static Init *ForeachDagApply(Init *LHS, DagInit *MHSd, Init *RHS,
  1176. Record *CurRec) {
  1177. bool Change = false;
  1178. Init *Val = ItemApply(LHS, MHSd->getOperator(), RHS, CurRec);
  1179. if (Val != MHSd->getOperator())
  1180. Change = true;
  1181. SmallVector<std::pair<Init *, StringInit *>, 8> NewArgs;
  1182. for (unsigned int i = 0; i < MHSd->getNumArgs(); ++i) {
  1183. Init *Arg = MHSd->getArg(i);
  1184. Init *NewArg;
  1185. StringInit *ArgName = MHSd->getArgName(i);
  1186. if (DagInit *Argd = dyn_cast<DagInit>(Arg))
  1187. NewArg = ForeachDagApply(LHS, Argd, RHS, CurRec);
  1188. else
  1189. NewArg = ItemApply(LHS, Arg, RHS, CurRec);
  1190. NewArgs.push_back(std::make_pair(NewArg, ArgName));
  1191. if (Arg != NewArg)
  1192. Change = true;
  1193. }
  1194. if (Change)
  1195. return DagInit::get(Val, nullptr, NewArgs);
  1196. return MHSd;
  1197. }
  1198. // Applies RHS to all elements of MHS, using LHS as a temp variable.
  1199. static Init *ForeachHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
  1200. Record *CurRec) {
  1201. if (DagInit *MHSd = dyn_cast<DagInit>(MHS))
  1202. return ForeachDagApply(LHS, MHSd, RHS, CurRec);
  1203. if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
  1204. SmallVector<Init *, 8> NewList(MHSl->begin(), MHSl->end());
  1205. for (Init *&Item : NewList) {
  1206. Init *NewItem = ItemApply(LHS, Item, RHS, CurRec);
  1207. if (NewItem != Item)
  1208. Item = NewItem;
  1209. }
  1210. return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
  1211. }
  1212. return nullptr;
  1213. }
  1214. // Evaluates RHS for all elements of MHS, using LHS as a temp variable.
  1215. // Creates a new list with the elements that evaluated to true.
  1216. static Init *FilterHelper(Init *LHS, Init *MHS, Init *RHS, RecTy *Type,
  1217. Record *CurRec) {
  1218. if (ListInit *MHSl = dyn_cast<ListInit>(MHS)) {
  1219. SmallVector<Init *, 8> NewList;
  1220. for (Init *Item : MHSl->getValues()) {
  1221. Init *Include = ItemApply(LHS, Item, RHS, CurRec);
  1222. if (!Include)
  1223. return nullptr;
  1224. if (IntInit *IncludeInt =
  1225. dyn_cast_or_null<IntInit>(Include->convertInitializerTo(
  1226. IntRecTy::get(LHS->getRecordKeeper())))) {
  1227. if (IncludeInt->getValue())
  1228. NewList.push_back(Item);
  1229. } else {
  1230. return nullptr;
  1231. }
  1232. }
  1233. return ListInit::get(NewList, cast<ListRecTy>(Type)->getElementType());
  1234. }
  1235. return nullptr;
  1236. }
  1237. Init *TernOpInit::Fold(Record *CurRec) const {
  1238. RecordKeeper &RK = getRecordKeeper();
  1239. switch (getOpcode()) {
  1240. case SUBST: {
  1241. DefInit *LHSd = dyn_cast<DefInit>(LHS);
  1242. VarInit *LHSv = dyn_cast<VarInit>(LHS);
  1243. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  1244. DefInit *MHSd = dyn_cast<DefInit>(MHS);
  1245. VarInit *MHSv = dyn_cast<VarInit>(MHS);
  1246. StringInit *MHSs = dyn_cast<StringInit>(MHS);
  1247. DefInit *RHSd = dyn_cast<DefInit>(RHS);
  1248. VarInit *RHSv = dyn_cast<VarInit>(RHS);
  1249. StringInit *RHSs = dyn_cast<StringInit>(RHS);
  1250. if (LHSd && MHSd && RHSd) {
  1251. Record *Val = RHSd->getDef();
  1252. if (LHSd->getAsString() == RHSd->getAsString())
  1253. Val = MHSd->getDef();
  1254. return DefInit::get(Val);
  1255. }
  1256. if (LHSv && MHSv && RHSv) {
  1257. std::string Val = std::string(RHSv->getName());
  1258. if (LHSv->getAsString() == RHSv->getAsString())
  1259. Val = std::string(MHSv->getName());
  1260. return VarInit::get(Val, getType());
  1261. }
  1262. if (LHSs && MHSs && RHSs) {
  1263. std::string Val = std::string(RHSs->getValue());
  1264. std::string::size_type found;
  1265. std::string::size_type idx = 0;
  1266. while (true) {
  1267. found = Val.find(std::string(LHSs->getValue()), idx);
  1268. if (found == std::string::npos)
  1269. break;
  1270. Val.replace(found, LHSs->getValue().size(),
  1271. std::string(MHSs->getValue()));
  1272. idx = found + MHSs->getValue().size();
  1273. }
  1274. return StringInit::get(RK, Val);
  1275. }
  1276. break;
  1277. }
  1278. case FOREACH: {
  1279. if (Init *Result = ForeachHelper(LHS, MHS, RHS, getType(), CurRec))
  1280. return Result;
  1281. break;
  1282. }
  1283. case FILTER: {
  1284. if (Init *Result = FilterHelper(LHS, MHS, RHS, getType(), CurRec))
  1285. return Result;
  1286. break;
  1287. }
  1288. case IF: {
  1289. if (IntInit *LHSi = dyn_cast_or_null<IntInit>(
  1290. LHS->convertInitializerTo(IntRecTy::get(RK)))) {
  1291. if (LHSi->getValue())
  1292. return MHS;
  1293. return RHS;
  1294. }
  1295. break;
  1296. }
  1297. case DAG: {
  1298. ListInit *MHSl = dyn_cast<ListInit>(MHS);
  1299. ListInit *RHSl = dyn_cast<ListInit>(RHS);
  1300. bool MHSok = MHSl || isa<UnsetInit>(MHS);
  1301. bool RHSok = RHSl || isa<UnsetInit>(RHS);
  1302. if (isa<UnsetInit>(MHS) && isa<UnsetInit>(RHS))
  1303. break; // Typically prevented by the parser, but might happen with template args
  1304. if (MHSok && RHSok && (!MHSl || !RHSl || MHSl->size() == RHSl->size())) {
  1305. SmallVector<std::pair<Init *, StringInit *>, 8> Children;
  1306. unsigned Size = MHSl ? MHSl->size() : RHSl->size();
  1307. for (unsigned i = 0; i != Size; ++i) {
  1308. Init *Node = MHSl ? MHSl->getElement(i) : UnsetInit::get(RK);
  1309. Init *Name = RHSl ? RHSl->getElement(i) : UnsetInit::get(RK);
  1310. if (!isa<StringInit>(Name) && !isa<UnsetInit>(Name))
  1311. return const_cast<TernOpInit *>(this);
  1312. Children.emplace_back(Node, dyn_cast<StringInit>(Name));
  1313. }
  1314. return DagInit::get(LHS, nullptr, Children);
  1315. }
  1316. break;
  1317. }
  1318. case SUBSTR: {
  1319. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  1320. IntInit *MHSi = dyn_cast<IntInit>(MHS);
  1321. IntInit *RHSi = dyn_cast<IntInit>(RHS);
  1322. if (LHSs && MHSi && RHSi) {
  1323. int64_t StringSize = LHSs->getValue().size();
  1324. int64_t Start = MHSi->getValue();
  1325. int64_t Length = RHSi->getValue();
  1326. if (Start < 0 || Start > StringSize)
  1327. PrintError(CurRec->getLoc(),
  1328. Twine("!substr start position is out of range 0...") +
  1329. std::to_string(StringSize) + ": " +
  1330. std::to_string(Start));
  1331. if (Length < 0)
  1332. PrintError(CurRec->getLoc(), "!substr length must be nonnegative");
  1333. return StringInit::get(RK, LHSs->getValue().substr(Start, Length),
  1334. LHSs->getFormat());
  1335. }
  1336. break;
  1337. }
  1338. case FIND: {
  1339. StringInit *LHSs = dyn_cast<StringInit>(LHS);
  1340. StringInit *MHSs = dyn_cast<StringInit>(MHS);
  1341. IntInit *RHSi = dyn_cast<IntInit>(RHS);
  1342. if (LHSs && MHSs && RHSi) {
  1343. int64_t SourceSize = LHSs->getValue().size();
  1344. int64_t Start = RHSi->getValue();
  1345. if (Start < 0 || Start > SourceSize)
  1346. PrintError(CurRec->getLoc(),
  1347. Twine("!find start position is out of range 0...") +
  1348. std::to_string(SourceSize) + ": " +
  1349. std::to_string(Start));
  1350. auto I = LHSs->getValue().find(MHSs->getValue(), Start);
  1351. if (I == std::string::npos)
  1352. return IntInit::get(RK, -1);
  1353. return IntInit::get(RK, I);
  1354. }
  1355. break;
  1356. }
  1357. }
  1358. return const_cast<TernOpInit *>(this);
  1359. }
  1360. Init *TernOpInit::resolveReferences(Resolver &R) const {
  1361. Init *lhs = LHS->resolveReferences(R);
  1362. if (getOpcode() == IF && lhs != LHS) {
  1363. if (IntInit *Value = dyn_cast_or_null<IntInit>(
  1364. lhs->convertInitializerTo(IntRecTy::get(getRecordKeeper())))) {
  1365. // Short-circuit
  1366. if (Value->getValue())
  1367. return MHS->resolveReferences(R);
  1368. return RHS->resolveReferences(R);
  1369. }
  1370. }
  1371. Init *mhs = MHS->resolveReferences(R);
  1372. Init *rhs;
  1373. if (getOpcode() == FOREACH || getOpcode() == FILTER) {
  1374. ShadowResolver SR(R);
  1375. SR.addShadow(lhs);
  1376. rhs = RHS->resolveReferences(SR);
  1377. } else {
  1378. rhs = RHS->resolveReferences(R);
  1379. }
  1380. if (LHS != lhs || MHS != mhs || RHS != rhs)
  1381. return (TernOpInit::get(getOpcode(), lhs, mhs, rhs, getType()))
  1382. ->Fold(R.getCurrentRecord());
  1383. return const_cast<TernOpInit *>(this);
  1384. }
  1385. std::string TernOpInit::getAsString() const {
  1386. std::string Result;
  1387. bool UnquotedLHS = false;
  1388. switch (getOpcode()) {
  1389. case DAG: Result = "!dag"; break;
  1390. case FILTER: Result = "!filter"; UnquotedLHS = true; break;
  1391. case FOREACH: Result = "!foreach"; UnquotedLHS = true; break;
  1392. case IF: Result = "!if"; break;
  1393. case SUBST: Result = "!subst"; break;
  1394. case SUBSTR: Result = "!substr"; break;
  1395. case FIND: Result = "!find"; break;
  1396. }
  1397. return (Result + "(" +
  1398. (UnquotedLHS ? LHS->getAsUnquotedString() : LHS->getAsString()) +
  1399. ", " + MHS->getAsString() + ", " + RHS->getAsString() + ")");
  1400. }
  1401. static void ProfileFoldOpInit(FoldingSetNodeID &ID, Init *Start, Init *List,
  1402. Init *A, Init *B, Init *Expr, RecTy *Type) {
  1403. ID.AddPointer(Start);
  1404. ID.AddPointer(List);
  1405. ID.AddPointer(A);
  1406. ID.AddPointer(B);
  1407. ID.AddPointer(Expr);
  1408. ID.AddPointer(Type);
  1409. }
  1410. FoldOpInit *FoldOpInit::get(Init *Start, Init *List, Init *A, Init *B,
  1411. Init *Expr, RecTy *Type) {
  1412. FoldingSetNodeID ID;
  1413. ProfileFoldOpInit(ID, Start, List, A, B, Expr, Type);
  1414. detail::RecordKeeperImpl &RK = Start->getRecordKeeper().getImpl();
  1415. void *IP = nullptr;
  1416. if (FoldOpInit *I = RK.TheFoldOpInitPool.FindNodeOrInsertPos(ID, IP))
  1417. return I;
  1418. FoldOpInit *I = new (RK.Allocator) FoldOpInit(Start, List, A, B, Expr, Type);
  1419. RK.TheFoldOpInitPool.InsertNode(I, IP);
  1420. return I;
  1421. }
  1422. void FoldOpInit::Profile(FoldingSetNodeID &ID) const {
  1423. ProfileFoldOpInit(ID, Start, List, A, B, Expr, getType());
  1424. }
  1425. Init *FoldOpInit::Fold(Record *CurRec) const {
  1426. if (ListInit *LI = dyn_cast<ListInit>(List)) {
  1427. Init *Accum = Start;
  1428. for (Init *Elt : *LI) {
  1429. MapResolver R(CurRec);
  1430. R.set(A, Accum);
  1431. R.set(B, Elt);
  1432. Accum = Expr->resolveReferences(R);
  1433. }
  1434. return Accum;
  1435. }
  1436. return const_cast<FoldOpInit *>(this);
  1437. }
  1438. Init *FoldOpInit::resolveReferences(Resolver &R) const {
  1439. Init *NewStart = Start->resolveReferences(R);
  1440. Init *NewList = List->resolveReferences(R);
  1441. ShadowResolver SR(R);
  1442. SR.addShadow(A);
  1443. SR.addShadow(B);
  1444. Init *NewExpr = Expr->resolveReferences(SR);
  1445. if (Start == NewStart && List == NewList && Expr == NewExpr)
  1446. return const_cast<FoldOpInit *>(this);
  1447. return get(NewStart, NewList, A, B, NewExpr, getType())
  1448. ->Fold(R.getCurrentRecord());
  1449. }
  1450. Init *FoldOpInit::getBit(unsigned Bit) const {
  1451. return VarBitInit::get(const_cast<FoldOpInit *>(this), Bit);
  1452. }
  1453. std::string FoldOpInit::getAsString() const {
  1454. return (Twine("!foldl(") + Start->getAsString() + ", " + List->getAsString() +
  1455. ", " + A->getAsUnquotedString() + ", " + B->getAsUnquotedString() +
  1456. ", " + Expr->getAsString() + ")")
  1457. .str();
  1458. }
  1459. static void ProfileIsAOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
  1460. Init *Expr) {
  1461. ID.AddPointer(CheckType);
  1462. ID.AddPointer(Expr);
  1463. }
  1464. IsAOpInit *IsAOpInit::get(RecTy *CheckType, Init *Expr) {
  1465. FoldingSetNodeID ID;
  1466. ProfileIsAOpInit(ID, CheckType, Expr);
  1467. detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
  1468. void *IP = nullptr;
  1469. if (IsAOpInit *I = RK.TheIsAOpInitPool.FindNodeOrInsertPos(ID, IP))
  1470. return I;
  1471. IsAOpInit *I = new (RK.Allocator) IsAOpInit(CheckType, Expr);
  1472. RK.TheIsAOpInitPool.InsertNode(I, IP);
  1473. return I;
  1474. }
  1475. void IsAOpInit::Profile(FoldingSetNodeID &ID) const {
  1476. ProfileIsAOpInit(ID, CheckType, Expr);
  1477. }
  1478. Init *IsAOpInit::Fold() const {
  1479. if (TypedInit *TI = dyn_cast<TypedInit>(Expr)) {
  1480. // Is the expression type known to be (a subclass of) the desired type?
  1481. if (TI->getType()->typeIsConvertibleTo(CheckType))
  1482. return IntInit::get(getRecordKeeper(), 1);
  1483. if (isa<RecordRecTy>(CheckType)) {
  1484. // If the target type is not a subclass of the expression type, or if
  1485. // the expression has fully resolved to a record, we know that it can't
  1486. // be of the required type.
  1487. if (!CheckType->typeIsConvertibleTo(TI->getType()) || isa<DefInit>(Expr))
  1488. return IntInit::get(getRecordKeeper(), 0);
  1489. } else {
  1490. // We treat non-record types as not castable.
  1491. return IntInit::get(getRecordKeeper(), 0);
  1492. }
  1493. }
  1494. return const_cast<IsAOpInit *>(this);
  1495. }
  1496. Init *IsAOpInit::resolveReferences(Resolver &R) const {
  1497. Init *NewExpr = Expr->resolveReferences(R);
  1498. if (Expr != NewExpr)
  1499. return get(CheckType, NewExpr)->Fold();
  1500. return const_cast<IsAOpInit *>(this);
  1501. }
  1502. Init *IsAOpInit::getBit(unsigned Bit) const {
  1503. return VarBitInit::get(const_cast<IsAOpInit *>(this), Bit);
  1504. }
  1505. std::string IsAOpInit::getAsString() const {
  1506. return (Twine("!isa<") + CheckType->getAsString() + ">(" +
  1507. Expr->getAsString() + ")")
  1508. .str();
  1509. }
  1510. static void ProfileExistsOpInit(FoldingSetNodeID &ID, RecTy *CheckType,
  1511. Init *Expr) {
  1512. ID.AddPointer(CheckType);
  1513. ID.AddPointer(Expr);
  1514. }
  1515. ExistsOpInit *ExistsOpInit::get(RecTy *CheckType, Init *Expr) {
  1516. FoldingSetNodeID ID;
  1517. ProfileExistsOpInit(ID, CheckType, Expr);
  1518. detail::RecordKeeperImpl &RK = Expr->getRecordKeeper().getImpl();
  1519. void *IP = nullptr;
  1520. if (ExistsOpInit *I = RK.TheExistsOpInitPool.FindNodeOrInsertPos(ID, IP))
  1521. return I;
  1522. ExistsOpInit *I = new (RK.Allocator) ExistsOpInit(CheckType, Expr);
  1523. RK.TheExistsOpInitPool.InsertNode(I, IP);
  1524. return I;
  1525. }
  1526. void ExistsOpInit::Profile(FoldingSetNodeID &ID) const {
  1527. ProfileExistsOpInit(ID, CheckType, Expr);
  1528. }
  1529. Init *ExistsOpInit::Fold(Record *CurRec, bool IsFinal) const {
  1530. if (StringInit *Name = dyn_cast<StringInit>(Expr)) {
  1531. if (!CurRec && !IsFinal)
  1532. return const_cast<ExistsOpInit *>(this);
  1533. // Self-references are allowed, but their resolution is delayed until
  1534. // the final resolve to ensure that we get the correct type for them.
  1535. auto *Anonymous = dyn_cast<AnonymousNameInit>(CurRec->getNameInit());
  1536. if (Name == CurRec->getNameInit() ||
  1537. (Anonymous && Name == Anonymous->getNameInit())) {
  1538. if (!IsFinal)
  1539. return const_cast<ExistsOpInit *>(this);
  1540. // No doubt that there exists a record, so we should check if types are
  1541. // compatiable.
  1542. return IntInit::get(getRecordKeeper(),
  1543. CurRec->getType()->typeIsA(CheckType));
  1544. }
  1545. // Look up all defined records to see if we can find one.
  1546. Record *D = CheckType->getRecordKeeper().getDef(Name->getValue());
  1547. if (!D) {
  1548. if (IsFinal)
  1549. return IntInit::get(getRecordKeeper(), 0);
  1550. return const_cast<ExistsOpInit *>(this);
  1551. }
  1552. // Check if types are compatiable.
  1553. return IntInit::get(getRecordKeeper(),
  1554. DefInit::get(D)->getType()->typeIsA(CheckType));
  1555. }
  1556. return const_cast<ExistsOpInit *>(this);
  1557. }
  1558. Init *ExistsOpInit::resolveReferences(Resolver &R) const {
  1559. Init *NewExpr = Expr->resolveReferences(R);
  1560. if (Expr != NewExpr || R.isFinal())
  1561. return get(CheckType, NewExpr)->Fold(R.getCurrentRecord(), R.isFinal());
  1562. return const_cast<ExistsOpInit *>(this);
  1563. }
  1564. Init *ExistsOpInit::getBit(unsigned Bit) const {
  1565. return VarBitInit::get(const_cast<ExistsOpInit *>(this), Bit);
  1566. }
  1567. std::string ExistsOpInit::getAsString() const {
  1568. return (Twine("!exists<") + CheckType->getAsString() + ">(" +
  1569. Expr->getAsString() + ")")
  1570. .str();
  1571. }
  1572. RecTy *TypedInit::getFieldType(StringInit *FieldName) const {
  1573. if (RecordRecTy *RecordType = dyn_cast<RecordRecTy>(getType())) {
  1574. for (Record *Rec : RecordType->getClasses()) {
  1575. if (RecordVal *Field = Rec->getValue(FieldName))
  1576. return Field->getType();
  1577. }
  1578. }
  1579. return nullptr;
  1580. }
  1581. Init *
  1582. TypedInit::convertInitializerTo(RecTy *Ty) const {
  1583. if (getType() == Ty || getType()->typeIsA(Ty))
  1584. return const_cast<TypedInit *>(this);
  1585. if (isa<BitRecTy>(getType()) && isa<BitsRecTy>(Ty) &&
  1586. cast<BitsRecTy>(Ty)->getNumBits() == 1)
  1587. return BitsInit::get(getRecordKeeper(), {const_cast<TypedInit *>(this)});
  1588. return nullptr;
  1589. }
  1590. Init *TypedInit::convertInitializerBitRange(ArrayRef<unsigned> Bits) const {
  1591. BitsRecTy *T = dyn_cast<BitsRecTy>(getType());
  1592. if (!T) return nullptr; // Cannot subscript a non-bits variable.
  1593. unsigned NumBits = T->getNumBits();
  1594. SmallVector<Init *, 16> NewBits;
  1595. NewBits.reserve(Bits.size());
  1596. for (unsigned Bit : Bits) {
  1597. if (Bit >= NumBits)
  1598. return nullptr;
  1599. NewBits.push_back(VarBitInit::get(const_cast<TypedInit *>(this), Bit));
  1600. }
  1601. return BitsInit::get(getRecordKeeper(), NewBits);
  1602. }
  1603. Init *TypedInit::getCastTo(RecTy *Ty) const {
  1604. // Handle the common case quickly
  1605. if (getType() == Ty || getType()->typeIsA(Ty))
  1606. return const_cast<TypedInit *>(this);
  1607. if (Init *Converted = convertInitializerTo(Ty)) {
  1608. assert(!isa<TypedInit>(Converted) ||
  1609. cast<TypedInit>(Converted)->getType()->typeIsA(Ty));
  1610. return Converted;
  1611. }
  1612. if (!getType()->typeIsConvertibleTo(Ty))
  1613. return nullptr;
  1614. return UnOpInit::get(UnOpInit::CAST, const_cast<TypedInit *>(this), Ty)
  1615. ->Fold(nullptr);
  1616. }
  1617. Init *TypedInit::convertInitListSlice(ArrayRef<unsigned> Elements) const {
  1618. ListRecTy *T = dyn_cast<ListRecTy>(getType());
  1619. if (!T) return nullptr; // Cannot subscript a non-list variable.
  1620. if (Elements.size() == 1)
  1621. return VarListElementInit::get(const_cast<TypedInit *>(this), Elements[0]);
  1622. SmallVector<Init*, 8> ListInits;
  1623. ListInits.reserve(Elements.size());
  1624. for (unsigned Element : Elements)
  1625. ListInits.push_back(VarListElementInit::get(const_cast<TypedInit *>(this),
  1626. Element));
  1627. return ListInit::get(ListInits, T->getElementType());
  1628. }
  1629. VarInit *VarInit::get(StringRef VN, RecTy *T) {
  1630. Init *Value = StringInit::get(T->getRecordKeeper(), VN);
  1631. return VarInit::get(Value, T);
  1632. }
  1633. VarInit *VarInit::get(Init *VN, RecTy *T) {
  1634. detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
  1635. VarInit *&I = RK.TheVarInitPool[std::make_pair(T, VN)];
  1636. if (!I)
  1637. I = new (RK.Allocator) VarInit(VN, T);
  1638. return I;
  1639. }
  1640. StringRef VarInit::getName() const {
  1641. StringInit *NameString = cast<StringInit>(getNameInit());
  1642. return NameString->getValue();
  1643. }
  1644. Init *VarInit::getBit(unsigned Bit) const {
  1645. if (getType() == BitRecTy::get(getRecordKeeper()))
  1646. return const_cast<VarInit*>(this);
  1647. return VarBitInit::get(const_cast<VarInit*>(this), Bit);
  1648. }
  1649. Init *VarInit::resolveReferences(Resolver &R) const {
  1650. if (Init *Val = R.resolve(VarName))
  1651. return Val;
  1652. return const_cast<VarInit *>(this);
  1653. }
  1654. VarBitInit *VarBitInit::get(TypedInit *T, unsigned B) {
  1655. detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
  1656. VarBitInit *&I = RK.TheVarBitInitPool[std::make_pair(T, B)];
  1657. if (!I)
  1658. I = new (RK.Allocator) VarBitInit(T, B);
  1659. return I;
  1660. }
  1661. std::string VarBitInit::getAsString() const {
  1662. return TI->getAsString() + "{" + utostr(Bit) + "}";
  1663. }
  1664. Init *VarBitInit::resolveReferences(Resolver &R) const {
  1665. Init *I = TI->resolveReferences(R);
  1666. if (TI != I)
  1667. return I->getBit(getBitNum());
  1668. return const_cast<VarBitInit*>(this);
  1669. }
  1670. VarListElementInit *VarListElementInit::get(TypedInit *T, unsigned E) {
  1671. detail::RecordKeeperImpl &RK = T->getRecordKeeper().getImpl();
  1672. VarListElementInit *&I = RK.TheVarListElementInitPool[std::make_pair(T, E)];
  1673. if (!I)
  1674. I = new (RK.Allocator) VarListElementInit(T, E);
  1675. return I;
  1676. }
  1677. std::string VarListElementInit::getAsString() const {
  1678. return TI->getAsString() + "[" + utostr(Element) + "]";
  1679. }
  1680. Init *VarListElementInit::resolveReferences(Resolver &R) const {
  1681. Init *NewTI = TI->resolveReferences(R);
  1682. if (ListInit *List = dyn_cast<ListInit>(NewTI)) {
  1683. // Leave out-of-bounds array references as-is. This can happen without
  1684. // being an error, e.g. in the untaken "branch" of an !if expression.
  1685. if (getElementNum() < List->size())
  1686. return List->getElement(getElementNum());
  1687. }
  1688. if (NewTI != TI && isa<TypedInit>(NewTI))
  1689. return VarListElementInit::get(cast<TypedInit>(NewTI), getElementNum());
  1690. return const_cast<VarListElementInit *>(this);
  1691. }
  1692. Init *VarListElementInit::getBit(unsigned Bit) const {
  1693. if (getType() == BitRecTy::get(getRecordKeeper()))
  1694. return const_cast<VarListElementInit*>(this);
  1695. return VarBitInit::get(const_cast<VarListElementInit*>(this), Bit);
  1696. }
  1697. DefInit::DefInit(Record *D)
  1698. : TypedInit(IK_DefInit, D->getType()), Def(D) {}
  1699. DefInit *DefInit::get(Record *R) {
  1700. return R->getDefInit();
  1701. }
  1702. Init *DefInit::convertInitializerTo(RecTy *Ty) const {
  1703. if (auto *RRT = dyn_cast<RecordRecTy>(Ty))
  1704. if (getType()->typeIsConvertibleTo(RRT))
  1705. return const_cast<DefInit *>(this);
  1706. return nullptr;
  1707. }
  1708. RecTy *DefInit::getFieldType(StringInit *FieldName) const {
  1709. if (const RecordVal *RV = Def->getValue(FieldName))
  1710. return RV->getType();
  1711. return nullptr;
  1712. }
  1713. std::string DefInit::getAsString() const { return std::string(Def->getName()); }
  1714. static void ProfileVarDefInit(FoldingSetNodeID &ID,
  1715. Record *Class,
  1716. ArrayRef<Init *> Args) {
  1717. ID.AddInteger(Args.size());
  1718. ID.AddPointer(Class);
  1719. for (Init *I : Args)
  1720. ID.AddPointer(I);
  1721. }
  1722. VarDefInit::VarDefInit(Record *Class, unsigned N)
  1723. : TypedInit(IK_VarDefInit, RecordRecTy::get(Class)), Class(Class),
  1724. NumArgs(N) {}
  1725. VarDefInit *VarDefInit::get(Record *Class, ArrayRef<Init *> Args) {
  1726. FoldingSetNodeID ID;
  1727. ProfileVarDefInit(ID, Class, Args);
  1728. detail::RecordKeeperImpl &RK = Class->getRecords().getImpl();
  1729. void *IP = nullptr;
  1730. if (VarDefInit *I = RK.TheVarDefInitPool.FindNodeOrInsertPos(ID, IP))
  1731. return I;
  1732. void *Mem = RK.Allocator.Allocate(totalSizeToAlloc<Init *>(Args.size()),
  1733. alignof(VarDefInit));
  1734. VarDefInit *I = new (Mem) VarDefInit(Class, Args.size());
  1735. std::uninitialized_copy(Args.begin(), Args.end(),
  1736. I->getTrailingObjects<Init *>());
  1737. RK.TheVarDefInitPool.InsertNode(I, IP);
  1738. return I;
  1739. }
  1740. void VarDefInit::Profile(FoldingSetNodeID &ID) const {
  1741. ProfileVarDefInit(ID, Class, args());
  1742. }
  1743. DefInit *VarDefInit::instantiate() {
  1744. if (!Def) {
  1745. RecordKeeper &Records = Class->getRecords();
  1746. auto NewRecOwner = std::make_unique<Record>(Records.getNewAnonymousName(),
  1747. Class->getLoc(), Records,
  1748. /*IsAnonymous=*/true);
  1749. Record *NewRec = NewRecOwner.get();
  1750. // Copy values from class to instance
  1751. for (const RecordVal &Val : Class->getValues())
  1752. NewRec->addValue(Val);
  1753. // Copy assertions from class to instance.
  1754. NewRec->appendAssertions(Class);
  1755. // Substitute and resolve template arguments
  1756. ArrayRef<Init *> TArgs = Class->getTemplateArgs();
  1757. MapResolver R(NewRec);
  1758. for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
  1759. if (i < args_size())
  1760. R.set(TArgs[i], getArg(i));
  1761. else
  1762. R.set(TArgs[i], NewRec->getValue(TArgs[i])->getValue());
  1763. NewRec->removeValue(TArgs[i]);
  1764. }
  1765. NewRec->resolveReferences(R);
  1766. // Add superclasses.
  1767. ArrayRef<std::pair<Record *, SMRange>> SCs = Class->getSuperClasses();
  1768. for (const auto &SCPair : SCs)
  1769. NewRec->addSuperClass(SCPair.first, SCPair.second);
  1770. NewRec->addSuperClass(Class,
  1771. SMRange(Class->getLoc().back(),
  1772. Class->getLoc().back()));
  1773. // Resolve internal references and store in record keeper
  1774. NewRec->resolveReferences();
  1775. Records.addDef(std::move(NewRecOwner));
  1776. // Check the assertions.
  1777. NewRec->checkRecordAssertions();
  1778. Def = DefInit::get(NewRec);
  1779. }
  1780. return Def;
  1781. }
  1782. Init *VarDefInit::resolveReferences(Resolver &R) const {
  1783. TrackUnresolvedResolver UR(&R);
  1784. bool Changed = false;
  1785. SmallVector<Init *, 8> NewArgs;
  1786. NewArgs.reserve(args_size());
  1787. for (Init *Arg : args()) {
  1788. Init *NewArg = Arg->resolveReferences(UR);
  1789. NewArgs.push_back(NewArg);
  1790. Changed |= NewArg != Arg;
  1791. }
  1792. if (Changed) {
  1793. auto New = VarDefInit::get(Class, NewArgs);
  1794. if (!UR.foundUnresolved())
  1795. return New->instantiate();
  1796. return New;
  1797. }
  1798. return const_cast<VarDefInit *>(this);
  1799. }
  1800. Init *VarDefInit::Fold() const {
  1801. if (Def)
  1802. return Def;
  1803. TrackUnresolvedResolver R;
  1804. for (Init *Arg : args())
  1805. Arg->resolveReferences(R);
  1806. if (!R.foundUnresolved())
  1807. return const_cast<VarDefInit *>(this)->instantiate();
  1808. return const_cast<VarDefInit *>(this);
  1809. }
  1810. std::string VarDefInit::getAsString() const {
  1811. std::string Result = Class->getNameInitAsString() + "<";
  1812. const char *sep = "";
  1813. for (Init *Arg : args()) {
  1814. Result += sep;
  1815. sep = ", ";
  1816. Result += Arg->getAsString();
  1817. }
  1818. return Result + ">";
  1819. }
  1820. FieldInit *FieldInit::get(Init *R, StringInit *FN) {
  1821. detail::RecordKeeperImpl &RK = R->getRecordKeeper().getImpl();
  1822. FieldInit *&I = RK.TheFieldInitPool[std::make_pair(R, FN)];
  1823. if (!I)
  1824. I = new (RK.Allocator) FieldInit(R, FN);
  1825. return I;
  1826. }
  1827. Init *FieldInit::getBit(unsigned Bit) const {
  1828. if (getType() == BitRecTy::get(getRecordKeeper()))
  1829. return const_cast<FieldInit*>(this);
  1830. return VarBitInit::get(const_cast<FieldInit*>(this), Bit);
  1831. }
  1832. Init *FieldInit::resolveReferences(Resolver &R) const {
  1833. Init *NewRec = Rec->resolveReferences(R);
  1834. if (NewRec != Rec)
  1835. return FieldInit::get(NewRec, FieldName)->Fold(R.getCurrentRecord());
  1836. return const_cast<FieldInit *>(this);
  1837. }
  1838. Init *FieldInit::Fold(Record *CurRec) const {
  1839. if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
  1840. Record *Def = DI->getDef();
  1841. if (Def == CurRec)
  1842. PrintFatalError(CurRec->getLoc(),
  1843. Twine("Attempting to access field '") +
  1844. FieldName->getAsUnquotedString() + "' of '" +
  1845. Rec->getAsString() + "' is a forbidden self-reference");
  1846. Init *FieldVal = Def->getValue(FieldName)->getValue();
  1847. if (FieldVal->isConcrete())
  1848. return FieldVal;
  1849. }
  1850. return const_cast<FieldInit *>(this);
  1851. }
  1852. bool FieldInit::isConcrete() const {
  1853. if (DefInit *DI = dyn_cast<DefInit>(Rec)) {
  1854. Init *FieldVal = DI->getDef()->getValue(FieldName)->getValue();
  1855. return FieldVal->isConcrete();
  1856. }
  1857. return false;
  1858. }
  1859. static void ProfileCondOpInit(FoldingSetNodeID &ID,
  1860. ArrayRef<Init *> CondRange,
  1861. ArrayRef<Init *> ValRange,
  1862. const RecTy *ValType) {
  1863. assert(CondRange.size() == ValRange.size() &&
  1864. "Number of conditions and values must match!");
  1865. ID.AddPointer(ValType);
  1866. ArrayRef<Init *>::iterator Case = CondRange.begin();
  1867. ArrayRef<Init *>::iterator Val = ValRange.begin();
  1868. while (Case != CondRange.end()) {
  1869. ID.AddPointer(*Case++);
  1870. ID.AddPointer(*Val++);
  1871. }
  1872. }
  1873. void CondOpInit::Profile(FoldingSetNodeID &ID) const {
  1874. ProfileCondOpInit(ID, ArrayRef(getTrailingObjects<Init *>(), NumConds),
  1875. ArrayRef(getTrailingObjects<Init *>() + NumConds, NumConds),
  1876. ValType);
  1877. }
  1878. CondOpInit *CondOpInit::get(ArrayRef<Init *> CondRange,
  1879. ArrayRef<Init *> ValRange, RecTy *Ty) {
  1880. assert(CondRange.size() == ValRange.size() &&
  1881. "Number of conditions and values must match!");
  1882. FoldingSetNodeID ID;
  1883. ProfileCondOpInit(ID, CondRange, ValRange, Ty);
  1884. detail::RecordKeeperImpl &RK = Ty->getRecordKeeper().getImpl();
  1885. void *IP = nullptr;
  1886. if (CondOpInit *I = RK.TheCondOpInitPool.FindNodeOrInsertPos(ID, IP))
  1887. return I;
  1888. void *Mem = RK.Allocator.Allocate(
  1889. totalSizeToAlloc<Init *>(2 * CondRange.size()), alignof(BitsInit));
  1890. CondOpInit *I = new(Mem) CondOpInit(CondRange.size(), Ty);
  1891. std::uninitialized_copy(CondRange.begin(), CondRange.end(),
  1892. I->getTrailingObjects<Init *>());
  1893. std::uninitialized_copy(ValRange.begin(), ValRange.end(),
  1894. I->getTrailingObjects<Init *>()+CondRange.size());
  1895. RK.TheCondOpInitPool.InsertNode(I, IP);
  1896. return I;
  1897. }
  1898. Init *CondOpInit::resolveReferences(Resolver &R) const {
  1899. SmallVector<Init*, 4> NewConds;
  1900. bool Changed = false;
  1901. for (const Init *Case : getConds()) {
  1902. Init *NewCase = Case->resolveReferences(R);
  1903. NewConds.push_back(NewCase);
  1904. Changed |= NewCase != Case;
  1905. }
  1906. SmallVector<Init*, 4> NewVals;
  1907. for (const Init *Val : getVals()) {
  1908. Init *NewVal = Val->resolveReferences(R);
  1909. NewVals.push_back(NewVal);
  1910. Changed |= NewVal != Val;
  1911. }
  1912. if (Changed)
  1913. return (CondOpInit::get(NewConds, NewVals,
  1914. getValType()))->Fold(R.getCurrentRecord());
  1915. return const_cast<CondOpInit *>(this);
  1916. }
  1917. Init *CondOpInit::Fold(Record *CurRec) const {
  1918. RecordKeeper &RK = getRecordKeeper();
  1919. for ( unsigned i = 0; i < NumConds; ++i) {
  1920. Init *Cond = getCond(i);
  1921. Init *Val = getVal(i);
  1922. if (IntInit *CondI = dyn_cast_or_null<IntInit>(
  1923. Cond->convertInitializerTo(IntRecTy::get(RK)))) {
  1924. if (CondI->getValue())
  1925. return Val->convertInitializerTo(getValType());
  1926. } else {
  1927. return const_cast<CondOpInit *>(this);
  1928. }
  1929. }
  1930. PrintFatalError(CurRec->getLoc(),
  1931. CurRec->getName() +
  1932. " does not have any true condition in:" +
  1933. this->getAsString());
  1934. return nullptr;
  1935. }
  1936. bool CondOpInit::isConcrete() const {
  1937. for (const Init *Case : getConds())
  1938. if (!Case->isConcrete())
  1939. return false;
  1940. for (const Init *Val : getVals())
  1941. if (!Val->isConcrete())
  1942. return false;
  1943. return true;
  1944. }
  1945. bool CondOpInit::isComplete() const {
  1946. for (const Init *Case : getConds())
  1947. if (!Case->isComplete())
  1948. return false;
  1949. for (const Init *Val : getVals())
  1950. if (!Val->isConcrete())
  1951. return false;
  1952. return true;
  1953. }
  1954. std::string CondOpInit::getAsString() const {
  1955. std::string Result = "!cond(";
  1956. for (unsigned i = 0; i < getNumConds(); i++) {
  1957. Result += getCond(i)->getAsString() + ": ";
  1958. Result += getVal(i)->getAsString();
  1959. if (i != getNumConds()-1)
  1960. Result += ", ";
  1961. }
  1962. return Result + ")";
  1963. }
  1964. Init *CondOpInit::getBit(unsigned Bit) const {
  1965. return VarBitInit::get(const_cast<CondOpInit *>(this), Bit);
  1966. }
  1967. static void ProfileDagInit(FoldingSetNodeID &ID, Init *V, StringInit *VN,
  1968. ArrayRef<Init *> ArgRange,
  1969. ArrayRef<StringInit *> NameRange) {
  1970. ID.AddPointer(V);
  1971. ID.AddPointer(VN);
  1972. ArrayRef<Init *>::iterator Arg = ArgRange.begin();
  1973. ArrayRef<StringInit *>::iterator Name = NameRange.begin();
  1974. while (Arg != ArgRange.end()) {
  1975. assert(Name != NameRange.end() && "Arg name underflow!");
  1976. ID.AddPointer(*Arg++);
  1977. ID.AddPointer(*Name++);
  1978. }
  1979. assert(Name == NameRange.end() && "Arg name overflow!");
  1980. }
  1981. DagInit *DagInit::get(Init *V, StringInit *VN, ArrayRef<Init *> ArgRange,
  1982. ArrayRef<StringInit *> NameRange) {
  1983. assert(ArgRange.size() == NameRange.size());
  1984. FoldingSetNodeID ID;
  1985. ProfileDagInit(ID, V, VN, ArgRange, NameRange);
  1986. detail::RecordKeeperImpl &RK = V->getRecordKeeper().getImpl();
  1987. void *IP = nullptr;
  1988. if (DagInit *I = RK.TheDagInitPool.FindNodeOrInsertPos(ID, IP))
  1989. return I;
  1990. void *Mem = RK.Allocator.Allocate(
  1991. totalSizeToAlloc<Init *, StringInit *>(ArgRange.size(), NameRange.size()),
  1992. alignof(BitsInit));
  1993. DagInit *I = new (Mem) DagInit(V, VN, ArgRange.size(), NameRange.size());
  1994. std::uninitialized_copy(ArgRange.begin(), ArgRange.end(),
  1995. I->getTrailingObjects<Init *>());
  1996. std::uninitialized_copy(NameRange.begin(), NameRange.end(),
  1997. I->getTrailingObjects<StringInit *>());
  1998. RK.TheDagInitPool.InsertNode(I, IP);
  1999. return I;
  2000. }
  2001. DagInit *
  2002. DagInit::get(Init *V, StringInit *VN,
  2003. ArrayRef<std::pair<Init*, StringInit*>> args) {
  2004. SmallVector<Init *, 8> Args;
  2005. SmallVector<StringInit *, 8> Names;
  2006. for (const auto &Arg : args) {
  2007. Args.push_back(Arg.first);
  2008. Names.push_back(Arg.second);
  2009. }
  2010. return DagInit::get(V, VN, Args, Names);
  2011. }
  2012. void DagInit::Profile(FoldingSetNodeID &ID) const {
  2013. ProfileDagInit(ID, Val, ValName,
  2014. ArrayRef(getTrailingObjects<Init *>(), NumArgs),
  2015. ArrayRef(getTrailingObjects<StringInit *>(), NumArgNames));
  2016. }
  2017. Record *DagInit::getOperatorAsDef(ArrayRef<SMLoc> Loc) const {
  2018. if (DefInit *DefI = dyn_cast<DefInit>(Val))
  2019. return DefI->getDef();
  2020. PrintFatalError(Loc, "Expected record as operator");
  2021. return nullptr;
  2022. }
  2023. Init *DagInit::resolveReferences(Resolver &R) const {
  2024. SmallVector<Init*, 8> NewArgs;
  2025. NewArgs.reserve(arg_size());
  2026. bool ArgsChanged = false;
  2027. for (const Init *Arg : getArgs()) {
  2028. Init *NewArg = Arg->resolveReferences(R);
  2029. NewArgs.push_back(NewArg);
  2030. ArgsChanged |= NewArg != Arg;
  2031. }
  2032. Init *Op = Val->resolveReferences(R);
  2033. if (Op != Val || ArgsChanged)
  2034. return DagInit::get(Op, ValName, NewArgs, getArgNames());
  2035. return const_cast<DagInit *>(this);
  2036. }
  2037. bool DagInit::isConcrete() const {
  2038. if (!Val->isConcrete())
  2039. return false;
  2040. for (const Init *Elt : getArgs()) {
  2041. if (!Elt->isConcrete())
  2042. return false;
  2043. }
  2044. return true;
  2045. }
  2046. std::string DagInit::getAsString() const {
  2047. std::string Result = "(" + Val->getAsString();
  2048. if (ValName)
  2049. Result += ":" + ValName->getAsUnquotedString();
  2050. if (!arg_empty()) {
  2051. Result += " " + getArg(0)->getAsString();
  2052. if (getArgName(0)) Result += ":$" + getArgName(0)->getAsUnquotedString();
  2053. for (unsigned i = 1, e = getNumArgs(); i != e; ++i) {
  2054. Result += ", " + getArg(i)->getAsString();
  2055. if (getArgName(i)) Result += ":$" + getArgName(i)->getAsUnquotedString();
  2056. }
  2057. }
  2058. return Result + ")";
  2059. }
  2060. //===----------------------------------------------------------------------===//
  2061. // Other implementations
  2062. //===----------------------------------------------------------------------===//
  2063. RecordVal::RecordVal(Init *N, RecTy *T, FieldKind K)
  2064. : Name(N), TyAndKind(T, K) {
  2065. setValue(UnsetInit::get(N->getRecordKeeper()));
  2066. assert(Value && "Cannot create unset value for current type!");
  2067. }
  2068. // This constructor accepts the same arguments as the above, but also
  2069. // a source location.
  2070. RecordVal::RecordVal(Init *N, SMLoc Loc, RecTy *T, FieldKind K)
  2071. : Name(N), Loc(Loc), TyAndKind(T, K) {
  2072. setValue(UnsetInit::get(N->getRecordKeeper()));
  2073. assert(Value && "Cannot create unset value for current type!");
  2074. }
  2075. StringRef RecordVal::getName() const {
  2076. return cast<StringInit>(getNameInit())->getValue();
  2077. }
  2078. std::string RecordVal::getPrintType() const {
  2079. if (getType() == StringRecTy::get(getRecordKeeper())) {
  2080. if (auto *StrInit = dyn_cast<StringInit>(Value)) {
  2081. if (StrInit->hasCodeFormat())
  2082. return "code";
  2083. else
  2084. return "string";
  2085. } else {
  2086. return "string";
  2087. }
  2088. } else {
  2089. return TyAndKind.getPointer()->getAsString();
  2090. }
  2091. }
  2092. bool RecordVal::setValue(Init *V) {
  2093. if (V) {
  2094. Value = V->getCastTo(getType());
  2095. if (Value) {
  2096. assert(!isa<TypedInit>(Value) ||
  2097. cast<TypedInit>(Value)->getType()->typeIsA(getType()));
  2098. if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
  2099. if (!isa<BitsInit>(Value)) {
  2100. SmallVector<Init *, 64> Bits;
  2101. Bits.reserve(BTy->getNumBits());
  2102. for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
  2103. Bits.push_back(Value->getBit(I));
  2104. Value = BitsInit::get(V->getRecordKeeper(), Bits);
  2105. }
  2106. }
  2107. }
  2108. return Value == nullptr;
  2109. }
  2110. Value = nullptr;
  2111. return false;
  2112. }
  2113. // This version of setValue takes a source location and resets the
  2114. // location in the RecordVal.
  2115. bool RecordVal::setValue(Init *V, SMLoc NewLoc) {
  2116. Loc = NewLoc;
  2117. if (V) {
  2118. Value = V->getCastTo(getType());
  2119. if (Value) {
  2120. assert(!isa<TypedInit>(Value) ||
  2121. cast<TypedInit>(Value)->getType()->typeIsA(getType()));
  2122. if (BitsRecTy *BTy = dyn_cast<BitsRecTy>(getType())) {
  2123. if (!isa<BitsInit>(Value)) {
  2124. SmallVector<Init *, 64> Bits;
  2125. Bits.reserve(BTy->getNumBits());
  2126. for (unsigned I = 0, E = BTy->getNumBits(); I < E; ++I)
  2127. Bits.push_back(Value->getBit(I));
  2128. Value = BitsInit::get(getRecordKeeper(), Bits);
  2129. }
  2130. }
  2131. }
  2132. return Value == nullptr;
  2133. }
  2134. Value = nullptr;
  2135. return false;
  2136. }
  2137. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2138. #include "llvm/TableGen/Record.h"
  2139. LLVM_DUMP_METHOD void RecordVal::dump() const { errs() << *this; }
  2140. #endif
  2141. void RecordVal::print(raw_ostream &OS, bool PrintSem) const {
  2142. if (isNonconcreteOK()) OS << "field ";
  2143. OS << getPrintType() << " " << getNameInitAsString();
  2144. if (getValue())
  2145. OS << " = " << *getValue();
  2146. if (PrintSem) OS << ";\n";
  2147. }
  2148. void Record::updateClassLoc(SMLoc Loc) {
  2149. assert(Locs.size() == 1);
  2150. ForwardDeclarationLocs.push_back(Locs.front());
  2151. Locs.clear();
  2152. Locs.push_back(Loc);
  2153. }
  2154. void Record::checkName() {
  2155. // Ensure the record name has string type.
  2156. const TypedInit *TypedName = cast<const TypedInit>(Name);
  2157. if (!isa<StringRecTy>(TypedName->getType()))
  2158. PrintFatalError(getLoc(), Twine("Record name '") + Name->getAsString() +
  2159. "' is not a string!");
  2160. }
  2161. RecordRecTy *Record::getType() {
  2162. SmallVector<Record *, 4> DirectSCs;
  2163. getDirectSuperClasses(DirectSCs);
  2164. return RecordRecTy::get(TrackedRecords, DirectSCs);
  2165. }
  2166. DefInit *Record::getDefInit() {
  2167. if (!CorrespondingDefInit) {
  2168. CorrespondingDefInit =
  2169. new (TrackedRecords.getImpl().Allocator) DefInit(this);
  2170. }
  2171. return CorrespondingDefInit;
  2172. }
  2173. unsigned Record::getNewUID(RecordKeeper &RK) {
  2174. return RK.getImpl().LastRecordID++;
  2175. }
  2176. void Record::setName(Init *NewName) {
  2177. Name = NewName;
  2178. checkName();
  2179. // DO NOT resolve record values to the name at this point because
  2180. // there might be default values for arguments of this def. Those
  2181. // arguments might not have been resolved yet so we don't want to
  2182. // prematurely assume values for those arguments were not passed to
  2183. // this def.
  2184. //
  2185. // Nonetheless, it may be that some of this Record's values
  2186. // reference the record name. Indeed, the reason for having the
  2187. // record name be an Init is to provide this flexibility. The extra
  2188. // resolve steps after completely instantiating defs takes care of
  2189. // this. See TGParser::ParseDef and TGParser::ParseDefm.
  2190. }
  2191. // NOTE for the next two functions:
  2192. // Superclasses are in post-order, so the final one is a direct
  2193. // superclass. All of its transitive superclases immediately precede it,
  2194. // so we can step through the direct superclasses in reverse order.
  2195. bool Record::hasDirectSuperClass(const Record *Superclass) const {
  2196. ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
  2197. for (int I = SCs.size() - 1; I >= 0; --I) {
  2198. const Record *SC = SCs[I].first;
  2199. if (SC == Superclass)
  2200. return true;
  2201. I -= SC->getSuperClasses().size();
  2202. }
  2203. return false;
  2204. }
  2205. void Record::getDirectSuperClasses(SmallVectorImpl<Record *> &Classes) const {
  2206. ArrayRef<std::pair<Record *, SMRange>> SCs = getSuperClasses();
  2207. while (!SCs.empty()) {
  2208. Record *SC = SCs.back().first;
  2209. SCs = SCs.drop_back(1 + SC->getSuperClasses().size());
  2210. Classes.push_back(SC);
  2211. }
  2212. }
  2213. void Record::resolveReferences(Resolver &R, const RecordVal *SkipVal) {
  2214. Init *OldName = getNameInit();
  2215. Init *NewName = Name->resolveReferences(R);
  2216. if (NewName != OldName) {
  2217. // Re-register with RecordKeeper.
  2218. setName(NewName);
  2219. }
  2220. // Resolve the field values.
  2221. for (RecordVal &Value : Values) {
  2222. if (SkipVal == &Value) // Skip resolve the same field as the given one
  2223. continue;
  2224. if (Init *V = Value.getValue()) {
  2225. Init *VR = V->resolveReferences(R);
  2226. if (Value.setValue(VR)) {
  2227. std::string Type;
  2228. if (TypedInit *VRT = dyn_cast<TypedInit>(VR))
  2229. Type =
  2230. (Twine("of type '") + VRT->getType()->getAsString() + "' ").str();
  2231. PrintFatalError(
  2232. getLoc(),
  2233. Twine("Invalid value ") + Type + "found when setting field '" +
  2234. Value.getNameInitAsString() + "' of type '" +
  2235. Value.getType()->getAsString() +
  2236. "' after resolving references: " + VR->getAsUnquotedString() +
  2237. "\n");
  2238. }
  2239. }
  2240. }
  2241. // Resolve the assertion expressions.
  2242. for (auto &Assertion : Assertions) {
  2243. Init *Value = Assertion.Condition->resolveReferences(R);
  2244. Assertion.Condition = Value;
  2245. Value = Assertion.Message->resolveReferences(R);
  2246. Assertion.Message = Value;
  2247. }
  2248. }
  2249. void Record::resolveReferences(Init *NewName) {
  2250. RecordResolver R(*this);
  2251. R.setName(NewName);
  2252. R.setFinal(true);
  2253. resolveReferences(R);
  2254. }
  2255. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2256. LLVM_DUMP_METHOD void Record::dump() const { errs() << *this; }
  2257. #endif
  2258. raw_ostream &llvm::operator<<(raw_ostream &OS, const Record &R) {
  2259. OS << R.getNameInitAsString();
  2260. ArrayRef<Init *> TArgs = R.getTemplateArgs();
  2261. if (!TArgs.empty()) {
  2262. OS << "<";
  2263. bool NeedComma = false;
  2264. for (const Init *TA : TArgs) {
  2265. if (NeedComma) OS << ", ";
  2266. NeedComma = true;
  2267. const RecordVal *RV = R.getValue(TA);
  2268. assert(RV && "Template argument record not found??");
  2269. RV->print(OS, false);
  2270. }
  2271. OS << ">";
  2272. }
  2273. OS << " {";
  2274. ArrayRef<std::pair<Record *, SMRange>> SC = R.getSuperClasses();
  2275. if (!SC.empty()) {
  2276. OS << "\t//";
  2277. for (const auto &SuperPair : SC)
  2278. OS << " " << SuperPair.first->getNameInitAsString();
  2279. }
  2280. OS << "\n";
  2281. for (const RecordVal &Val : R.getValues())
  2282. if (Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
  2283. OS << Val;
  2284. for (const RecordVal &Val : R.getValues())
  2285. if (!Val.isNonconcreteOK() && !R.isTemplateArg(Val.getNameInit()))
  2286. OS << Val;
  2287. return OS << "}\n";
  2288. }
  2289. SMLoc Record::getFieldLoc(StringRef FieldName) const {
  2290. const RecordVal *R = getValue(FieldName);
  2291. if (!R)
  2292. PrintFatalError(getLoc(), "Record `" + getName() +
  2293. "' does not have a field named `" + FieldName + "'!\n");
  2294. return R->getLoc();
  2295. }
  2296. Init *Record::getValueInit(StringRef FieldName) const {
  2297. const RecordVal *R = getValue(FieldName);
  2298. if (!R || !R->getValue())
  2299. PrintFatalError(getLoc(), "Record `" + getName() +
  2300. "' does not have a field named `" + FieldName + "'!\n");
  2301. return R->getValue();
  2302. }
  2303. StringRef Record::getValueAsString(StringRef FieldName) const {
  2304. std::optional<StringRef> S = getValueAsOptionalString(FieldName);
  2305. if (!S)
  2306. PrintFatalError(getLoc(), "Record `" + getName() +
  2307. "' does not have a field named `" + FieldName + "'!\n");
  2308. return *S;
  2309. }
  2310. std::optional<StringRef>
  2311. Record::getValueAsOptionalString(StringRef FieldName) const {
  2312. const RecordVal *R = getValue(FieldName);
  2313. if (!R || !R->getValue())
  2314. return std::nullopt;
  2315. if (isa<UnsetInit>(R->getValue()))
  2316. return std::nullopt;
  2317. if (StringInit *SI = dyn_cast<StringInit>(R->getValue()))
  2318. return SI->getValue();
  2319. PrintFatalError(getLoc(),
  2320. "Record `" + getName() + "', ` field `" + FieldName +
  2321. "' exists but does not have a string initializer!");
  2322. }
  2323. BitsInit *Record::getValueAsBitsInit(StringRef FieldName) const {
  2324. const RecordVal *R = getValue(FieldName);
  2325. if (!R || !R->getValue())
  2326. PrintFatalError(getLoc(), "Record `" + getName() +
  2327. "' does not have a field named `" + FieldName + "'!\n");
  2328. if (BitsInit *BI = dyn_cast<BitsInit>(R->getValue()))
  2329. return BI;
  2330. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
  2331. "' exists but does not have a bits value");
  2332. }
  2333. ListInit *Record::getValueAsListInit(StringRef FieldName) const {
  2334. const RecordVal *R = getValue(FieldName);
  2335. if (!R || !R->getValue())
  2336. PrintFatalError(getLoc(), "Record `" + getName() +
  2337. "' does not have a field named `" + FieldName + "'!\n");
  2338. if (ListInit *LI = dyn_cast<ListInit>(R->getValue()))
  2339. return LI;
  2340. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" + FieldName +
  2341. "' exists but does not have a list value");
  2342. }
  2343. std::vector<Record*>
  2344. Record::getValueAsListOfDefs(StringRef FieldName) const {
  2345. ListInit *List = getValueAsListInit(FieldName);
  2346. std::vector<Record*> Defs;
  2347. for (Init *I : List->getValues()) {
  2348. if (DefInit *DI = dyn_cast<DefInit>(I))
  2349. Defs.push_back(DI->getDef());
  2350. else
  2351. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2352. FieldName + "' list is not entirely DefInit!");
  2353. }
  2354. return Defs;
  2355. }
  2356. int64_t Record::getValueAsInt(StringRef FieldName) const {
  2357. const RecordVal *R = getValue(FieldName);
  2358. if (!R || !R->getValue())
  2359. PrintFatalError(getLoc(), "Record `" + getName() +
  2360. "' does not have a field named `" + FieldName + "'!\n");
  2361. if (IntInit *II = dyn_cast<IntInit>(R->getValue()))
  2362. return II->getValue();
  2363. PrintFatalError(getLoc(), Twine("Record `") + getName() + "', field `" +
  2364. FieldName +
  2365. "' exists but does not have an int value: " +
  2366. R->getValue()->getAsString());
  2367. }
  2368. std::vector<int64_t>
  2369. Record::getValueAsListOfInts(StringRef FieldName) const {
  2370. ListInit *List = getValueAsListInit(FieldName);
  2371. std::vector<int64_t> Ints;
  2372. for (Init *I : List->getValues()) {
  2373. if (IntInit *II = dyn_cast<IntInit>(I))
  2374. Ints.push_back(II->getValue());
  2375. else
  2376. PrintFatalError(getLoc(),
  2377. Twine("Record `") + getName() + "', field `" + FieldName +
  2378. "' exists but does not have a list of ints value: " +
  2379. I->getAsString());
  2380. }
  2381. return Ints;
  2382. }
  2383. std::vector<StringRef>
  2384. Record::getValueAsListOfStrings(StringRef FieldName) const {
  2385. ListInit *List = getValueAsListInit(FieldName);
  2386. std::vector<StringRef> Strings;
  2387. for (Init *I : List->getValues()) {
  2388. if (StringInit *SI = dyn_cast<StringInit>(I))
  2389. Strings.push_back(SI->getValue());
  2390. else
  2391. PrintFatalError(getLoc(),
  2392. Twine("Record `") + getName() + "', field `" + FieldName +
  2393. "' exists but does not have a list of strings value: " +
  2394. I->getAsString());
  2395. }
  2396. return Strings;
  2397. }
  2398. Record *Record::getValueAsDef(StringRef FieldName) const {
  2399. const RecordVal *R = getValue(FieldName);
  2400. if (!R || !R->getValue())
  2401. PrintFatalError(getLoc(), "Record `" + getName() +
  2402. "' does not have a field named `" + FieldName + "'!\n");
  2403. if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
  2404. return DI->getDef();
  2405. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2406. FieldName + "' does not have a def initializer!");
  2407. }
  2408. Record *Record::getValueAsOptionalDef(StringRef FieldName) const {
  2409. const RecordVal *R = getValue(FieldName);
  2410. if (!R || !R->getValue())
  2411. PrintFatalError(getLoc(), "Record `" + getName() +
  2412. "' does not have a field named `" + FieldName + "'!\n");
  2413. if (DefInit *DI = dyn_cast<DefInit>(R->getValue()))
  2414. return DI->getDef();
  2415. if (isa<UnsetInit>(R->getValue()))
  2416. return nullptr;
  2417. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2418. FieldName + "' does not have either a def initializer or '?'!");
  2419. }
  2420. bool Record::getValueAsBit(StringRef FieldName) const {
  2421. const RecordVal *R = getValue(FieldName);
  2422. if (!R || !R->getValue())
  2423. PrintFatalError(getLoc(), "Record `" + getName() +
  2424. "' does not have a field named `" + FieldName + "'!\n");
  2425. if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
  2426. return BI->getValue();
  2427. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2428. FieldName + "' does not have a bit initializer!");
  2429. }
  2430. bool Record::getValueAsBitOrUnset(StringRef FieldName, bool &Unset) const {
  2431. const RecordVal *R = getValue(FieldName);
  2432. if (!R || !R->getValue())
  2433. PrintFatalError(getLoc(), "Record `" + getName() +
  2434. "' does not have a field named `" + FieldName.str() + "'!\n");
  2435. if (isa<UnsetInit>(R->getValue())) {
  2436. Unset = true;
  2437. return false;
  2438. }
  2439. Unset = false;
  2440. if (BitInit *BI = dyn_cast<BitInit>(R->getValue()))
  2441. return BI->getValue();
  2442. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2443. FieldName + "' does not have a bit initializer!");
  2444. }
  2445. DagInit *Record::getValueAsDag(StringRef FieldName) const {
  2446. const RecordVal *R = getValue(FieldName);
  2447. if (!R || !R->getValue())
  2448. PrintFatalError(getLoc(), "Record `" + getName() +
  2449. "' does not have a field named `" + FieldName + "'!\n");
  2450. if (DagInit *DI = dyn_cast<DagInit>(R->getValue()))
  2451. return DI;
  2452. PrintFatalError(getLoc(), "Record `" + getName() + "', field `" +
  2453. FieldName + "' does not have a dag initializer!");
  2454. }
  2455. // Check all record assertions: For each one, resolve the condition
  2456. // and message, then call CheckAssert().
  2457. // Note: The condition and message are probably already resolved,
  2458. // but resolving again allows calls before records are resolved.
  2459. void Record::checkRecordAssertions() {
  2460. RecordResolver R(*this);
  2461. R.setFinal(true);
  2462. for (const auto &Assertion : getAssertions()) {
  2463. Init *Condition = Assertion.Condition->resolveReferences(R);
  2464. Init *Message = Assertion.Message->resolveReferences(R);
  2465. CheckAssert(Assertion.Loc, Condition, Message);
  2466. }
  2467. }
  2468. // Report a warning if the record has unused template arguments.
  2469. void Record::checkUnusedTemplateArgs() {
  2470. for (const Init *TA : getTemplateArgs()) {
  2471. const RecordVal *Arg = getValue(TA);
  2472. if (!Arg->isUsed())
  2473. PrintWarning(Arg->getLoc(),
  2474. "unused template argument: " + Twine(Arg->getName()));
  2475. }
  2476. }
  2477. RecordKeeper::RecordKeeper()
  2478. : Impl(std::make_unique<detail::RecordKeeperImpl>(*this)) {}
  2479. RecordKeeper::~RecordKeeper() = default;
  2480. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2481. LLVM_DUMP_METHOD void RecordKeeper::dump() const { errs() << *this; }
  2482. #endif
  2483. raw_ostream &llvm::operator<<(raw_ostream &OS, const RecordKeeper &RK) {
  2484. OS << "------------- Classes -----------------\n";
  2485. for (const auto &C : RK.getClasses())
  2486. OS << "class " << *C.second;
  2487. OS << "------------- Defs -----------------\n";
  2488. for (const auto &D : RK.getDefs())
  2489. OS << "def " << *D.second;
  2490. return OS;
  2491. }
  2492. /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
  2493. /// an identifier.
  2494. Init *RecordKeeper::getNewAnonymousName() {
  2495. return AnonymousNameInit::get(*this, getImpl().AnonCounter++);
  2496. }
  2497. // These functions implement the phase timing facility. Starting a timer
  2498. // when one is already running stops the running one.
  2499. void RecordKeeper::startTimer(StringRef Name) {
  2500. if (TimingGroup) {
  2501. if (LastTimer && LastTimer->isRunning()) {
  2502. LastTimer->stopTimer();
  2503. if (BackendTimer) {
  2504. LastTimer->clear();
  2505. BackendTimer = false;
  2506. }
  2507. }
  2508. LastTimer = new Timer("", Name, *TimingGroup);
  2509. LastTimer->startTimer();
  2510. }
  2511. }
  2512. void RecordKeeper::stopTimer() {
  2513. if (TimingGroup) {
  2514. assert(LastTimer && "No phase timer was started");
  2515. LastTimer->stopTimer();
  2516. }
  2517. }
  2518. void RecordKeeper::startBackendTimer(StringRef Name) {
  2519. if (TimingGroup) {
  2520. startTimer(Name);
  2521. BackendTimer = true;
  2522. }
  2523. }
  2524. void RecordKeeper::stopBackendTimer() {
  2525. if (TimingGroup) {
  2526. if (BackendTimer) {
  2527. stopTimer();
  2528. BackendTimer = false;
  2529. }
  2530. }
  2531. }
  2532. std::vector<Record *>
  2533. RecordKeeper::getAllDerivedDefinitions(StringRef ClassName) const {
  2534. // We cache the record vectors for single classes. Many backends request
  2535. // the same vectors multiple times.
  2536. auto Pair = ClassRecordsMap.try_emplace(ClassName);
  2537. if (Pair.second)
  2538. Pair.first->second = getAllDerivedDefinitions(ArrayRef(ClassName));
  2539. return Pair.first->second;
  2540. }
  2541. std::vector<Record *> RecordKeeper::getAllDerivedDefinitions(
  2542. ArrayRef<StringRef> ClassNames) const {
  2543. SmallVector<Record *, 2> ClassRecs;
  2544. std::vector<Record *> Defs;
  2545. assert(ClassNames.size() > 0 && "At least one class must be passed.");
  2546. for (const auto &ClassName : ClassNames) {
  2547. Record *Class = getClass(ClassName);
  2548. if (!Class)
  2549. PrintFatalError("The class '" + ClassName + "' is not defined\n");
  2550. ClassRecs.push_back(Class);
  2551. }
  2552. for (const auto &OneDef : getDefs()) {
  2553. if (all_of(ClassRecs, [&OneDef](const Record *Class) {
  2554. return OneDef.second->isSubClassOf(Class);
  2555. }))
  2556. Defs.push_back(OneDef.second.get());
  2557. }
  2558. return Defs;
  2559. }
  2560. std::vector<Record *>
  2561. RecordKeeper::getAllDerivedDefinitionsIfDefined(StringRef ClassName) const {
  2562. return getClass(ClassName) ? getAllDerivedDefinitions(ClassName)
  2563. : std::vector<Record *>();
  2564. }
  2565. Init *MapResolver::resolve(Init *VarName) {
  2566. auto It = Map.find(VarName);
  2567. if (It == Map.end())
  2568. return nullptr;
  2569. Init *I = It->second.V;
  2570. if (!It->second.Resolved && Map.size() > 1) {
  2571. // Resolve mutual references among the mapped variables, but prevent
  2572. // infinite recursion.
  2573. Map.erase(It);
  2574. I = I->resolveReferences(*this);
  2575. Map[VarName] = {I, true};
  2576. }
  2577. return I;
  2578. }
  2579. Init *RecordResolver::resolve(Init *VarName) {
  2580. Init *Val = Cache.lookup(VarName);
  2581. if (Val)
  2582. return Val;
  2583. if (llvm::is_contained(Stack, VarName))
  2584. return nullptr; // prevent infinite recursion
  2585. if (RecordVal *RV = getCurrentRecord()->getValue(VarName)) {
  2586. if (!isa<UnsetInit>(RV->getValue())) {
  2587. Val = RV->getValue();
  2588. Stack.push_back(VarName);
  2589. Val = Val->resolveReferences(*this);
  2590. Stack.pop_back();
  2591. }
  2592. } else if (Name && VarName == getCurrentRecord()->getNameInit()) {
  2593. Stack.push_back(VarName);
  2594. Val = Name->resolveReferences(*this);
  2595. Stack.pop_back();
  2596. }
  2597. Cache[VarName] = Val;
  2598. return Val;
  2599. }
  2600. Init *TrackUnresolvedResolver::resolve(Init *VarName) {
  2601. Init *I = nullptr;
  2602. if (R) {
  2603. I = R->resolve(VarName);
  2604. if (I && !FoundUnresolved) {
  2605. // Do not recurse into the resolved initializer, as that would change
  2606. // the behavior of the resolver we're delegating, but do check to see
  2607. // if there are unresolved variables remaining.
  2608. TrackUnresolvedResolver Sub;
  2609. I->resolveReferences(Sub);
  2610. FoundUnresolved |= Sub.FoundUnresolved;
  2611. }
  2612. }
  2613. if (!I)
  2614. FoundUnresolved = true;
  2615. return I;
  2616. }
  2617. Init *HasReferenceResolver::resolve(Init *VarName)
  2618. {
  2619. if (VarName == VarNameToTrack)
  2620. Found = true;
  2621. return nullptr;
  2622. }