BfContext.cpp 107 KB

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