BfContext.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240
  1. #pragma warning(push)
  2. #pragma warning(disable:4800)
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4141)
  5. #pragma warning(disable:4624)
  6. #pragma warning(disable:4146)
  7. #pragma warning(disable:4267)
  8. #pragma warning(disable:4291)
  9. #include "BfCompiler.h"
  10. #include "BfSystem.h"
  11. #include "BfParser.h"
  12. #include "BfExprEvaluator.h"
  13. #include "llvm/IR/Function.h"
  14. #include "llvm/IR/Module.h"
  15. #include "llvm/IR/BasicBlock.h"
  16. #include "llvm/Support/FileSystem.h"
  17. //#include "llvm/Support/Dwarf.h"
  18. #include "llvm/ADT/SparseSet.h"
  19. #include "llvm/Transforms/Utils/Cloning.h"
  20. #include <fcntl.h>
  21. #include "BfConstResolver.h"
  22. #include "BfMangler.h"
  23. #include "BeefySysLib/util/PerfTimer.h"
  24. #include "BeefySysLib/util/BeefPerf.h"
  25. #include "BfSourceClassifier.h"
  26. #include "BfAutoComplete.h"
  27. #include "BfResolvePass.h"
  28. #include "CeMachine.h"
  29. #pragma warning(pop)
  30. USING_NS_BF;
  31. using namespace llvm;
  32. BfContext::BfContext(BfCompiler* compiler) :
  33. mTypeDefTypeRefPool(true),
  34. mNamedTypeRefPool(true)
  35. {
  36. mCompiler = compiler;
  37. mSystem = compiler->mSystem;
  38. mBfTypeType = NULL;
  39. mBfClassVDataPtrType = NULL;
  40. mBfObjectType = NULL;
  41. mCanSkipObjectCtor = true;
  42. mCanSkipValueTypeCtor = true;
  43. mMappedObjectRevision = 0;
  44. mDeleting = false;
  45. mLockModules = false;
  46. mAllowLockYield = true;
  47. mCurTypeState = NULL;
  48. mCurNamespaceNodes = NULL;
  49. mCurConstraintState = NULL;
  50. mResolvingVarField = false;
  51. mAssertOnPopulateType = false;
  52. for (int i = 0; i < BfTypeCode_Length; i++)
  53. {
  54. mPrimitiveTypes[i] = NULL;
  55. mPrimitiveStructTypes[i] = NULL;
  56. }
  57. mScratchModule = new BfModule(this, "");
  58. mScratchModule->mIsSpecialModule = true;
  59. mScratchModule->mIsScratchModule = true;
  60. mScratchModule->mIsReified = true;
  61. mScratchModule->mGeneratesCode = false;
  62. mScratchModule->Init();
  63. mUnreifiedModule = new BfModule(this, "");
  64. mUnreifiedModule->mIsSpecialModule = true;
  65. mUnreifiedModule->mIsScratchModule = true;
  66. mUnreifiedModule->mIsReified = false;
  67. mUnreifiedModule->mGeneratesCode = false;
  68. mUnreifiedModule->Init();
  69. mValueTypeDeinitSentinel = (BfMethodInstance*)1;
  70. mCurStringObjectPoolId = 0;
  71. mHasReifiedQueuedRebuildTypes = false;
  72. }
  73. void BfReportMemory();
  74. BfContext::~BfContext()
  75. {
  76. BfLogSysM("Deleting Context...\n");
  77. mDeleting = true;
  78. for (auto& kv : mSavedTypeDataMap)
  79. delete kv.mValue;
  80. for (auto localMethod : mLocalMethodGraveyard)
  81. delete localMethod;
  82. int numTypesDeleted = 0;
  83. for (auto type : mResolvedTypes)
  84. {
  85. //_CrtCheckMemory();
  86. delete type;
  87. }
  88. delete mScratchModule;
  89. delete mUnreifiedModule;
  90. for (auto module : mModules)
  91. delete module;
  92. BfReportMemory();
  93. }
  94. void BfContext::ReportMemory(MemReporter* memReporter)
  95. {
  96. memReporter->Add(sizeof(BfContext));
  97. }
  98. void BfContext::ProcessMethod(BfMethodInstance* methodInstance)
  99. {
  100. // When we are doing as resolveOnly pass over unused methods in the compiler,
  101. // we use the scratch module to ensure mIsResolveOnly flag is set when we
  102. // process the method
  103. auto defModule = methodInstance->mDeclModule;
  104. if ((!methodInstance->mIsReified) && (!mCompiler->mIsResolveOnly))
  105. defModule = mUnreifiedModule;
  106. auto typeInst = methodInstance->GetOwner();
  107. defModule->ProcessMethod(methodInstance);
  108. mCompiler->mStats.mMethodsProcessed++;
  109. if (!methodInstance->mIsReified)
  110. mCompiler->mStats.mUnreifiedMethodsProcessed++;
  111. mCompiler->UpdateCompletion();
  112. }
  113. int BfContext::GetStringLiteralId(const StringImpl& str)
  114. {
  115. // Note: We do need string pooling in resolve, for intrinsic names and such
  116. int* idPtr = NULL;
  117. if (mStringObjectPool.TryGetValue(str, &idPtr))
  118. return *idPtr;
  119. mCurStringObjectPoolId++;
  120. mStringObjectPool[str] = mCurStringObjectPoolId;
  121. BfStringPoolEntry stringPoolEntry;
  122. stringPoolEntry.mString = str;
  123. stringPoolEntry.mFirstUsedRevision = mCompiler->mRevision;
  124. stringPoolEntry.mLastUsedRevision = mCompiler->mRevision;
  125. mStringObjectIdMap[mCurStringObjectPoolId] = stringPoolEntry;
  126. return mCurStringObjectPoolId;
  127. }
  128. void BfContext::AssignModule(BfType* type)
  129. {
  130. auto typeInst = type->ToTypeInstance();
  131. if (typeInst->mModule != NULL)
  132. {
  133. BF_ASSERT(!typeInst->mModule->mIsReified);
  134. }
  135. BfModule* module = NULL;
  136. bool needsModuleInit = false;
  137. // We used to have this "IsReified" check, but we DO want to create modules for unreified types even if they remain unused.
  138. // What was that IsReified check catching?
  139. // It screwed up the reification of generic types- they just got switched to mScratchModule from mUnreifiedModule, but didn't ever generate code.
  140. if (/*(!type->IsReified()) ||*/ (type->IsUnspecializedType()) || (type->IsVar()) || (type->IsTypeAlias()) || (type->IsFunction()))
  141. {
  142. if (typeInst->mIsReified)
  143. module = mScratchModule;
  144. else
  145. module = mUnreifiedModule;
  146. typeInst->mModule = module;
  147. BfTypeProcessRequest* typeProcessEntry = mPopulateTypeWorkList.Alloc();
  148. typeProcessEntry->mType = type;
  149. BF_ASSERT(typeProcessEntry->mType->mContext == this);
  150. BfLogSysM("HandleTypeWorkItem: %p -> %p\n", type, typeProcessEntry->mType);
  151. mCompiler->mStats.mTypesQueued++;
  152. mCompiler->UpdateCompletion();
  153. }
  154. else
  155. {
  156. auto typeInst = type->ToTypeInstance();
  157. BF_ASSERT(typeInst != NULL);
  158. auto project = typeInst->mTypeDef->mProject;
  159. if ((project->mSingleModule) && (typeInst->mIsReified))
  160. {
  161. BfModule** modulePtr = NULL;
  162. if (mProjectModule.TryAdd(project, NULL, &modulePtr))
  163. {
  164. String moduleName = project->mName;
  165. module = new BfModule(this, moduleName);
  166. module->mIsReified = true;
  167. module->mProject = project;
  168. typeInst->mModule = module;
  169. BF_ASSERT(!mLockModules);
  170. mModules.push_back(module);
  171. *modulePtr = module;
  172. needsModuleInit = true;
  173. }
  174. else
  175. {
  176. module = *modulePtr;
  177. typeInst->mModule = module;
  178. }
  179. }
  180. else
  181. {
  182. String moduleName = GenerateModuleName(typeInst);
  183. module = new BfModule(this, moduleName);
  184. module->mIsReified = typeInst->mIsReified;
  185. module->mProject = project;
  186. typeInst->mModule = module;
  187. BF_ASSERT(!mLockModules);
  188. mModules.push_back(module);
  189. needsModuleInit = true;
  190. }
  191. }
  192. auto localTypeInst = type->ToTypeInstance();
  193. BF_ASSERT((localTypeInst != NULL) || (mCompiler->mPassInstance->HasFailed()));
  194. if ((localTypeInst != NULL) && (!module->mIsScratchModule))
  195. {
  196. BF_ASSERT(localTypeInst->mContext == this);
  197. module->mOwnedTypeInstances.push_back(localTypeInst);
  198. }
  199. module->CalcGeneratesCode();
  200. if (needsModuleInit)
  201. module->Init();
  202. }
  203. void BfContext::HandleTypeWorkItem(BfType* type)
  204. {
  205. AssignModule(type);
  206. }
  207. void BfContext::EnsureHotMangledVirtualMethodName(BfMethodInstance* methodInstance)
  208. {
  209. BP_ZONE("BfContext::EnsureHotMangledVirtualMethodName");
  210. if ((methodInstance != NULL) && (methodInstance->GetMethodInfoEx()->mMangledName.IsEmpty()))
  211. BfMangler::Mangle(methodInstance->GetMethodInfoEx()->mMangledName, mCompiler->GetMangleKind(), methodInstance);
  212. }
  213. void BfContext::EnsureHotMangledVirtualMethodNames()
  214. {
  215. BP_ZONE("BfContext::EnsureHotMangledVirtualMethodNames");
  216. for (auto type : mResolvedTypes)
  217. {
  218. auto typeInst = type->ToTypeInstance();
  219. if (typeInst == NULL)
  220. continue;
  221. for (auto& methodEntry : typeInst->mVirtualMethodTable)
  222. {
  223. BfMethodInstance* methodInstance = methodEntry.mImplementingMethod;
  224. if ((methodInstance != NULL) && (methodInstance->GetMethodInfoEx()->mMangledName.IsEmpty()))
  225. BfMangler::Mangle(methodInstance->GetMethodInfoEx()->mMangledName, mCompiler->GetMangleKind(), methodInstance);
  226. }
  227. }
  228. }
  229. void BfContext::CheckLockYield()
  230. {
  231. if (mAllowLockYield)
  232. mSystem->CheckLockYield();
  233. }
  234. bool BfContext::IsCancellingAndYield()
  235. {
  236. CheckLockYield();
  237. return mCompiler->mCanceling;
  238. }
  239. void BfContext::QueueFinishModule(BfModule* module)
  240. {
  241. bool needsDefer = false;
  242. BF_ASSERT(module != mScratchModule);
  243. BF_ASSERT(module != mUnreifiedModule);
  244. if (mCompiler->mMaxInterfaceSlots == -1)
  245. {
  246. if (module->mUsedSlotCount == 0)
  247. needsDefer = true;
  248. else if (module->mHasFullDebugInfo)
  249. {
  250. // The virtual index for methods requires waiting
  251. for (auto ownedTypeInst : module->mOwnedTypeInstances)
  252. {
  253. if (ownedTypeInst->IsInterface())
  254. needsDefer = true;
  255. else if (ownedTypeInst->IsObject())
  256. {
  257. for (auto& methodGroup : ownedTypeInst->mMethodInstanceGroups)
  258. {
  259. auto methodInstance = methodGroup.mDefault;
  260. if (methodInstance == NULL)
  261. continue;
  262. if ((methodInstance->mVirtualTableIdx != -1) && (!methodInstance->mMethodDef->mIsOverride))
  263. needsDefer = true;
  264. }
  265. }
  266. }
  267. }
  268. }
  269. if (!needsDefer)
  270. mFinishedModuleWorkList.push_back(module);
  271. module->mAwaitingFinish = true;
  272. }
  273. // For simplicity - if we're canceling then we just rebuild modules that had certain types of pending work items
  274. void BfContext::CancelWorkItems()
  275. {
  276. /*return;
  277. BfLogSysM("BfContext::CancelWorkItems\n");
  278. for (int workIdx = 0; workIdx < (int)mMethodSpecializationWorkList.size(); workIdx++)
  279. {
  280. auto workItemRef = mMethodSpecializationWorkList[workIdx];
  281. if (workItemRef != NULL)
  282. workItemRef->mFromModule->mHadBuildError = true;
  283. workIdx = mMethodSpecializationWorkList.RemoveAt(workIdx);
  284. }
  285. mMethodSpecializationWorkList.Clear();
  286. for (int workIdx = 0; workIdx < (int)mInlineMethodWorkList.size(); workIdx++)
  287. {
  288. auto workItemRef = mInlineMethodWorkList[workIdx];
  289. if (workItemRef != NULL)
  290. workItemRef->mFromModule->mHadBuildError = true;
  291. workIdx = mInlineMethodWorkList.RemoveAt(workIdx);
  292. }
  293. mInlineMethodWorkList.Clear();
  294. for (int workIdx = 0; workIdx < (int)mMethodWorkList.size(); workIdx++)
  295. {
  296. auto workItemRef = mMethodWorkList[workIdx];
  297. if (workItemRef != NULL)
  298. workItemRef->mFromModule->mHadBuildError = true;
  299. workIdx = mMethodWorkList.RemoveAt(workIdx);
  300. }
  301. mMethodWorkList.Clear();*/
  302. }
  303. bool BfContext::ProcessWorkList(bool onlyReifiedTypes, bool onlyReifiedMethods)
  304. {
  305. bool didAnyWork = false;
  306. while (!mCompiler->mCanceling)
  307. {
  308. BfParser* resolveParser = NULL;
  309. if (mCompiler->mResolvePassData != NULL)
  310. resolveParser = mCompiler->mResolvePassData->mParser;
  311. bool didWork = false;
  312. //for (auto itr = mReifyModuleWorkList.begin(); itr != mReifyModuleWorkList.end(); )
  313. for (int workIdx = 0; workIdx < mReifyModuleWorkList.size(); workIdx++)
  314. {
  315. BP_ZONE("PWL_ReifyModule");
  316. if (IsCancellingAndYield())
  317. break;
  318. BfModule* module = mReifyModuleWorkList[workIdx];
  319. if (module == NULL)
  320. {
  321. workIdx = mReifyModuleWorkList.RemoveAt(workIdx);
  322. continue;
  323. }
  324. if (!module->mIsReified)
  325. module->ReifyModule();
  326. workIdx = mReifyModuleWorkList.RemoveAt(workIdx);
  327. didWork = true;
  328. }
  329. for (int workIdx = 0; workIdx < (int)mPopulateTypeWorkList.size(); workIdx++)
  330. {
  331. //BP_ZONE("PWL_PopulateType");
  332. if (IsCancellingAndYield())
  333. break;
  334. auto workItemRef = mPopulateTypeWorkList[workIdx];
  335. if (workItemRef == NULL)
  336. {
  337. workIdx = mPopulateTypeWorkList.RemoveAt(workIdx);
  338. continue;
  339. }
  340. BfType* type = workItemRef->mType;
  341. bool rebuildType = workItemRef->mRebuildType;
  342. if ((onlyReifiedTypes) && (!type->IsReified()))
  343. {
  344. continue;
  345. }
  346. auto typeInst = type->ToTypeInstance();
  347. if ((typeInst != NULL) && (resolveParser != NULL))
  348. {
  349. if (!typeInst->mTypeDef->GetLatest()->HasSource(resolveParser))
  350. {
  351. continue;
  352. }
  353. }
  354. workIdx = mPopulateTypeWorkList.RemoveAt(workIdx);
  355. if (rebuildType)
  356. RebuildType(type);
  357. BF_ASSERT(this == type->mContext);
  358. auto useModule = type->GetModule();
  359. if (useModule == NULL)
  360. {
  361. if (mCompiler->mOptions.mCompileOnDemandKind == BfCompileOnDemandKind_AlwaysInclude)
  362. useModule = mScratchModule;
  363. else
  364. useModule = mUnreifiedModule;
  365. }
  366. useModule->PopulateType(type, BfPopulateType_Full);
  367. mCompiler->mStats.mQueuedTypesProcessed++;
  368. mCompiler->UpdateCompletion();
  369. didWork = true;
  370. }
  371. for (int workIdx = 0; workIdx < (int)mTypeRefVerifyWorkList.size(); workIdx++)
  372. {
  373. if (IsCancellingAndYield())
  374. break;
  375. auto workItemRef = mTypeRefVerifyWorkList[workIdx];
  376. if (workItemRef == NULL)
  377. {
  378. workIdx = mTypeRefVerifyWorkList.RemoveAt(workIdx);
  379. continue;
  380. }
  381. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(workItemRef->mFromModule->mCurTypeInstance, workItemRef->mCurTypeInstance);
  382. auto refTypeInst = workItemRef->mType->ToTypeInstance();
  383. if (refTypeInst->mCustomAttributes == NULL)
  384. workItemRef->mFromModule->PopulateType(refTypeInst, BfPopulateType_AllowStaticMethods);
  385. if (refTypeInst != NULL)
  386. workItemRef->mFromModule->CheckErrorAttributes(refTypeInst, NULL, refTypeInst->mCustomAttributes, workItemRef->mRefNode);
  387. workIdx = mTypeRefVerifyWorkList.RemoveAt(workIdx);
  388. didWork = true;
  389. }
  390. //while (mMethodSpecializationWorkList.size() != 0)
  391. // For the first pass, we want to handle the reified requests first. This helps rebuilds require
  392. // fewer reifications of methods
  393. for (int methodSpecializationPass = 0; methodSpecializationPass < 2; methodSpecializationPass++)
  394. {
  395. bool wantsReified = methodSpecializationPass == 0;
  396. for (int workIdx = 0; workIdx < (int)mMethodSpecializationWorkList.size(); workIdx++)
  397. {
  398. if (IsCancellingAndYield())
  399. break;
  400. auto workItemRef = mMethodSpecializationWorkList[workIdx];
  401. if (workItemRef == NULL)
  402. {
  403. workIdx = mMethodSpecializationWorkList.RemoveAt(workIdx);
  404. continue;
  405. }
  406. if (wantsReified != workItemRef->mFromModule->mIsReified)
  407. continue;
  408. auto methodSpecializationRequest = *workItemRef;
  409. auto module = workItemRef->mFromModule;
  410. workIdx = mMethodSpecializationWorkList.RemoveAt(workIdx);
  411. auto typeInst = methodSpecializationRequest.mType->ToTypeInstance();
  412. BfMethodDef* methodDef = NULL;
  413. if (methodSpecializationRequest.mForeignType != NULL)
  414. {
  415. module->PopulateType(methodSpecializationRequest.mForeignType);
  416. methodDef = methodSpecializationRequest.mForeignType->mTypeDef->mMethods[methodSpecializationRequest.mMethodIdx];
  417. }
  418. else
  419. {
  420. module->PopulateType(typeInst);
  421. if (methodSpecializationRequest.mMethodIdx >= typeInst->mTypeDef->mMethods.mSize)
  422. continue;
  423. methodDef = typeInst->mTypeDef->mMethods[methodSpecializationRequest.mMethodIdx];
  424. }
  425. module->GetMethodInstance(typeInst, methodDef, methodSpecializationRequest.mMethodGenericArguments,
  426. (BfGetMethodInstanceFlags)(methodSpecializationRequest.mFlags | BfGetMethodInstanceFlag_ResultNotUsed), methodSpecializationRequest.mForeignType);
  427. didWork = true;
  428. }
  429. }
  430. for (int workIdx = 0; workIdx < mMethodWorkList.size(); workIdx++)
  431. {
  432. BP_ZONE("PWL_ProcessMethod");
  433. mSystem->CheckLockYield();
  434. // Don't allow canceling out of the first pass - otherwise we'll just keep reprocessing the
  435. // head of the file over and over
  436. if ((resolveParser == NULL) && (mCompiler->mCanceling))
  437. break;
  438. auto workItem = mMethodWorkList[workIdx];
  439. if (workItem == NULL)
  440. {
  441. workIdx = mMethodWorkList.RemoveAt(workIdx);
  442. continue;
  443. }
  444. intptr prevPopulateTypeWorkListSize = mPopulateTypeWorkList.size();
  445. intptr prevInlineMethodWorkListSize = mInlineMethodWorkList.size();
  446. auto module = workItem->mFromModule;
  447. auto methodInstance = workItem->mMethodInstance;
  448. bool wantProcessMethod = methodInstance != NULL;
  449. if ((workItem->mFromModuleRebuildIdx != -1) && (workItem->mFromModuleRebuildIdx != module->mRebuildIdx))
  450. wantProcessMethod = false;
  451. if (methodInstance != NULL)
  452. BF_ASSERT(methodInstance->mMethodProcessRequest == workItem);
  453. bool hasBeenProcessed = true;
  454. if (wantProcessMethod)
  455. {
  456. if ((onlyReifiedMethods) && (!methodInstance->mIsReified))
  457. {
  458. continue;
  459. }
  460. auto owner = methodInstance->mMethodInstanceGroup->mOwner;
  461. BF_ASSERT(!module->mAwaitingFinish);
  462. if ((resolveParser != NULL) && (methodInstance->mMethodDef->mDeclaringType != NULL) && (methodInstance->mMethodDef->mDeclaringType->GetDefinition()->mSource != resolveParser))
  463. {
  464. continue;
  465. }
  466. hasBeenProcessed = methodInstance->mHasBeenProcessed;
  467. BF_ASSERT(module->mContext == this);
  468. if (owner->IsIncomplete())
  469. module->PopulateType(owner, BfPopulateType_Full);
  470. if (methodInstance->mDeclModule != NULL)
  471. {
  472. if (!mCompiler->mIsResolveOnly)
  473. BF_ASSERT(!methodInstance->mIsReified || methodInstance->mDeclModule->mIsModuleMutable);
  474. ProcessMethod(methodInstance);
  475. }
  476. }
  477. workIdx = mMethodWorkList.RemoveAt(workIdx);
  478. if (methodInstance != NULL)
  479. methodInstance->mMethodProcessRequest = NULL;
  480. if ((!module->mAwaitingFinish) && (module->WantsFinishModule()))
  481. {
  482. BfLogSysM("Module finished: %p %s HadBuildErrors:%d\n", module, module->mModuleName.c_str(), module->mHadBuildError);
  483. QueueFinishModule(module);
  484. }
  485. didWork = true;
  486. }
  487. // for (int workIdx = 0; workIdx < (int)mFinishedSlotAwaitModuleWorkList.size(); workIdx++)
  488. // {
  489. // auto& moduleRef = mFinishedSlotAwaitModuleWorkList[workIdx];
  490. // if (moduleRef == NULL)
  491. // {
  492. // workIdx = mFinishedSlotAwaitModuleWorkList.RemoveAt(workIdx);
  493. // continue;
  494. // }
  495. //
  496. // auto module = moduleRef;
  497. // if (mCompiler->mMaxInterfaceSlots >= 0)
  498. // {
  499. // mFinishedModuleWorkList.Add(module);
  500. // }
  501. //
  502. // workIdx = mFinishedSlotAwaitModuleWorkList.RemoveAt(workIdx);
  503. // didWork = true;
  504. // }
  505. for (int workIdx = 0; workIdx < (int)mFinishedModuleWorkList.size(); workIdx++)
  506. {
  507. //auto module = *moduleItr;
  508. auto& moduleRef = mFinishedModuleWorkList[workIdx];
  509. if (moduleRef == NULL)
  510. {
  511. workIdx = mFinishedModuleWorkList.RemoveAt(workIdx);
  512. continue;
  513. }
  514. auto module = moduleRef;
  515. if (!module->mAwaitingFinish)
  516. {
  517. BfLogSysM("mFinishedModuleWorkList removing old:%p\n", module);
  518. workIdx = mFinishedModuleWorkList.RemoveAt(workIdx);
  519. continue;
  520. }
  521. //if (module->mAwaitingFinish)
  522. BfLogSysM("mFinishedModuleWorkList handling:%p\n", module);
  523. mSystem->CheckLockYield();
  524. if (mPopulateTypeWorkList.size() > 0)
  525. {
  526. // We can't finish modules unless all DI forward references have been replaced
  527. break;
  528. }
  529. BP_ZONE("PWL_ProcessFinishedModule");
  530. bool hasUnfinishedSpecModule = false;
  531. for (auto& specModulePair : module->mSpecializedMethodModules)
  532. {
  533. auto specModule = specModulePair.mValue;
  534. if ((specModule->mAwaitingFinish) || (specModule->mIsModuleMutable))
  535. hasUnfinishedSpecModule = true;
  536. }
  537. if (hasUnfinishedSpecModule)
  538. {
  539. continue;
  540. }
  541. if (!module->mIsSpecialModule)
  542. {
  543. module->Finish();
  544. if (mCompiler->mIsResolveOnly)
  545. module->ClearModuleData();
  546. }
  547. mCompiler->UpdateCompletion();
  548. workIdx = mFinishedModuleWorkList.RemoveAt(workIdx);
  549. didWork = true;
  550. }
  551. for (int workIdx = 0; workIdx < (int)mInlineMethodWorkList.size(); workIdx++)
  552. {
  553. BP_ZONE("PWL_ProcessMethod");
  554. mSystem->CheckLockYield();
  555. // Don't allow canceling out of the first pass - otherwise we'll just keep reprocessing the
  556. // head of the file over and over
  557. if ((resolveParser == NULL) && (mCompiler->mCanceling))
  558. break;
  559. auto workItemRef = mInlineMethodWorkList[workIdx];
  560. if (workItemRef == NULL)
  561. {
  562. workIdx = mInlineMethodWorkList.RemoveAt(workIdx);
  563. continue;
  564. }
  565. auto workItem = *workItemRef;
  566. auto owner = workItem.mMethodInstance->mMethodInstanceGroup->mOwner;
  567. auto module = workItem.mFromModule;
  568. auto methodInstance = workItem.mMethodInstance;
  569. BF_ASSERT(module->mIsModuleMutable);
  570. module->PrepareForIRWriting(methodInstance->GetOwner());
  571. workIdx = mInlineMethodWorkList.RemoveAt(workIdx);
  572. BfLogSysM("Module %p inlining method %p into func:%p\n", module, methodInstance, workItem.mFunc);
  573. BfMethodInstance dupMethodInstance;
  574. dupMethodInstance.CopyFrom(methodInstance);
  575. dupMethodInstance.mIRFunction = workItem.mFunc;
  576. dupMethodInstance.mIsReified = true;
  577. dupMethodInstance.mInCEMachine = false; // Only have the original one
  578. BF_ASSERT(module->mIsReified); // We should only bother inlining in reified modules
  579. {
  580. // These errors SHOULD be duplicates, but if we have no other errors at all then we don't ignoreErrors, which
  581. // may help unveil some kinds of compiler bugs
  582. SetAndRestoreValue<bool> prevIgnoreErrors(module->mIgnoreErrors, mCompiler->mPassInstance->HasFailed());
  583. module->ProcessMethod(&dupMethodInstance, true);
  584. }
  585. static int sMethodIdx = 0;
  586. module->mBfIRBuilder->Func_SetLinkage(workItem.mFunc, BfIRLinkageType_Internal);
  587. BF_ASSERT(module->mContext == this);
  588. BF_ASSERT(module->mIsModuleMutable);
  589. if (module->WantsFinishModule())
  590. {
  591. BfLogSysM("Module finished: %s (from inlining)\n", module->mModuleName.c_str());
  592. QueueFinishModule(module);
  593. }
  594. didWork = true;
  595. }
  596. if (!didWork)
  597. {
  598. if ((mPopulateTypeWorkList.size() == 0) && (resolveParser == NULL))
  599. {
  600. BP_ZONE("PWL_CheckIncompleteGenerics");
  601. for (auto type : mResolvedTypes)
  602. {
  603. if ((type->IsIncomplete()) && (type->HasBeenReferenced()))
  604. {
  605. // The only reason a type instance wouldn't have already been in the work list is
  606. // because it's a generic specialization that was eligible for deletion,
  607. // but it has been referenced now so we need to complete it, OR
  608. // if this is from a newly-reified module
  609. if ((type->IsSpecializedByAutoCompleteMethod()) && (type->mDefineState >= BfTypeDefineState_Defined))
  610. {
  611. // We don't process methods for these
  612. }
  613. else
  614. {
  615. BfTypeProcessRequest* typeProcessRequest = mPopulateTypeWorkList.Alloc();
  616. typeProcessRequest->mType = type;
  617. mCompiler->mStats.mTypesQueued++;
  618. mCompiler->UpdateCompletion();
  619. didWork = true;
  620. }
  621. }
  622. }
  623. }
  624. }
  625. if (!didWork)
  626. break;
  627. didAnyWork = true;
  628. }
  629. return didAnyWork;
  630. }
  631. void BfContext::HandleChangedTypeDef(BfTypeDef* typeDef, bool isAutoCompleteTempType)
  632. {
  633. BF_ASSERT(typeDef->mEmitParent == NULL);
  634. if ((mCompiler->mResolvePassData == NULL) || (!typeDef->HasSource(mCompiler->mResolvePassData->mParser)))
  635. return;
  636. if (typeDef->mDefState != BfTypeDef::DefState_Defined)
  637. {
  638. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  639. {
  640. auto _CheckSource = [&](BfTypeDef* checkTypeDef)
  641. {
  642. auto typeDecl = checkTypeDef->mTypeDeclaration;
  643. if (checkTypeDef->mNextRevision != NULL)
  644. typeDecl = checkTypeDef->mNextRevision->mTypeDeclaration;
  645. if (typeDecl == NULL)
  646. return;
  647. if (typeDecl->GetSourceData() == mCompiler->mResolvePassData->mParser->mSourceData)
  648. {
  649. SetAndRestoreValue<bool> prevSkipTypeDeclaration(mCompiler->mResolvePassData->mSourceClassifier->mSkipTypeDeclarations, true);
  650. auto classifier = mCompiler->mResolvePassData->mSourceClassifier;
  651. classifier->mSkipMethodInternals = isAutoCompleteTempType;
  652. classifier->Handle(typeDecl);
  653. }
  654. };
  655. if (typeDef->mIsCombinedPartial)
  656. {
  657. for (auto partial : typeDef->mPartials)
  658. _CheckSource(partial);
  659. }
  660. else
  661. {
  662. _CheckSource(typeDef);
  663. }
  664. }
  665. }
  666. if ((!typeDef->mIsPartial) && (!isAutoCompleteTempType))
  667. {
  668. if ((typeDef->mDefState == BfTypeDef::DefState_New) ||
  669. (typeDef->mDefState == BfTypeDef::DefState_Deleted) ||
  670. (typeDef->mDefState == BfTypeDef::DefState_Signature_Changed))
  671. {
  672. mCompiler->mPassInstance->mHadSignatureChanges = true;
  673. }
  674. }
  675. }
  676. BfType * BfContext::FindTypeById(int typeId)
  677. {
  678. for (auto type : mResolvedTypes)
  679. {
  680. if (type->mTypeId == typeId)
  681. return type;
  682. }
  683. return NULL;
  684. }
  685. void BfContext::AddTypeToWorkList(BfType* type)
  686. {
  687. //BF_ASSERT(!mAssertOnPopulateType);
  688. BF_ASSERT((type->mRebuildFlags & BfTypeRebuildFlag_InTempPool) == 0);
  689. if ((type->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) == 0)
  690. {
  691. type->mRebuildFlags = (BfTypeRebuildFlags)(type->mRebuildFlags | BfTypeRebuildFlag_AddedToWorkList);
  692. BfTypeProcessRequest* typeProcessRequest = mPopulateTypeWorkList.Alloc();
  693. typeProcessRequest->mType = type;
  694. mCompiler->mStats.mTypesQueued++;
  695. mCompiler->UpdateCompletion();
  696. }
  697. }
  698. void BfContext::ValidateDependencies()
  699. {
  700. #if _DEBUG
  701. // BP_ZONE("BfContext::ValidateDependencies");
  702. // BfLogSysM("ValidateDependencies\n");
  703. //
  704. // bool deletedNewTypes = false;
  705. // auto itr = mResolvedTypes.begin();
  706. // while (itr != mResolvedTypes.end())
  707. // {
  708. // auto type = itr.mCurEntry->mValue;
  709. // if ((type->IsGenericTypeInstance()) && (type->mDefineState > BfTypeDefineState_Undefined))
  710. // {
  711. // // We can't contain deleted generic arguments without being deleted ourselves
  712. // BfTypeInstance* genericType = (BfTypeInstance*)type;
  713. //
  714. // for (auto genericTypeArg : genericType->mTypeGenericArguments)
  715. // {
  716. // auto depType = genericTypeArg->ToDependedType();
  717. // if (depType != NULL)
  718. // {
  719. // BF_ASSERT(depType->mDependencyMap.mTypeSet.ContainsKey(type));
  720. // }
  721. // }
  722. // }
  723. // ++itr;
  724. // }
  725. #endif
  726. }
  727. void BfContext::RebuildType(BfType* type, bool deleteOnDemandTypes, bool rebuildModule, bool placeSpecializiedInPurgatory)
  728. {
  729. BfTypeInstance* typeInst = type->ToTypeInstance();
  730. if (type->IsDeleting())
  731. {
  732. return;
  733. }
  734. type->mDirty = true;
  735. bool wantDeleteType = (type->IsOnDemand()) && (deleteOnDemandTypes);
  736. if (type->IsConstExprValue())
  737. {
  738. auto constExprType = (BfConstExprValueType*)type;
  739. if ((constExprType->mValue.mTypeCode != BfTypeCode_StringId) && (constExprType->mType->mSize != mScratchModule->GetPrimitiveType(constExprType->mValue.mTypeCode)->mSize))
  740. wantDeleteType = true;
  741. }
  742. if (wantDeleteType)
  743. {
  744. BfLogSysM("On-demand type %p attempted rebuild - deleting\n", type);
  745. DeleteType(type);
  746. auto depType = type->ToDependedType();
  747. if (depType != NULL)
  748. RebuildDependentTypes(depType);
  749. return;
  750. }
  751. if (typeInst == NULL)
  752. {
  753. type->mDefineState = BfTypeDefineState_Undefined;
  754. BfTypeProcessRequest* typeProcessRequest = mPopulateTypeWorkList.Alloc();
  755. typeProcessRequest->mType = type;
  756. mCompiler->mStats.mTypesQueued++;
  757. mCompiler->UpdateCompletion();
  758. return;
  759. }
  760. BF_ASSERT_REL(typeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting);
  761. // We need to verify lookups before we rebuild the type, because a type lookup change needs to count as a TypeDataChanged
  762. VerifyTypeLookups(typeInst);
  763. if (typeInst->mRevision != mCompiler->mRevision)
  764. {
  765. BfLogSysM("Setting revision. Type: %p Revision: %d\n", typeInst, mCompiler->mRevision);
  766. typeInst->mRevision = mCompiler->mRevision;
  767. }
  768. if ((typeInst->IsTypeAlias()) != (typeInst->mTypeDef->mTypeCode == BfTypeCode_TypeAlias))
  769. {
  770. BfLogSysM("TypeAlias %p status changed - deleting\n", typeInst);
  771. DeleteType(type);
  772. return;
  773. }
  774. if ((typeInst->IsBoxed()) && (typeInst->mTypeDef->mEmitParent != NULL))
  775. typeInst->mTypeDef = typeInst->mTypeDef->mEmitParent;
  776. if (mSystem->mWorkspaceConfigChanged)
  777. {
  778. typeInst->mTypeOptionsIdx = -2;
  779. }
  780. if (typeInst->mTypeFailed)
  781. {
  782. // The type definition failed, so we need to rebuild everyone that was depending on us
  783. RebuildDependentTypes(typeInst);
  784. }
  785. if (typeInst->mTypeDef->GetDefinition()->mDefState == BfTypeDef::DefState_Deleted)
  786. return;
  787. if (typeInst->mDefineState == BfTypeDefineState_Undefined)
  788. {
  789. // If we haven't added this type the worklist yet then we reprocess the type rebuilding
  790. if ((typeInst->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) != 0)
  791. return;
  792. }
  793. if (typeInst->mIsReified)
  794. mHasReifiedQueuedRebuildTypes = true;
  795. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags & ~BfTypeRebuildFlag_AddedToWorkList);
  796. bool addToWorkList = true;
  797. if ((typeInst->IsGenericTypeInstance()) && (!typeInst->IsUnspecializedType()) && (placeSpecializiedInPurgatory))
  798. {
  799. mCompiler->mGenericInstancePurgatory.push_back(typeInst);
  800. addToWorkList = false;
  801. }
  802. String typeName = mScratchModule->TypeToString(typeInst, BfTypeNameFlags_None);
  803. BfLogSysM("%p Rebuild Type: %p %s deleted:%d\n", this, typeInst, typeName.c_str(), typeInst->IsDeleting());
  804. if (addToWorkList)
  805. {
  806. AddTypeToWorkList(typeInst);
  807. }
  808. // Why did we need to do this? This caused all struct types to be rebuilt when we needed to rebuild ValueType due to
  809. // ValueType.Equals<T> needing to rebuild -- which happens if any structs that have been compared have a signature change.
  810. /*for (auto depItr : typeInst->mDependencyMap)
  811. {
  812. auto dependentType = depItr.first;
  813. auto dependencyFlags = depItr.second.mFlags;
  814. if (dependencyFlags & BfDependencyMap::DependencyFlag_DerivedFrom)
  815. {
  816. //BfLogSysM("Setting BaseTypeMayBeIncomplete on %p from %p\n", dependentType, typeInst);
  817. //dependentType->mBaseTypeMayBeIncomplete = true;
  818. if (!dependentType->IsIncomplete())
  819. RebuildType(dependentType);
  820. }
  821. }*/
  822. if ((mCompiler->IsHotCompile()) && (!typeInst->IsTypeAlias()))
  823. {
  824. BF_ASSERT(typeInst->mHotTypeData != NULL);
  825. if (typeInst->mHotTypeData != NULL)
  826. {
  827. auto hotLatestVersionHead = typeInst->mHotTypeData->GetLatestVersionHead();
  828. if (!hotLatestVersionHead->mPopulatedInterfaceMapping)
  829. {
  830. typeInst->CalcHotVirtualData(&hotLatestVersionHead->mInterfaceMapping);
  831. hotLatestVersionHead->mPopulatedInterfaceMapping = true;
  832. }
  833. PopulateHotTypeDataVTable(typeInst);
  834. }
  835. }
  836. else
  837. {
  838. delete typeInst->mHotTypeData;
  839. typeInst->mHotTypeData = NULL;
  840. }
  841. auto typeDef = typeInst->mTypeDef;
  842. // Process deps before clearing mMethodInstanceGroups, to make sure we delete any methodrefs pointing to us before
  843. // deleting those methods
  844. for (auto& dep : typeInst->mDependencyMap)
  845. {
  846. auto depType = dep.mKey;
  847. auto depFlags = dep.mValue.mFlags;
  848. // If a MethodRef depends ON US, that means it's a local method that we own. MethodRefs directly point to
  849. // methodInstances, so these will be invalid now.
  850. if (depType->IsMethodRef())
  851. {
  852. auto methodRefType = (BfMethodRefType*)depType;
  853. BF_ASSERT(methodRefType->mOwner == typeInst);
  854. DeleteType(methodRefType);
  855. }
  856. if ((depFlags & BfDependencyMap::DependencyFlag_UnspecializedType) != 0)
  857. {
  858. if ((depType->mDefineState != BfTypeDefineState_Undefined) && (depType->mRevision != mCompiler->mRevision))
  859. {
  860. // Rebuild undefined type. This isn't necessary when we modify the typeDef, but when we change configurations then
  861. // the specialized types will rebuild
  862. //TODO: WE just added "no rebuild module" to this. I'm not sure what this is all about anyway...
  863. RebuildType(depType, true, false);
  864. }
  865. }
  866. }
  867. // At some point we thought we didn't have to do this for resolve-only, but this logic is important for removing
  868. // specialized methods that are causing errors
  869. if (addToWorkList)
  870. {
  871. if (typeDef->mDefState == BfTypeDef::DefState_Signature_Changed)
  872. {
  873. typeInst->mSignatureRevision = mCompiler->mRevision;
  874. }
  875. else
  876. {
  877. bool needMethodCallsRebuild = false;
  878. for (auto& methodInstGroup : typeInst->mMethodInstanceGroups)
  879. {
  880. if (methodInstGroup.mMethodSpecializationMap != NULL)
  881. {
  882. for (auto& methodSpecializationItr : *methodInstGroup.mMethodSpecializationMap)
  883. {
  884. auto methodInstance = methodSpecializationItr.mValue;
  885. if ((!methodInstance->mIsUnspecialized) && (methodInstance->mHasFailed))
  886. {
  887. // A specialized generic method has failed, but the unspecialized version did not. This
  888. // can only happen for 'var' constrained methods, and we need to cause all referring
  889. // types to rebuild to ensure we're really specializing only the correct methods
  890. needMethodCallsRebuild = true;
  891. }
  892. }
  893. }
  894. }
  895. if (needMethodCallsRebuild)
  896. {
  897. TypeMethodSignaturesChanged(typeInst);
  898. }
  899. }
  900. }
  901. typeInst->ReleaseData();
  902. type->mDefineState = BfTypeDefineState_Undefined;
  903. typeInst->mSpecializedMethodReferences.Clear();
  904. typeInst->mAlwaysIncludeFlags = BfAlwaysIncludeFlag_None;
  905. typeInst->mHasBeenInstantiated = false;
  906. typeInst->mLookupResults.Clear();
  907. typeInst->mIsUnion = false;
  908. typeInst->mIsCRepr = false;
  909. typeInst->mPacking = 0;
  910. typeInst->mIsSplattable = false;
  911. typeInst->mHasUnderlyingArray = false;
  912. typeInst->mIsTypedPrimitive = false;
  913. typeInst->mMergedFieldDataCount = 0;
  914. typeInst->mTypeIncomplete = true;
  915. typeInst->mNeedsMethodProcessing = false;
  916. typeInst->mHasBeenInstantiated = false;
  917. typeInst->mHasParameterizedBase = false;
  918. typeInst->mTypeFailed = false;
  919. typeInst->mTypeWarned = false;
  920. typeInst->mHasUnderlyingArray = false;
  921. typeInst->mHasPackingHoles = false;
  922. typeInst->mWantsGCMarking = false;
  923. typeInst->mHasDeclError = false;
  924. delete typeInst->mTypeInfoEx;
  925. typeInst->mTypeInfoEx = NULL;
  926. if (typeInst->mCeTypeInfo != NULL)
  927. typeInst->mCeTypeInfo->mRebuildMap.Clear();
  928. if (typeInst->mTypeDef->mEmitParent != NULL)
  929. {
  930. auto emitTypeDef = typeInst->mTypeDef;
  931. typeInst->mTypeDef = emitTypeDef->mEmitParent;
  932. BfLogSysM("Type %p queueing delete of typeDef %p, resetting typeDef to %p\n", typeInst, emitTypeDef, typeInst->mTypeDef);
  933. if (emitTypeDef->mDefState != BfTypeDef::DefState_Deleted)
  934. {
  935. emitTypeDef->mDefState = BfTypeDef::DefState_Deleted;
  936. AutoCrit autoCrit(mSystem->mDataLock);
  937. BF_ASSERT(!mSystem->mTypeDefDeleteQueue.Contains(emitTypeDef));
  938. mSystem->mTypeDefDeleteQueue.push_back(emitTypeDef);
  939. for (auto& dep : typeInst->mDependencyMap)
  940. {
  941. if (auto typeInst = dep.mKey->ToTypeInstance())
  942. {
  943. if (typeInst->mTypeDef == emitTypeDef)
  944. RebuildType(typeInst);
  945. }
  946. }
  947. }
  948. }
  949. //typeInst->mTypeDef->ClearEmitted();
  950. for (auto localMethod : typeInst->mOwnedLocalMethods)
  951. delete localMethod;
  952. typeInst->mOwnedLocalMethods.Clear();
  953. if (typeInst->IsGenericTypeInstance())
  954. {
  955. auto genericTypeInstance = (BfTypeInstance*)typeInst;
  956. genericTypeInstance->mGenericTypeInfo->mTypeGenericArgumentRefs.Clear();
  957. for (auto genericParam : genericTypeInstance->mGenericTypeInfo->mGenericParams)
  958. genericParam->Release();
  959. genericTypeInstance->mGenericTypeInfo->mInitializedGenericParams = false;
  960. genericTypeInstance->mGenericTypeInfo->mFinishedGenericParams = false;
  961. genericTypeInstance->mGenericTypeInfo->mGenericParams.Clear();
  962. genericTypeInstance->mGenericTypeInfo->mValidatedGenericConstraints = false;
  963. genericTypeInstance->mGenericTypeInfo->mHadValidateErrors = false;
  964. if (genericTypeInstance->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  965. genericTypeInstance->mGenericTypeInfo->mGenericExtensionInfo->Clear();
  966. genericTypeInstance->mGenericTypeInfo->mProjectsReferenced.Clear();
  967. }
  968. typeInst->mStaticSearchMap.Clear();
  969. typeInst->mInternalAccessMap.Clear();
  970. typeInst->mInterfaces.Clear();
  971. typeInst->mInterfaceMethodTable.Clear();
  972. for (auto operatorInfo : typeInst->mOperatorInfo)
  973. delete operatorInfo;
  974. typeInst->mOperatorInfo.Clear();
  975. typeInst->mMethodInstanceGroups.Clear();
  976. typeInst->mFieldInstances.Clear();
  977. for (auto methodInst : typeInst->mInternalMethods)
  978. delete methodInst;
  979. typeInst->mInternalMethods.Clear();
  980. typeInst->mHasStaticInitMethod = false;
  981. typeInst->mHasStaticMarkMethod = false;
  982. typeInst->mHasStaticDtorMethod = false;
  983. typeInst->mHasTLSFindMethod = false;
  984. typeInst->mBaseType = NULL;
  985. delete typeInst->mCustomAttributes;
  986. typeInst->mCustomAttributes = NULL;
  987. delete typeInst->mAttributeData;
  988. typeInst->mAttributeData = NULL;
  989. typeInst->mVirtualMethodTableSize = 0;
  990. typeInst->mVirtualMethodTable.Clear();
  991. typeInst->mSize = -1;
  992. typeInst->mAlign = -1;
  993. typeInst->mInstSize = -1;
  994. typeInst->mInstAlign = -1;
  995. typeInst->mInheritDepth = 0;
  996. delete typeInst->mConstHolder;
  997. typeInst->mConstHolder = NULL;
  998. if ((typeInst->mModule != NULL) && (rebuildModule))
  999. {
  1000. typeInst->mModule->StartNewRevision();
  1001. typeInst->mRevision = mCompiler->mRevision;
  1002. }
  1003. }
  1004. void BfContext::RebuildDependentTypes(BfDependedType* dType)
  1005. {
  1006. TypeDataChanged(dType, true);
  1007. auto typeInst = dType->ToTypeInstance();
  1008. if (typeInst != NULL)
  1009. TypeMethodSignaturesChanged(typeInst);
  1010. }
  1011. void BfContext::RebuildDependentTypes_MidCompile(BfDependedType* dType, const String& reason)
  1012. {
  1013. dType->mRebuildFlags = (BfTypeRebuildFlags)(dType->mRebuildFlags | BfTypeRebuildFlag_ChangedMidCompile);
  1014. int prevDeletedTypes = mCompiler->mStats.mTypesDeleted;
  1015. if (mCompiler->mIsResolveOnly)
  1016. mCompiler->mNeedsFullRefresh = true;
  1017. BfLogSysM("Rebuilding dependent types MidCompile Type:%p Reason:%s\n", dType, reason.c_str());
  1018. RebuildDependentTypes(dType);
  1019. if (mCompiler->mStats.mTypesDeleted != prevDeletedTypes)
  1020. {
  1021. BfLogSysM("Rebuilding dependent types MidCompile Type:%p Reason:%s - updating after deleting types\n", dType, reason.c_str());
  1022. UpdateAfterDeletingTypes();
  1023. }
  1024. }
  1025. // Dependencies cascade as such:
  1026. // DerivedFrom / StructMemberData: these change the layout of memory for the dependent classes,
  1027. // so not only do the dependent classes need to be rebuild, but any other classes relying on those derived classes
  1028. // (either by derivation, containment, or field reading) need to have their code recompiled as well.
  1029. // ReadFields: when ClassB depends on the data layout of ClassA, and ClassC reads a field from
  1030. // ClassB, it means that ClassC code needs to be recompiled if ClassA data layout changes, but performing a ReadField
  1031. // (obviously) doesn't change the data layout of ClassC
  1032. // Calls: non-cascading dependency, since it's independent of data layout ConstValue: non-cascading data change
  1033. void BfContext::TypeDataChanged(BfDependedType* dType, bool isNonStaticDataChange)
  1034. {
  1035. BfLogSysM("TypeDataChanged %p\n", dType);
  1036. auto rebuildFlag = isNonStaticDataChange ? BfTypeRebuildFlag_NonStaticChange : BfTypeRebuildFlag_StaticChange;
  1037. if ((dType->mRebuildFlags & rebuildFlag) != 0) // Already did this change?
  1038. return;
  1039. dType->mRebuildFlags = (BfTypeRebuildFlags)(dType->mRebuildFlags | rebuildFlag);
  1040. // We need to rebuild all other types that rely on our data layout
  1041. for (auto& depItr : dType->mDependencyMap)
  1042. {
  1043. auto dependentType = depItr.mKey;
  1044. auto dependencyFlags = depItr.mValue.mFlags;
  1045. auto dependentDType = dependentType->ToDependedType();
  1046. if (dependentDType != NULL)
  1047. {
  1048. auto dependentTypeInstance = dependentType->ToTypeInstance();
  1049. if (isNonStaticDataChange)
  1050. {
  1051. bool hadChange = false;
  1052. if ((dependencyFlags &
  1053. (BfDependencyMap::DependencyFlag_DerivedFrom |
  1054. BfDependencyMap::DependencyFlag_ValueTypeMemberData |
  1055. BfDependencyMap::DependencyFlag_NameReference |
  1056. BfDependencyMap::DependencyFlag_ValueTypeSizeDep)) != 0)
  1057. {
  1058. hadChange = true;
  1059. }
  1060. // This case is for when we were declared as a class on a previous compilation,
  1061. // but then we were changed to a struct
  1062. if ((dType->IsValueType()) &&
  1063. (dependencyFlags & BfDependencyMap::DependencyFlag_PtrMemberData))
  1064. {
  1065. hadChange = true;
  1066. }
  1067. if (mCompiler->IsHotCompile())
  1068. {
  1069. // VData layout may be changing if there's a data change...
  1070. if (dependencyFlags & BfDependencyMap::DependencyFlag_VirtualCall)
  1071. {
  1072. hadChange = true;
  1073. }
  1074. }
  1075. if (hadChange)
  1076. TypeDataChanged(dependentDType, true);
  1077. }
  1078. if (dependencyFlags & BfDependencyMap::DependencyFlag_ConstValue)
  1079. {
  1080. TypeDataChanged(dependentDType, false);
  1081. // The ConstValue dependency may be that dependentType used one of our consts as
  1082. // a default value to a method param, so assume callsites need rebuilding
  1083. if (dependentTypeInstance != NULL)
  1084. TypeMethodSignaturesChanged(dependentTypeInstance);
  1085. }
  1086. if (dependentType->mRevision != mCompiler->mRevision)
  1087. {
  1088. // We need to include DependencyFlag_ParamOrReturnValue because it could be a struct that changes its splatting ability
  1089. // We can't ONLY check against structs, though, because a type could change from a class to a struct
  1090. if (dependencyFlags &
  1091. (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_ParamOrReturnValue |
  1092. BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_MethodGenericArg |
  1093. BfDependencyMap::DependencyFlag_Allocates))
  1094. {
  1095. RebuildType(dependentType);
  1096. }
  1097. else if (((dependencyFlags & BfDependencyMap::DependencyFlag_NameReference) != 0) &&
  1098. ((dType->mRebuildFlags & BfTypeRebuildFlag_ChangedMidCompile) != 0) &&
  1099. (dType->IsTypeAlias()))
  1100. {
  1101. RebuildType(dependentType);
  1102. }
  1103. }
  1104. }
  1105. else
  1106. {
  1107. if (dependentType->mRevision != mCompiler->mRevision)
  1108. {
  1109. // Not a type instance, probably something like a sized array
  1110. RebuildType(dependentType);
  1111. }
  1112. }
  1113. }
  1114. if (dType->mRevision != mCompiler->mRevision)
  1115. RebuildType(dType);
  1116. }
  1117. void BfContext::TypeMethodSignaturesChanged(BfTypeInstance* typeInst)
  1118. {
  1119. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_MethodSignatureChange) // Already did change?
  1120. return;
  1121. typeInst->mRebuildFlags = (BfTypeRebuildFlags) (typeInst->mRebuildFlags | BfTypeRebuildFlag_MethodSignatureChange);
  1122. BfLogSysM("TypeMethodSignaturesChanged %p\n", typeInst);
  1123. // These don't happen in TypeDataChanged because we don't need to cascade
  1124. for (auto& depItr : typeInst->mDependencyMap)
  1125. {
  1126. auto dependentType = depItr.mKey;
  1127. auto dependencyFlags = depItr.mValue.mFlags;
  1128. if (dependentType->mRevision != mCompiler->mRevision)
  1129. {
  1130. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1131. if ((dependencyFlags & BfDependencyMap::DependencyFlag_Calls) ||
  1132. (dependencyFlags & BfDependencyMap::DependencyFlag_VirtualCall) ||
  1133. (dependencyFlags & BfDependencyMap::DependencyFlag_InlinedCall) ||
  1134. (dependencyFlags & BfDependencyMap::DependencyFlag_MethodGenericArg) ||
  1135. (dependencyFlags & BfDependencyMap::DependencyFlag_CustomAttribute) ||
  1136. (dependencyFlags & BfDependencyMap::DependencyFlag_DerivedFrom) ||
  1137. (dependencyFlags & BfDependencyMap::DependencyFlag_ImplementsInterface))
  1138. {
  1139. RebuildType(dependentType);
  1140. }
  1141. }
  1142. }
  1143. }
  1144. void BfContext::TypeInlineMethodInternalsChanged(BfTypeInstance* typeInst)
  1145. {
  1146. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_MethodInlineInternalsChange) // Already did change?
  1147. return;
  1148. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_MethodInlineInternalsChange);
  1149. // These don't happen in TypeDataChanged because we don't need to cascade
  1150. for (auto& depItr : typeInst->mDependencyMap)
  1151. {
  1152. auto dependentType = depItr.mKey;
  1153. auto dependencyFlags = depItr.mValue.mFlags;
  1154. if (dependentType->mRevision != mCompiler->mRevision)
  1155. {
  1156. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1157. if ((dependencyFlags & BfDependencyMap::DependencyFlag_InlinedCall) != 0)
  1158. {
  1159. RebuildType(dependentType);
  1160. }
  1161. }
  1162. }
  1163. }
  1164. void BfContext::TypeConstEvalChanged(BfTypeInstance* typeInst)
  1165. {
  1166. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_ConstEvalChange) // Already did change?
  1167. return;
  1168. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_ConstEvalChange);
  1169. // These don't happen in TypeDataChanged because we don't need to cascade
  1170. for (auto& depItr : typeInst->mDependencyMap)
  1171. {
  1172. auto dependentType = depItr.mKey;
  1173. auto dependencyFlags = depItr.mValue.mFlags;
  1174. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1175. if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEval) != 0)
  1176. {
  1177. auto depTypeInst = dependentType->ToTypeInstance();
  1178. if (depTypeInst != NULL)
  1179. TypeConstEvalChanged(depTypeInst);
  1180. if (dependentType->mRevision != mCompiler->mRevision)
  1181. RebuildType(dependentType);
  1182. }
  1183. else if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEvalConstField) != 0)
  1184. {
  1185. auto depTypeInst = dependentType->ToTypeInstance();
  1186. if (depTypeInst != NULL)
  1187. TypeConstEvalFieldChanged(depTypeInst);
  1188. if (dependentType->mRevision != mCompiler->mRevision)
  1189. RebuildType(dependentType);
  1190. }
  1191. }
  1192. }
  1193. void BfContext::TypeConstEvalFieldChanged(BfTypeInstance* typeInst)
  1194. {
  1195. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_ConstEvalFieldChange) // Already did change?
  1196. return;
  1197. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_ConstEvalFieldChange);
  1198. // These don't happen in TypeDataChanged because we don't need to cascade
  1199. for (auto& depItr : typeInst->mDependencyMap)
  1200. {
  1201. auto dependentType = depItr.mKey;
  1202. auto dependencyFlags = depItr.mValue.mFlags;
  1203. if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEvalConstField) != 0)
  1204. {
  1205. auto depTypeInst = dependentType->ToTypeInstance();
  1206. if (depTypeInst != NULL)
  1207. TypeConstEvalFieldChanged(depTypeInst);
  1208. if (dependentType->mRevision != mCompiler->mRevision)
  1209. RebuildType(dependentType);
  1210. }
  1211. }
  1212. }
  1213. void BfContext::PopulateHotTypeDataVTable(BfTypeInstance* typeInstance)
  1214. {
  1215. BP_ZONE("BfContext::PopulateHotTypeDataVTable");
  1216. if (typeInstance->IsTypeAlias())
  1217. return;
  1218. // The hot virtual table only holds our new entries, not the vtable entries inherited from our base classes
  1219. auto hotTypeData = typeInstance->mHotTypeData;
  1220. if (hotTypeData == NULL)
  1221. return;
  1222. if (typeInstance->IsIncomplete())
  1223. {
  1224. if (mCompiler->mHotState->mCommittedHotCompileIdx > 0)
  1225. {
  1226. // Should already be populated
  1227. BF_ASSERT(hotTypeData->mVTableOrigLength != -1);
  1228. }
  1229. return;
  1230. }
  1231. if (hotTypeData->mVTableOrigLength == -1)
  1232. {
  1233. auto committedHotTypeVersion = typeInstance->mHotTypeData->GetTypeVersion(mCompiler->mHotState->mCommittedHotCompileIdx);
  1234. if (committedHotTypeVersion != NULL)
  1235. {
  1236. hotTypeData->mVTableOrigLength = typeInstance->mVirtualMethodTableSize;
  1237. hotTypeData->mOrigInterfaceMethodsLength = typeInstance->GetIFaceVMethodSize();
  1238. }
  1239. BfLogSysM("PopulateHotTypeDataVTable set %p HotDataType->mVTableOrigLength To %d\n", typeInstance, hotTypeData->mVTableOrigLength);
  1240. }
  1241. int vTableStart = -1;
  1242. int primaryVTableSize = 0;
  1243. if (typeInstance->IsInterface())
  1244. {
  1245. // Interfaces don't have vext markers
  1246. vTableStart = 0;
  1247. #ifdef _DEBUG
  1248. for (int vIdx = 0; vIdx < (int)typeInstance->mVirtualMethodTable.size(); vIdx++)
  1249. {
  1250. auto& methodRef = typeInstance->mVirtualMethodTable[vIdx].mDeclaringMethod;
  1251. if (methodRef.mMethodNum == -1)
  1252. {
  1253. BF_DBG_FATAL("Shouldn't have vext marker");
  1254. }
  1255. }
  1256. #endif
  1257. }
  1258. else
  1259. {
  1260. for (int vIdx = 0; vIdx < (int)typeInstance->mVirtualMethodTable.size(); vIdx++)
  1261. {
  1262. auto& methodRef = typeInstance->mVirtualMethodTable[vIdx].mDeclaringMethod;
  1263. if (methodRef.mMethodNum == -1)
  1264. {
  1265. if (methodRef.mTypeInstance == typeInstance)
  1266. {
  1267. vTableStart = vIdx;
  1268. }
  1269. else if (vTableStart != -1)
  1270. {
  1271. BF_DBG_FATAL("Shouldn't have another vext marker");
  1272. break;
  1273. }
  1274. }
  1275. }
  1276. }
  1277. primaryVTableSize = (int)typeInstance->mVirtualMethodTable.size() - vTableStart;
  1278. BF_ASSERT(vTableStart != -1);
  1279. if (primaryVTableSize > (int)hotTypeData->mVTableEntries.size())
  1280. hotTypeData->mVTableEntries.Resize(primaryVTableSize);
  1281. int methodIdx = -1;
  1282. for (int vIdx = 0; vIdx < primaryVTableSize; vIdx++)
  1283. {
  1284. auto& methodRef = typeInstance->mVirtualMethodTable[vTableStart + vIdx].mDeclaringMethod;
  1285. methodIdx++;
  1286. auto methodInstance = (BfMethodInstance*)methodRef;
  1287. if (methodInstance == NULL)
  1288. continue;
  1289. BF_ASSERT(methodRef.mTypeInstance == typeInstance);
  1290. BF_ASSERT(methodInstance->mVirtualTableIdx != -1);
  1291. BF_ASSERT(!methodInstance->mMethodDef->mIsOverride);
  1292. // Find the original non-override method
  1293. /*while (methodInstance->mMethodDef->mIsOverride)
  1294. {
  1295. BfTypeInstance* parent = methodInstance->GetOwner()->mBaseType;
  1296. auto parentVirtualMethod = parent->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  1297. BF_ASSERT(parentVirtualMethod->mVirtualTableIdx != -1);
  1298. methodInstance = parentVirtualMethod;
  1299. }*/
  1300. BF_ASSERT(!methodInstance->mMethodInfoEx->mMangledName.IsEmpty());
  1301. auto& entry = hotTypeData->mVTableEntries[vIdx];
  1302. if (entry.mFuncName.empty())
  1303. {
  1304. entry.mFuncName = methodInstance->mMethodInfoEx->mMangledName;
  1305. }
  1306. else
  1307. {
  1308. // Make sure its the same still
  1309. BF_ASSERT(entry.mFuncName == methodInstance->mMethodInfoEx->mMangledName);
  1310. }
  1311. }
  1312. }
  1313. void BfContext::SaveDeletingType(BfType* type)
  1314. {
  1315. if (mCompiler->mIsResolveOnly)
  1316. return;
  1317. if ((type->mRebuildFlags) && ((type->mRebuildFlags & BfTypeRebuildFlag_TypeDataSaved) != 0))
  1318. return;
  1319. type->mRebuildFlags = (BfTypeRebuildFlags)(type->mRebuildFlags | BfTypeRebuildFlag_TypeDataSaved);
  1320. String mangledName = BfSafeMangler::Mangle(type, mUnreifiedModule);
  1321. BfLogSysM("Saving deleted type: %p %s\n", type, mangledName.c_str());
  1322. BfSavedTypeData** savedTypeDataPtr;
  1323. BfSavedTypeData* savedTypeData;
  1324. if (mSavedTypeDataMap.TryAdd(mangledName, NULL, &savedTypeDataPtr))
  1325. {
  1326. savedTypeData = new BfSavedTypeData();
  1327. *savedTypeDataPtr = savedTypeData;
  1328. }
  1329. else
  1330. {
  1331. // This can happen if we have a conflicting type definition
  1332. savedTypeData = *savedTypeDataPtr;
  1333. }
  1334. savedTypeData->mTypeId = type->mTypeId;
  1335. while ((int)mSavedTypeData.size() <= savedTypeData->mTypeId)
  1336. mSavedTypeData.Add(NULL);
  1337. mSavedTypeData[savedTypeData->mTypeId] = savedTypeData;
  1338. auto typeInst = type->ToTypeInstance();
  1339. if (typeInst != NULL)
  1340. {
  1341. delete savedTypeData->mHotTypeData;
  1342. if (mCompiler->IsHotCompile())
  1343. savedTypeData->mHotTypeData = typeInst->mHotTypeData;
  1344. else
  1345. delete typeInst->mHotTypeData;
  1346. typeInst->mHotTypeData = NULL;
  1347. }
  1348. }
  1349. BfType* BfContext::FindType(const StringImpl& fullTypeName)
  1350. {
  1351. int genericArgCount = 0;
  1352. String typeName = fullTypeName;
  1353. if (typeName.EndsWith('>'))
  1354. {
  1355. // Generic
  1356. }
  1357. BfTypeDef* typeDef = mSystem->FindTypeDef(typeName, genericArgCount);
  1358. if (typeDef == NULL)
  1359. return NULL;
  1360. return mUnreifiedModule->ResolveTypeDef(typeDef);
  1361. }
  1362. String BfContext::TypeIdToString(int typeId)
  1363. {
  1364. auto type = mTypes[typeId];
  1365. if (type != NULL)
  1366. return mScratchModule->TypeToString(type);
  1367. if (mCompiler->mHotState != NULL)
  1368. {
  1369. for (auto& kv : mCompiler->mHotState->mDeletedTypeNameMap)
  1370. {
  1371. if (kv.mValue == typeId)
  1372. return kv.mKey;
  1373. }
  1374. }
  1375. return StrFormat("#%d", typeId);
  1376. }
  1377. BfHotTypeData* BfContext::GetHotTypeData(int typeId)
  1378. {
  1379. auto type = mTypes[typeId];
  1380. if (type != NULL)
  1381. {
  1382. auto typeInst = type->ToTypeInstance();
  1383. if (typeInst != NULL)
  1384. return typeInst->mHotTypeData;
  1385. }
  1386. if (typeId < (int)mSavedTypeData.size())
  1387. {
  1388. auto savedTypeData = mSavedTypeData[typeId];
  1389. if (savedTypeData != NULL)
  1390. return savedTypeData->mHotTypeData;
  1391. }
  1392. return NULL;
  1393. }
  1394. void BfContext::ReflectInit()
  1395. {
  1396. auto bfModule = mScratchModule;
  1397. bfModule->CreatePointerType(bfModule->GetPrimitiveType(BfTypeCode_NullPtr));
  1398. ///
  1399. auto typeDefType = bfModule->ResolveTypeDef(mCompiler->mTypeTypeDef)->ToTypeInstance();
  1400. if (!typeDefType)
  1401. return;
  1402. BF_ASSERT(typeDefType != NULL);
  1403. mBfTypeType = typeDefType->ToTypeInstance();
  1404. auto typeInstanceDefType = bfModule->ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  1405. if (!typeInstanceDefType)
  1406. return;
  1407. auto typeInstanceDefTypeInstance = typeInstanceDefType->ToTypeInstance();
  1408. auto typeDef = mSystem->FindTypeDef("System.ClassVData");
  1409. BF_ASSERT(typeDef != NULL);
  1410. auto bfClassVDataType = bfModule->ResolveTypeDef(typeDef)->ToTypeInstance();
  1411. mBfClassVDataPtrType = bfModule->CreatePointerType(bfClassVDataType);
  1412. }
  1413. void BfContext::DeleteType(BfType* type, bool deferDepRebuilds)
  1414. {
  1415. if (type == mBfObjectType)
  1416. mBfObjectType = NULL;
  1417. if (type == mBfTypeType)
  1418. mBfObjectType = NULL;
  1419. if (type->mRebuildFlags & BfTypeRebuildFlag_Deleted)
  1420. return;
  1421. mCompiler->mStats.mTypesDeleted++;
  1422. BfDependedType* dType = type->ToDependedType();
  1423. BfTypeInstance* typeInst = type->ToTypeInstance();
  1424. if (typeInst != NULL)
  1425. {
  1426. if (mCompiler->mHotState != NULL)
  1427. {
  1428. if ((typeInst->mHotTypeData != NULL) && (typeInst->mHotTypeData->mPendingDataChange))
  1429. mCompiler->mHotState->RemovePendingChanges(typeInst);
  1430. String typeName = mScratchModule->TypeToString(typeInst);
  1431. mCompiler->mHotState->mDeletedTypeNameMap[typeName] = typeInst->mTypeId;
  1432. }
  1433. auto module = typeInst->mModule;
  1434. // Don't remove the mModule pointer in typeInst -- if the type ends up being a zombie then we still need
  1435. // to generate the VData from the type
  1436. if (module != NULL)
  1437. {
  1438. if (module->mIsScratchModule)
  1439. {
  1440. BF_ASSERT(module->mOwnedTypeInstances.size() == 0);
  1441. }
  1442. else
  1443. {
  1444. auto itr = std::find(module->mOwnedTypeInstances.begin(), module->mOwnedTypeInstances.end(), typeInst);
  1445. module->mOwnedTypeInstances.erase(itr);
  1446. if ((module->mOwnedTypeInstances.size() == 0) && (module != mScratchModule))
  1447. {
  1448. // This module is no longer needed
  1449. module->RemoveModuleData();
  1450. module->mIsDeleting = true;
  1451. auto itr = std::find(mModules.begin(), mModules.end(), module);
  1452. mModules.erase(itr);
  1453. // This was only needed for 'zombie modules', which we don't need anymore?
  1454. // To avoid linking errors. Used instead of directly removing from mModules.
  1455. mDeletingModules.push_back(module);
  1456. }
  1457. }
  1458. }
  1459. }
  1460. type->mRebuildFlags = (BfTypeRebuildFlags)((type->mRebuildFlags | BfTypeRebuildFlag_Deleted) & ~BfTypeRebuildFlag_DeleteQueued);
  1461. SaveDeletingType(type);
  1462. mTypes[type->mTypeId] = NULL;
  1463. BfLogSysM("Deleting Type: %p %s\n", type, mScratchModule->TypeToString(type).c_str());
  1464. if (typeInst != NULL)
  1465. {
  1466. for (auto& methodInstGroup : typeInst->mMethodInstanceGroups)
  1467. {
  1468. if ((methodInstGroup.mDefault != NULL) && (methodInstGroup.mDefault->mInCEMachine))
  1469. mCompiler->mCEMachine->RemoveMethod(methodInstGroup.mDefault);
  1470. if (methodInstGroup.mMethodSpecializationMap != NULL)
  1471. {
  1472. for (auto& methodSpecializationItr : *methodInstGroup.mMethodSpecializationMap)
  1473. {
  1474. auto methodInstance = methodSpecializationItr.mValue;
  1475. if (methodInstance->mInCEMachine)
  1476. mCompiler->mCEMachine->RemoveMethod(methodInstance);
  1477. }
  1478. }
  1479. }
  1480. }
  1481. // All dependencies cause rebuilds when we delete types
  1482. if (dType != NULL)
  1483. {
  1484. //TODO: Do PopulateHotTypeDataVTable then store the HotTypeDataData
  1485. if (dType->IsUnspecializedType())
  1486. {
  1487. /*auto itr = mScratchModule->mClassVDataRefs.find(typeInst);
  1488. if (itr != mScratchModule->mClassVDataRefs.end())
  1489. mScratchModule->mClassVDataRefs.erase(itr);*/
  1490. mScratchModule->mClassVDataRefs.Remove(typeInst);
  1491. }
  1492. //UH - I think this is not true.
  1493. // If A derives from B, and C derives from B, if we delete 'A' then it's true that
  1494. // 'C' won't rebuild otherwise, BUT 'B' would fail to build but it would do a TypeDataChanged once it WAS able to built. Right?
  1495. // Even though we do rebuilds on all types below, we specifically need to call
  1496. // TypeDataChanged here for cascading data dependencies
  1497. /*if (!deferDepRebuilds)
  1498. TypeDataChanged(typeInst, true);*/
  1499. Array<BfType*> rebuildTypeQueue;
  1500. for (auto& depItr : dType->mDependencyMap)
  1501. {
  1502. //bool rebuildType = false;
  1503. auto dependentType = depItr.mKey;
  1504. auto dependentTypeInst = dependentType->ToTypeInstance();
  1505. auto dependencyEntry = depItr.mValue;
  1506. if ((dependencyEntry.mFlags & (BfDependencyMap::DependencyFlag_MethodGenericArg)) != 0)
  1507. {
  1508. if (!dependentType->IsDeleting())
  1509. {
  1510. if ((deferDepRebuilds) && (dependentTypeInst != NULL))
  1511. mQueuedSpecializedMethodRebuildTypes.Add(dependentTypeInst);
  1512. }
  1513. }
  1514. if ((dependencyEntry.mFlags & (BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  1515. {
  1516. // This type can't exist anymore
  1517. DeleteType(dependentType, deferDepRebuilds);
  1518. continue;
  1519. }
  1520. if (dependentTypeInst == NULL)
  1521. {
  1522. // This was something like a sized array
  1523. DeleteType(dependentType, deferDepRebuilds);
  1524. continue;
  1525. }
  1526. if ((dependencyEntry.mFlags & ~(BfDependencyMap::DependencyFlag_UnspecializedType | BfDependencyMap::DependencyFlag_WeakReference)) == 0)
  1527. continue; // Not a cause for rebuilding
  1528. if (dependentTypeInst->IsOnDemand())
  1529. {
  1530. // Force on-demand dependencies to rebuild themselves
  1531. DeleteType(dependentType, deferDepRebuilds);
  1532. continue;
  1533. }
  1534. if (dType->IsBoxed())
  1535. {
  1536. // Allow these to just be implicitly used. This solves some issues with switching between ignoreWrites settings in resolveOnly compilation
  1537. continue;
  1538. }
  1539. if ((deferDepRebuilds) && (dependentTypeInst != NULL))
  1540. mFailTypes.Add(dependentTypeInst);
  1541. else
  1542. {
  1543. rebuildTypeQueue.Add(dependentType);
  1544. }
  1545. }
  1546. if (type->IsMethodRef())
  1547. {
  1548. // Detach
  1549. auto methodRefType = (BfMethodRefType*)type;
  1550. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  1551. BF_ASSERT(methodInstance->mMethodInstanceGroup->mRefCount > 0);
  1552. methodInstance->mMethodInstanceGroup->mRefCount--;
  1553. methodRefType->mMethodRef = NULL;
  1554. methodInstance->mHasMethodRefType = false;
  1555. }
  1556. for (auto dependentType : rebuildTypeQueue)
  1557. RebuildType(dependentType);
  1558. }
  1559. }
  1560. void BfContext::UpdateAfterDeletingTypes()
  1561. {
  1562. BP_ZONE("BfContext::UpdateAfterDeletingTypes");
  1563. BfLogSysM("UpdateAfterDeletingTypes\n");
  1564. int graveyardStart = (int)mTypeGraveyard.size();
  1565. while (true)
  1566. {
  1567. bool deletedNewTypes = false;
  1568. auto itr = mResolvedTypes.begin();
  1569. while (itr != mResolvedTypes.end())
  1570. {
  1571. auto type = itr.mCurEntry->mValue;
  1572. bool doDelete = false;
  1573. //BfLogSysM("Removing entry\n");
  1574. bool isDeleting = type->IsDeleting();
  1575. if ((!isDeleting) && (type->IsDependentOnUnderlyingType()))
  1576. {
  1577. auto underlyingType = type->GetUnderlyingType();
  1578. if ((underlyingType != NULL) && (underlyingType->IsDeleting()))
  1579. {
  1580. deletedNewTypes = true;
  1581. isDeleting = true;
  1582. DeleteType(type);
  1583. }
  1584. }
  1585. if (isDeleting)
  1586. {
  1587. doDelete = true;
  1588. }
  1589. else
  1590. {
  1591. #if _DEBUG
  1592. if (type->IsGenericTypeInstance())
  1593. {
  1594. // We can't contain deleted generic arguments without being deleted ourselves
  1595. BfTypeInstance* genericType = (BfTypeInstance*)type;
  1596. for (auto genericTypeArg : genericType->mGenericTypeInfo->mTypeGenericArguments)
  1597. {
  1598. BF_ASSERT((!genericTypeArg->IsDeleting()));
  1599. }
  1600. }
  1601. #endif
  1602. }
  1603. if (doDelete)
  1604. {
  1605. BF_ASSERT((type->mRebuildFlags & BfTypeRebuildFlag_Deleted) == BfTypeRebuildFlag_Deleted);
  1606. itr = mResolvedTypes.Erase(itr);
  1607. mTypeGraveyard.push_back(type);
  1608. }
  1609. else
  1610. ++itr;
  1611. }
  1612. if (!deletedNewTypes)
  1613. break;
  1614. }
  1615. #if _DEBUG
  1616. // auto itr = mResolvedTypes.begin();
  1617. // while (itr != mResolvedTypes.end())
  1618. // {
  1619. // auto type = itr.mCurEntry->mType;
  1620. // BF_ASSERT((type->mRebuildFlags & ~(BfTypeRebuildFlag_Deleted)) == 0);
  1621. // ++itr;
  1622. // }
  1623. #endif
  1624. if (!mCompiler->mIsResolveOnly)
  1625. {
  1626. BP_ZONE("BfContext::UpdateAfterDeletingTypes saving typeData");
  1627. for (int graveyardIdx = graveyardStart; graveyardIdx < (int)mTypeGraveyard.size(); graveyardIdx++)
  1628. {
  1629. auto type = mTypeGraveyard[graveyardIdx];
  1630. SaveDeletingType(type);
  1631. }
  1632. }
  1633. }
  1634. // This happens before the old defs have been injected
  1635. void BfContext::PreUpdateRevisedTypes()
  1636. {
  1637. // if (mCompiler->IsHotCompile())
  1638. // {
  1639. // for (auto typeEntry : mResolvedTypes)
  1640. // {
  1641. // auto type = typeEntry->mType;
  1642. // auto typeInst = type->ToTypeInstance();
  1643. // if (typeInst == NULL)
  1644. // continue;
  1645. //
  1646. // auto typeDef = typeInst->mTypeDef;
  1647. // if ((typeDef->mDefState != BfTypeDef::DefState_New) && (typeDef->mDefState != BfTypeDef::DefState_Defined))
  1648. // {
  1649. // if (typeInst->mHotTypeData == NULL)
  1650. // {
  1651. // typeInst->mHotTypeData = new BfHotTypeData();
  1652. // typeInst->CalcHotVirtualData(&typeInst->mHotTypeData->mInterfaceMapping);
  1653. // }
  1654. // PopulateHotTypeDataVTable(typeInst);
  1655. // }
  1656. // }
  1657. // }
  1658. }
  1659. // Note that this method can also cause modules to be build in other contexts.
  1660. // That's why we do our UpdateAfterDeletingTypes after all the contexts' UpdateRevisedTypes
  1661. void BfContext::UpdateRevisedTypes()
  1662. {
  1663. BP_ZONE("BfContext::UpdateRevisedTypes");
  1664. BfLogSysM("BfContext::UpdateRevisedTypes\n");
  1665. auto _CheckCanSkipCtor = [&](BfTypeDef* typeDef)
  1666. {
  1667. if (typeDef == NULL)
  1668. return true;
  1669. typeDef = typeDef->GetLatest();
  1670. for (auto fieldDef : typeDef->mFields)
  1671. {
  1672. if (fieldDef->mIsStatic)
  1673. continue;
  1674. if (fieldDef->mInitializer != NULL)
  1675. return false;
  1676. }
  1677. for (auto methodDef : typeDef->mMethods)
  1678. {
  1679. if (methodDef->mMethodType == BfMethodType_Init)
  1680. return false;
  1681. }
  1682. return true;
  1683. };
  1684. auto _CheckCanSkipCtorByName = [&](const StringImpl& name)
  1685. {
  1686. BfAtomComposite qualifiedFindName;
  1687. if (!mSystem->ParseAtomComposite(name, qualifiedFindName))
  1688. return true;
  1689. auto itr = mSystem->mTypeDefs.TryGet(qualifiedFindName);
  1690. while (itr)
  1691. {
  1692. BfTypeDef* typeDef = *itr;
  1693. if ((typeDef->mDefState != BfTypeDef::DefState_Deleted) &&
  1694. (!typeDef->mIsCombinedPartial))
  1695. {
  1696. if (typeDef->mFullNameEx == qualifiedFindName)
  1697. if (!_CheckCanSkipCtor(typeDef))
  1698. return false;
  1699. }
  1700. itr.MoveToNextHashMatch();
  1701. }
  1702. return true;
  1703. };
  1704. bool wantsCanSkipObjectCtor = _CheckCanSkipCtorByName("System.Object");
  1705. bool wantsCanSkipValueTypeCtor = _CheckCanSkipCtorByName("System.ValueType");
  1706. int wantPtrSize;
  1707. if ((mCompiler->mOptions.mMachineType == BfMachineType_x86) |
  1708. (mCompiler->mOptions.mMachineType == BfMachineType_ARM) ||
  1709. (mCompiler->mOptions.mMachineType == BfMachineType_Wasm32))
  1710. wantPtrSize = 4;
  1711. else
  1712. wantPtrSize = 8;
  1713. if ((wantPtrSize != mSystem->mPtrSize) || (wantsCanSkipObjectCtor != mCanSkipObjectCtor) || (wantsCanSkipValueTypeCtor != mCanSkipValueTypeCtor))
  1714. {
  1715. BfLogSysM("Full rebuild. Pointer: %d CanSkipObjectCtor:%d CanSkipValueTypeCtor:%d\n", wantPtrSize, wantsCanSkipObjectCtor, wantsCanSkipValueTypeCtor);
  1716. mSystem->mPtrSize = wantPtrSize;
  1717. mCanSkipObjectCtor = wantsCanSkipObjectCtor;
  1718. mCanSkipValueTypeCtor = wantsCanSkipValueTypeCtor;
  1719. auto intPtrType = mScratchModule->GetPrimitiveType(BfTypeCode_IntPtr);
  1720. auto uintPtrType = mScratchModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  1721. if (intPtrType != NULL)
  1722. {
  1723. RebuildType(intPtrType);
  1724. mScratchModule->PopulateType(intPtrType);
  1725. }
  1726. if (uintPtrType != NULL)
  1727. {
  1728. RebuildType(uintPtrType);
  1729. mScratchModule->PopulateType(uintPtrType);
  1730. }
  1731. // Rebuild all types
  1732. for (auto type : mResolvedTypes)
  1733. {
  1734. RebuildType(type);
  1735. }
  1736. }
  1737. // Temporarily store failTypes - we may need to re-insert into them after another failure
  1738. auto failTypes = mFailTypes;
  1739. mFailTypes.Clear();
  1740. bool wantsDebugInfo = (mCompiler->mOptions.mEmitDebugInfo);
  1741. Array<BfTypeInstance*> defStateChangedQueue;
  1742. Array<BfTypeInstance*> defEmitParentCheckQueue;
  1743. Dictionary<String, uint64> lastWriteTimeMap;
  1744. bool rebuildAllFilesChanged = mCompiler->mRebuildChangedFileSet.Contains("*");
  1745. // Do primary 'rebuild' scan
  1746. for (auto type : mResolvedTypes)
  1747. {
  1748. auto typeInst = type->ToTypeInstance();
  1749. if (type == NULL)
  1750. {
  1751. BF_FATAL("We shouldn't have NULLs");
  1752. continue;
  1753. }
  1754. /*if ((!mCompiler->mIsResolveOnly) && (!type->IsNull()) && (!type->IsUnspecializedType()))
  1755. {
  1756. // We need to completely rebuild all types if we switch from having debug info to not having debug info
  1757. if ((typeInst != NULL) && (typeInst->mModule != NULL) && (typeInst->mModule->mHasDebugInfo != wantsDebugInfo))
  1758. {
  1759. RebuildType(type);
  1760. }
  1761. }*/
  1762. if (typeInst == NULL)
  1763. continue;
  1764. if (typeInst->IsDeleting())
  1765. continue;
  1766. auto typeDef = typeInst->mTypeDef;
  1767. if (typeDef->mEmitParent != NULL)
  1768. defEmitParentCheckQueue.Add(typeInst);
  1769. if (typeDef->mProject->mDisabled)
  1770. {
  1771. DeleteType(type);
  1772. continue;
  1773. }
  1774. typeInst->mRebuildFlags = BfTypeRebuildFlag_None;
  1775. if (typeDef->mIsPartial)
  1776. {
  1777. // This was a type that wasn't marked as partial before but now it is, so it doesn't need its own typedef
  1778. // since we will have a separate type instance for the combined partials
  1779. DeleteType(type);
  1780. continue;
  1781. }
  1782. if (typeInst->mCeTypeInfo != NULL)
  1783. {
  1784. bool changed = false;
  1785. for (auto& kv : typeInst->mCeTypeInfo->mRebuildMap)
  1786. {
  1787. mCompiler->mHasComptimeRebuilds = true;
  1788. if (kv.mKey.mKind == CeRebuildKey::Kind_File)
  1789. {
  1790. String* keyPtr = NULL;
  1791. uint64* valuePtr = NULL;
  1792. if (lastWriteTimeMap.TryAdd(kv.mKey.mString, &keyPtr, &valuePtr))
  1793. {
  1794. *valuePtr = BfpFile_GetTime_LastWrite(kv.mKey.mString.c_str());
  1795. }
  1796. if (*valuePtr != kv.mValue.mInt)
  1797. changed = true;
  1798. mCompiler->mRebuildFileSet.Add(kv.mKey.mString);
  1799. }
  1800. if ((kv.mKey.mKind == CeRebuildKey::Kind_File) || (kv.mKey.mKind == CeRebuildKey::Kind_Directory))
  1801. {
  1802. if ((rebuildAllFilesChanged) || (mCompiler->mRebuildChangedFileSet.Contains(kv.mKey.mString)))
  1803. changed = true;
  1804. mCompiler->mRebuildFileSet.Add(kv.mKey.mString);
  1805. }
  1806. }
  1807. if (changed)
  1808. {
  1809. RebuildType(typeInst);
  1810. }
  1811. }
  1812. if ((typeInst->mHotTypeData != NULL) && (!mCompiler->IsHotCompile()))
  1813. {
  1814. if (typeInst->mHotTypeData->GetLatestVersion()->mDeclHotCompileIdx != 0)
  1815. {
  1816. // Type was rebuilt with hot changes - rebuild back to normal
  1817. delete typeInst->mHotTypeData;
  1818. typeInst->mHotTypeData = NULL;
  1819. RebuildType(typeInst);
  1820. }
  1821. }
  1822. auto checkTypeDef = typeDef;
  1823. if (typeDef->mEmitParent != NULL)
  1824. checkTypeDef = typeDef->mEmitParent;
  1825. if (checkTypeDef->mDefState == BfTypeDef::DefState_Defined)
  1826. {
  1827. BF_ASSERT(typeDef->mNextRevision == NULL);
  1828. continue;
  1829. }
  1830. if (checkTypeDef->mDefState != BfTypeDef::DefState_New)
  1831. {
  1832. defStateChangedQueue.Add(typeInst);
  1833. }
  1834. }
  1835. // We consumed this above
  1836. mCompiler->mRebuildChangedFileSet.Clear();
  1837. for (auto typeInst : defStateChangedQueue)
  1838. {
  1839. BP_ZONE("BfContext::UpdateRevisedTypes defStateChangedQueue");
  1840. auto typeDef = typeInst->mTypeDef;
  1841. bool isTypeDefinedInContext = true;
  1842. if (typeDef->mEmitParent != NULL)
  1843. {
  1844. typeDef = typeDef->mEmitParent;
  1845. }
  1846. if (typeDef->mDefState == BfTypeDef::DefState_Deleted)
  1847. {
  1848. HandleChangedTypeDef(typeDef);
  1849. DeleteType(typeInst);
  1850. continue;
  1851. }
  1852. if (typeDef->mDefState == BfTypeDef::DefState_InlinedInternals_Changed)
  1853. {
  1854. TypeInlineMethodInternalsChanged(typeInst);
  1855. }
  1856. bool isSignatureChange = typeDef->mDefState == BfTypeDef::DefState_Signature_Changed;
  1857. if (((typeDef->mDefState == BfTypeDef::DefState_Internals_Changed) || (typeDef->mDefState == BfTypeDef::DefState_InlinedInternals_Changed)) &&
  1858. (typeInst->IsInterface()))
  1859. {
  1860. isSignatureChange = true;
  1861. }
  1862. if ((typeDef->mDefState != BfTypeDef::DefState_Refresh) && ((typeInst->mDependencyMap.mFlagsUnion & BfDependencyMap::DependencyFlag_ConstEval) != 0))
  1863. {
  1864. TypeConstEvalChanged(typeInst);
  1865. }
  1866. if (isSignatureChange)
  1867. {
  1868. TypeDataChanged(typeInst, true);
  1869. TypeMethodSignaturesChanged(typeInst);
  1870. }
  1871. /*if (!mCompiler->mIsResolveOnly)
  1872. {
  1873. OutputDebugStrF("TypeDef: %s %d %p\n", typeDef->mName.c_str(), typeDef->mDefState, &typeDef->mDefState);
  1874. }*/
  1875. RebuildType(typeInst);
  1876. }
  1877. for (auto typeInst : failTypes)
  1878. {
  1879. if (!typeInst->IsDeleting())
  1880. {
  1881. if (!typeInst->mTypeDef->mProject->mDisabled)
  1882. {
  1883. BfLogSysM("Rebuilding failed type %p\n", typeInst);
  1884. RebuildType(typeInst);
  1885. }
  1886. }
  1887. }
  1888. for (auto typeInst : defEmitParentCheckQueue)
  1889. {
  1890. if (typeInst->IsDeleting())
  1891. continue;
  1892. auto typeDef = typeInst->mTypeDef;
  1893. if (typeDef->mEmitParent != NULL)
  1894. {
  1895. if (typeDef->mDefState == BfTypeDef::DefState_Deleted)
  1896. {
  1897. BfLogSysM("Type %p typeDef %p deleted, setting to emitParent %p\n", typeInst, typeDef, typeDef->mEmitParent);
  1898. typeInst->mTypeDef = typeDef->mEmitParent;
  1899. }
  1900. else
  1901. {
  1902. auto emitTypeDef = typeDef;
  1903. typeDef = typeDef->mEmitParent;
  1904. if (typeDef->mNextRevision != NULL)
  1905. {
  1906. BfLogSysM("Type %p typeDef %p emitparent %p has next revision, setting emittedDirty\n", typeInst, emitTypeDef, typeDef);
  1907. emitTypeDef->mDefState = BfTypeDef::DefState_EmittedDirty;
  1908. }
  1909. }
  1910. }
  1911. }
  1912. //
  1913. {
  1914. AutoCrit autoCrit(mSystem->mDataLock);
  1915. auto options = &mCompiler->mOptions;
  1916. HashContext workspaceConfigHashCtx;
  1917. workspaceConfigHashCtx.MixinStr(options->mTargetTriple);
  1918. workspaceConfigHashCtx.MixinStr(options->mTargetCPU);
  1919. workspaceConfigHashCtx.Mixin(options->mForceRebuildIdx);
  1920. workspaceConfigHashCtx.Mixin(options->mMachineType);
  1921. workspaceConfigHashCtx.Mixin(options->mToolsetType);
  1922. workspaceConfigHashCtx.Mixin(options->mSIMDSetting);
  1923. workspaceConfigHashCtx.Mixin(options->mEmitDebugInfo);
  1924. workspaceConfigHashCtx.Mixin(options->mEmitLineInfo);
  1925. workspaceConfigHashCtx.Mixin(options->mNoFramePointerElim);
  1926. workspaceConfigHashCtx.Mixin(options->mInitLocalVariables);
  1927. workspaceConfigHashCtx.Mixin(options->mRuntimeChecks);
  1928. workspaceConfigHashCtx.Mixin(options->mAllowStructByVal);
  1929. workspaceConfigHashCtx.Mixin(options->mEmitDynamicCastCheck);
  1930. workspaceConfigHashCtx.Mixin(options->mAllowHotSwapping);
  1931. workspaceConfigHashCtx.Mixin(options->mObjectHasDebugFlags);
  1932. workspaceConfigHashCtx.Mixin(options->mEnableRealtimeLeakCheck);
  1933. workspaceConfigHashCtx.Mixin(options->mEmitObjectAccessCheck);
  1934. workspaceConfigHashCtx.Mixin(options->mArithmeticChecks);
  1935. workspaceConfigHashCtx.Mixin(options->mEnableCustodian);
  1936. workspaceConfigHashCtx.Mixin(options->mEnableSideStack);
  1937. workspaceConfigHashCtx.Mixin(options->mHasVDataExtender);
  1938. workspaceConfigHashCtx.Mixin(options->mDebugAlloc);
  1939. workspaceConfigHashCtx.Mixin(options->mOmitDebugHelpers);
  1940. workspaceConfigHashCtx.Mixin(options->mUseDebugBackingParams);
  1941. workspaceConfigHashCtx.Mixin(options->mWriteIR);
  1942. workspaceConfigHashCtx.Mixin(options->mGenerateObj);
  1943. workspaceConfigHashCtx.Mixin(options->mAllocStackCount);
  1944. workspaceConfigHashCtx.Mixin(options->mExtraResolveChecks);
  1945. workspaceConfigHashCtx.Mixin(options->mMaxSplatRegs);
  1946. workspaceConfigHashCtx.MixinStr(options->mMallocLinkName);
  1947. workspaceConfigHashCtx.MixinStr(options->mFreeLinkName);
  1948. for (auto& typeOptions : mSystem->mTypeOptions)
  1949. {
  1950. workspaceConfigHashCtx.Mixin(typeOptions.mTypeFilters.size());
  1951. for (auto& filter : typeOptions.mTypeFilters)
  1952. workspaceConfigHashCtx.MixinStr(filter);
  1953. workspaceConfigHashCtx.Mixin(typeOptions.mAttributeFilters.size());
  1954. for (auto& filter : typeOptions.mAttributeFilters)
  1955. workspaceConfigHashCtx.MixinStr(filter);
  1956. workspaceConfigHashCtx.Mixin(typeOptions.mSIMDSetting);
  1957. workspaceConfigHashCtx.Mixin(typeOptions.mOptimizationLevel);
  1958. workspaceConfigHashCtx.Mixin(typeOptions.mEmitDebugInfo);
  1959. workspaceConfigHashCtx.Mixin(typeOptions.mAndFlags);
  1960. workspaceConfigHashCtx.Mixin(typeOptions.mOrFlags);
  1961. workspaceConfigHashCtx.Mixin(typeOptions.mReflectMethodFilters.size());
  1962. for (auto& filter : typeOptions.mReflectMethodFilters)
  1963. {
  1964. workspaceConfigHashCtx.MixinStr(filter.mFilter);
  1965. workspaceConfigHashCtx.Mixin(filter.mAndFlags);
  1966. workspaceConfigHashCtx.Mixin(filter.mOrFlags);
  1967. }
  1968. workspaceConfigHashCtx.Mixin(typeOptions.mReflectMethodAttributeFilters.size());
  1969. for (auto& filter : typeOptions.mReflectMethodAttributeFilters)
  1970. {
  1971. workspaceConfigHashCtx.MixinStr(filter.mFilter);
  1972. workspaceConfigHashCtx.Mixin(filter.mAndFlags);
  1973. workspaceConfigHashCtx.Mixin(filter.mOrFlags);
  1974. }
  1975. workspaceConfigHashCtx.Mixin(typeOptions.mAllocStackTraceDepth);
  1976. }
  1977. // for (auto project : mSystem->mProjects)
  1978. // {
  1979. // workspaceConfigHashCtx.MixinStr(project->mName);
  1980. // }
  1981. Val128 workspaceConfigHash = workspaceConfigHashCtx.Finish128();
  1982. mSystem->mWorkspaceConfigChanged = mSystem->mWorkspaceConfigHash != workspaceConfigHash;
  1983. if (mSystem->mWorkspaceConfigChanged)
  1984. {
  1985. // If the type options have changed, we know we will rebuild all types and thus
  1986. // remap their mTypeOptionsIdx
  1987. mSystem->mMergedTypeOptions.Clear();
  1988. mSystem->mWorkspaceConfigHash = workspaceConfigHash;
  1989. }
  1990. for (auto project : mSystem->mProjects)
  1991. {
  1992. HashContext buildConfigHashCtx;
  1993. buildConfigHashCtx.Mixin(workspaceConfigHash);
  1994. if (!mCompiler->mIsResolveOnly)
  1995. {
  1996. auto& codeGenOptions = project->mCodeGenOptions;
  1997. buildConfigHashCtx.MixinStr(mCompiler->mOutputDirectory);
  1998. buildConfigHashCtx.Mixin(project->mAlwaysIncludeAll);
  1999. buildConfigHashCtx.Mixin(project->mSingleModule);
  2000. bool isTestConfig = project->mTargetType == BfTargetType_BeefTest;
  2001. buildConfigHashCtx.Mixin(isTestConfig);
  2002. buildConfigHashCtx.Mixin(codeGenOptions.mOptLevel);
  2003. buildConfigHashCtx.Mixin(codeGenOptions.mSizeLevel);
  2004. buildConfigHashCtx.Mixin(codeGenOptions.mUseCFLAA);
  2005. buildConfigHashCtx.Mixin(codeGenOptions.mUseNewSROA);
  2006. buildConfigHashCtx.Mixin(codeGenOptions.mDisableTailCalls);
  2007. buildConfigHashCtx.Mixin(codeGenOptions.mDisableUnitAtATime);
  2008. buildConfigHashCtx.Mixin(codeGenOptions.mDisableUnrollLoops);
  2009. buildConfigHashCtx.Mixin(codeGenOptions.mBBVectorize);
  2010. buildConfigHashCtx.Mixin(codeGenOptions.mSLPVectorize);
  2011. buildConfigHashCtx.Mixin(codeGenOptions.mLoopVectorize);
  2012. buildConfigHashCtx.Mixin(codeGenOptions.mRerollLoops);
  2013. buildConfigHashCtx.Mixin(codeGenOptions.mLoadCombine);
  2014. buildConfigHashCtx.Mixin(codeGenOptions.mDisableGVNLoadPRE);
  2015. buildConfigHashCtx.Mixin(codeGenOptions.mVerifyInput);
  2016. buildConfigHashCtx.Mixin(codeGenOptions.mVerifyOutput);
  2017. buildConfigHashCtx.Mixin(codeGenOptions.mStripDebug);
  2018. buildConfigHashCtx.Mixin(codeGenOptions.mMergeFunctions);
  2019. buildConfigHashCtx.Mixin(codeGenOptions.mEnableMLSM);
  2020. buildConfigHashCtx.Mixin(codeGenOptions.mRunSLPAfterLoopVectorization);
  2021. buildConfigHashCtx.Mixin(codeGenOptions.mUseGVNAfterVectorization);
  2022. }
  2023. buildConfigHashCtx.Mixin(project->mDisabled);
  2024. buildConfigHashCtx.Mixin(project->mTargetType);
  2025. for (auto dep : project->mDependencies)
  2026. {
  2027. String depName = dep->mName;
  2028. buildConfigHashCtx.MixinStr(depName);
  2029. }
  2030. Val128 buildConfigHash = buildConfigHashCtx.Finish128();
  2031. HashContext vDataConfigHashCtx;
  2032. vDataConfigHashCtx.Mixin(buildConfigHash);
  2033. vDataConfigHashCtx.MixinStr(project->mStartupObject);
  2034. vDataConfigHashCtx.Mixin(project->mTargetType);
  2035. //Val128 vDataConfigHash = buildConfigHash;
  2036. //vDataConfigHash = Hash128(project->mStartupObject.c_str(), (int)project->mStartupObject.length() + 1, vDataConfigHash);
  2037. //vDataConfigHash = Hash128(&project->mTargetType, sizeof(project->mTargetType), vDataConfigHash);
  2038. auto vDataConfigHash = vDataConfigHashCtx.Finish128();
  2039. project->mBuildConfigChanged = buildConfigHash != project->mBuildConfigHash;
  2040. project->mBuildConfigHash = buildConfigHash;
  2041. project->mVDataConfigHash = vDataConfigHash;
  2042. }
  2043. }
  2044. Array<BfModule*> moduleRebuildList;
  2045. for (int moduleIdx = 0; moduleIdx < (int)mModules.size(); moduleIdx++)
  2046. {
  2047. //mCompiler->mOutputDirectory
  2048. auto module = mModules[moduleIdx];
  2049. // This logic needs to run on both us and our mOptModule
  2050. //for (int subModuleIdx = 0; subModuleIdx < 2; subModuleIdx++)
  2051. auto subModule = module;
  2052. while (subModule != NULL)
  2053. {
  2054. //auto subModule = module;
  2055. //if (subModuleIdx == -1)
  2056. //subModule = module->mOptModule;
  2057. // If we canceled the last build, we could have specialized method modules referring to projects that have
  2058. // since been deleted or disabled - so remove those
  2059. for (auto methodModuleItr = subModule->mSpecializedMethodModules.begin(); methodModuleItr != subModule->mSpecializedMethodModules.end(); )
  2060. {
  2061. auto& projectList = methodModuleItr->mKey;
  2062. auto specModule = methodModuleItr->mValue;
  2063. bool hasDisabledProject = false;
  2064. for (auto checkProject : projectList)
  2065. hasDisabledProject |= checkProject->mDisabled;
  2066. if (hasDisabledProject)
  2067. {
  2068. delete specModule;
  2069. methodModuleItr = subModule->mSpecializedMethodModules.Remove(methodModuleItr);
  2070. }
  2071. else
  2072. ++methodModuleItr;
  2073. }
  2074. subModule = subModule->mNextAltModule;
  2075. }
  2076. if ((module->mProject != NULL) && (module->mProject->mDisabled))
  2077. {
  2078. continue;
  2079. }
  2080. // Module previously had error so we have to rebuild the whole thing
  2081. bool needsModuleRebuild = module->mHadBuildError;
  2082. if ((module->mHadHotObjectWrites) && (!mCompiler->IsHotCompile()))
  2083. {
  2084. module->mHadHotObjectWrites = false; // Handled, can reset now
  2085. needsModuleRebuild = true;
  2086. }
  2087. if (module->mProject != NULL)
  2088. {
  2089. if ((module->mIsHotModule) && (mCompiler->mOptions.mHotProject == NULL))
  2090. needsModuleRebuild = true;
  2091. if (module->mProject->mBuildConfigChanged)
  2092. needsModuleRebuild = true;
  2093. }
  2094. if (mCompiler->mInterfaceSlotCountChanged)
  2095. {
  2096. if ((module->mUsedSlotCount >= 0) && (module->mUsedSlotCount != mCompiler->mMaxInterfaceSlots))
  2097. needsModuleRebuild = true;
  2098. }
  2099. if (needsModuleRebuild)
  2100. moduleRebuildList.push_back(module);
  2101. if (module->mIsSpecialModule) // vdata, external, data
  2102. continue;
  2103. bool wantMethodSpecializations = !mCompiler->mIsResolveOnly;
  2104. // We don't really need this on for resolveOnly passes, but this is useful to force on for debugging.
  2105. // The following block is fairly useful for detecting dependency errors.
  2106. wantMethodSpecializations = true;
  2107. }
  2108. mCompiler->mInterfaceSlotCountChanged = false;
  2109. for (auto module : moduleRebuildList)
  2110. {
  2111. if (!module->mIsDeleting)
  2112. module->StartNewRevision();
  2113. }
  2114. // Ensure even unspecialized types an interfaces get rebuilt
  2115. // In particular, this is needed if we build a non-hotswap config and then
  2116. // build a hotswap config-- we need to make sure all those methods have
  2117. // HotMethodData
  2118. if (mSystem->mWorkspaceConfigChanged)
  2119. {
  2120. for (auto type : mResolvedTypes)
  2121. {
  2122. RebuildType(type);
  2123. }
  2124. }
  2125. }
  2126. void BfContext::VerifyTypeLookups(BfTypeInstance* typeInst)
  2127. {
  2128. for (auto& lookupEntryPair : typeInst->mLookupResults)
  2129. {
  2130. BfTypeLookupEntry& lookupEntry = lookupEntryPair.mKey;
  2131. bool isDirty = false;
  2132. if (lookupEntry.mName.IsEmpty())
  2133. {
  2134. // If the name lookup failed before, thats because we didn't have the right atoms. Are there new atoms now?
  2135. if (lookupEntry.mAtomUpdateIdx != mSystem->mAtomUpdateIdx)
  2136. isDirty = true;
  2137. }
  2138. else
  2139. {
  2140. // If any atoms have been placed in the graveyard, typesHash will be zero and thus cause a rebuild
  2141. uint32 atomUpdateIdx = lookupEntry.mName.GetAtomUpdateIdx();
  2142. if (atomUpdateIdx == 0)
  2143. {
  2144. isDirty = true;
  2145. }
  2146. else
  2147. {
  2148. // Sanity check, mostly checking that useTypeDef wasn't deleted
  2149. BF_ASSERT((lookupEntry.mUseTypeDef->mName->mAtomUpdateIdx >= 1) && (lookupEntry.mUseTypeDef->mName->mAtomUpdateIdx <= mSystem->mAtomUpdateIdx));
  2150. // Only do the actual lookup if types were added or removed whose name is contained in one of the name parts referenced
  2151. if (atomUpdateIdx != lookupEntry.mAtomUpdateIdx)
  2152. {
  2153. // NOTE: we purposely don't use mNextRevision here. If the the was NOT rebuilt then that means we didn't actually rebuild
  2154. // so the mNextRevision will be ignored
  2155. auto useTypeDef = lookupEntry.mUseTypeDef;
  2156. BfTypeDef* ambiguousTypeDef = NULL;
  2157. BfTypeLookupResult* lookupResult = &lookupEntryPair.mValue;
  2158. BfTypeLookupResultCtx lookupResultCtx;
  2159. lookupResultCtx.mResult = lookupResult;
  2160. lookupResultCtx.mIsVerify = true;
  2161. BfTypeDef* result = typeInst->mModule->FindTypeDefRaw(lookupEntry.mName, lookupEntry.mNumGenericParams, typeInst, useTypeDef, NULL, &lookupResultCtx);
  2162. if ((result == NULL) && (lookupResult->mFoundInnerType))
  2163. {
  2164. // Allow this- if there were new types added then the types would be rebuilt already
  2165. }
  2166. else if (result != lookupResult->mTypeDef)
  2167. {
  2168. isDirty = true;
  2169. }
  2170. else
  2171. lookupEntry.mAtomUpdateIdx = atomUpdateIdx;
  2172. }
  2173. }
  2174. }
  2175. if (isDirty)
  2176. {
  2177. // Clear lookup results to avoid infinite recursion
  2178. typeInst->mLookupResults.Clear();
  2179. // We need to treat this lookup as if it changed the whole type signature
  2180. TypeDataChanged(typeInst, true);
  2181. TypeMethodSignaturesChanged(typeInst);
  2182. RebuildType(typeInst);
  2183. break;
  2184. }
  2185. }
  2186. }
  2187. void BfContext::GenerateModuleName_TypeInst(BfTypeInstance* typeInst, String& name)
  2188. {
  2189. auto resolveModule = typeInst->mIsReified ? mScratchModule : mUnreifiedModule;
  2190. auto outerType = resolveModule->GetOuterType(typeInst);
  2191. int startGenericIdx = 0;
  2192. if (outerType != NULL)
  2193. {
  2194. startGenericIdx = (int)outerType->mTypeDef->mGenericParamDefs.size();
  2195. GenerateModuleName_Type(outerType, name);
  2196. /*if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2197. name += '_';*/
  2198. }
  2199. else
  2200. {
  2201. for (int i = 0; i < typeInst->mTypeDef->mNamespace.mSize; i++)
  2202. {
  2203. auto atom = typeInst->mTypeDef->mNamespace.mParts[i];
  2204. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2205. name += '_';
  2206. name += atom->mString;
  2207. }
  2208. }
  2209. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2210. name += '_';
  2211. if (typeInst->mTypeDef->IsGlobalsContainer())
  2212. name += "GLOBALS_";
  2213. else
  2214. name += typeInst->mTypeDef->mName->mString;
  2215. if (typeInst->IsClosure())
  2216. {
  2217. auto closureType = (BfClosureType*)typeInst;
  2218. name += closureType->mNameAdd;
  2219. return;
  2220. }
  2221. if (typeInst->mGenericTypeInfo != NULL)
  2222. {
  2223. for (int genericIdx = startGenericIdx; genericIdx < (int)typeInst->mGenericTypeInfo->mTypeGenericArguments.size(); genericIdx++)
  2224. {
  2225. auto type = typeInst->mGenericTypeInfo->mTypeGenericArguments[genericIdx];
  2226. GenerateModuleName_Type(type, name);
  2227. }
  2228. }
  2229. }
  2230. void BfContext::GenerateModuleName_Type(BfType* type, String& name)
  2231. {
  2232. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2233. name += '_';
  2234. if (type->IsBoxed())
  2235. {
  2236. auto boxedType = (BfBoxedType*)type;
  2237. if (boxedType->IsBoxedStructPtr())
  2238. name += "BOXPTR_";
  2239. else
  2240. name += "BOX_";
  2241. GenerateModuleName_Type(boxedType->mElementType, name);
  2242. return;
  2243. }
  2244. if (type->IsPrimitiveType())
  2245. {
  2246. auto primType = (BfPrimitiveType*)type;
  2247. name += primType->mTypeDef->mName->mString;
  2248. return;
  2249. }
  2250. if (type->IsPointer())
  2251. {
  2252. auto ptrType = (BfPointerType*)type;
  2253. name += "PTR_";
  2254. GenerateModuleName_Type(ptrType->mElementType, name);
  2255. return;
  2256. }
  2257. if (type->IsTuple())
  2258. {
  2259. auto tupleType = (BfTypeInstance*)type;
  2260. name += "TUPLE_";
  2261. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  2262. {
  2263. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  2264. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  2265. String fieldName = fieldDef->mName;
  2266. if ((fieldName[0] < '0') || (fieldName[0] > '9'))
  2267. name += StrFormat("U%d@%s", fieldName.length() + 1, fieldName.c_str());
  2268. GenerateModuleName_Type(fieldInstance->mResolvedType, name);
  2269. }
  2270. return;
  2271. }
  2272. if (type->IsDelegateFromTypeRef() || type->IsFunctionFromTypeRef())
  2273. {
  2274. auto typeInst = type->ToTypeInstance();
  2275. auto delegateInfo = type->GetDelegateInfo();
  2276. auto methodDef = typeInst->mTypeDef->mMethods[0];
  2277. if (type->IsDelegateFromTypeRef())
  2278. name += "DELEGATE_";
  2279. else
  2280. name += "FUNCTION_";
  2281. GenerateModuleName_Type(mScratchModule->ResolveTypeRef(methodDef->mReturnTypeRef), name);
  2282. name += "_";
  2283. for (int paramIdx = 0; paramIdx < methodDef->mParams.size(); paramIdx++)
  2284. {
  2285. if (paramIdx > 0)
  2286. name += "_";
  2287. auto paramDef = methodDef->mParams[paramIdx];
  2288. GenerateModuleName_Type(mScratchModule->ResolveTypeRef(paramDef->mTypeRef), name);
  2289. name += "_";
  2290. name += paramDef->mName;
  2291. }
  2292. return;
  2293. }
  2294. if (type->IsMethodRef())
  2295. {
  2296. auto methodRefType = (BfMethodRefType*)type;
  2297. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  2298. name += "METHOD_";
  2299. GenerateModuleName_Type(methodInstance->GetOwner(), name);
  2300. name += "_";
  2301. String addName = methodInstance->mMethodDef->mName;
  2302. for (auto&& c : addName)
  2303. {
  2304. if ((c == '$') || (c == '@'))
  2305. c = '_';
  2306. }
  2307. name += addName;
  2308. }
  2309. if (type->IsConstExprValue())
  2310. {
  2311. auto constExprType = (BfConstExprValueType*)type;
  2312. if (BfIRConstHolder::IsInt(constExprType->mValue.mTypeCode))
  2313. {
  2314. if (constExprType->mValue.mInt64 < 0)
  2315. name += StrFormat("_%ld", -constExprType->mValue.mInt64);
  2316. else
  2317. name += StrFormat("%ld", constExprType->mValue.mInt64);
  2318. return;
  2319. }
  2320. }
  2321. auto typeInst = type->ToTypeInstance();
  2322. if (typeInst != NULL)
  2323. {
  2324. GenerateModuleName_TypeInst(typeInst, name);
  2325. return;
  2326. }
  2327. }
  2328. String BfContext::GenerateModuleName(BfTypeInstance* typeInst)
  2329. {
  2330. String name;
  2331. GenerateModuleName_Type(typeInst, name);
  2332. int maxChars = 80;
  2333. if (name.length() > 80)
  2334. {
  2335. name.RemoveToEnd(80);
  2336. name += "__";
  2337. }
  2338. for (int i = 0; i < (int)name.length(); i++)
  2339. {
  2340. char c = name[i];
  2341. if (c == '@')
  2342. name[i] = '_';
  2343. }
  2344. String tryName = name;
  2345. for (int i = 2; true; i++)
  2346. {
  2347. if (!mUsedModuleNames.Contains(ToUpper(tryName)))
  2348. return tryName;
  2349. tryName = name + StrFormat("_%d", i);
  2350. }
  2351. return name;
  2352. }
  2353. bool BfContext::IsSentinelMethod(BfMethodInstance* methodInstance)
  2354. {
  2355. return (methodInstance != NULL) && ((uintptr)(methodInstance) <= 1);
  2356. }
  2357. void BfContext::VerifyTypeLookups()
  2358. {
  2359. BP_ZONE("BfContext::VerifyTypeLookups");
  2360. for (auto type : mResolvedTypes)
  2361. {
  2362. auto typeInst = type->ToTypeInstance();
  2363. if ((typeInst != NULL) && (!typeInst->IsDeleting()) && (!typeInst->IsIncomplete()))
  2364. {
  2365. VerifyTypeLookups(typeInst);
  2366. }
  2367. }
  2368. }
  2369. // When we are rebuilding 'typeInst' and we want to make sure that we rebuild all the methods that were
  2370. // actively referenced previously, this method will generate BfMethodSpecializationRequest for all used
  2371. // methods from previously-built modules
  2372. void BfContext::QueueMethodSpecializations(BfTypeInstance* typeInst, bool checkSpecializedMethodRebuildFlag)
  2373. {
  2374. BF_ASSERT(!typeInst->IsDeleting());
  2375. BP_ZONE("BfContext::QueueMethodSpecializations");
  2376. auto module = typeInst->mModule;
  2377. if (module == NULL)
  2378. return;
  2379. BfLogSysM("QueueMethodSpecializations typeInst %p module %p\n", typeInst, module);
  2380. if (!checkSpecializedMethodRebuildFlag)
  2381. {
  2382. // Modules that have already rebuilt have already explicitly added their method specialization requests.
  2383. // This pass is just for handling rebuilding old specialization requests
  2384. if (module->mRevision == mCompiler->mRevision)
  2385. return;
  2386. }
  2387. // Find any method specialization requests for types that are rebuilding, but from
  2388. // modules that are NOT rebuilding to be sure we generate those. Failure to do this
  2389. // will cause a link error from an old module
  2390. for (auto& methodRefKV : typeInst->mSpecializedMethodReferences)
  2391. {
  2392. auto& methodRef = methodRefKV.mKey;
  2393. auto& specializedMethodRefInfo = methodRefKV.mValue;
  2394. if (checkSpecializedMethodRebuildFlag)
  2395. {
  2396. if ((methodRef.mTypeInstance->mRebuildFlags & BfTypeRebuildFlag_SpecializedMethodRebuild) == 0)
  2397. continue;
  2398. }
  2399. else
  2400. {
  2401. if ((methodRef.mTypeInstance->mModule == NULL) ||
  2402. (methodRef.mTypeInstance->mModule->mRevision != mCompiler->mRevision))
  2403. continue;
  2404. }
  2405. bool allowMismatch = false;
  2406. if ((methodRef.mTypeInstance->IsInstanceOf(mCompiler->mInternalTypeDef)) || (methodRef.mTypeInstance->IsInstanceOf(mCompiler->mGCTypeDef)))
  2407. allowMismatch = true;
  2408. // The signature hash better not have changed, because if it did then we should have rebuilding 'module'
  2409. // because of dependencies! This infers a dependency error.
  2410. int newSignatureHash = (int)methodRef.mTypeInstance->mTypeDef->mSignatureHash;
  2411. BF_ASSERT((newSignatureHash == methodRef.mSignatureHash) || (allowMismatch));
  2412. BfMethodDef* methodDef = NULL;
  2413. if (methodRef.mMethodNum < methodRef.mTypeInstance->mTypeDef->mMethods.mSize)
  2414. methodDef = methodRef.mTypeInstance->mTypeDef->mMethods[methodRef.mMethodNum];
  2415. auto targetContext = methodRef.mTypeInstance->mContext;
  2416. BfMethodSpecializationRequest* specializationRequest = targetContext->mMethodSpecializationWorkList.Alloc();
  2417. if (specializedMethodRefInfo.mHasReifiedRef)
  2418. specializationRequest->mFromModule = typeInst->mModule;
  2419. else
  2420. specializationRequest->mFromModule = mUnreifiedModule;
  2421. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  2422. specializationRequest->mMethodIdx = methodRef.mMethodNum;
  2423. //specializationRequest->mMethodDef = methodRef.mTypeInstance->mTypeDef->mMethods[methodRef.mMethodNum];
  2424. specializationRequest->mMethodGenericArguments = methodRef.mMethodGenericArguments;
  2425. specializationRequest->mType = methodRef.mTypeInstance;
  2426. BfLogSysM("QueueMethodSpecializations typeInst %p specializationRequest %p methodDef %p fromModule %p\n", typeInst, specializationRequest, methodDef, specializationRequest->mFromModule);
  2427. }
  2428. }
  2429. void BfContext::MarkAsReferenced(BfDependedType* depType)
  2430. {
  2431. BF_ASSERT((depType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0);
  2432. depType->mRebuildFlags = (BfTypeRebuildFlags)(depType->mRebuildFlags & ~BfTypeRebuildFlag_AwaitingReference);
  2433. // bool madeFullPass = true;
  2434. // if (mCompiler->mCanceling)
  2435. // madeFullPass = false;
  2436. // if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mParser != NULL))
  2437. // madeFullPass = false;
  2438. // Having this in caused errors when we canceled and then compiled again
  2439. auto typeInst = depType->ToTypeInstance();
  2440. if (typeInst != NULL)
  2441. {
  2442. QueueMethodSpecializations(typeInst, false);
  2443. }
  2444. }
  2445. static int gCheckIdx = 0;
  2446. template <typename T>
  2447. void ReportRemovedItem(T workItem)
  2448. {
  2449. }
  2450. template <>
  2451. void ReportRemovedItem<BfMethodProcessRequest*>(BfMethodProcessRequest* workItem)
  2452. {
  2453. if (workItem->mMethodInstance != NULL)
  2454. BfLogSys(workItem->mFromModule->mSystem, "DoRemoveInvalidWorkItems MethodInstance:%p\n", workItem->mMethodInstance);
  2455. }
  2456. template <typename T>
  2457. void DoRemoveInvalidWorkItems(BfContext* bfContext, WorkQueue<T>& workList, bool requireValidType)
  2458. {
  2459. //auto itr = workList.begin();
  2460. //while (itr != workList.end())
  2461. for (int workIdx = 0; workIdx < (int)workList.size(); workIdx++)
  2462. {
  2463. gCheckIdx++;
  2464. //auto& workItem = *itr;
  2465. auto workItem = workList[workIdx];
  2466. if (workItem == NULL)
  2467. continue;
  2468. BfTypeInstance* typeInst = workItem->mType->ToTypeInstance();
  2469. if ((workItem->mType->IsDeleting()) ||
  2470. (workItem->mType->mRebuildFlags & BfTypeRebuildFlag_Deleted) ||
  2471. ((workItem->mRevision != -1) && (typeInst != NULL) && (workItem->mRevision != typeInst->mRevision)) ||
  2472. ((workItem->mSignatureRevision != -1) && (typeInst != NULL) && (workItem->mSignatureRevision != typeInst->mSignatureRevision)) ||
  2473. ((workItem->mFromModuleRevision != -1) && (workItem->mFromModuleRevision != workItem->mFromModule->mRevision)) ||
  2474. ((workItem->mFromModule != NULL) && (workItem->mFromModule->mIsDeleting)) ||
  2475. ((requireValidType) && (workItem->mType->mDefineState == BfTypeDefineState_Undefined)))
  2476. {
  2477. if (typeInst != NULL)
  2478. {
  2479. BF_ASSERT(
  2480. (workItem->mRevision < typeInst->mRevision) ||
  2481. ((workItem->mFromModule != NULL) && (workItem->mFromModuleRebuildIdx != -1) && (workItem->mFromModule->mRebuildIdx != workItem->mFromModuleRebuildIdx)) ||
  2482. ((workItem->mRevision == typeInst->mRevision) && (workItem->mType->mRebuildFlags & BfTypeRebuildFlag_Deleted)) ||
  2483. (workItem->mType->mDefineState == BfTypeDefineState_Undefined));
  2484. }
  2485. BfLogSys(bfContext->mSystem, "Removing work item: %p ReqId:%d\n", workItem, workItem->mReqId);
  2486. ReportRemovedItem(workItem);
  2487. workIdx = workList.RemoveAt(workIdx);
  2488. //itr = workList.erase(itr);
  2489. }
  2490. //else
  2491. //++itr;
  2492. }
  2493. }
  2494. void BfContext::RemoveInvalidFailTypes()
  2495. {
  2496. for (auto itr = mFailTypes.begin(); itr != mFailTypes.end(); )
  2497. {
  2498. auto typeInst = *itr;
  2499. BfLogSysM("Checking FailType: %p\n", typeInst);
  2500. if ((typeInst->IsDeleting()) || (typeInst->mRebuildFlags & BfTypeRebuildFlag_Deleted))
  2501. {
  2502. BfLogSysM("Removing Invalid FailType: %p\n", typeInst);
  2503. itr = mFailTypes.Remove(itr);
  2504. }
  2505. else
  2506. itr++;
  2507. }
  2508. }
  2509. // These work items are left over from a previous canceled run, OR from explicit method
  2510. // specializations being rebuilt when the type is rebuilt
  2511. void BfContext::RemoveInvalidWorkItems()
  2512. {
  2513. BfLogSysM("RemoveInvalidWorkItems %p\n", this);
  2514. // Delete any request that include deleted types.
  2515. // For the list items referring to methods we check the LLVMType because that lets us know
  2516. // whether or not the type has been reset since these work items were requested
  2517. DoRemoveInvalidWorkItems<BfMethodProcessRequest>(this, mMethodWorkList, true);
  2518. DoRemoveInvalidWorkItems<BfInlineMethodRequest>(this, mInlineMethodWorkList, true);
  2519. //TODO: We used to pass true into requireValidType, but this gets populated from UpdateRevisedTypes right before RemoveInvalidWorkItems,
  2520. // so we're passing false in here now. Don't just switch it back and forth - find why 'false' was causing an issue.
  2521. // Same with mMethodSpecializationWorkList
  2522. DoRemoveInvalidWorkItems<BfTypeProcessRequest>(this, mPopulateTypeWorkList, false);
  2523. DoRemoveInvalidWorkItems<BfMethodSpecializationRequest>(this, mMethodSpecializationWorkList, false/*true*/);
  2524. DoRemoveInvalidWorkItems<BfTypeRefVerifyRequest>(this, mTypeRefVerifyWorkList, false);
  2525. #ifdef _DEBUG
  2526. for (auto& workItem : mMethodWorkList)
  2527. {
  2528. //BF_ASSERT(workItem.mMethodInstance->mDeclModule != NULL);
  2529. }
  2530. for (auto workItem : mMethodSpecializationWorkList)
  2531. {
  2532. if (workItem == NULL)
  2533. continue;
  2534. for (auto genericArg : workItem->mMethodGenericArguments)
  2535. {
  2536. BF_ASSERT((genericArg->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  2537. BF_ASSERT(!genericArg->IsDeleting());
  2538. }
  2539. }
  2540. #endif
  2541. if (mCompiler->mRevision == mScratchModule->mRevision)
  2542. {
  2543. // We have deleted the old module so we need to recreate unspecialized LLVMFunctions
  2544. for (auto workListItem : mMethodWorkList)
  2545. {
  2546. if ((workListItem != NULL) && (workListItem->mType->IsUnspecializedType()))
  2547. {
  2548. workListItem->mMethodInstance->mIRFunction = BfIRFunction();
  2549. }
  2550. }
  2551. }
  2552. RemoveInvalidFailTypes();
  2553. }
  2554. void BfContext::RemapObject()
  2555. {
  2556. if (mCompiler->mBfObjectTypeDef == NULL)
  2557. return;
  2558. // There are several types that get their LLVM type mapped to Object, so make sure to remap that
  2559. // for when Object itself gets recreated
  2560. auto objectType = mScratchModule->ResolveTypeDef(mCompiler->mBfObjectTypeDef, BfPopulateType_Declaration);
  2561. auto objectTypeInst = objectType->ToTypeInstance();
  2562. if (objectTypeInst->mRevision == mMappedObjectRevision)
  2563. return;
  2564. mMappedObjectRevision = objectTypeInst->mRevision;
  2565. for (int paramKind = 0; paramKind < 2; paramKind++)
  2566. {
  2567. for (int paramIdx = 0; paramIdx < (int)mGenericParamTypes[paramKind].size(); paramIdx++)
  2568. {
  2569. auto genericParam = mGenericParamTypes[paramKind][paramIdx];
  2570. genericParam->mSize = objectType->mSize;
  2571. genericParam->mAlign = objectType->mAlign;
  2572. }
  2573. }
  2574. auto varType = mScratchModule->GetPrimitiveType(BfTypeCode_Var);
  2575. varType->mSize = objectType->mSize;
  2576. varType->mAlign = objectType->mAlign;
  2577. }
  2578. void BfContext::CheckSpecializedErrorData()
  2579. {
  2580. //TODO: Unecessary now?
  2581. /*for (auto& specializedErrorData : mSpecializedErrorData)
  2582. {
  2583. bool ignoreError = false;
  2584. if (specializedErrorData.mRefType->IsDeleting())
  2585. ignoreError = true;
  2586. if (specializedErrorData.mMethodInstance != NULL)
  2587. {
  2588. for (auto genericArg : specializedErrorData.mMethodInstance->mMethodGenericArguments)
  2589. if (genericArg->IsDeleting())
  2590. ignoreError = true;
  2591. }
  2592. if (ignoreError)
  2593. {
  2594. if (specializedErrorData.mMethodInstance->mIRFunction != NULL)
  2595. {
  2596. specializedErrorData.mMethodInstance->mIRFunction->eraseFromParent();
  2597. specializedErrorData.mMethodInstance->mIRFunction = NULL;
  2598. }
  2599. specializedErrorData.mError->mIgnore = true;
  2600. }
  2601. else
  2602. {
  2603. specializedErrorData.mModule->mHadBuildError = true;
  2604. mFailTypes.insert(specializedErrorData.mRefType);
  2605. }
  2606. }*/
  2607. }
  2608. void BfContext::TryUnreifyModules()
  2609. {
  2610. BP_ZONE("BfContext::TryUnreifyModules");
  2611. for (auto module : mModules)
  2612. {
  2613. if (module->mIsSpecialModule)
  2614. continue;
  2615. if (!module->mIsReified)
  2616. continue;
  2617. if (module->mLastUsedRevision == mCompiler->mRevision)
  2618. continue;
  2619. bool isRequired = false;
  2620. for (auto typeInst : module->mOwnedTypeInstances)
  2621. {
  2622. if (typeInst->mTypeDef->IsGlobalsContainer())
  2623. isRequired = true;
  2624. if (typeInst->IsAlwaysInclude())
  2625. isRequired = true;
  2626. }
  2627. if (isRequired)
  2628. continue;
  2629. module->UnreifyModule();
  2630. }
  2631. }
  2632. void BfContext::MarkUsedModules(BfProject* project, BfModule* module)
  2633. {
  2634. BP_ZONE("BfContext::MarkUsedModules");
  2635. BF_ASSERT(!module->mIsDeleting);
  2636. if (module->mIsScratchModule)
  2637. return;
  2638. if (project->mUsedModules.Contains(module))
  2639. return;
  2640. if (!mCompiler->IsModuleAccessible(module, project))
  2641. return;
  2642. project->mUsedModules.Add(module);
  2643. for (auto& typeDataKV : module->mTypeDataRefs)
  2644. project->mReferencedTypeData.Add(typeDataKV.mKey);
  2645. for (auto& slotKV : module->mInterfaceSlotRefs)
  2646. {
  2647. auto typeInstance = slotKV.mKey;
  2648. if ((typeInstance->mSlotNum < 0) && (mCompiler->mHotState != NULL))
  2649. mCompiler->mHotState->mHasNewInterfaceTypes = true;
  2650. mReferencedIFaceSlots.Add(typeInstance);
  2651. }
  2652. for (auto& kv : module->mStaticFieldRefs)
  2653. {
  2654. auto& fieldRef = kv.mKey;
  2655. auto typeInst = fieldRef.mTypeInstance;
  2656. BF_ASSERT(!typeInst->IsDataIncomplete());
  2657. BF_ASSERT(fieldRef.mFieldIdx < typeInst->mFieldInstances.size());
  2658. if (fieldRef.mFieldIdx < typeInst->mFieldInstances.size())
  2659. typeInst->mFieldInstances[fieldRef.mFieldIdx].mLastRevisionReferenced = mCompiler->mRevision;
  2660. }
  2661. module->mLastUsedRevision = mCompiler->mRevision;
  2662. for (auto usedModule : module->mModuleRefs)
  2663. {
  2664. MarkUsedModules(project, usedModule);
  2665. }
  2666. for (auto& kv : module->mSpecializedMethodModules)
  2667. {
  2668. MarkUsedModules(project, kv.mValue);
  2669. }
  2670. }
  2671. void BfContext::Finish()
  2672. {
  2673. }
  2674. void BfContext::Cleanup()
  2675. {
  2676. BfLogSysM("BfContext::Cleanup() MethodWorkList: %d LocalMethodGraveyard: %d\n", mMethodWorkList.size(), mLocalMethodGraveyard.size());
  2677. // Can't clean up LLVM types, they are allocated with a bump allocator
  2678. RemoveInvalidFailTypes();
  2679. mCompiler->mCompileState = BfCompiler::CompileState_Cleanup;
  2680. ///
  2681. {
  2682. Array<BfLocalMethod*> survivingLocalMethods;
  2683. for (auto localMethod : mLocalMethodGraveyard)
  2684. {
  2685. bool inCEMachine = false;
  2686. if (localMethod->mMethodInstanceGroup != NULL)
  2687. {
  2688. if ((localMethod->mMethodInstanceGroup->mDefault != NULL) && (localMethod->mMethodInstanceGroup->mDefault->mInCEMachine))
  2689. inCEMachine = true;
  2690. if (localMethod->mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  2691. {
  2692. for (auto& kv : *localMethod->mMethodInstanceGroup->mMethodSpecializationMap)
  2693. if (kv.mValue->mInCEMachine)
  2694. inCEMachine = true;
  2695. }
  2696. }
  2697. if (inCEMachine)
  2698. {
  2699. localMethod->mMethodInstanceGroup->mOwner->mOwnedLocalMethods.Add(localMethod);
  2700. }
  2701. else if ((localMethod->mMethodInstanceGroup != NULL) && (localMethod->mMethodInstanceGroup->mRefCount > 0))
  2702. {
  2703. BfLogSysM("BfContext::Cleanup surviving local method with refs %p\n", localMethod);
  2704. localMethod->Dispose();
  2705. survivingLocalMethods.push_back(localMethod);
  2706. }
  2707. else if (!mMethodWorkList.empty())
  2708. {
  2709. // We can't remove the local methods if they still may be referenced by a BfMethodRefType used to specialize a method
  2710. BfLogSysM("BfContext::Cleanup surviving local method %p\n", localMethod);
  2711. localMethod->Dispose();
  2712. survivingLocalMethods.push_back(localMethod);
  2713. }
  2714. else
  2715. delete localMethod;
  2716. }
  2717. mLocalMethodGraveyard = survivingLocalMethods;
  2718. }
  2719. // Clean up deleted BfTypes
  2720. // These need to get deleted before the modules because we access mModule in the MethodInstance dtors
  2721. for (int pass = 0; pass < 2; pass++)
  2722. {
  2723. for (int i = 0; i < (int)mTypeGraveyard.size(); i++)
  2724. {
  2725. auto type = mTypeGraveyard[i];
  2726. if (type == NULL)
  2727. continue;
  2728. bool deleteNow = (type->IsBoxed() == (pass == 0));
  2729. if (!deleteNow)
  2730. continue;
  2731. BF_ASSERT(type->mRebuildFlags & BfTypeRebuildFlag_Deleted);
  2732. delete type;
  2733. mTypeGraveyard[i] = NULL;
  2734. }
  2735. }
  2736. mTypeGraveyard.Clear();
  2737. if (!mDeletingModules.IsEmpty())
  2738. {
  2739. // Clear our invalid modules in mUsedModules list
  2740. for (auto project : mSystem->mProjects)
  2741. {
  2742. for (auto itr = project->mUsedModules.begin(); itr != project->mUsedModules.end(); )
  2743. {
  2744. if ((*itr)->mIsDeleting)
  2745. itr = project->mUsedModules.Remove(itr);
  2746. else
  2747. ++itr;
  2748. }
  2749. }
  2750. }
  2751. for (auto module : mDeletingModules)
  2752. {
  2753. int idx = (int)mFinishedModuleWorkList.IndexOf(module);
  2754. if (idx != -1)
  2755. mFinishedModuleWorkList.RemoveAt(idx);
  2756. idx = (int)mFinishedSlotAwaitModuleWorkList.IndexOf(module);
  2757. if (idx != -1)
  2758. mFinishedSlotAwaitModuleWorkList.RemoveAt(idx);
  2759. delete module;
  2760. }
  2761. mDeletingModules.Clear();
  2762. for (auto typeDef : mTypeDefGraveyard)
  2763. delete typeDef;
  2764. mTypeDefGraveyard.Clear();
  2765. mScratchModule->Cleanup();
  2766. mUnreifiedModule->Cleanup();
  2767. for (auto module : mModules)
  2768. module->Cleanup();
  2769. }