BfContext.cpp 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605
  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. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_InRebuildType);
  874. defer(
  875. {
  876. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags & ~BfTypeRebuildFlag_InRebuildType);
  877. });
  878. if (mCompiler->mCeMachine != NULL)
  879. mCompiler->mCeMachine->ClearTypeData(typeInst);
  880. BF_ASSERT_REL(typeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting);
  881. // We need to verify lookups before we rebuild the type, because a type lookup change needs to count as a TypeDataChanged
  882. VerifyTypeLookups(typeInst);
  883. if (typeInst->mRevision != mCompiler->mRevision)
  884. {
  885. BfLogSysM("Setting revision. Type: %p Revision: %d\n", typeInst, mCompiler->mRevision);
  886. typeInst->mRevision = mCompiler->mRevision;
  887. if (typeInst->IsGenericTypeInstance())
  888. {
  889. BfLogSysM("Setting BfTypeRebuildFlag_PendingGenericArgDep for type %p\n", typeInst);
  890. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_PendingGenericArgDep);
  891. }
  892. }
  893. if ((typeInst->IsTypeAlias()) != (typeInst->mTypeDef->mTypeCode == BfTypeCode_TypeAlias))
  894. {
  895. BfLogSysM("TypeAlias %p status changed - deleting\n", typeInst);
  896. DeleteType(type);
  897. return;
  898. }
  899. if ((typeInst->IsBoxed()) && (typeInst->mTypeDef->mEmitParent != NULL))
  900. typeInst->mTypeDef = typeInst->mTypeDef->mEmitParent;
  901. if (mSystem->mWorkspaceConfigChanged)
  902. {
  903. typeInst->mTypeOptionsIdx = -2;
  904. }
  905. if (typeInst->mTypeFailed)
  906. {
  907. // The type definition failed, so we need to rebuild everyone that was depending on us
  908. RebuildDependentTypes(typeInst);
  909. }
  910. if (typeInst->mTypeDef->GetDefinition()->mDefState == BfTypeDef::DefState_Deleted)
  911. return;
  912. if (typeInst->mDefineState == BfTypeDefineState_Undefined)
  913. {
  914. // If we haven't added this type the worklist yet then we reprocess the type rebuilding
  915. if ((typeInst->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) != 0)
  916. return;
  917. }
  918. if (typeInst->mIsReified)
  919. mHasReifiedQueuedRebuildTypes = true;
  920. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags & ~BfTypeRebuildFlag_AddedToWorkList);
  921. bool addToWorkList = true;
  922. if ((typeInst->IsGenericTypeInstance()) && (!typeInst->IsUnspecializedType()) && (placeSpecializiedInPurgatory))
  923. {
  924. mCompiler->mGenericInstancePurgatory.push_back(typeInst);
  925. addToWorkList = false;
  926. }
  927. String typeName = mScratchModule->TypeToString(typeInst, BfTypeNameFlags_None);
  928. BfLogSysM("%p Rebuild Type: %p %s deleted:%d\n", this, typeInst, typeName.c_str(), typeInst->IsDeleting());
  929. if (addToWorkList)
  930. {
  931. AddTypeToWorkList(typeInst);
  932. }
  933. // Why did we need to do this? This caused all struct types to be rebuilt when we needed to rebuild ValueType due to
  934. // ValueType.Equals<T> needing to rebuild -- which happens if any structs that have been compared have a signature change.
  935. /*for (auto depItr : typeInst->mDependencyMap)
  936. {
  937. auto dependentType = depItr.first;
  938. auto dependencyFlags = depItr.second.mFlags;
  939. if (dependencyFlags & BfDependencyMap::DependencyFlag_DerivedFrom)
  940. {
  941. //BfLogSysM("Setting BaseTypeMayBeIncomplete on %p from %p\n", dependentType, typeInst);
  942. //dependentType->mBaseTypeMayBeIncomplete = true;
  943. if (!dependentType->IsIncomplete())
  944. RebuildType(dependentType);
  945. }
  946. }*/
  947. if ((mCompiler->IsHotCompile()) && (!typeInst->IsTypeAlias()))
  948. {
  949. BF_ASSERT(typeInst->mHotTypeData != NULL);
  950. if (typeInst->mHotTypeData != NULL)
  951. {
  952. auto hotLatestVersionHead = typeInst->mHotTypeData->GetLatestVersionHead();
  953. if (!hotLatestVersionHead->mPopulatedInterfaceMapping)
  954. {
  955. typeInst->CalcHotVirtualData(&hotLatestVersionHead->mInterfaceMapping);
  956. hotLatestVersionHead->mPopulatedInterfaceMapping = true;
  957. }
  958. PopulateHotTypeDataVTable(typeInst);
  959. }
  960. }
  961. else
  962. {
  963. delete typeInst->mHotTypeData;
  964. typeInst->mHotTypeData = NULL;
  965. }
  966. auto typeDef = typeInst->mTypeDef;
  967. // Process deps before clearing mMethodInstanceGroups, to make sure we delete any methodrefs pointing to us before
  968. // deleting those methods
  969. for (auto& dep : typeInst->mDependencyMap)
  970. {
  971. auto depType = dep.mKey;
  972. auto depFlags = dep.mValue.mFlags;
  973. // If a MethodRef depends ON US, that means it's a local method that we own. MethodRefs directly point to
  974. // methodInstances, so these will be invalid now.
  975. if (depType->IsMethodRef())
  976. {
  977. auto methodRefType = (BfMethodRefType*)depType;
  978. BF_ASSERT(methodRefType->mOwner == typeInst);
  979. DeleteType(methodRefType);
  980. }
  981. if ((depFlags & BfDependencyMap::DependencyFlag_UnspecializedType) != 0)
  982. {
  983. if ((depType->mDefineState != BfTypeDefineState_Undefined) && (depType->mRevision != mCompiler->mRevision))
  984. {
  985. // Rebuild undefined type. This isn't necessary when we modify the typeDef, but when we change configurations then
  986. // the specialized types will rebuild
  987. //TODO: WE just added "no rebuild module" to this. I'm not sure what this is all about anyway...
  988. RebuildType(depType, true, false);
  989. }
  990. }
  991. }
  992. // At some point we thought we didn't have to do this for resolve-only, but this logic is important for removing
  993. // specialized methods that are causing errors
  994. if (addToWorkList)
  995. {
  996. if (typeDef->mDefState == BfTypeDef::DefState_Signature_Changed)
  997. {
  998. typeInst->mSignatureRevision = mCompiler->mRevision;
  999. }
  1000. else
  1001. {
  1002. bool needMethodCallsRebuild = false;
  1003. for (auto& methodInstGroup : typeInst->mMethodInstanceGroups)
  1004. {
  1005. if (methodInstGroup.mMethodSpecializationMap != NULL)
  1006. {
  1007. for (auto& methodSpecializationItr : *methodInstGroup.mMethodSpecializationMap)
  1008. {
  1009. auto methodInstance = methodSpecializationItr.mValue;
  1010. if ((!methodInstance->mIsUnspecialized) && (methodInstance->mHasFailed))
  1011. {
  1012. // A specialized generic method has failed, but the unspecialized version did not. This
  1013. // can only happen for 'var' constrained methods, and we need to cause all referring
  1014. // types to rebuild to ensure we're really specializing only the correct methods
  1015. needMethodCallsRebuild = true;
  1016. }
  1017. }
  1018. }
  1019. }
  1020. if (needMethodCallsRebuild)
  1021. {
  1022. TypeMethodSignaturesChanged(typeInst);
  1023. }
  1024. }
  1025. }
  1026. typeInst->ReleaseData();
  1027. type->mDefineState = BfTypeDefineState_Undefined;
  1028. typeInst->mSpecializedMethodReferences.Clear();
  1029. typeInst->mAlwaysIncludeFlags = BfAlwaysIncludeFlag_None;
  1030. typeInst->mHasBeenInstantiated = false;
  1031. typeInst->mLookupResults.Clear();
  1032. typeInst->mIsUnion = false;
  1033. typeInst->mIsCRepr = false;
  1034. typeInst->mPacking = 0;
  1035. typeInst->mIsSplattable = false;
  1036. typeInst->mHasUnderlyingArray = false;
  1037. typeInst->mIsTypedPrimitive = false;
  1038. typeInst->mMergedFieldDataCount = 0;
  1039. typeInst->mTypeIncomplete = true;
  1040. typeInst->mNeedsMethodProcessing = false;
  1041. typeInst->mHasBeenInstantiated = false;
  1042. typeInst->mHasParameterizedBase = false;
  1043. typeInst->mTypeFailed = false;
  1044. typeInst->mTypeWarned = false;
  1045. typeInst->mHasUnderlyingArray = false;
  1046. typeInst->mHasPackingHoles = false;
  1047. typeInst->mWantsGCMarking = false;
  1048. typeInst->mHasDeclError = false;
  1049. typeInst->mHasAppendWantMark = false;
  1050. delete typeInst->mTypeInfoEx;
  1051. typeInst->mTypeInfoEx = NULL;
  1052. if (typeInst->mCeTypeInfo != NULL)
  1053. typeInst->mCeTypeInfo->mRebuildMap.Clear();
  1054. if (typeInst->mTypeDef->mEmitParent != NULL)
  1055. {
  1056. auto emitTypeDef = typeInst->mTypeDef;
  1057. typeInst->mTypeDef = emitTypeDef->mEmitParent;
  1058. if (typeInst->mTypeDef->mIsPartial)
  1059. typeInst->mTypeDef = mSystem->GetCombinedPartial(typeInst->mTypeDef);
  1060. BfLogSysM("Type %p queueing delete of typeDef %p, resetting typeDef to %p\n", typeInst, emitTypeDef, typeInst->mTypeDef);
  1061. if (emitTypeDef->mDefState != BfTypeDef::DefState_Deleted)
  1062. {
  1063. emitTypeDef->mDefState = BfTypeDef::DefState_Deleted;
  1064. AutoCrit autoCrit(mSystem->mDataLock);
  1065. BF_ASSERT(!mSystem->mTypeDefDeleteQueue.Contains(emitTypeDef));
  1066. mSystem->mTypeDefDeleteQueue.push_back(emitTypeDef);
  1067. for (auto& dep : typeInst->mDependencyMap)
  1068. {
  1069. if (auto typeInst = dep.mKey->ToTypeInstance())
  1070. {
  1071. if (typeInst->mTypeDef == emitTypeDef)
  1072. RebuildType(typeInst);
  1073. }
  1074. }
  1075. }
  1076. }
  1077. //typeInst->mTypeDef->ClearEmitted();
  1078. for (auto localMethod : typeInst->mOwnedLocalMethods)
  1079. delete localMethod;
  1080. typeInst->mOwnedLocalMethods.Clear();
  1081. if (typeInst->IsGenericTypeInstance())
  1082. {
  1083. auto genericTypeInstance = (BfTypeInstance*)typeInst;
  1084. for (auto genericParam : genericTypeInstance->mGenericTypeInfo->mGenericParams)
  1085. genericParam->Release();
  1086. genericTypeInstance->mGenericTypeInfo->mInitializedGenericParams = false;
  1087. genericTypeInstance->mGenericTypeInfo->mFinishedGenericParams = false;
  1088. genericTypeInstance->mGenericTypeInfo->mGenericParams.Clear();
  1089. genericTypeInstance->mGenericTypeInfo->mValidatedGenericConstraints = false;
  1090. genericTypeInstance->mGenericTypeInfo->mHadValidateErrors = false;
  1091. if (genericTypeInstance->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  1092. genericTypeInstance->mGenericTypeInfo->mGenericExtensionInfo->Clear();
  1093. genericTypeInstance->mGenericTypeInfo->mProjectsReferenced.Clear();
  1094. }
  1095. typeInst->mStaticSearchMap.Clear();
  1096. typeInst->mInternalAccessMap.Clear();
  1097. typeInst->mInterfaces.Clear();
  1098. typeInst->mInterfaceMethodTable.Clear();
  1099. for (auto operatorInfo : typeInst->mOperatorInfo)
  1100. delete operatorInfo;
  1101. typeInst->mOperatorInfo.Clear();
  1102. typeInst->mMethodInstanceGroups.Clear();
  1103. typeInst->mFieldInstances.Clear();
  1104. for (auto methodInst : typeInst->mInternalMethods)
  1105. delete methodInst;
  1106. typeInst->mInternalMethods.Clear();
  1107. typeInst->mHasStaticInitMethod = false;
  1108. typeInst->mHasStaticMarkMethod = false;
  1109. typeInst->mHasStaticDtorMethod = false;
  1110. typeInst->mHasTLSFindMethod = false;
  1111. typeInst->mBaseType = NULL;
  1112. delete typeInst->mCustomAttributes;
  1113. typeInst->mCustomAttributes = NULL;
  1114. delete typeInst->mAttributeData;
  1115. typeInst->mAttributeData = NULL;
  1116. typeInst->mVirtualMethodTableSize = 0;
  1117. typeInst->mVirtualMethodTable.Clear();
  1118. typeInst->mReifyMethodDependencies.Clear();
  1119. typeInst->mSize = -1;
  1120. typeInst->mAlign = -1;
  1121. typeInst->mInstSize = -1;
  1122. typeInst->mInstAlign = -1;
  1123. typeInst->mInheritDepth = 0;
  1124. delete typeInst->mConstHolder;
  1125. typeInst->mConstHolder = NULL;
  1126. if ((typeInst->mModule != NULL) && (rebuildModule))
  1127. {
  1128. typeInst->mModule->StartNewRevision();
  1129. typeInst->mRevision = mCompiler->mRevision;
  1130. }
  1131. }
  1132. void BfContext::RebuildDependentTypes(BfDependedType* dType)
  1133. {
  1134. TypeDataChanged(dType, true);
  1135. auto typeInst = dType->ToTypeInstance();
  1136. if (typeInst != NULL)
  1137. TypeMethodSignaturesChanged(typeInst);
  1138. }
  1139. void BfContext::QueueMidCompileRebuildDependentTypes(BfDependedType* dType, const String& reason)
  1140. {
  1141. BfLogSysM("QueueMidCompileRebuildDependentTypes Type:%p Reason:%s\n", dType, reason.c_str());
  1142. auto workEntry = mMidCompileWorkList.Alloc();
  1143. workEntry->mType = dType;
  1144. workEntry->mReason = reason;
  1145. }
  1146. void BfContext::RebuildDependentTypes_MidCompile(BfDependedType* dType, const String& reason)
  1147. {
  1148. BF_ASSERT(!dType->IsDeleting());
  1149. auto module = dType->GetModule();
  1150. if ((module != NULL) && (!module->mIsSpecialModule))
  1151. {
  1152. BF_ASSERT(!module->mIsDeleting);
  1153. BF_ASSERT(!module->mOwnedTypeInstances.IsEmpty());
  1154. }
  1155. mCompiler->mStats.mMidCompileRebuilds++;
  1156. dType->mRebuildFlags = (BfTypeRebuildFlags)(dType->mRebuildFlags | BfTypeRebuildFlag_ChangedMidCompile);
  1157. int prevDeletedTypes = mCompiler->mStats.mTypesDeleted;
  1158. if (mCompiler->mIsResolveOnly)
  1159. {
  1160. if (mCompiler->mLastMidCompileRefreshRevision == mCompiler->mRevision - 1)
  1161. {
  1162. // Don't repeatedly full refresh in the case of non-deterministic emits
  1163. }
  1164. else
  1165. {
  1166. mCompiler->mNeedsFullRefresh = true;
  1167. mCompiler->mLastMidCompileRefreshRevision = mCompiler->mRevision;
  1168. }
  1169. }
  1170. BfLogSysM("Rebuilding dependent types MidCompile Type:%p Reason:%s\n", dType, reason.c_str());
  1171. RebuildDependentTypes(dType);
  1172. if (mCompiler->mStats.mTypesDeleted != prevDeletedTypes)
  1173. {
  1174. BfLogSysM("Rebuilding dependent types MidCompile Type:%p Reason:%s - updating after deleting types\n", dType, reason.c_str());
  1175. UpdateAfterDeletingTypes();
  1176. }
  1177. }
  1178. bool BfContext::IsRebuilding(BfType* type)
  1179. {
  1180. return ((type->mRebuildFlags & BfTypeRebuildFlag_InRebuildType) != 0);
  1181. }
  1182. bool BfContext::CanRebuild(BfType* type)
  1183. {
  1184. if (type->mRevision == mCompiler->mRevision)
  1185. return false;
  1186. if ((type->mDefineState == BfTypeDefineState_Declaring) ||
  1187. (type->mDefineState == BfTypeDefineState_ResolvingBaseType) ||
  1188. (type->mDefineState == BfTypeDefineState_CETypeInit) ||
  1189. (type->mDefineState == BfTypeDefineState_DefinedAndMethodsSlotting))
  1190. return false;
  1191. return true;
  1192. }
  1193. // Dependencies cascade as such:
  1194. // DerivedFrom / StructMemberData: these change the layout of memory for the dependent classes,
  1195. // so not only do the dependent classes need to be rebuild, but any other classes relying on those derived classes
  1196. // (either by derivation, containment, or field reading) need to have their code recompiled as well.
  1197. // ReadFields: when ClassB depends on the data layout of ClassA, and ClassC reads a field from
  1198. // ClassB, it means that ClassC code needs to be recompiled if ClassA data layout changes, but performing a ReadField
  1199. // (obviously) doesn't change the data layout of ClassC
  1200. // Calls: non-cascading dependency, since it's independent of data layout ConstValue: non-cascading data change
  1201. void BfContext::TypeDataChanged(BfDependedType* dType, bool isNonStaticDataChange)
  1202. {
  1203. BfLogSysM("TypeDataChanged %p\n", dType);
  1204. auto rebuildFlag = isNonStaticDataChange ? BfTypeRebuildFlag_NonStaticChange : BfTypeRebuildFlag_StaticChange;
  1205. if ((dType->mRebuildFlags & rebuildFlag) != 0) // Already did this change?
  1206. return;
  1207. dType->mRebuildFlags = (BfTypeRebuildFlags)(dType->mRebuildFlags | rebuildFlag);
  1208. // We need to rebuild all other types that rely on our data layout
  1209. for (auto& depItr : dType->mDependencyMap)
  1210. {
  1211. auto dependentType = depItr.mKey;
  1212. auto dependencyFlags = depItr.mValue.mFlags;
  1213. auto dependentDType = dependentType->ToDependedType();
  1214. if (dependentDType != NULL)
  1215. {
  1216. auto dependentTypeInstance = dependentType->ToTypeInstance();
  1217. if (isNonStaticDataChange)
  1218. {
  1219. bool hadChange = false;
  1220. if ((dependencyFlags &
  1221. (BfDependencyMap::DependencyFlag_DerivedFrom |
  1222. BfDependencyMap::DependencyFlag_ValueTypeMemberData |
  1223. BfDependencyMap::DependencyFlag_NameReference |
  1224. BfDependencyMap::DependencyFlag_ValueTypeSizeDep)) != 0)
  1225. {
  1226. hadChange = true;
  1227. }
  1228. // This case is for when we were declared as a class on a previous compilation,
  1229. // but then we were changed to a struct
  1230. if ((dType->IsValueType()) &&
  1231. (dependencyFlags & BfDependencyMap::DependencyFlag_PtrMemberData))
  1232. {
  1233. hadChange = true;
  1234. }
  1235. if (mCompiler->IsHotCompile())
  1236. {
  1237. // VData layout may be changing if there's a data change...
  1238. if (dependencyFlags & BfDependencyMap::DependencyFlag_VirtualCall)
  1239. {
  1240. hadChange = true;
  1241. }
  1242. }
  1243. if (hadChange)
  1244. TypeDataChanged(dependentDType, true);
  1245. }
  1246. if (dependencyFlags & BfDependencyMap::DependencyFlag_ConstValue)
  1247. {
  1248. TypeDataChanged(dependentDType, false);
  1249. // The ConstValue dependency may be that dependentType used one of our consts as
  1250. // a default value to a method param, so assume callsites need rebuilding
  1251. if (dependentTypeInstance != NULL)
  1252. TypeMethodSignaturesChanged(dependentTypeInstance);
  1253. }
  1254. if (CanRebuild(dependentType))
  1255. {
  1256. // We need to include DependencyFlag_ParamOrReturnValue because it could be a struct that changes its splatting ability
  1257. // We can't ONLY check against structs, though, because a type could change from a class to a struct
  1258. if (dependencyFlags &
  1259. (BfDependencyMap::DependencyFlag_ReadFields | BfDependencyMap::DependencyFlag_ParamOrReturnValue |
  1260. BfDependencyMap::DependencyFlag_LocalUsage | BfDependencyMap::DependencyFlag_MethodGenericArg |
  1261. BfDependencyMap::DependencyFlag_Allocates | BfDependencyMap::DependencyFlag_TypeSignature))
  1262. {
  1263. RebuildType(dependentType);
  1264. }
  1265. else if (((dependencyFlags & BfDependencyMap::DependencyFlag_NameReference) != 0) &&
  1266. ((dType->mRebuildFlags & BfTypeRebuildFlag_ChangedMidCompile) != 0) &&
  1267. (dType->IsTypeAlias()))
  1268. {
  1269. RebuildType(dependentType);
  1270. }
  1271. }
  1272. }
  1273. else
  1274. {
  1275. if (CanRebuild(dependentType))
  1276. {
  1277. // Not a type instance, probably something like a sized array
  1278. RebuildType(dependentType);
  1279. }
  1280. }
  1281. }
  1282. if (CanRebuild(dType))
  1283. RebuildType(dType);
  1284. }
  1285. void BfContext::TypeMethodSignaturesChanged(BfTypeInstance* typeInst)
  1286. {
  1287. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_MethodSignatureChange) // Already did change?
  1288. return;
  1289. typeInst->mRebuildFlags = (BfTypeRebuildFlags) (typeInst->mRebuildFlags | BfTypeRebuildFlag_MethodSignatureChange);
  1290. BfLogSysM("TypeMethodSignaturesChanged %p\n", typeInst);
  1291. // These don't happen in TypeDataChanged because we don't need to cascade
  1292. for (auto& depItr : typeInst->mDependencyMap)
  1293. {
  1294. auto dependentType = depItr.mKey;
  1295. auto dependencyFlags = depItr.mValue.mFlags;
  1296. if (dependentType->mRevision != mCompiler->mRevision)
  1297. {
  1298. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1299. if ((dependencyFlags & BfDependencyMap::DependencyFlag_Calls) ||
  1300. (dependencyFlags & BfDependencyMap::DependencyFlag_VirtualCall) ||
  1301. (dependencyFlags & BfDependencyMap::DependencyFlag_InlinedCall) ||
  1302. (dependencyFlags & BfDependencyMap::DependencyFlag_MethodGenericArg) ||
  1303. (dependencyFlags & BfDependencyMap::DependencyFlag_CustomAttribute) ||
  1304. (dependencyFlags & BfDependencyMap::DependencyFlag_DerivedFrom) ||
  1305. (dependencyFlags & BfDependencyMap::DependencyFlag_ImplementsInterface))
  1306. {
  1307. RebuildType(dependentType);
  1308. }
  1309. }
  1310. }
  1311. }
  1312. void BfContext::TypeInlineMethodInternalsChanged(BfTypeInstance* typeInst)
  1313. {
  1314. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_MethodInlineInternalsChange) // Already did change?
  1315. return;
  1316. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_MethodInlineInternalsChange);
  1317. // These don't happen in TypeDataChanged because we don't need to cascade
  1318. for (auto& depItr : typeInst->mDependencyMap)
  1319. {
  1320. auto dependentType = depItr.mKey;
  1321. auto dependencyFlags = depItr.mValue.mFlags;
  1322. if (dependentType->mRevision != mCompiler->mRevision)
  1323. {
  1324. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1325. if ((dependencyFlags & BfDependencyMap::DependencyFlag_InlinedCall) != 0)
  1326. {
  1327. RebuildType(dependentType);
  1328. }
  1329. }
  1330. }
  1331. }
  1332. void BfContext::TypeConstEvalChanged(BfTypeInstance* typeInst)
  1333. {
  1334. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_ConstEvalChange) // Already did change?
  1335. return;
  1336. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_ConstEvalChange);
  1337. // These don't happen in TypeDataChanged because we don't need to cascade
  1338. for (auto& depItr : typeInst->mDependencyMap)
  1339. {
  1340. auto dependentType = depItr.mKey;
  1341. auto dependencyFlags = depItr.mValue.mFlags;
  1342. // We don't need to cascade rebuilding for method-based usage - just rebuild the type directly (unlike TypeDataChanged, which cascades)
  1343. if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEval) != 0)
  1344. {
  1345. auto depTypeInst = dependentType->ToTypeInstance();
  1346. if (depTypeInst != NULL)
  1347. TypeConstEvalChanged(depTypeInst);
  1348. if (dependentType->mRevision != mCompiler->mRevision)
  1349. RebuildType(dependentType);
  1350. }
  1351. else if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEvalConstField) != 0)
  1352. {
  1353. auto depTypeInst = dependentType->ToTypeInstance();
  1354. if (depTypeInst != NULL)
  1355. TypeConstEvalFieldChanged(depTypeInst);
  1356. if (dependentType->mRevision != mCompiler->mRevision)
  1357. RebuildType(dependentType);
  1358. }
  1359. }
  1360. }
  1361. void BfContext::TypeConstEvalFieldChanged(BfTypeInstance* typeInst)
  1362. {
  1363. if (typeInst->mRebuildFlags & BfTypeRebuildFlag_ConstEvalFieldChange) // Already did change?
  1364. return;
  1365. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags | BfTypeRebuildFlag_ConstEvalFieldChange);
  1366. // These don't happen in TypeDataChanged because we don't need to cascade
  1367. for (auto& depItr : typeInst->mDependencyMap)
  1368. {
  1369. auto dependentType = depItr.mKey;
  1370. auto dependencyFlags = depItr.mValue.mFlags;
  1371. if ((dependencyFlags & BfDependencyMap::DependencyFlag_ConstEvalConstField) != 0)
  1372. {
  1373. auto depTypeInst = dependentType->ToTypeInstance();
  1374. if (depTypeInst != NULL)
  1375. TypeConstEvalFieldChanged(depTypeInst);
  1376. if (dependentType->mRevision != mCompiler->mRevision)
  1377. RebuildType(dependentType);
  1378. }
  1379. }
  1380. }
  1381. void BfContext::PopulateHotTypeDataVTable(BfTypeInstance* typeInstance)
  1382. {
  1383. BP_ZONE("BfContext::PopulateHotTypeDataVTable");
  1384. if (typeInstance->IsTypeAlias())
  1385. return;
  1386. // The hot virtual table only holds our new entries, not the vtable entries inherited from our base classes
  1387. auto hotTypeData = typeInstance->mHotTypeData;
  1388. if (hotTypeData == NULL)
  1389. return;
  1390. if (typeInstance->IsIncomplete())
  1391. return;
  1392. if (hotTypeData->mVTableOrigLength == -1)
  1393. {
  1394. auto committedHotTypeVersion = typeInstance->mHotTypeData->GetTypeVersion(mCompiler->mHotState->mCommittedHotCompileIdx);
  1395. if (committedHotTypeVersion != NULL)
  1396. {
  1397. hotTypeData->mVTableOrigLength = typeInstance->mVirtualMethodTableSize;
  1398. hotTypeData->mOrigInterfaceMethodsLength = typeInstance->GetIFaceVMethodSize();
  1399. }
  1400. BfLogSysM("PopulateHotTypeDataVTable set %p HotDataType->mVTableOrigLength To %d\n", typeInstance, hotTypeData->mVTableOrigLength);
  1401. }
  1402. int vTableStart = -1;
  1403. int primaryVTableSize = 0;
  1404. if (typeInstance->IsInterface())
  1405. {
  1406. // Interfaces don't have vext markers
  1407. vTableStart = 0;
  1408. #ifdef _DEBUG
  1409. for (int vIdx = 0; vIdx < (int)typeInstance->mVirtualMethodTable.size(); vIdx++)
  1410. {
  1411. auto& methodRef = typeInstance->mVirtualMethodTable[vIdx].mDeclaringMethod;
  1412. if (methodRef.mMethodNum == -1)
  1413. {
  1414. BF_DBG_FATAL("Shouldn't have vext marker");
  1415. }
  1416. }
  1417. #endif
  1418. }
  1419. else
  1420. {
  1421. for (int vIdx = 0; vIdx < (int)typeInstance->mVirtualMethodTable.size(); vIdx++)
  1422. {
  1423. auto& methodRef = typeInstance->mVirtualMethodTable[vIdx].mDeclaringMethod;
  1424. if (methodRef.mMethodNum == -1)
  1425. {
  1426. if (methodRef.mTypeInstance == typeInstance)
  1427. {
  1428. vTableStart = vIdx;
  1429. }
  1430. else if (vTableStart != -1)
  1431. {
  1432. BF_DBG_FATAL("Shouldn't have another vext marker");
  1433. break;
  1434. }
  1435. }
  1436. }
  1437. }
  1438. primaryVTableSize = (int)typeInstance->mVirtualMethodTable.size() - vTableStart;
  1439. BF_ASSERT(vTableStart != -1);
  1440. if (primaryVTableSize > (int)hotTypeData->mVTableEntries.size())
  1441. hotTypeData->mVTableEntries.Resize(primaryVTableSize);
  1442. int methodIdx = -1;
  1443. for (int vIdx = 0; vIdx < primaryVTableSize; vIdx++)
  1444. {
  1445. auto& methodRef = typeInstance->mVirtualMethodTable[vTableStart + vIdx].mDeclaringMethod;
  1446. methodIdx++;
  1447. auto methodInstance = (BfMethodInstance*)methodRef;
  1448. if (methodInstance == NULL)
  1449. continue;
  1450. BF_ASSERT(methodRef.mTypeInstance == typeInstance);
  1451. BF_ASSERT(methodInstance->mVirtualTableIdx != -1);
  1452. BF_ASSERT(!methodInstance->mMethodDef->mIsOverride);
  1453. // Find the original non-override method
  1454. /*while (methodInstance->mMethodDef->mIsOverride)
  1455. {
  1456. BfTypeInstance* parent = methodInstance->GetOwner()->mBaseType;
  1457. auto parentVirtualMethod = parent->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  1458. BF_ASSERT(parentVirtualMethod->mVirtualTableIdx != -1);
  1459. methodInstance = parentVirtualMethod;
  1460. }*/
  1461. if ((methodInstance->mMethodInfoEx == NULL) || (methodInstance->mMethodInfoEx->mMangledName.IsEmpty()))
  1462. {
  1463. // This should not occur, we should have build these mangled names already
  1464. EnsureHotMangledVirtualMethodName(methodInstance);
  1465. }
  1466. BF_ASSERT(!methodInstance->mMethodInfoEx->mMangledName.IsEmpty());
  1467. auto& entry = hotTypeData->mVTableEntries[vIdx];
  1468. if (entry.mFuncName.empty())
  1469. {
  1470. entry.mFuncName = methodInstance->mMethodInfoEx->mMangledName;
  1471. }
  1472. else
  1473. {
  1474. // Make sure its the same still
  1475. BF_ASSERT(entry.mFuncName == methodInstance->mMethodInfoEx->mMangledName);
  1476. }
  1477. }
  1478. }
  1479. void BfContext::SaveDeletingType(BfType* type)
  1480. {
  1481. if (mCompiler->mIsResolveOnly)
  1482. return;
  1483. if ((type->mRebuildFlags) && ((type->mRebuildFlags & BfTypeRebuildFlag_TypeDataSaved) != 0))
  1484. return;
  1485. type->mRebuildFlags = (BfTypeRebuildFlags)(type->mRebuildFlags | BfTypeRebuildFlag_TypeDataSaved);
  1486. String mangledName = BfSafeMangler::Mangle(type, mUnreifiedModule);
  1487. BfLogSysM("Saving deleted type: %p %s\n", type, mangledName.c_str());
  1488. BfSavedTypeData** savedTypeDataPtr;
  1489. BfSavedTypeData* savedTypeData;
  1490. if (mSavedTypeDataMap.TryAdd(mangledName, NULL, &savedTypeDataPtr))
  1491. {
  1492. savedTypeData = new BfSavedTypeData();
  1493. *savedTypeDataPtr = savedTypeData;
  1494. }
  1495. else
  1496. {
  1497. // This can happen if we have a conflicting type definition
  1498. savedTypeData = *savedTypeDataPtr;
  1499. }
  1500. savedTypeData->mTypeId = type->mTypeId;
  1501. while ((int)mSavedTypeData.size() <= savedTypeData->mTypeId)
  1502. mSavedTypeData.Add(NULL);
  1503. mSavedTypeData[savedTypeData->mTypeId] = savedTypeData;
  1504. auto typeInst = type->ToTypeInstance();
  1505. if (typeInst != NULL)
  1506. {
  1507. delete savedTypeData->mHotTypeData;
  1508. if (mCompiler->IsHotCompile())
  1509. savedTypeData->mHotTypeData = typeInst->mHotTypeData;
  1510. else
  1511. delete typeInst->mHotTypeData;
  1512. typeInst->mHotTypeData = NULL;
  1513. }
  1514. }
  1515. BfType* BfContext::FindType(const StringImpl& fullTypeName)
  1516. {
  1517. int genericArgCount = 0;
  1518. String typeName = fullTypeName;
  1519. if (typeName.EndsWith('>'))
  1520. {
  1521. // Generic
  1522. }
  1523. BfTypeDef* typeDef = mSystem->FindTypeDef(typeName, genericArgCount);
  1524. if (typeDef == NULL)
  1525. return NULL;
  1526. return mUnreifiedModule->ResolveTypeDef(typeDef);
  1527. }
  1528. String BfContext::TypeIdToString(int typeId)
  1529. {
  1530. auto type = mTypes[typeId];
  1531. if (type != NULL)
  1532. return mScratchModule->TypeToString(type);
  1533. if (mCompiler->mHotState != NULL)
  1534. {
  1535. for (auto& kv : mCompiler->mHotState->mDeletedTypeNameMap)
  1536. {
  1537. if (kv.mValue == typeId)
  1538. return kv.mKey;
  1539. }
  1540. }
  1541. return StrFormat("#%d", typeId);
  1542. }
  1543. BfHotTypeData* BfContext::GetHotTypeData(int typeId)
  1544. {
  1545. auto type = mTypes[typeId];
  1546. if (type != NULL)
  1547. {
  1548. auto typeInst = type->ToTypeInstance();
  1549. if (typeInst != NULL)
  1550. return typeInst->mHotTypeData;
  1551. }
  1552. if (typeId < (int)mSavedTypeData.size())
  1553. {
  1554. auto savedTypeData = mSavedTypeData[typeId];
  1555. if (savedTypeData != NULL)
  1556. return savedTypeData->mHotTypeData;
  1557. }
  1558. return NULL;
  1559. }
  1560. void BfContext::ReflectInit()
  1561. {
  1562. auto bfModule = mScratchModule;
  1563. bfModule->CreatePointerType(bfModule->GetPrimitiveType(BfTypeCode_NullPtr));
  1564. ///
  1565. auto typeDefType = bfModule->ResolveTypeDef(mCompiler->mTypeTypeDef)->ToTypeInstance();
  1566. if (!typeDefType)
  1567. return;
  1568. BF_ASSERT(typeDefType != NULL);
  1569. mBfTypeType = typeDefType->ToTypeInstance();
  1570. auto typeInstanceDefType = bfModule->ResolveTypeDef(mCompiler->mReflectTypeInstanceTypeDef);
  1571. if (!typeInstanceDefType)
  1572. return;
  1573. auto typeInstanceDefTypeInstance = typeInstanceDefType->ToTypeInstance();
  1574. auto typeDef = mSystem->FindTypeDef("System.ClassVData");
  1575. BF_ASSERT(typeDef != NULL);
  1576. auto bfClassVDataType = bfModule->ResolveTypeDef(typeDef)->ToTypeInstance();
  1577. mBfClassVDataPtrType = bfModule->CreatePointerType(bfClassVDataType);
  1578. }
  1579. void BfContext::DeleteType(BfType* type, bool deferDepRebuilds)
  1580. {
  1581. if (type == mBfObjectType)
  1582. mBfObjectType = NULL;
  1583. if (type == mBfTypeType)
  1584. mBfObjectType = NULL;
  1585. if (type->mRebuildFlags & BfTypeRebuildFlag_Deleted)
  1586. return;
  1587. mCompiler->mDepsMayHaveDeletedTypes = true;
  1588. mCompiler->mStats.mTypesDeleted++;
  1589. BfDependedType* dType = type->ToDependedType();
  1590. BfTypeInstance* typeInst = type->ToTypeInstance();
  1591. if (typeInst != NULL)
  1592. {
  1593. if (mCompiler->mHotState != NULL)
  1594. {
  1595. if ((typeInst->mHotTypeData != NULL) && (typeInst->mHotTypeData->mPendingDataChange))
  1596. mCompiler->mHotState->RemovePendingChanges(typeInst);
  1597. String typeName = mScratchModule->TypeToString(typeInst);
  1598. mCompiler->mHotState->mDeletedTypeNameMap[typeName] = typeInst->mTypeId;
  1599. }
  1600. auto module = typeInst->mModule;
  1601. // Don't remove the mModule pointer in typeInst -- if the type ends up being a zombie then we still need
  1602. // to generate the VData from the type
  1603. if (module != NULL)
  1604. {
  1605. if (module->mIsScratchModule)
  1606. {
  1607. BF_ASSERT(module->mOwnedTypeInstances.size() == 0);
  1608. }
  1609. else
  1610. {
  1611. module->mOwnedTypeInstances.Remove(typeInst);
  1612. if ((module->mOwnedTypeInstances.size() == 0) && (module != mScratchModule))
  1613. {
  1614. BfLogSysM("Setting module mIsDeleting %p due to mOwnedTypeInstances being empty\n", module);
  1615. // This module is no longer needed
  1616. module->RemoveModuleData();
  1617. module->mIsDeleting = true;
  1618. mModules.Remove(module);
  1619. // This was only needed for 'zombie modules', which we don't need anymore?
  1620. // To avoid linking errors. Used instead of directly removing from mModules.
  1621. mDeletingModules.Add(module);
  1622. }
  1623. }
  1624. }
  1625. }
  1626. type->mRebuildFlags = (BfTypeRebuildFlags)((type->mRebuildFlags | BfTypeRebuildFlag_Deleted) & ~BfTypeRebuildFlag_DeleteQueued);
  1627. SaveDeletingType(type);
  1628. mTypes[type->mTypeId] = NULL;
  1629. BfLogSysM("Deleting Type: %p %s\n", type, mScratchModule->TypeToString(type).c_str());
  1630. if (typeInst != NULL)
  1631. {
  1632. for (auto& methodInstGroup : typeInst->mMethodInstanceGroups)
  1633. {
  1634. if ((methodInstGroup.mDefault != NULL) && (methodInstGroup.mDefault->mInCEMachine))
  1635. mCompiler->mCeMachine->RemoveMethod(methodInstGroup.mDefault);
  1636. if (methodInstGroup.mMethodSpecializationMap != NULL)
  1637. {
  1638. for (auto& methodSpecializationItr : *methodInstGroup.mMethodSpecializationMap)
  1639. {
  1640. auto methodInstance = methodSpecializationItr.mValue;
  1641. if (methodInstance->mInCEMachine)
  1642. mCompiler->mCeMachine->RemoveMethod(methodInstance);
  1643. }
  1644. }
  1645. }
  1646. }
  1647. // All dependencies cause rebuilds when we delete types
  1648. if (dType != NULL)
  1649. {
  1650. //TODO: Do PopulateHotTypeDataVTable then store the HotTypeDataData
  1651. if (dType->IsUnspecializedType())
  1652. {
  1653. /*auto itr = mScratchModule->mClassVDataRefs.find(typeInst);
  1654. if (itr != mScratchModule->mClassVDataRefs.end())
  1655. mScratchModule->mClassVDataRefs.erase(itr);*/
  1656. mScratchModule->mClassVDataRefs.Remove(typeInst);
  1657. }
  1658. //UH - I think this is not true.
  1659. // If A derives from B, and C derives from B, if we delete 'A' then it's true that
  1660. // 'C' won't rebuild otherwise, BUT 'B' would fail to build but it would do a TypeDataChanged once it WAS able to built. Right?
  1661. // Even though we do rebuilds on all types below, we specifically need to call
  1662. // TypeDataChanged here for cascading data dependencies
  1663. /*if (!deferDepRebuilds)
  1664. TypeDataChanged(typeInst, true);*/
  1665. Array<BfType*> rebuildTypeQueue;
  1666. for (auto& depItr : dType->mDependencyMap)
  1667. {
  1668. //bool rebuildType = false;
  1669. auto dependentType = depItr.mKey;
  1670. auto dependentTypeInst = dependentType->ToTypeInstance();
  1671. auto dependencyEntry = depItr.mValue;
  1672. if ((dependencyEntry.mFlags & (BfDependencyMap::DependencyFlag_MethodGenericArg)) != 0)
  1673. {
  1674. if (!dependentType->IsDeleting())
  1675. {
  1676. if ((deferDepRebuilds) && (dependentTypeInst != NULL))
  1677. mQueuedSpecializedMethodRebuildTypes.Add(dependentTypeInst);
  1678. }
  1679. }
  1680. if ((dependencyEntry.mFlags & (BfDependencyMap::DependencyFlag_TypeGenericArg)) != 0)
  1681. {
  1682. // This type can't exist anymore
  1683. DeleteType(dependentType, deferDepRebuilds);
  1684. continue;
  1685. }
  1686. if (dependentTypeInst == NULL)
  1687. {
  1688. // This was something like a sized array
  1689. DeleteType(dependentType, deferDepRebuilds);
  1690. continue;
  1691. }
  1692. if ((dependencyEntry.mFlags & ~(BfDependencyMap::DependencyFlag_UnspecializedType | BfDependencyMap::DependencyFlag_WeakReference)) == 0)
  1693. continue; // Not a cause for rebuilding
  1694. if (dependentTypeInst->IsOnDemand())
  1695. {
  1696. // Force on-demand dependencies to rebuild themselves
  1697. DeleteType(dependentType, deferDepRebuilds);
  1698. continue;
  1699. }
  1700. if (dType->IsBoxed())
  1701. {
  1702. // Allow these to just be implicitly used. This solves some issues with switching between ignoreWrites settings in resolveOnly compilation
  1703. continue;
  1704. }
  1705. if ((deferDepRebuilds) && (dependentTypeInst != NULL))
  1706. {
  1707. mFailTypes.TryAdd(dependentTypeInst, BfFailKind_Normal);
  1708. }
  1709. else
  1710. {
  1711. rebuildTypeQueue.Add(dependentType);
  1712. }
  1713. }
  1714. if (type->IsMethodRef())
  1715. {
  1716. // Detach
  1717. auto methodRefType = (BfMethodRefType*)type;
  1718. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  1719. BF_ASSERT(methodInstance->mMethodInstanceGroup->mRefCount > 0);
  1720. methodInstance->mMethodInstanceGroup->mRefCount--;
  1721. methodRefType->mMethodRef = NULL;
  1722. methodInstance->mHasMethodRefType = false;
  1723. }
  1724. for (auto dependentType : rebuildTypeQueue)
  1725. {
  1726. auto dependentTypeInst = dependentType->ToTypeInstance();
  1727. // This guards against recompile loops
  1728. if (CanRebuild(dependentType))
  1729. {
  1730. RebuildType(dependentType);
  1731. }
  1732. else if (IsRebuilding(dependentType))
  1733. {
  1734. // Ignore
  1735. }
  1736. else if (dependentTypeInst != NULL)
  1737. {
  1738. mGhostDependencies.Add(type);
  1739. // This keeps us from crashing from accessing deleted types on subsequent compiles
  1740. mFailTypes.TryAdd(dependentTypeInst, BfFailKind_Normal);
  1741. }
  1742. }
  1743. }
  1744. }
  1745. void BfContext::UpdateAfterDeletingTypes()
  1746. {
  1747. BP_ZONE("BfContext::UpdateAfterDeletingTypes");
  1748. BfLogSysM("UpdateAfterDeletingTypes\n");
  1749. int graveyardStart = (int)mTypeGraveyard.size();
  1750. while (true)
  1751. {
  1752. bool deletedNewTypes = false;
  1753. auto itr = mResolvedTypes.begin();
  1754. while (itr != mResolvedTypes.end())
  1755. {
  1756. auto type = mResolvedTypes.mEntries[itr.mCurEntry].mValue;
  1757. bool doDelete = false;
  1758. //BfLogSysM("Removing entry\n");
  1759. bool isDeleting = type->IsDeleting();
  1760. if ((!isDeleting) && (type->IsDependentOnUnderlyingType()))
  1761. {
  1762. auto underlyingType = type->GetUnderlyingType();
  1763. if ((underlyingType != NULL) && (underlyingType->IsDeleting()))
  1764. {
  1765. deletedNewTypes = true;
  1766. isDeleting = true;
  1767. DeleteType(type);
  1768. }
  1769. }
  1770. if (isDeleting)
  1771. {
  1772. doDelete = true;
  1773. }
  1774. else
  1775. {
  1776. #if _DEBUG
  1777. if (type->IsGenericTypeInstance())
  1778. {
  1779. // We can't contain deleted generic arguments without being deleted ourselves
  1780. BfTypeInstance* genericType = (BfTypeInstance*)type;
  1781. for (auto genericTypeArg : genericType->mGenericTypeInfo->mTypeGenericArguments)
  1782. {
  1783. BF_ASSERT((!genericTypeArg->IsDeleting()));
  1784. auto argDepType = genericTypeArg->ToDependedType();
  1785. if (argDepType != NULL)
  1786. {
  1787. BfDependencyMap::DependencyEntry* depEntry = NULL;
  1788. argDepType->mDependencyMap.mTypeSet.TryGetValue(type, &depEntry);
  1789. BF_ASSERT(depEntry != NULL);
  1790. BF_ASSERT((depEntry->mFlags & BfDependencyMap::DependencyFlag_TypeGenericArg) != 0);
  1791. }
  1792. }
  1793. }
  1794. #endif
  1795. }
  1796. if (doDelete)
  1797. {
  1798. BF_ASSERT((type->mRebuildFlags & BfTypeRebuildFlag_Deleted) == BfTypeRebuildFlag_Deleted);
  1799. itr = mResolvedTypes.Erase(itr);
  1800. mTypeGraveyard.push_back(type);
  1801. }
  1802. else
  1803. ++itr;
  1804. }
  1805. if (!deletedNewTypes)
  1806. break;
  1807. }
  1808. #if _DEBUG
  1809. // auto itr = mResolvedTypes.begin();
  1810. // while (itr != mResolvedTypes.end())
  1811. // {
  1812. // auto type = itr.mCurEntry->mType;
  1813. // BF_ASSERT((type->mRebuildFlags & ~(BfTypeRebuildFlag_Deleted)) == 0);
  1814. // ++itr;
  1815. // }
  1816. #endif
  1817. if (!mCompiler->mIsResolveOnly)
  1818. {
  1819. BP_ZONE("BfContext::UpdateAfterDeletingTypes saving typeData");
  1820. for (int graveyardIdx = graveyardStart; graveyardIdx < (int)mTypeGraveyard.size(); graveyardIdx++)
  1821. {
  1822. auto type = mTypeGraveyard[graveyardIdx];
  1823. SaveDeletingType(type);
  1824. }
  1825. }
  1826. mCompiler->mStats.mTypesDeleted_LastUpdateAfterDeletingTypes = mCompiler->mStats.mTypesDeleted;
  1827. }
  1828. // This happens before the old defs have been injected
  1829. void BfContext::PreUpdateRevisedTypes()
  1830. {
  1831. // if (mCompiler->IsHotCompile())
  1832. // {
  1833. // for (auto typeEntry : mResolvedTypes)
  1834. // {
  1835. // auto type = typeEntry->mType;
  1836. // auto typeInst = type->ToTypeInstance();
  1837. // if (typeInst == NULL)
  1838. // continue;
  1839. //
  1840. // auto typeDef = typeInst->mTypeDef;
  1841. // if ((typeDef->mDefState != BfTypeDef::DefState_New) && (typeDef->mDefState != BfTypeDef::DefState_Defined))
  1842. // {
  1843. // if (typeInst->mHotTypeData == NULL)
  1844. // {
  1845. // typeInst->mHotTypeData = new BfHotTypeData();
  1846. // typeInst->CalcHotVirtualData(&typeInst->mHotTypeData->mInterfaceMapping);
  1847. // }
  1848. // PopulateHotTypeDataVTable(typeInst);
  1849. // }
  1850. // }
  1851. // }
  1852. }
  1853. // Note that this method can also cause modules to be build in other contexts.
  1854. // That's why we do our UpdateAfterDeletingTypes after all the contexts' UpdateRevisedTypes
  1855. void BfContext::UpdateRevisedTypes()
  1856. {
  1857. BP_ZONE("BfContext::UpdateRevisedTypes");
  1858. BfLogSysM("BfContext::UpdateRevisedTypes\n");
  1859. auto _CheckCanSkipCtor = [&](BfTypeDef* typeDef)
  1860. {
  1861. if (typeDef == NULL)
  1862. return true;
  1863. typeDef = typeDef->GetLatest();
  1864. for (auto fieldDef : typeDef->mFields)
  1865. {
  1866. if (fieldDef->mIsStatic)
  1867. continue;
  1868. if (fieldDef->GetInitializer() != NULL)
  1869. return false;
  1870. }
  1871. for (auto methodDef : typeDef->mMethods)
  1872. {
  1873. if (methodDef->mMethodType == BfMethodType_Init)
  1874. return false;
  1875. }
  1876. return true;
  1877. };
  1878. auto _CheckCanSkipCtorByName = [&](const StringImpl& name)
  1879. {
  1880. BfAtomComposite qualifiedFindName;
  1881. if (!mSystem->ParseAtomComposite(name, qualifiedFindName))
  1882. return true;
  1883. auto itr = mSystem->mTypeDefs.TryGet(qualifiedFindName);
  1884. while (itr)
  1885. {
  1886. BfTypeDef* typeDef = *itr;
  1887. if ((typeDef->mDefState != BfTypeDef::DefState_Deleted) &&
  1888. (!typeDef->mIsCombinedPartial))
  1889. {
  1890. if (typeDef->mFullNameEx == qualifiedFindName)
  1891. if (!_CheckCanSkipCtor(typeDef))
  1892. return false;
  1893. }
  1894. itr.MoveToNextHashMatch();
  1895. }
  1896. return true;
  1897. };
  1898. bool wantsCanSkipObjectCtor = _CheckCanSkipCtorByName("System.Object");
  1899. bool wantsCanSkipValueTypeCtor = _CheckCanSkipCtorByName("System.ValueType");
  1900. int wantPtrSize;
  1901. if ((mCompiler->mOptions.mMachineType == BfMachineType_x86) |
  1902. (mCompiler->mOptions.mMachineType == BfMachineType_ARM) ||
  1903. (mCompiler->mOptions.mMachineType == BfMachineType_Wasm32))
  1904. wantPtrSize = 4;
  1905. else
  1906. wantPtrSize = 8;
  1907. if ((wantPtrSize != mSystem->mPtrSize) || (wantsCanSkipObjectCtor != mCanSkipObjectCtor) || (wantsCanSkipValueTypeCtor != mCanSkipValueTypeCtor))
  1908. {
  1909. BfLogSysM("Full rebuild. Pointer: %d CanSkipObjectCtor:%d CanSkipValueTypeCtor:%d\n", wantPtrSize, wantsCanSkipObjectCtor, wantsCanSkipValueTypeCtor);
  1910. mSystem->mPtrSize = wantPtrSize;
  1911. mCanSkipObjectCtor = wantsCanSkipObjectCtor;
  1912. mCanSkipValueTypeCtor = wantsCanSkipValueTypeCtor;
  1913. auto intPtrType = mScratchModule->GetPrimitiveType(BfTypeCode_IntPtr);
  1914. auto uintPtrType = mScratchModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  1915. if (intPtrType != NULL)
  1916. {
  1917. RebuildType(intPtrType);
  1918. mScratchModule->PopulateType(intPtrType);
  1919. }
  1920. if (uintPtrType != NULL)
  1921. {
  1922. RebuildType(uintPtrType);
  1923. mScratchModule->PopulateType(uintPtrType);
  1924. }
  1925. // Rebuild all types
  1926. Array<BfType*> allTypes;
  1927. for (auto type : mResolvedTypes)
  1928. allTypes.Add(type);
  1929. for (auto type : allTypes)
  1930. {
  1931. if (!type->IsDeleting())
  1932. RebuildType(type);
  1933. }
  1934. }
  1935. // Temporarily store failTypes - we may need to re-insert into them after another failure
  1936. auto failTypes = mFailTypes;
  1937. mFailTypes.Clear();
  1938. bool wantsDebugInfo = (mCompiler->mOptions.mEmitDebugInfo);
  1939. Array<BfTypeInstance*> defStateChangedQueue;
  1940. Array<BfTypeInstance*> defEmitParentCheckQueue;
  1941. Dictionary<String, uint64> lastWriteTimeMap;
  1942. bool rebuildAllFilesChanged = mCompiler->mRebuildChangedFileSet.Contains("*");
  1943. uint64 projectDepHash = 0;
  1944. // Do primary 'rebuild' scan
  1945. for (auto type : mResolvedTypes)
  1946. {
  1947. auto typeInst = type->ToTypeInstance();
  1948. if (type == NULL)
  1949. {
  1950. BF_FATAL("We shouldn't have NULLs");
  1951. continue;
  1952. }
  1953. /*if ((!mCompiler->mIsResolveOnly) && (!type->IsNull()) && (!type->IsUnspecializedType()))
  1954. {
  1955. // We need to completely rebuild all types if we switch from having debug info to not having debug info
  1956. if ((typeInst != NULL) && (typeInst->mModule != NULL) && (typeInst->mModule->mHasDebugInfo != wantsDebugInfo))
  1957. {
  1958. RebuildType(type);
  1959. }
  1960. }*/
  1961. if (typeInst == NULL)
  1962. continue;
  1963. if (typeInst->IsDeleting())
  1964. continue;
  1965. auto typeDef = typeInst->mTypeDef;
  1966. if (typeDef->mEmitParent != NULL)
  1967. defEmitParentCheckQueue.Add(typeInst);
  1968. if (typeDef->mProject->mDisabled)
  1969. {
  1970. DeleteType(type);
  1971. continue;
  1972. }
  1973. // Clear flags we don't want to propagate
  1974. typeInst->mRebuildFlags = (BfTypeRebuildFlags)(typeInst->mRebuildFlags & (BfTypeRebuildFlag_UnderlyingTypeDeferred | BfTypeRebuildFlag_PendingGenericArgDep));
  1975. if (typeDef->mIsPartial)
  1976. {
  1977. // This was a type that wasn't marked as partial before but now it is, so it doesn't need its own typedef
  1978. // since we will have a separate type instance for the combined partials
  1979. DeleteType(type);
  1980. continue;
  1981. }
  1982. if (typeInst->mCeTypeInfo != NULL)
  1983. {
  1984. bool changed = false;
  1985. for (auto& kv : typeInst->mCeTypeInfo->mRebuildMap)
  1986. {
  1987. mCompiler->mHasComptimeRebuilds = true;
  1988. if (kv.mKey.mKind == CeRebuildKey::Kind_File)
  1989. {
  1990. String* keyPtr = NULL;
  1991. uint64* valuePtr = NULL;
  1992. if (lastWriteTimeMap.TryAdd(kv.mKey.mString, &keyPtr, &valuePtr))
  1993. {
  1994. *valuePtr = BfpFile_GetTime_LastWrite(kv.mKey.mString.c_str());
  1995. }
  1996. if (*valuePtr != kv.mValue.mInt)
  1997. changed = true;
  1998. mCompiler->mRebuildFileSet.Add(kv.mKey.mString);
  1999. }
  2000. if ((kv.mKey.mKind == CeRebuildKey::Kind_File) || (kv.mKey.mKind == CeRebuildKey::Kind_Directory))
  2001. {
  2002. if ((rebuildAllFilesChanged) || (mCompiler->mRebuildChangedFileSet.Contains(kv.mKey.mString)))
  2003. changed = true;
  2004. mCompiler->mRebuildFileSet.Add(kv.mKey.mString);
  2005. }
  2006. if (kv.mKey.mKind == CeRebuildKey::Kind_TypeDeclListHash)
  2007. {
  2008. if (projectDepHash == 0)
  2009. projectDepHash = mSystem->GetTypeDeclListHash();
  2010. if (kv.mValue.mInt != projectDepHash)
  2011. changed = true;
  2012. }
  2013. }
  2014. if (changed)
  2015. {
  2016. TypeDataChanged(typeInst, true);
  2017. TypeMethodSignaturesChanged(typeInst);
  2018. }
  2019. }
  2020. if ((typeInst->mHotTypeData != NULL) && (!mCompiler->IsHotCompile()))
  2021. {
  2022. if (typeInst->mHotTypeData->GetLatestVersion()->mDeclHotCompileIdx != 0)
  2023. {
  2024. // Type was rebuilt with hot changes - rebuild back to normal
  2025. delete typeInst->mHotTypeData;
  2026. typeInst->mHotTypeData = NULL;
  2027. RebuildType(typeInst);
  2028. }
  2029. }
  2030. auto checkTypeDef = typeDef;
  2031. if (typeDef->mEmitParent != NULL)
  2032. checkTypeDef = typeDef->mEmitParent;
  2033. if (checkTypeDef->mDefState == BfTypeDef::DefState_Defined)
  2034. {
  2035. BF_ASSERT(typeDef->mNextRevision == NULL);
  2036. continue;
  2037. }
  2038. if (checkTypeDef->mDefState != BfTypeDef::DefState_New)
  2039. {
  2040. defStateChangedQueue.Add(typeInst);
  2041. }
  2042. }
  2043. // We consumed this above
  2044. mCompiler->mRebuildChangedFileSet.Clear();
  2045. for (auto typeInst : defStateChangedQueue)
  2046. {
  2047. BP_ZONE("BfContext::UpdateRevisedTypes defStateChangedQueue");
  2048. auto typeDef = typeInst->mTypeDef;
  2049. bool isTypeDefinedInContext = true;
  2050. if (typeDef->mEmitParent != NULL)
  2051. {
  2052. typeDef = typeDef->mEmitParent;
  2053. }
  2054. if (typeDef->mDefState == BfTypeDef::DefState_Deleted)
  2055. {
  2056. HandleChangedTypeDef(typeDef);
  2057. DeleteType(typeInst);
  2058. continue;
  2059. }
  2060. if (typeDef->mDefState == BfTypeDef::DefState_InlinedInternals_Changed)
  2061. {
  2062. TypeInlineMethodInternalsChanged(typeInst);
  2063. }
  2064. bool isSignatureChange = typeDef->mDefState == BfTypeDef::DefState_Signature_Changed;
  2065. if (((typeDef->mDefState == BfTypeDef::DefState_Internals_Changed) || (typeDef->mDefState == BfTypeDef::DefState_InlinedInternals_Changed)) &&
  2066. (typeInst->IsInterface()))
  2067. {
  2068. isSignatureChange = true;
  2069. }
  2070. if ((typeDef->mDefState != BfTypeDef::DefState_Refresh) && ((typeInst->mDependencyMap.mFlagsUnion & BfDependencyMap::DependencyFlag_ConstEval) != 0))
  2071. {
  2072. TypeConstEvalChanged(typeInst);
  2073. }
  2074. if (isSignatureChange)
  2075. {
  2076. TypeDataChanged(typeInst, true);
  2077. TypeMethodSignaturesChanged(typeInst);
  2078. }
  2079. /*if (!mCompiler->mIsResolveOnly)
  2080. {
  2081. OutputDebugStrF("TypeDef: %s %d %p\n", typeDef->mName.c_str(), typeDef->mDefState, &typeDef->mDefState);
  2082. }*/
  2083. RebuildType(typeInst);
  2084. }
  2085. for (auto failKV : failTypes)
  2086. {
  2087. auto typeInst = failKV.mKey;
  2088. if (!typeInst->IsDeleting())
  2089. {
  2090. if (!typeInst->mTypeDef->mProject->mDisabled)
  2091. {
  2092. BfLogSysM("Rebuilding failed type %p %d\n", typeInst, (int)failKV.mValue);
  2093. if (failKV.mValue == BfFailKind_Deep)
  2094. TypeDataChanged(typeInst, true);
  2095. else
  2096. RebuildType(typeInst);
  2097. }
  2098. }
  2099. }
  2100. // Handle these "mid-compiles" now so we handle them as early-stage
  2101. BfParser* resolveParser = NULL;
  2102. if ((mCompiler->mResolvePassData != NULL) && (!mCompiler->mResolvePassData->mParsers.IsEmpty()))
  2103. resolveParser = mCompiler->mResolvePassData->mParsers[0];
  2104. for (int workIdx = 0; workIdx < (int)mMidCompileWorkList.size(); workIdx++)
  2105. {
  2106. auto workItemRef = mMidCompileWorkList[workIdx];
  2107. if (workItemRef == NULL)
  2108. {
  2109. workIdx = mMidCompileWorkList.RemoveAt(workIdx);
  2110. continue;
  2111. }
  2112. BfType* type = workItemRef->mType;
  2113. String reason = workItemRef->mReason;
  2114. auto typeInst = type->ToTypeInstance();
  2115. if ((typeInst != NULL) && (resolveParser != NULL))
  2116. {
  2117. if (!typeInst->mTypeDef->GetLatest()->HasSource(resolveParser))
  2118. {
  2119. continue;
  2120. }
  2121. }
  2122. workIdx = mMidCompileWorkList.RemoveAt(workIdx);
  2123. BfLogSysM("Handling prior-revision MidCompile on type %s in early-stage UpdateRevisedTypes\n", type);
  2124. RebuildDependentTypes(type->ToDependedType());
  2125. //RebuildDependentTypes_MidCompile(type->ToDependedType(), reason);
  2126. }
  2127. for (auto typeInst : defEmitParentCheckQueue)
  2128. {
  2129. if (typeInst->IsDeleting())
  2130. continue;
  2131. auto typeDef = typeInst->mTypeDef;
  2132. if (typeDef->mEmitParent != NULL)
  2133. {
  2134. if (typeDef->mDefState == BfTypeDef::DefState_Deleted)
  2135. {
  2136. BfLogSysM("Type %p typeDef %p deleted, setting to emitParent %p\n", typeInst, typeDef, typeDef->mEmitParent);
  2137. typeInst->mTypeDef = typeDef->mEmitParent;
  2138. }
  2139. else
  2140. {
  2141. auto emitTypeDef = typeDef;
  2142. typeDef = typeDef->mEmitParent;
  2143. if (typeDef->mNextRevision != NULL)
  2144. {
  2145. BfLogSysM("Type %p typeDef %p emitparent %p has next revision, setting emittedDirty\n", typeInst, emitTypeDef, typeDef);
  2146. emitTypeDef->mDefState = BfTypeDef::DefState_EmittedDirty;
  2147. }
  2148. }
  2149. }
  2150. }
  2151. //
  2152. {
  2153. AutoCrit autoCrit(mSystem->mDataLock);
  2154. auto options = &mCompiler->mOptions;
  2155. HashContext workspaceConfigHashCtx;
  2156. workspaceConfigHashCtx.MixinStr(options->mTargetTriple);
  2157. workspaceConfigHashCtx.MixinStr(options->mTargetCPU);
  2158. workspaceConfigHashCtx.Mixin(options->mForceRebuildIdx);
  2159. workspaceConfigHashCtx.Mixin(options->mMachineType);
  2160. workspaceConfigHashCtx.Mixin(options->mToolsetType);
  2161. workspaceConfigHashCtx.Mixin(options->mSIMDSetting);
  2162. workspaceConfigHashCtx.Mixin(options->mEmitDebugInfo);
  2163. workspaceConfigHashCtx.Mixin(options->mEmitLineInfo);
  2164. workspaceConfigHashCtx.Mixin(options->mNoFramePointerElim);
  2165. workspaceConfigHashCtx.Mixin(options->mInitLocalVariables);
  2166. workspaceConfigHashCtx.Mixin(options->mRuntimeChecks);
  2167. workspaceConfigHashCtx.Mixin(options->mAllowStructByVal);
  2168. workspaceConfigHashCtx.Mixin(options->mEmitDynamicCastCheck);
  2169. workspaceConfigHashCtx.Mixin(options->mAllowHotSwapping);
  2170. workspaceConfigHashCtx.Mixin(options->mObjectHasDebugFlags);
  2171. workspaceConfigHashCtx.Mixin(options->mEnableRealtimeLeakCheck);
  2172. workspaceConfigHashCtx.Mixin(options->mEmitObjectAccessCheck);
  2173. workspaceConfigHashCtx.Mixin(options->mArithmeticChecks);
  2174. workspaceConfigHashCtx.Mixin(options->mEnableCustodian);
  2175. workspaceConfigHashCtx.Mixin(options->mEnableSideStack);
  2176. workspaceConfigHashCtx.Mixin(options->mHasVDataExtender);
  2177. workspaceConfigHashCtx.Mixin(options->mDebugAlloc);
  2178. workspaceConfigHashCtx.Mixin(options->mOmitDebugHelpers);
  2179. workspaceConfigHashCtx.Mixin(options->mUseDebugBackingParams);
  2180. workspaceConfigHashCtx.Mixin(options->mWriteIR);
  2181. workspaceConfigHashCtx.Mixin(options->mGenerateObj);
  2182. workspaceConfigHashCtx.Mixin(options->mAllocStackCount);
  2183. workspaceConfigHashCtx.Mixin(options->mExtraResolveChecks);
  2184. workspaceConfigHashCtx.Mixin(options->mMaxSplatRegs);
  2185. workspaceConfigHashCtx.MixinStr(options->mMallocLinkName);
  2186. workspaceConfigHashCtx.MixinStr(options->mFreeLinkName);
  2187. for (auto& typeOptions : mSystem->mTypeOptions)
  2188. {
  2189. workspaceConfigHashCtx.Mixin(typeOptions.mTypeFilters.size());
  2190. for (auto& filter : typeOptions.mTypeFilters)
  2191. workspaceConfigHashCtx.MixinStr(filter);
  2192. workspaceConfigHashCtx.Mixin(typeOptions.mAttributeFilters.size());
  2193. for (auto& filter : typeOptions.mAttributeFilters)
  2194. workspaceConfigHashCtx.MixinStr(filter);
  2195. workspaceConfigHashCtx.Mixin(typeOptions.mSIMDSetting);
  2196. workspaceConfigHashCtx.Mixin(typeOptions.mOptimizationLevel);
  2197. workspaceConfigHashCtx.Mixin(typeOptions.mEmitDebugInfo);
  2198. workspaceConfigHashCtx.Mixin(typeOptions.mAndFlags);
  2199. workspaceConfigHashCtx.Mixin(typeOptions.mOrFlags);
  2200. workspaceConfigHashCtx.Mixin(typeOptions.mReflectMethodFilters.size());
  2201. for (auto& filter : typeOptions.mReflectMethodFilters)
  2202. {
  2203. workspaceConfigHashCtx.MixinStr(filter.mFilter);
  2204. workspaceConfigHashCtx.Mixin(filter.mAndFlags);
  2205. workspaceConfigHashCtx.Mixin(filter.mOrFlags);
  2206. }
  2207. workspaceConfigHashCtx.Mixin(typeOptions.mReflectMethodAttributeFilters.size());
  2208. for (auto& filter : typeOptions.mReflectMethodAttributeFilters)
  2209. {
  2210. workspaceConfigHashCtx.MixinStr(filter.mFilter);
  2211. workspaceConfigHashCtx.Mixin(filter.mAndFlags);
  2212. workspaceConfigHashCtx.Mixin(filter.mOrFlags);
  2213. }
  2214. workspaceConfigHashCtx.Mixin(typeOptions.mAllocStackTraceDepth);
  2215. }
  2216. // for (auto project : mSystem->mProjects)
  2217. // {
  2218. // workspaceConfigHashCtx.MixinStr(project->mName);
  2219. // }
  2220. Val128 workspaceConfigHash = workspaceConfigHashCtx.Finish128();
  2221. mSystem->mWorkspaceConfigChanged = mSystem->mWorkspaceConfigHash != workspaceConfigHash;
  2222. if (mSystem->mWorkspaceConfigChanged)
  2223. {
  2224. // If the type options have changed, we know we will rebuild all types and thus
  2225. // remap their mTypeOptionsIdx
  2226. mSystem->mMergedTypeOptions.Clear();
  2227. mSystem->mWorkspaceConfigHash = workspaceConfigHash;
  2228. }
  2229. for (auto project : mSystem->mProjects)
  2230. {
  2231. HashContext buildConfigHashCtx;
  2232. buildConfigHashCtx.Mixin(workspaceConfigHash);
  2233. if (!mCompiler->mIsResolveOnly)
  2234. {
  2235. auto& codeGenOptions = project->mCodeGenOptions;
  2236. buildConfigHashCtx.MixinStr(mCompiler->mOutputDirectory);
  2237. buildConfigHashCtx.Mixin(project->mAlwaysIncludeAll);
  2238. buildConfigHashCtx.Mixin(project->mSingleModule);
  2239. bool isTestConfig = project->mTargetType == BfTargetType_BeefTest;
  2240. buildConfigHashCtx.Mixin(isTestConfig);
  2241. buildConfigHashCtx.Mixin(codeGenOptions.mOptLevel);
  2242. buildConfigHashCtx.Mixin(codeGenOptions.mSizeLevel);
  2243. buildConfigHashCtx.Mixin(codeGenOptions.mUseCFLAA);
  2244. buildConfigHashCtx.Mixin(codeGenOptions.mUseNewSROA);
  2245. buildConfigHashCtx.Mixin(codeGenOptions.mDisableTailCalls);
  2246. buildConfigHashCtx.Mixin(codeGenOptions.mDisableUnitAtATime);
  2247. buildConfigHashCtx.Mixin(codeGenOptions.mDisableUnrollLoops);
  2248. buildConfigHashCtx.Mixin(codeGenOptions.mBBVectorize);
  2249. buildConfigHashCtx.Mixin(codeGenOptions.mSLPVectorize);
  2250. buildConfigHashCtx.Mixin(codeGenOptions.mLoopVectorize);
  2251. buildConfigHashCtx.Mixin(codeGenOptions.mRerollLoops);
  2252. buildConfigHashCtx.Mixin(codeGenOptions.mLoadCombine);
  2253. buildConfigHashCtx.Mixin(codeGenOptions.mDisableGVNLoadPRE);
  2254. buildConfigHashCtx.Mixin(codeGenOptions.mVerifyInput);
  2255. buildConfigHashCtx.Mixin(codeGenOptions.mVerifyOutput);
  2256. buildConfigHashCtx.Mixin(codeGenOptions.mStripDebug);
  2257. buildConfigHashCtx.Mixin(codeGenOptions.mMergeFunctions);
  2258. buildConfigHashCtx.Mixin(codeGenOptions.mEnableMLSM);
  2259. buildConfigHashCtx.Mixin(codeGenOptions.mRunSLPAfterLoopVectorization);
  2260. buildConfigHashCtx.Mixin(codeGenOptions.mUseGVNAfterVectorization);
  2261. }
  2262. buildConfigHashCtx.Mixin(project->mDisabled);
  2263. buildConfigHashCtx.Mixin(project->mTargetType);
  2264. for (auto dep : project->mDependencies)
  2265. {
  2266. String depName = dep->mName;
  2267. buildConfigHashCtx.MixinStr(depName);
  2268. }
  2269. Val128 buildConfigHash = buildConfigHashCtx.Finish128();
  2270. HashContext vDataConfigHashCtx;
  2271. vDataConfigHashCtx.Mixin(buildConfigHash);
  2272. vDataConfigHashCtx.MixinStr(project->mStartupObject);
  2273. vDataConfigHashCtx.Mixin(project->mTargetType);
  2274. //Val128 vDataConfigHash = buildConfigHash;
  2275. //vDataConfigHash = Hash128(project->mStartupObject.c_str(), (int)project->mStartupObject.length() + 1, vDataConfigHash);
  2276. //vDataConfigHash = Hash128(&project->mTargetType, sizeof(project->mTargetType), vDataConfigHash);
  2277. auto vDataConfigHash = vDataConfigHashCtx.Finish128();
  2278. project->mBuildConfigChanged = buildConfigHash != project->mBuildConfigHash;
  2279. project->mBuildConfigHash = buildConfigHash;
  2280. project->mVDataConfigHash = vDataConfigHash;
  2281. }
  2282. }
  2283. Array<BfModule*> moduleRebuildList;
  2284. for (int moduleIdx = 0; moduleIdx < (int)mModules.size(); moduleIdx++)
  2285. {
  2286. //mCompiler->mOutputDirectory
  2287. auto module = mModules[moduleIdx];
  2288. // This logic needs to run on both us and our mOptModule
  2289. //for (int subModuleIdx = 0; subModuleIdx < 2; subModuleIdx++)
  2290. auto subModule = module;
  2291. while (subModule != NULL)
  2292. {
  2293. //auto subModule = module;
  2294. //if (subModuleIdx == -1)
  2295. //subModule = module->mOptModule;
  2296. // If we canceled the last build, we could have specialized method modules referring to projects that have
  2297. // since been deleted or disabled - so remove those
  2298. for (auto methodModuleItr = subModule->mSpecializedMethodModules.begin(); methodModuleItr != subModule->mSpecializedMethodModules.end(); )
  2299. {
  2300. auto& projectList = methodModuleItr->mKey;
  2301. auto specModule = methodModuleItr->mValue;
  2302. bool hasDisabledProject = false;
  2303. for (auto checkProject : projectList)
  2304. hasDisabledProject |= checkProject->mDisabled;
  2305. if (hasDisabledProject)
  2306. {
  2307. delete specModule;
  2308. methodModuleItr = subModule->mSpecializedMethodModules.Remove(methodModuleItr);
  2309. }
  2310. else
  2311. ++methodModuleItr;
  2312. }
  2313. subModule = subModule->mNextAltModule;
  2314. }
  2315. if ((module->mProject != NULL) && (module->mProject->mDisabled))
  2316. {
  2317. continue;
  2318. }
  2319. // Module previously had error so we have to rebuild the whole thing
  2320. bool needsModuleRebuild = module->mHadBuildError;
  2321. if ((module->mHadHotObjectWrites) && (!mCompiler->IsHotCompile()))
  2322. {
  2323. module->mHadHotObjectWrites = false; // Handled, can reset now
  2324. needsModuleRebuild = true;
  2325. }
  2326. if (module->mProject != NULL)
  2327. {
  2328. if ((module->mIsHotModule) && (mCompiler->mOptions.mHotProject == NULL))
  2329. needsModuleRebuild = true;
  2330. if (module->mProject->mBuildConfigChanged)
  2331. needsModuleRebuild = true;
  2332. }
  2333. if (mCompiler->mInterfaceSlotCountChanged)
  2334. {
  2335. if ((module->mUsedSlotCount >= 0) && (module->mUsedSlotCount != mCompiler->mMaxInterfaceSlots))
  2336. needsModuleRebuild = true;
  2337. }
  2338. if (needsModuleRebuild)
  2339. moduleRebuildList.push_back(module);
  2340. if (module->mIsSpecialModule) // vdata, external, data
  2341. continue;
  2342. bool wantMethodSpecializations = !mCompiler->mIsResolveOnly;
  2343. // We don't really need this on for resolveOnly passes, but this is useful to force on for debugging.
  2344. // The following block is fairly useful for detecting dependency errors.
  2345. wantMethodSpecializations = true;
  2346. }
  2347. mCompiler->mInterfaceSlotCountChanged = false;
  2348. for (auto module : moduleRebuildList)
  2349. {
  2350. if (!module->mIsDeleting)
  2351. module->StartNewRevision();
  2352. }
  2353. // Ensure even unspecialized types an interfaces get rebuilt
  2354. // In particular, this is needed if we build a non-hotswap config and then
  2355. // build a hotswap config-- we need to make sure all those methods have
  2356. // HotMethodData
  2357. if (mSystem->mWorkspaceConfigChanged)
  2358. {
  2359. for (auto type : mResolvedTypes)
  2360. {
  2361. RebuildType(type);
  2362. }
  2363. }
  2364. BfLogSysM("BfContext::UpdateRevisedTypes done.\n");
  2365. }
  2366. void BfContext::VerifyTypeLookups(BfTypeInstance* typeInst)
  2367. {
  2368. for (auto& lookupEntryPair : typeInst->mLookupResults)
  2369. {
  2370. BfTypeLookupEntry& lookupEntry = lookupEntryPair.mKey;
  2371. bool isDirty = false;
  2372. if (lookupEntry.mName.IsEmpty())
  2373. {
  2374. // If the name lookup failed before, thats because we didn't have the right atoms. Are there new atoms now?
  2375. if (lookupEntry.mAtomUpdateIdx != mSystem->mAtomUpdateIdx)
  2376. isDirty = true;
  2377. }
  2378. else
  2379. {
  2380. // If any atoms have been placed in the graveyard, typesHash will be zero and thus cause a rebuild
  2381. uint32 atomUpdateIdx = lookupEntry.mName.GetAtomUpdateIdx();
  2382. if (atomUpdateIdx == 0)
  2383. {
  2384. isDirty = true;
  2385. }
  2386. else
  2387. {
  2388. // Sanity check, mostly checking that useTypeDef wasn't deleted
  2389. BF_ASSERT((lookupEntry.mUseTypeDef->mName->mAtomUpdateIdx >= 1) && (lookupEntry.mUseTypeDef->mName->mAtomUpdateIdx <= mSystem->mAtomUpdateIdx));
  2390. // Only do the actual lookup if types were added or removed whose name is contained in one of the name parts referenced
  2391. if (atomUpdateIdx != lookupEntry.mAtomUpdateIdx)
  2392. {
  2393. // NOTE: we purposely don't use mNextRevision here. If the the was NOT rebuilt then that means we didn't actually rebuild
  2394. // so the mNextRevision will be ignored
  2395. auto useTypeDef = lookupEntry.mUseTypeDef;
  2396. BfTypeDef* ambiguousTypeDef = NULL;
  2397. BfTypeLookupResult* lookupResult = &lookupEntryPair.mValue;
  2398. BfTypeLookupResultCtx lookupResultCtx;
  2399. lookupResultCtx.mResult = lookupResult;
  2400. lookupResultCtx.mIsVerify = true;
  2401. BfTypeDef* result = typeInst->mModule->FindTypeDefRaw(lookupEntry.mName, lookupEntry.mNumGenericParams, typeInst, useTypeDef, NULL, &lookupResultCtx);
  2402. if ((result == NULL) && (lookupResult->mFoundInnerType))
  2403. {
  2404. // Allow this- if there were new types added then the types would be rebuilt already
  2405. }
  2406. else if (result != lookupResult->mTypeDef)
  2407. {
  2408. isDirty = true;
  2409. }
  2410. else
  2411. lookupEntry.mAtomUpdateIdx = atomUpdateIdx;
  2412. }
  2413. }
  2414. }
  2415. if (isDirty)
  2416. {
  2417. // Clear lookup results to avoid infinite recursion
  2418. typeInst->mLookupResults.Clear();
  2419. // We need to treat this lookup as if it changed the whole type signature
  2420. TypeDataChanged(typeInst, true);
  2421. TypeMethodSignaturesChanged(typeInst);
  2422. RebuildType(typeInst);
  2423. break;
  2424. }
  2425. }
  2426. }
  2427. void BfContext::GenerateModuleName_TypeInst(BfTypeInstance* typeInst, StringImpl& name)
  2428. {
  2429. auto resolveModule = typeInst->mIsReified ? mScratchModule : mUnreifiedModule;
  2430. auto outerType = resolveModule->GetOuterType(typeInst);
  2431. int startGenericIdx = 0;
  2432. if (outerType != NULL)
  2433. {
  2434. startGenericIdx = (int)outerType->mTypeDef->mGenericParamDefs.size();
  2435. GenerateModuleName_Type(outerType, name);
  2436. /*if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2437. name += '_';*/
  2438. }
  2439. else
  2440. {
  2441. for (int i = 0; i < typeInst->mTypeDef->mNamespace.mSize; i++)
  2442. {
  2443. auto atom = typeInst->mTypeDef->mNamespace.mParts[i];
  2444. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2445. name += '_';
  2446. name += atom->mString;
  2447. }
  2448. }
  2449. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2450. name += '_';
  2451. if (typeInst->mTypeDef->IsGlobalsContainer())
  2452. name += "GLOBALS_";
  2453. else
  2454. name += typeInst->mTypeDef->mName->mString;
  2455. if (typeInst->IsClosure())
  2456. {
  2457. auto closureType = (BfClosureType*)typeInst;
  2458. name += closureType->mNameAdd;
  2459. return;
  2460. }
  2461. if (typeInst->mGenericTypeInfo != NULL)
  2462. {
  2463. for (int genericIdx = startGenericIdx; genericIdx < (int)typeInst->mGenericTypeInfo->mTypeGenericArguments.size(); genericIdx++)
  2464. {
  2465. auto type = typeInst->mGenericTypeInfo->mTypeGenericArguments[genericIdx];
  2466. GenerateModuleName_Type(type, name);
  2467. }
  2468. }
  2469. }
  2470. void BfContext::GenerateModuleName_Type(BfType* type, StringImpl& name)
  2471. {
  2472. if ((!name.empty()) && (name[name.length() - 1] != '_'))
  2473. name += '_';
  2474. if (type->IsBoxed())
  2475. {
  2476. auto boxedType = (BfBoxedType*)type;
  2477. if (boxedType->IsBoxedStructPtr())
  2478. name += "BOXPTR_";
  2479. else
  2480. name += "BOX_";
  2481. GenerateModuleName_Type(boxedType->mElementType, name);
  2482. return;
  2483. }
  2484. if (type->IsPrimitiveType())
  2485. {
  2486. auto primType = (BfPrimitiveType*)type;
  2487. name += primType->mTypeDef->mName->mString;
  2488. return;
  2489. }
  2490. if (type->IsPointer())
  2491. {
  2492. auto ptrType = (BfPointerType*)type;
  2493. name += "PTR_";
  2494. GenerateModuleName_Type(ptrType->mElementType, name);
  2495. return;
  2496. }
  2497. if (type->IsTuple())
  2498. {
  2499. auto tupleType = (BfTypeInstance*)type;
  2500. name += "TUPLE_";
  2501. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  2502. {
  2503. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  2504. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  2505. String fieldName = fieldDef->mName;
  2506. if ((fieldName[0] < '0') || (fieldName[0] > '9'))
  2507. name += StrFormat("U%d@%s", fieldName.length() + 1, fieldName.c_str());
  2508. GenerateModuleName_Type(fieldInstance->mResolvedType, name);
  2509. }
  2510. return;
  2511. }
  2512. if (type->IsDelegateFromTypeRef() || type->IsFunctionFromTypeRef())
  2513. {
  2514. auto typeInst = type->ToTypeInstance();
  2515. auto delegateInfo = type->GetDelegateInfo();
  2516. auto methodDef = typeInst->mTypeDef->mMethods[0];
  2517. if (type->IsDelegateFromTypeRef())
  2518. name += "DELEGATE_";
  2519. else
  2520. name += "FUNCTION_";
  2521. GenerateModuleName_Type(mScratchModule->ResolveTypeRef(methodDef->mReturnTypeRef), name);
  2522. name += "_";
  2523. for (int paramIdx = 0; paramIdx < methodDef->mParams.size(); paramIdx++)
  2524. {
  2525. if (paramIdx > 0)
  2526. name += "_";
  2527. auto paramDef = methodDef->mParams[paramIdx];
  2528. GenerateModuleName_Type(mScratchModule->ResolveTypeRef(paramDef->mTypeRef), name);
  2529. name += "_";
  2530. name += paramDef->mName;
  2531. }
  2532. return;
  2533. }
  2534. if (type->IsMethodRef())
  2535. {
  2536. auto methodRefType = (BfMethodRefType*)type;
  2537. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  2538. name += "METHOD_";
  2539. GenerateModuleName_Type(methodInstance->GetOwner(), name);
  2540. name += "_";
  2541. String addName = methodInstance->mMethodDef->mName;
  2542. for (auto&& c : addName)
  2543. {
  2544. if ((c == '$') || (c == '@'))
  2545. c = '_';
  2546. }
  2547. name += addName;
  2548. }
  2549. if (type->IsConstExprValue())
  2550. {
  2551. auto constExprType = (BfConstExprValueType*)type;
  2552. if (BfIRConstHolder::IsInt(constExprType->mValue.mTypeCode))
  2553. {
  2554. if (constExprType->mValue.mInt64 < 0)
  2555. name += StrFormat("_%ld", -constExprType->mValue.mInt64);
  2556. else
  2557. name += StrFormat("%ld", constExprType->mValue.mInt64);
  2558. return;
  2559. }
  2560. }
  2561. auto typeInst = type->ToTypeInstance();
  2562. if (typeInst != NULL)
  2563. {
  2564. GenerateModuleName_TypeInst(typeInst, name);
  2565. return;
  2566. }
  2567. }
  2568. void BfContext::GenerateModuleName(BfTypeInstance* typeInst, StringImpl& name)
  2569. {
  2570. GenerateModuleName_Type(typeInst, name);
  2571. int maxChars = 80;
  2572. if (name.length() > 80)
  2573. {
  2574. name.RemoveToEnd(80);
  2575. name += "__";
  2576. }
  2577. for (int i = 0; i < (int)name.length(); i++)
  2578. {
  2579. char c = name[i];
  2580. if (c == '@')
  2581. name[i] = '_';
  2582. }
  2583. for (int i = 2; true; i++)
  2584. {
  2585. StringT<256> upperName = name;
  2586. MakeUpper(upperName);
  2587. if (!mUsedModuleNames.Contains(upperName))
  2588. return;
  2589. if (i > 2)
  2590. {
  2591. int lastUnderscore = (int)name.LastIndexOf('_');
  2592. if (lastUnderscore != -1)
  2593. name.RemoveToEnd(lastUnderscore);
  2594. }
  2595. name += StrFormat("_%d", i);
  2596. }
  2597. }
  2598. bool BfContext::IsSentinelMethod(BfMethodInstance* methodInstance)
  2599. {
  2600. return (methodInstance != NULL) && ((uintptr)(methodInstance) <= 1);
  2601. }
  2602. void BfContext::VerifyTypeLookups()
  2603. {
  2604. BP_ZONE("BfContext::VerifyTypeLookups");
  2605. for (auto type : mResolvedTypes)
  2606. {
  2607. auto typeInst = type->ToTypeInstance();
  2608. if ((typeInst != NULL) && (!typeInst->IsDeleting()) && (!typeInst->IsIncomplete()))
  2609. {
  2610. VerifyTypeLookups(typeInst);
  2611. }
  2612. }
  2613. }
  2614. // When we are rebuilding 'typeInst' and we want to make sure that we rebuild all the methods that were
  2615. // actively referenced previously, this method will generate BfMethodSpecializationRequest for all used
  2616. // methods from previously-built modules
  2617. void BfContext::QueueMethodSpecializations(BfTypeInstance* typeInst, bool checkSpecializedMethodRebuildFlag)
  2618. {
  2619. BF_ASSERT(!typeInst->IsDeleting());
  2620. BP_ZONE("BfContext::QueueMethodSpecializations");
  2621. auto module = typeInst->mModule;
  2622. if (module == NULL)
  2623. return;
  2624. BfLogSysM("QueueMethodSpecializations typeInst %p module %p\n", typeInst, module);
  2625. if (!checkSpecializedMethodRebuildFlag)
  2626. {
  2627. // Modules that have already rebuilt have already explicitly added their method specialization requests.
  2628. // This pass is just for handling rebuilding old specialization requests
  2629. if (module->mRevision == mCompiler->mRevision)
  2630. return;
  2631. }
  2632. // Find any method specialization requests for types that are rebuilding, but from
  2633. // modules that are NOT rebuilding to be sure we generate those. Failure to do this
  2634. // will cause a link error from an old module
  2635. for (auto& methodRefKV : typeInst->mSpecializedMethodReferences)
  2636. {
  2637. auto& methodRef = methodRefKV.mKey;
  2638. auto& specializedMethodRefInfo = methodRefKV.mValue;
  2639. if (checkSpecializedMethodRebuildFlag)
  2640. {
  2641. if ((methodRef.mTypeInstance->mRebuildFlags & BfTypeRebuildFlag_SpecializedMethodRebuild) == 0)
  2642. continue;
  2643. }
  2644. else
  2645. {
  2646. if ((methodRef.mTypeInstance->mModule == NULL) ||
  2647. (methodRef.mTypeInstance->mModule->mRevision != mCompiler->mRevision))
  2648. continue;
  2649. }
  2650. bool allowMismatch = false;
  2651. if ((methodRef.mTypeInstance->IsInstanceOf(mCompiler->mInternalTypeDef)) || (methodRef.mTypeInstance->IsInstanceOf(mCompiler->mGCTypeDef)))
  2652. allowMismatch = true;
  2653. // The signature hash better not have changed, because if it did then we should have rebuilding 'module'
  2654. // because of dependencies! This infers a dependency error.
  2655. int newSignatureHash = (int)methodRef.mTypeInstance->mTypeDef->mSignatureHash;
  2656. BF_ASSERT((newSignatureHash == methodRef.mSignatureHash) || (allowMismatch));
  2657. BfMethodDef* methodDef = NULL;
  2658. if (methodRef.mMethodNum < methodRef.mTypeInstance->mTypeDef->mMethods.mSize)
  2659. methodDef = methodRef.mTypeInstance->mTypeDef->mMethods[methodRef.mMethodNum];
  2660. auto targetContext = methodRef.mTypeInstance->mContext;
  2661. BfMethodSpecializationRequest* specializationRequest = targetContext->mMethodSpecializationWorkList.Alloc();
  2662. if (specializedMethodRefInfo.mHasReifiedRef)
  2663. specializationRequest->mFromModule = typeInst->mModule;
  2664. else
  2665. specializationRequest->mFromModule = mUnreifiedModule;
  2666. specializationRequest->mFromModuleRevision = typeInst->mModule->mRevision;
  2667. specializationRequest->mMethodIdx = methodRef.mMethodNum;
  2668. //specializationRequest->mMethodDef = methodRef.mTypeInstance->mTypeDef->mMethods[methodRef.mMethodNum];
  2669. specializationRequest->mMethodGenericArguments = methodRef.mMethodGenericArguments;
  2670. specializationRequest->mType = methodRef.mTypeInstance;
  2671. BfLogSysM("QueueMethodSpecializations typeInst %p specializationRequest %p methodDef %p fromModule %p\n", typeInst, specializationRequest, methodDef, specializationRequest->mFromModule);
  2672. }
  2673. }
  2674. void BfContext::MarkAsReferenced(BfDependedType* depType)
  2675. {
  2676. BF_ASSERT((depType->mRebuildFlags & BfTypeRebuildFlag_AwaitingReference) != 0);
  2677. depType->mRebuildFlags = (BfTypeRebuildFlags)(depType->mRebuildFlags & ~BfTypeRebuildFlag_AwaitingReference);
  2678. // bool madeFullPass = true;
  2679. // if (mCompiler->mCanceling)
  2680. // madeFullPass = false;
  2681. // if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mParser != NULL))
  2682. // madeFullPass = false;
  2683. // Having this in caused errors when we canceled and then compiled again
  2684. auto typeInst = depType->ToTypeInstance();
  2685. if (typeInst != NULL)
  2686. {
  2687. QueueMethodSpecializations(typeInst, false);
  2688. }
  2689. }
  2690. static int gCheckIdx = 0;
  2691. template <typename T>
  2692. void ReportRemovedItem(T workItem)
  2693. {
  2694. }
  2695. template <>
  2696. void ReportRemovedItem<BfMethodProcessRequest*>(BfMethodProcessRequest* workItem)
  2697. {
  2698. if (workItem->mMethodInstance != NULL)
  2699. BfLogSys(workItem->mFromModule->mSystem, "DoRemoveInvalidWorkItems MethodInstance:%p\n", workItem->mMethodInstance);
  2700. }
  2701. bool BfContext::IsWorkItemValid(BfWorkListEntry* item)
  2702. {
  2703. return true;
  2704. }
  2705. bool BfContext::IsWorkItemValid(BfMethodInstance* methodInstance)
  2706. {
  2707. if (methodInstance == NULL)
  2708. return false;
  2709. for (auto& param : methodInstance->mParams)
  2710. {
  2711. if (param.mResolvedType->IsDeleting())
  2712. return false;
  2713. }
  2714. if (methodInstance->mMethodInfoEx != NULL)
  2715. {
  2716. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  2717. if (genericArg->IsDeleting())
  2718. return false;
  2719. }
  2720. return true;
  2721. }
  2722. bool BfContext::IsWorkItemValid(BfMethodProcessRequest* item)
  2723. {
  2724. // If we had mid-compile rebuilds then we may have deleted types referenced in methods
  2725. if (mCompiler->mStats.mMidCompileRebuilds == 0)
  2726. return true;
  2727. if (!IsWorkItemValid(item->mMethodInstance))
  2728. return false;
  2729. return true;
  2730. }
  2731. bool BfContext::IsWorkItemValid(BfInlineMethodRequest* item)
  2732. {
  2733. if (mCompiler->mStats.mMidCompileRebuilds == 0)
  2734. return true;
  2735. if (!IsWorkItemValid(item->mMethodInstance))
  2736. return false;
  2737. if (item->mMethodInstance->GetOwner()->IsDeleting())
  2738. return false;
  2739. return true;
  2740. }
  2741. bool BfContext::IsWorkItemValid(BfMethodSpecializationRequest* item)
  2742. {
  2743. // If we had mid-compile rebuilds then we may have deleted types referenced in methods
  2744. if (mCompiler->mStats.mMidCompileRebuilds == 0)
  2745. return true;
  2746. for (auto type : item->mMethodGenericArguments)
  2747. if (type->IsDeleting())
  2748. return false;
  2749. if ((item->mForeignType != NULL) && (item->mForeignType->IsDeleting()))
  2750. return false;
  2751. return true;
  2752. }
  2753. template <typename T>
  2754. void DoRemoveInvalidWorkItems(BfContext* bfContext, WorkQueue<T>& workList, bool requireValidType)
  2755. {
  2756. //auto itr = workList.begin();
  2757. //while (itr != workList.end())
  2758. for (int workIdx = 0; workIdx < (int)workList.size(); workIdx++)
  2759. {
  2760. gCheckIdx++;
  2761. //auto& workItem = *itr;
  2762. auto workItem = workList[workIdx];
  2763. if (workItem == NULL)
  2764. continue;
  2765. BfTypeInstance* typeInst = workItem->mType->ToTypeInstance();
  2766. if ((workItem->mType->IsDeleting()) ||
  2767. (workItem->mType->mRebuildFlags & BfTypeRebuildFlag_Deleted) ||
  2768. ((workItem->mRevision != -1) && (typeInst != NULL) && (workItem->mRevision != typeInst->mRevision)) ||
  2769. ((workItem->mSignatureRevision != -1) && (typeInst != NULL) && (workItem->mSignatureRevision != typeInst->mSignatureRevision)) ||
  2770. ((workItem->mFromModuleRevision != -1) && (workItem->mFromModuleRevision != workItem->mFromModule->mRevision)) ||
  2771. ((workItem->mFromModule != NULL) && (workItem->mFromModule->mIsDeleting)) ||
  2772. ((requireValidType) && (workItem->mType->mDefineState == BfTypeDefineState_Undefined)) ||
  2773. (!bfContext->IsWorkItemValid(workItem)))
  2774. {
  2775. if (typeInst != NULL)
  2776. {
  2777. BF_ASSERT(
  2778. (workItem->mRevision < typeInst->mRevision) ||
  2779. ((workItem->mFromModule != NULL) && (workItem->mFromModuleRebuildIdx != -1) && (workItem->mFromModule->mRebuildIdx != workItem->mFromModuleRebuildIdx)) ||
  2780. ((workItem->mRevision == typeInst->mRevision) && (workItem->mType->mRebuildFlags & BfTypeRebuildFlag_Deleted)) ||
  2781. (workItem->mType->mDefineState == BfTypeDefineState_Undefined));
  2782. }
  2783. BfLogSys(bfContext->mSystem, "Removing work item: %p ReqId:%d\n", workItem, workItem->mReqId);
  2784. ReportRemovedItem(workItem);
  2785. workIdx = workList.RemoveAt(workIdx);
  2786. //itr = workList.erase(itr);
  2787. }
  2788. //else
  2789. //++itr;
  2790. }
  2791. }
  2792. void BfContext::RemoveInvalidFailTypes()
  2793. {
  2794. for (auto itr = mFailTypes.begin(); itr != mFailTypes.end(); )
  2795. {
  2796. auto typeInst = itr->mKey;
  2797. BfLogSysM("Checking FailType: %p\n", typeInst);
  2798. if ((typeInst->IsDeleting()) || (typeInst->mRebuildFlags & BfTypeRebuildFlag_Deleted))
  2799. {
  2800. BfLogSysM("Removing Invalid FailType: %p\n", typeInst);
  2801. itr = mFailTypes.Remove(itr);
  2802. }
  2803. else
  2804. itr++;
  2805. }
  2806. }
  2807. // These work items are left over from a previous canceled run, OR from explicit method
  2808. // specializations being rebuilt when the type is rebuilt
  2809. void BfContext::RemoveInvalidWorkItems()
  2810. {
  2811. BfLogSysM("RemoveInvalidWorkItems %p\n", this);
  2812. // Delete any request that include deleted types.
  2813. // For the list items referring to methods we check the LLVMType because that lets us know
  2814. // whether or not the type has been reset since these work items were requested
  2815. DoRemoveInvalidWorkItems<BfMethodProcessRequest>(this, mMethodWorkList, true);
  2816. DoRemoveInvalidWorkItems<BfInlineMethodRequest>(this, mInlineMethodWorkList, true);
  2817. //TODO: We used to pass true into requireValidType, but this gets populated from UpdateRevisedTypes right before RemoveInvalidWorkItems,
  2818. // so we're passing false in here now. Don't just switch it back and forth - find why 'false' was causing an issue.
  2819. // Same with mMethodSpecializationWorkList
  2820. DoRemoveInvalidWorkItems<BfTypeProcessRequest>(this, mPopulateTypeWorkList, false);
  2821. DoRemoveInvalidWorkItems<BfMidCompileRequest>(this, mMidCompileWorkList, false);
  2822. DoRemoveInvalidWorkItems<BfMethodSpecializationRequest>(this, mMethodSpecializationWorkList, false/*true*/);
  2823. DoRemoveInvalidWorkItems<BfTypeRefVerifyRequest>(this, mTypeRefVerifyWorkList, false);
  2824. #ifdef _DEBUG
  2825. for (auto& workItem : mMethodWorkList)
  2826. {
  2827. //BF_ASSERT(workItem.mMethodInstance->mDeclModule != NULL);
  2828. }
  2829. for (auto workItem : mMethodSpecializationWorkList)
  2830. {
  2831. if (workItem == NULL)
  2832. continue;
  2833. for (auto genericArg : workItem->mMethodGenericArguments)
  2834. {
  2835. BF_ASSERT((genericArg->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  2836. BF_ASSERT(!genericArg->IsDeleting());
  2837. }
  2838. }
  2839. #endif
  2840. if (mCompiler->mRevision == mScratchModule->mRevision)
  2841. {
  2842. // We have deleted the old module so we need to recreate unspecialized LLVMFunctions
  2843. for (auto workListItem : mMethodWorkList)
  2844. {
  2845. if ((workListItem != NULL) && (workListItem->mType->IsUnspecializedType()))
  2846. {
  2847. workListItem->mMethodInstance->mIRFunction = BfIRFunction();
  2848. }
  2849. }
  2850. }
  2851. RemoveInvalidFailTypes();
  2852. }
  2853. void BfContext::RemapObject()
  2854. {
  2855. if (mCompiler->mBfObjectTypeDef == NULL)
  2856. return;
  2857. // There are several types that get their LLVM type mapped to Object, so make sure to remap that
  2858. // for when Object itself gets recreated
  2859. auto objectType = mScratchModule->ResolveTypeDef(mCompiler->mBfObjectTypeDef, BfPopulateType_Declaration);
  2860. auto objectTypeInst = objectType->ToTypeInstance();
  2861. if (objectTypeInst->mRevision == mMappedObjectRevision)
  2862. return;
  2863. mMappedObjectRevision = objectTypeInst->mRevision;
  2864. for (int paramKind = 0; paramKind < 2; paramKind++)
  2865. {
  2866. for (int paramIdx = 0; paramIdx < (int)mGenericParamTypes[paramKind].size(); paramIdx++)
  2867. {
  2868. auto genericParam = mGenericParamTypes[paramKind][paramIdx];
  2869. genericParam->mSize = objectType->mSize;
  2870. genericParam->mAlign = objectType->mAlign;
  2871. }
  2872. }
  2873. auto varType = mScratchModule->GetPrimitiveType(BfTypeCode_Var);
  2874. varType->mSize = objectType->mSize;
  2875. varType->mAlign = objectType->mAlign;
  2876. }
  2877. void BfContext::CheckSpecializedErrorData()
  2878. {
  2879. //TODO: Unecessary now?
  2880. /*for (auto& specializedErrorData : mSpecializedErrorData)
  2881. {
  2882. bool ignoreError = false;
  2883. if (specializedErrorData.mRefType->IsDeleting())
  2884. ignoreError = true;
  2885. if (specializedErrorData.mMethodInstance != NULL)
  2886. {
  2887. for (auto genericArg : specializedErrorData.mMethodInstance->mMethodGenericArguments)
  2888. if (genericArg->IsDeleting())
  2889. ignoreError = true;
  2890. }
  2891. if (ignoreError)
  2892. {
  2893. if (specializedErrorData.mMethodInstance->mIRFunction != NULL)
  2894. {
  2895. specializedErrorData.mMethodInstance->mIRFunction->eraseFromParent();
  2896. specializedErrorData.mMethodInstance->mIRFunction = NULL;
  2897. }
  2898. specializedErrorData.mError->mIgnore = true;
  2899. }
  2900. else
  2901. {
  2902. specializedErrorData.mModule->mHadBuildError = true;
  2903. mFailTypes.insert(specializedErrorData.mRefType);
  2904. }
  2905. }*/
  2906. }
  2907. void BfContext::TryUnreifyModules()
  2908. {
  2909. BP_ZONE("BfContext::TryUnreifyModules");
  2910. for (auto module : mModules)
  2911. {
  2912. if (module->mIsSpecialModule)
  2913. continue;
  2914. if (!module->mIsReified)
  2915. continue;
  2916. if (module->mLastUsedRevision == mCompiler->mRevision)
  2917. continue;
  2918. bool isRequired = false;
  2919. for (auto typeInst : module->mOwnedTypeInstances)
  2920. {
  2921. if (typeInst->mTypeDef->IsGlobalsContainer())
  2922. isRequired = true;
  2923. if (typeInst->IsAlwaysInclude())
  2924. isRequired = true;
  2925. }
  2926. if (isRequired)
  2927. continue;
  2928. module->UnreifyModule();
  2929. }
  2930. }
  2931. void BfContext::MarkUsedModules(BfProject* project, BfModule* module)
  2932. {
  2933. BP_ZONE("BfContext::MarkUsedModules");
  2934. if (module->mIsDeleting)
  2935. return;
  2936. BF_ASSERT_REL(!module->mIsDeleting);
  2937. if (module->mIsScratchModule)
  2938. return;
  2939. if (project->mUsedModules.Contains(module))
  2940. return;
  2941. if (!mCompiler->IsModuleAccessible(module, project))
  2942. return;
  2943. project->mUsedModules.Add(module);
  2944. for (auto& typeDataKV : module->mTypeDataRefs)
  2945. project->mReferencedTypeData.Add(typeDataKV.mKey);
  2946. for (auto& slotKV : module->mInterfaceSlotRefs)
  2947. {
  2948. auto typeInstance = slotKV.mKey;
  2949. if ((typeInstance->mSlotNum < 0) && (mCompiler->mHotState != NULL))
  2950. mCompiler->mHotState->mHasNewInterfaceTypes = true;
  2951. mReferencedIFaceSlots.Add(typeInstance);
  2952. }
  2953. for (auto& kv : module->mStaticFieldRefs)
  2954. {
  2955. auto& fieldRef = kv.mKey;
  2956. auto typeInst = fieldRef.mTypeInstance;
  2957. BF_ASSERT(!typeInst->IsDataIncomplete());
  2958. BF_ASSERT(fieldRef.mFieldIdx < typeInst->mFieldInstances.size());
  2959. if (fieldRef.mFieldIdx < typeInst->mFieldInstances.size())
  2960. typeInst->mFieldInstances[fieldRef.mFieldIdx].mLastRevisionReferenced = mCompiler->mRevision;
  2961. }
  2962. module->mLastUsedRevision = mCompiler->mRevision;
  2963. for (auto usedModule : module->mModuleRefs)
  2964. {
  2965. MarkUsedModules(project, usedModule);
  2966. }
  2967. for (auto& kv : module->mSpecializedMethodModules)
  2968. {
  2969. MarkUsedModules(project, kv.mValue);
  2970. }
  2971. }
  2972. void BfContext::Finish()
  2973. {
  2974. }
  2975. void BfContext::Cleanup()
  2976. {
  2977. BfLogSysM("BfContext::Cleanup() MethodWorkList: %d LocalMethodGraveyard: %d\n", mMethodWorkList.size(), mLocalMethodGraveyard.size());
  2978. // Can't clean up LLVM types, they are allocated with a bump allocator
  2979. RemoveInvalidFailTypes();
  2980. mCompiler->mCompileState = BfCompiler::CompileState_Cleanup;
  2981. if (mCompiler->mStats.mTypesDeleted_LastUpdateAfterDeletingTypes != mCompiler->mStats.mTypesDeleted)
  2982. {
  2983. // Should only occur for internal compiler errors
  2984. BF_ASSERT(mCompiler->mExtraCompileRequested);
  2985. UpdateAfterDeletingTypes();
  2986. }
  2987. ///
  2988. {
  2989. Array<BfLocalMethod*> survivingLocalMethods;
  2990. for (auto localMethod : mLocalMethodGraveyard)
  2991. {
  2992. bool inCEMachine = false;
  2993. if (localMethod->mMethodInstanceGroup != NULL)
  2994. {
  2995. if ((localMethod->mMethodInstanceGroup->mDefault != NULL) && (localMethod->mMethodInstanceGroup->mDefault->mInCEMachine))
  2996. inCEMachine = true;
  2997. if (localMethod->mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  2998. {
  2999. for (auto& kv : *localMethod->mMethodInstanceGroup->mMethodSpecializationMap)
  3000. if (kv.mValue->mInCEMachine)
  3001. inCEMachine = true;
  3002. }
  3003. }
  3004. if (inCEMachine)
  3005. {
  3006. localMethod->mMethodInstanceGroup->mOwner->mOwnedLocalMethods.Add(localMethod);
  3007. }
  3008. else if ((localMethod->mMethodInstanceGroup != NULL) && (localMethod->mMethodInstanceGroup->mRefCount > 0))
  3009. {
  3010. BfLogSysM("BfContext::Cleanup surviving local method with refs %p\n", localMethod);
  3011. localMethod->Dispose();
  3012. survivingLocalMethods.push_back(localMethod);
  3013. }
  3014. else if (!mMethodWorkList.empty())
  3015. {
  3016. // We can't remove the local methods if they still may be referenced by a BfMethodRefType used to specialize a method
  3017. BfLogSysM("BfContext::Cleanup surviving local method %p\n", localMethod);
  3018. localMethod->Dispose();
  3019. survivingLocalMethods.push_back(localMethod);
  3020. }
  3021. else
  3022. delete localMethod;
  3023. }
  3024. mLocalMethodGraveyard = survivingLocalMethods;
  3025. }
  3026. // Clean up deleted BfTypes
  3027. // These need to get deleted before the modules because we access mModule in the MethodInstance dtors
  3028. for (int pass = 0; pass < 2; pass++)
  3029. {
  3030. for (int i = 0; i < (int)mTypeGraveyard.size(); i++)
  3031. {
  3032. auto type = mTypeGraveyard[i];
  3033. if (type == NULL)
  3034. continue;
  3035. bool deleteNow = (type->IsBoxed() == (pass == 0));
  3036. if (!deleteNow)
  3037. continue;
  3038. BF_ASSERT(type->mRebuildFlags & BfTypeRebuildFlag_Deleted);
  3039. delete type;
  3040. mTypeGraveyard[i] = NULL;
  3041. }
  3042. }
  3043. mTypeGraveyard.Clear();
  3044. mGhostDependencies.Clear();
  3045. if (!mDeletingModules.IsEmpty())
  3046. {
  3047. // Clear our invalid modules in mUsedModules list
  3048. for (auto project : mSystem->mProjects)
  3049. {
  3050. for (auto itr = project->mUsedModules.begin(); itr != project->mUsedModules.end(); )
  3051. {
  3052. auto module = *itr;
  3053. if (module->mIsDeleting)
  3054. itr = project->mUsedModules.Remove(itr);
  3055. else
  3056. {
  3057. BF_ASSERT_REL(module->mRevision > -2);
  3058. ++itr;
  3059. }
  3060. }
  3061. }
  3062. }
  3063. for (auto module : mDeletingModules)
  3064. {
  3065. int idx = (int)mFinishedModuleWorkList.IndexOf(module);
  3066. if (idx != -1)
  3067. mFinishedModuleWorkList.RemoveAt(idx);
  3068. idx = (int)mFinishedSlotAwaitModuleWorkList.IndexOf(module);
  3069. if (idx != -1)
  3070. mFinishedSlotAwaitModuleWorkList.RemoveAt(idx);
  3071. delete module;
  3072. }
  3073. mDeletingModules.Clear();
  3074. for (auto typeDef : mTypeDefGraveyard)
  3075. delete typeDef;
  3076. mTypeDefGraveyard.Clear();
  3077. mScratchModule->Cleanup();
  3078. mUnreifiedModule->Cleanup();
  3079. for (auto module : mModules)
  3080. module->Cleanup();
  3081. }