JavascriptArray.inl 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #pragma once
  6. namespace Js
  7. {
  8. //
  9. // Walks all the nodes in this BTree in sorted order.
  10. //
  11. template<typename Func>
  12. void SegmentBTree::Walk(Func& func) const
  13. {
  14. if (!IsLeaf())
  15. {
  16. children[0].Walk(func);
  17. }
  18. for (unsigned int i = 0; i < segmentCount; i++)
  19. {
  20. Assert(keys[i] == segments[i]->left);
  21. func(segments[i]);
  22. if (!IsLeaf())
  23. {
  24. children[i + 1].Walk(func);
  25. }
  26. }
  27. }
  28. template <typename Fn>
  29. SparseArraySegmentBase *
  30. JavascriptArray::ForEachSegment(Fn fn) const
  31. {
  32. return ForEachSegment(this->head, fn);
  33. }
  34. template <typename Fn>
  35. SparseArraySegmentBase *
  36. JavascriptArray::ForEachSegment(SparseArraySegmentBase * segment, Fn fn)
  37. {
  38. DebugOnly(uint32 lastindex = segment? segment->left : 0);
  39. SparseArraySegmentBase * current = segment;
  40. while (current)
  41. {
  42. // Verify that all the segment are sorted
  43. Assert(current->left >= lastindex);
  44. if (fn(current))
  45. {
  46. break;
  47. }
  48. DebugOnly(lastindex = current->left + current->length);
  49. current = current->next;
  50. }
  51. return current;
  52. }
  53. //
  54. // Link prev and current. If prev is NULL, make current the head segment.
  55. //
  56. template<>
  57. inline void JavascriptArray::LinkSegments(SparseArraySegment<int>* prev, SparseArraySegment<int>* current)
  58. {
  59. if (prev && prev->next == nullptr && SparseArraySegmentBase::IsLeafSegment(prev, this->GetScriptContext()->GetRecycler()))
  60. {
  61. prev = this->ReallocNonLeafSegment(prev, current);
  62. }
  63. else
  64. {
  65. LinkSegmentsCommon(prev, current);
  66. }
  67. }
  68. template<>
  69. inline void JavascriptArray::LinkSegments(SparseArraySegment<double>* prev, SparseArraySegment<double>* current)
  70. {
  71. if (prev && prev->next == nullptr && SparseArraySegmentBase::IsLeafSegment(prev, this->GetScriptContext()->GetRecycler()))
  72. {
  73. prev = this->ReallocNonLeafSegment(prev, current);
  74. }
  75. else
  76. {
  77. LinkSegmentsCommon(prev, current);
  78. }
  79. }
  80. template<typename T>
  81. inline void JavascriptArray::LinkSegments(SparseArraySegment<T>* prev, SparseArraySegment<T>* current)
  82. {
  83. LinkSegmentsCommon(prev, current);
  84. }
  85. template<typename T>
  86. inline SparseArraySegment<T>* JavascriptArray::ReallocNonLeafSegment(SparseArraySegment<T> *seg, SparseArraySegmentBase* nextSeg)
  87. {
  88. // Find the segment prior to seg.
  89. SparseArraySegmentBase *prior = nullptr;
  90. if (seg != this->head)
  91. {
  92. for (prior = this->head; prior->next != seg; prior = prior->next)
  93. {
  94. Assert(prior->next);
  95. }
  96. }
  97. Recycler *recycler = this->GetScriptContext()->GetRecycler();
  98. SparseArraySegment<T> *newSeg = SparseArraySegment<T>::AllocateSegment(recycler, seg->left, seg->length, nextSeg);
  99. js_memcpy_s(newSeg->elements, sizeof(T) * seg->length, seg->elements, sizeof(T) * seg->length);
  100. LinkSegmentsCommon(prior, newSeg);
  101. LinkSegmentsCommon(newSeg, nextSeg);
  102. if (GetLastUsedSegment() == seg)
  103. {
  104. SetLastUsedSegment(newSeg);
  105. }
  106. SegmentBTree * segmentMap = GetSegmentMap();
  107. if (segmentMap)
  108. {
  109. segmentMap->SwapSegment(seg->left, seg, newSeg);
  110. }
  111. return newSeg;
  112. }
  113. /*static*/
  114. template<typename T, uint InlinePropertySlots>
  115. __inline SparseArraySegment<typename T::TElement> *JavascriptArray::InitArrayAndHeadSegment(
  116. T *const array,
  117. const uint32 length,
  118. const uint32 size,
  119. const bool wasZeroAllocated)
  120. {
  121. Assert(!array->HasSegmentMap());
  122. SparseArraySegment<typename T::TElement>* head =
  123. DetermineInlineHeadSegmentPointer<T, InlinePropertySlots, false>(array);
  124. if(wasZeroAllocated)
  125. {
  126. if(length != 0)
  127. {
  128. head->length = length;
  129. }
  130. head->size = size;
  131. }
  132. else
  133. {
  134. new(head) SparseArraySegment<typename T::TElement>(0, length, size);
  135. }
  136. array->SetHeadAndLastUsedSegment(head);
  137. array->SetHasNoMissingValues();
  138. return head;
  139. }
  140. template<typename unitType, typename className>
  141. __inline className * JavascriptArray::New(Recycler * recycler, DynamicType * type)
  142. {
  143. size_t allocationPlusSize;
  144. uint alignedInlineElementSlots;
  145. DetermineAllocationSize<className, 0>(
  146. SparseArraySegmentBase::SMALL_CHUNK_SIZE,
  147. &allocationPlusSize,
  148. &alignedInlineElementSlots);
  149. return RecyclerNewPlusZ(recycler, allocationPlusSize, className, type, alignedInlineElementSlots);
  150. }
  151. /*static*/
  152. template<typename unitType, typename className, uint inlineSlots>
  153. className* JavascriptArray::New(uint32 length, DynamicType* arrayType, Recycler* recycler)
  154. {
  155. CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
  156. Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
  157. if(length > SparseArraySegmentBase::HEAD_CHUNK_SIZE)
  158. {
  159. // Use empty segment until we try to store something. Call AllocateHead() at that point.
  160. return RecyclerNew(recycler, className, length, arrayType);
  161. }
  162. size_t allocationPlusSize;
  163. uint alignedInlineElementSlots;
  164. className* array;
  165. if (!length) // zero length - use default head chunk size
  166. {
  167. DetermineAllocationSize<className, inlineSlots>(
  168. SparseArraySegmentBase::HEAD_CHUNK_SIZE,
  169. &allocationPlusSize,
  170. &alignedInlineElementSlots);
  171. }
  172. else //Small array
  173. {
  174. Assert(length <= SparseArraySegmentBase::HEAD_CHUNK_SIZE);
  175. DetermineAllocationSize<className, inlineSlots>(length, &allocationPlusSize, &alignedInlineElementSlots);
  176. }
  177. array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
  178. SparseArraySegment<unitType> *head =
  179. InitArrayAndHeadSegment<className, inlineSlots>(array, 0, alignedInlineElementSlots, true);
  180. head->FillSegmentBuffer(0, alignedInlineElementSlots);
  181. return array;
  182. }
  183. //
  184. // Allocates the segment inline up to the length of SparseArraySegmentBase::INLINE_CHUNK_SIZE. The downside of having the segment
  185. // inline is that the segment space will never get freed unless the Array is collected.
  186. //
  187. /*static*/
  188. template<typename unitType, typename className, uint inlineSlots>
  189. className* JavascriptArray::NewLiteral(uint32 length, DynamicType* arrayType, Recycler* recycler)
  190. {
  191. CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
  192. Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
  193. className* array;
  194. if(HasInlineHeadSegment(length))
  195. {
  196. size_t allocationPlusSize;
  197. uint alignedInlineElementSlots;
  198. if(!length)
  199. {
  200. DetermineAllocationSize<className, inlineSlots>(
  201. SparseArraySegmentBase::SMALL_CHUNK_SIZE,
  202. &allocationPlusSize,
  203. &alignedInlineElementSlots);
  204. }
  205. else
  206. {
  207. DetermineAllocationSize<className, inlineSlots>(length, &allocationPlusSize, &alignedInlineElementSlots);
  208. }
  209. array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
  210. // An new array's head segment length is initialized to zero despite the array length being nonzero because the segment
  211. // doesn't have any values to begin with. An array literal though, is initialized with special op-codes that just store
  212. // the values and don't update the length, so update the length here.
  213. //
  214. // An array literal is also guaranteed to be fully initialized, so even though the head segment currently will have
  215. // missing values (after this update to length), it won't have missing values once the initialization is complete, so
  216. // maintain the state saying "does not have missing values". Furthermore, since the new array literal is not assigned to
  217. // a variable until it is fully initialized, there is no way for script code to use the array while it still has missing
  218. // values.
  219. SparseArraySegment<unitType> *head =
  220. InitArrayAndHeadSegment<className, inlineSlots>(array, length, alignedInlineElementSlots, true);
  221. head->FillSegmentBuffer(length, alignedInlineElementSlots);
  222. Assert(array->HasNoMissingValues());
  223. return array;
  224. }
  225. size_t allocationPlusSize;
  226. DetermineAllocationSize<className, inlineSlots>(0, &allocationPlusSize);
  227. array = RecyclerNewPlusZ(recycler, allocationPlusSize, className, length, arrayType);
  228. SparseArraySegment<unitType> *seg = SparseArraySegment<unitType>::AllocateLiteralHeadSegment(recycler, length);
  229. array->SetHeadAndLastUsedSegment(seg);
  230. array->SetHasNoMissingValues();
  231. // An new array's head segment length is initialized to zero despite the array length being nonzero because the segment
  232. // doesn't have any values to begin with. An array literal though, is initialized with special op-codes that just store
  233. // the values and don't update the length, so update the length here.
  234. //
  235. // An array literal is also guaranteed to be fully initialized, so even though the head segment currently will have
  236. // missing values (after this update to length), it won't have missing values once the initialization is complete, so
  237. // maintain the state saying "does not have missing values". Furthermore, since the new array literal is not assigned to
  238. // a variable until it is fully initialized, there is no way for script code to use the array while it still has missing
  239. // values.
  240. array->head->length = length;
  241. return array;
  242. }
  243. #if ENABLE_COPYONACCESS_ARRAY
  244. //
  245. // Allocates the segment inline up to the length of SparseArraySegmentBase::INLINE_CHUNK_SIZE. The downside of having the segment
  246. // inline is that the segment space will never get freed unless the Array is collected.
  247. //
  248. /*static*/
  249. template<typename unitType, typename className, uint inlineSlots>
  250. className* JavascriptArray::NewCopyOnAccessLiteral(DynamicType* arrayType, ArrayCallSiteInfo *arrayInfo, FunctionBody *functionBody, const Js::AuxArray<int32> *ints, Recycler* recycler)
  251. {
  252. CompileAssert(static_cast<PropertyIndex>(inlineSlots) == inlineSlots);
  253. Assert(DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(inlineSlots)) == inlineSlots);
  254. Assert(arrayInfo->IsNativeIntArray());
  255. className* array = RecyclerNewZ(recycler, JavascriptCopyOnAccessNativeIntArray, ints->count, arrayType);
  256. JavascriptLibrary *lib = functionBody->GetScriptContext()->GetLibrary();
  257. SparseArraySegment<unitType> *seg;
  258. if (JavascriptLibrary::IsCachedCopyOnAccessArrayCallSite(functionBody->GetScriptContext()->GetLibrary() , arrayInfo))
  259. {
  260. seg = lib->cacheForCopyOnAccessArraySegments->GetSegmentByIndex(arrayInfo->copyOnAccessArrayCacheIndex);
  261. }
  262. else
  263. {
  264. seg = SparseArraySegment<unitType>::AllocateLiteralHeadSegment(recycler, ints->count);
  265. }
  266. if (!JavascriptLibrary::IsCachedCopyOnAccessArrayCallSite(lib, arrayInfo))
  267. {
  268. JavascriptOperators::AddIntsToArraySegment(seg, ints);
  269. arrayInfo->copyOnAccessArrayCacheIndex = lib->cacheForCopyOnAccessArraySegments->AddSegment(seg);
  270. }
  271. array->SetHeadAndLastUsedSegment(reinterpret_cast<SparseArraySegmentBase *>(arrayInfo->copyOnAccessArrayCacheIndex)); // storing index in head on purpose: expect AV if treated as other array objects
  272. #if ENABLE_DEBUG_CONFIG_OPTIONS
  273. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::CopyOnAccessArrayPhase))
  274. {
  275. Output::Print(L"Create copy-on-access array: func(#%2d) index(%d) length(%d)\n",
  276. functionBody->GetFunctionNumber(), lib->cacheForCopyOnAccessArraySegments->GetCount(), ints->count);
  277. Output::Flush();
  278. }
  279. #endif
  280. return array;
  281. }
  282. #endif
  283. template<class T, uint InlinePropertySlots>
  284. __inline T *JavascriptArray::New(
  285. void *const stackAllocationPointer,
  286. const uint32 length,
  287. DynamicType *const arrayType)
  288. {
  289. Assert(arrayType);
  290. if(stackAllocationPointer)
  291. {
  292. bool isSufficientSpaceForInlinePropertySlots;
  293. const uint availableInlineElementSlots =
  294. DetermineAvailableInlineElementSlots<T, InlinePropertySlots>(
  295. T::StackAllocationSize,
  296. &isSufficientSpaceForInlinePropertySlots);
  297. if(isSufficientSpaceForInlinePropertySlots)
  298. {
  299. T *const array = new(stackAllocationPointer) T(length, arrayType);
  300. if(length <= availableInlineElementSlots)
  301. {
  302. SparseArraySegment<typename T::TElement> *const head =
  303. InitArrayAndHeadSegment<T, InlinePropertySlots>(array, 0, availableInlineElementSlots, false);
  304. head->FillSegmentBuffer(0, availableInlineElementSlots);
  305. }
  306. else
  307. {
  308. // Not enough room to allocate all required element slots inline. Leave the head segment as the empty
  309. // segment and let it be allocated as necessary.
  310. }
  311. Assert(array->HasNoMissingValues());
  312. return array;
  313. }
  314. }
  315. return New<typename T::TElement, T, InlinePropertySlots>(length, arrayType, arrayType->GetRecycler());
  316. }
  317. template<class T, uint InlinePropertySlots>
  318. __inline T *JavascriptArray::NewLiteral(
  319. void *const stackAllocationPointer,
  320. const uint32 length,
  321. DynamicType *const arrayType)
  322. {
  323. Assert(arrayType);
  324. if(stackAllocationPointer)
  325. {
  326. bool isSufficientSpaceForInlinePropertySlots;
  327. const uint availableInlineElementSlots =
  328. DetermineAvailableInlineElementSlots<T, InlinePropertySlots>(
  329. T::StackAllocationSize,
  330. &isSufficientSpaceForInlinePropertySlots);
  331. if(isSufficientSpaceForInlinePropertySlots)
  332. {
  333. T *const array = new(stackAllocationPointer) T(length, arrayType);
  334. if(length <= availableInlineElementSlots)
  335. {
  336. SparseArraySegment<typename T::TElement> *const head =
  337. InitArrayAndHeadSegment<T, InlinePropertySlots>(array, length, availableInlineElementSlots, false);
  338. head->FillSegmentBuffer(length, availableInlineElementSlots);
  339. Assert(array->HasNoMissingValues());
  340. return array;
  341. }
  342. // Not enough room to allocate all required element slots inline. Allocate the head segment separately.
  343. SparseArraySegment<typename T::TElement> *const head =
  344. SparseArraySegment<typename T::TElement>::AllocateLiteralHeadSegment(arrayType->GetRecycler(), length);
  345. array->SetHeadAndLastUsedSegment(head);
  346. array->SetHasNoMissingValues();
  347. return array;
  348. }
  349. }
  350. return NewLiteral<typename T::TElement, T, InlinePropertySlots>(length, arrayType, arrayType->GetRecycler());
  351. }
  352. template<typename T>
  353. __inline void JavascriptArray::DirectSetItemAt(uint32 itemIndex, T newValue)
  354. {
  355. Assert(itemIndex < InvalidIndex); // Otherwise the code below could overflow and set length = 0
  356. SparseArraySegment<T> *seg = (SparseArraySegment<T>*)this->GetLastUsedSegment();
  357. uint32 offset = itemIndex - seg->left;
  358. if(itemIndex >= seg->left && offset < seg->size)
  359. {
  360. DirectSetItemInLastUsedSegmentAt(offset, newValue);
  361. return;
  362. }
  363. DirectSetItem_Full(itemIndex, newValue);
  364. }
  365. template<typename T>
  366. __inline void JavascriptArray::DirectSetItemInLastUsedSegmentAt(const uint32 offset, const T newValue)
  367. {
  368. SparseArraySegment<T> *const seg = (SparseArraySegment<T>*)GetLastUsedSegment();
  369. Assert(seg);
  370. Assert(offset < seg->size);
  371. Assert(!(HasNoMissingValues() &&
  372. offset < seg->length &&
  373. SparseArraySegment<T>::IsMissingItem(&seg->elements[offset]) &&
  374. seg == head));
  375. const bool scanForMissingValues = NeedScanForMissingValuesUponSetItem(seg, offset);
  376. DebugOnly(VerifyNotNeedMarshal(newValue));
  377. seg->elements[offset] = newValue;
  378. if (offset >= seg->length)
  379. {
  380. if(offset > seg->length && seg == head)
  381. {
  382. SetHasNoMissingValues(false);
  383. }
  384. seg->length = offset + 1;
  385. const uint32 itemIndex = seg->left + offset;
  386. if (this->length <= itemIndex)
  387. {
  388. this->length = itemIndex + 1;
  389. }
  390. }
  391. else if(scanForMissingValues)
  392. {
  393. ScanForMissingValues<T>();
  394. }
  395. }
  396. #if ENABLE_PROFILE_INFO
  397. template<typename T>
  398. __inline void JavascriptArray::DirectProfiledSetItemInHeadSegmentAt(
  399. const uint32 offset,
  400. const T newValue,
  401. StElemInfo *const stElemInfo)
  402. {
  403. SparseArraySegment<T> *const seg = (SparseArraySegment<T>*)head;
  404. Assert(seg);
  405. Assert(offset < seg->size);
  406. Assert(!(HasNoMissingValues() &&
  407. offset < seg->length &&
  408. SparseArraySegment<T>::IsMissingItem(&seg->elements[offset])));
  409. Assert(stElemInfo);
  410. stElemInfo->filledMissingValue = offset < seg->length && SparseArraySegment<T>::IsMissingItem(&seg->elements[offset]);
  411. const bool scanForMissingValues = NeedScanForMissingValuesUponSetItem(seg, offset);
  412. DebugOnly(VerifyNotNeedMarshal(newValue));
  413. seg->elements[offset] = newValue;
  414. if (offset >= seg->length)
  415. {
  416. if(offset > seg->length)
  417. {
  418. SetHasNoMissingValues(false);
  419. }
  420. seg->length = offset + 1;
  421. const uint32 itemIndex = seg->left + offset;
  422. if (this->length <= itemIndex)
  423. {
  424. this->length = itemIndex + 1;
  425. }
  426. }
  427. else if(scanForMissingValues)
  428. {
  429. ScanForMissingValues<T>();
  430. }
  431. }
  432. #endif
  433. template<typename T>
  434. inline BOOL JavascriptArray::DirectGetItemAt(uint32 index, T* outVal)
  435. {
  436. #ifdef VALIDATE_ARRAY
  437. ValidateArray();
  438. #endif
  439. if (index >= length)
  440. {
  441. return false;
  442. }
  443. #ifdef VALIDATE_ARRAY
  444. T v_btree = NULL;
  445. SparseArraySegmentBase* seg_btree = nullptr;
  446. bool first_pass = true;
  447. #endif
  448. SparseArraySegmentBase* nextSeg;
  449. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  450. if (segmentMap)
  451. {
  452. SparseArraySegmentBase* matchOrNextSeg;
  453. segmentMap->Find(index, nextSeg, matchOrNextSeg);
  454. if (!nextSeg)
  455. {
  456. nextSeg = matchOrNextSeg;
  457. }
  458. }
  459. else
  460. {
  461. #ifdef VALIDATE_ARRAY
  462. SECOND_PASS:
  463. #endif
  464. nextSeg = this->GetBeginLookupSegment(index, false);
  465. }
  466. uint probeCost = 0;
  467. while (nextSeg != nullptr && nextSeg->left <= index)
  468. {
  469. uint32 limit = nextSeg->left + nextSeg->length;
  470. if (index < limit)
  471. {
  472. T* v = &((SparseArraySegment<T>*)nextSeg)->elements[index - nextSeg->left];
  473. this->SetLastUsedSegment(nextSeg);
  474. #ifdef VALIDATE_ARRAY
  475. Assert(segmentMap == GetSegmentMap());
  476. if (segmentMap && first_pass)
  477. {
  478. v_btree = *v;
  479. seg_btree= nextSeg;
  480. first_pass = false;
  481. goto SECOND_PASS;
  482. }
  483. else if (segmentMap && !first_pass)
  484. {
  485. Assert(seg_btree == nextSeg);
  486. }
  487. #endif
  488. if (SparseArraySegment<T>::IsMissingItem(v))
  489. {
  490. Assert(!(HasNoMissingValues() && nextSeg == head));
  491. return false;
  492. }
  493. *outVal = *v;
  494. return true;
  495. }
  496. nextSeg = nextSeg->next;
  497. Assert(segmentMap == GetSegmentMap());
  498. if (!segmentMap)
  499. {
  500. probeCost++;
  501. if (probeCost > SegmentBTree::GetLazyCrossOverLimit() && this->head != EmptySegment)
  502. {
  503. // Build a SegmentMap
  504. segmentMap = BuildSegmentMap();
  505. // Find the right segment
  506. SparseArraySegmentBase* matchOrNextSeg;
  507. segmentMap->Find(index, nextSeg, matchOrNextSeg);
  508. if (!nextSeg)
  509. {
  510. nextSeg = matchOrNextSeg;
  511. }
  512. }
  513. }
  514. }
  515. #ifdef VALIDATE_ARRAY
  516. Assert(segmentMap == GetSegmentMap());
  517. if (segmentMap && first_pass)
  518. {
  519. v_btree = NULL;
  520. seg_btree= nullptr;
  521. first_pass = false;
  522. goto SECOND_PASS;
  523. }
  524. else if (segmentMap && !first_pass)
  525. {
  526. Assert(v_btree == NULL && seg_btree == nullptr);
  527. }
  528. #endif
  529. return false;
  530. }
  531. template<typename T>
  532. void JavascriptArray::EnsureHead()
  533. {
  534. if (this->head == EmptySegment)
  535. {
  536. this->AllocateHead<T>();
  537. }
  538. }
  539. template<typename T>
  540. void JavascriptArray::AllocateHead()
  541. {
  542. Recycler* recycler = GetRecycler();
  543. uint32 allocLength;
  544. Assert(this->head == EmptySegment);
  545. if (this->length)
  546. {
  547. allocLength = this->length <= MaxInitialDenseLength ? this->length : SparseArraySegmentBase::HEAD_CHUNK_SIZE;
  548. this->head = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, allocLength, nullptr);
  549. }
  550. else
  551. {
  552. allocLength = SparseArraySegmentBase::HEAD_CHUNK_SIZE;
  553. this->head = SparseArraySegment<T>::AllocateSegment(recycler, 0, 0, allocLength, nullptr);
  554. }
  555. this->SetLastUsedSegment(this->head);
  556. SetHasNoMissingValues();
  557. }
  558. template<typename T>
  559. SparseArraySegment<T>* JavascriptArray::PrepareSegmentForMemOp(uint32 startIndex, uint32 length)
  560. {
  561. uint32 endIndex;
  562. if(UInt32Math::Add(startIndex, length - 1, &endIndex))
  563. {
  564. JavascriptError::ThrowRangeError(this->GetScriptContext(), JSERR_ArrayLengthAssignIncorrect);
  565. }
  566. if (endIndex >= this->length)
  567. {
  568. if (endIndex < JavascriptArray::InvalidIndex)
  569. {
  570. this->length = endIndex + 1;
  571. }
  572. else
  573. {
  574. JavascriptError::ThrowRangeError(this->GetScriptContext(), JSERR_ArrayLengthAssignIncorrect);
  575. }
  576. }
  577. this->EnsureHead<T>();
  578. Recycler* recycler = GetRecycler();
  579. //Find the segment where itemIndex is present or is at the boundary
  580. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(startIndex, false);
  581. SparseArraySegmentBase* prev = nullptr;
  582. SparseArraySegmentBase* startSeg = nullptr;
  583. SparseArraySegmentBase* endSeg = nullptr;
  584. SparseArraySegmentBase* startPrev = nullptr;
  585. uint32 growby, startOffset, endOffset;
  586. const auto FindStartAndEndSegment = [&]()
  587. {
  588. if (endIndex >= current->left + current->size)
  589. {
  590. current = (SparseArraySegment<T>*)head;
  591. }
  592. else
  593. {
  594. startSeg = endSeg = current;
  595. current = nullptr;
  596. }
  597. while (current != nullptr)
  598. {
  599. startOffset = startIndex - current->left;
  600. endOffset = endIndex - current->left;
  601. if (!startSeg)
  602. {
  603. if (startIndex <= current->left)
  604. {
  605. startPrev = prev;
  606. startSeg = current;
  607. }
  608. else if (startOffset <= current->size)
  609. {
  610. if ((nullptr == current->next) || (startIndex < current->next->left))
  611. {
  612. startPrev = prev;
  613. startSeg = current;
  614. }
  615. }
  616. }
  617. if (!endSeg)
  618. {
  619. if (endIndex <= current->left)
  620. {
  621. endSeg = current;
  622. break;
  623. }
  624. else if (endOffset <= current->size)
  625. {
  626. if ((nullptr == current->next) || (endIndex < current->next->left))
  627. {
  628. endSeg = current;
  629. break;
  630. }
  631. }
  632. }
  633. prev = current;
  634. current = (SparseArraySegment<T>*)current->next;
  635. }
  636. if (!startSeg && !endSeg)
  637. {
  638. startPrev = prev;
  639. }
  640. };
  641. const auto ResizeArrayIfStartIsOutsideArrayLength = [&]()
  642. {
  643. Assert(endSeg == nullptr);
  644. Assert(startIndex >= head->size);
  645. // Reallocate head if it meets a heuristics
  646. if (startPrev == head // prev segment is the head segment
  647. && !head->next // There is only one head segment in the array
  648. && startIndex - head->size <= MergeSegmentsLengthHeuristics // Distance to next index is relatively small
  649. )
  650. {
  651. current = ((Js::SparseArraySegment<T>*)head)->GrowByMin(recycler, startIndex + length - head->size);
  652. current->length = endIndex + 1;
  653. head = current;
  654. SetHasNoMissingValues(false);
  655. }
  656. else
  657. {
  658. //itemIndex is greater than the (left + size) of last segment in the linked list
  659. current = SparseArraySegment<T>::AllocateSegment(recycler, startIndex, length, (SparseArraySegment<T> *)nullptr);
  660. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  661. current->length = length;
  662. if (current == head)
  663. {
  664. Assert(startIndex == 0);
  665. Assert(current->length == length);
  666. SetHasNoMissingValues();
  667. }
  668. }
  669. };
  670. const auto ExtendStartSegmentForMemOp = [&]()
  671. {
  672. startOffset = startIndex - startSeg->left;
  673. if ((startIndex >= startSeg->left) && (startOffset < startSeg->size))
  674. {
  675. // startIndex is within startSeg
  676. if ((startOffset + length) > startSeg->size)
  677. {
  678. // if we don't have enough space in startSeg
  679. growby = length - (startSeg->size - startOffset);
  680. current = ((Js::SparseArraySegment<T>*)startSeg)->GrowByMin(recycler, growby);
  681. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  682. if (current == head)
  683. {
  684. if (startIndex > current->length)
  685. {
  686. // if it's the head segment and memset starts after the segment length, missing value is introduced
  687. SetHasNoMissingValues(false);
  688. }
  689. else if (!HasNoMissingValues())
  690. {
  691. // Have we overwritten all the missing values?
  692. if (!ScanForMissingValues<T>(0, startOffset))
  693. {
  694. SetHasNoMissingValues();
  695. }
  696. }
  697. }
  698. current->length = startOffset + length;
  699. }
  700. else
  701. {
  702. // if we have enough space in the startseg
  703. current = (Js::SparseArraySegment<T>*)startSeg;
  704. if (current == head)
  705. {
  706. if (startIndex > current->length)
  707. {
  708. // if it's the head segment and memset starts after the segment length, missing value is introduced
  709. SetHasNoMissingValues(false);
  710. }
  711. else if (!HasNoMissingValues())
  712. {
  713. // Have we overwritten all the missing values?
  714. if (!ScanForMissingValues<T>(0, startOffset))
  715. {
  716. SetHasNoMissingValues();
  717. }
  718. }
  719. }
  720. current->length = current->length > (startOffset + length) ? current->length : (startOffset + length);
  721. }
  722. }
  723. else if ((startIndex + 1) <= startSeg->left)
  724. {
  725. if (startIndex + 1 == startSeg->left && startPrev == head)
  726. {
  727. current = ((Js::SparseArraySegment<T>*)head)->GrowByMin(recycler, startIndex + length - head->size);
  728. current->length = endIndex + 1;
  729. head = current;
  730. }
  731. else
  732. {
  733. // startIndex is in between prev and startIndex
  734. current = SparseArraySegment<T>::AllocateSegment(recycler, startIndex, length, (SparseArraySegment<T> *)nullptr);
  735. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  736. if (current == head)
  737. {
  738. SetHasNoMissingValues();
  739. }
  740. current->length = length;
  741. }
  742. }
  743. else
  744. {
  745. Assert(startIndex == startSeg->left + startSeg->size);
  746. current = ((Js::SparseArraySegment<T>*)startSeg)->GrowByMin(recycler, length);
  747. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  748. if (current == head)
  749. {
  750. if (startIndex > current->length)
  751. {
  752. // if it's the head segment and memset starts after the segment length, missing value is introduced
  753. SetHasNoMissingValues(false);
  754. }
  755. }
  756. current->length = startOffset + length;
  757. }
  758. startSeg = current;
  759. };
  760. const auto AppendLeftOverItemsFromEndSegment = [&]()
  761. {
  762. if (!endSeg)
  763. {
  764. // end is beyond the length of the array
  765. Assert(endIndex == this->length - 1);
  766. current->next = nullptr;
  767. }
  768. else
  769. {
  770. endOffset = endIndex - endSeg->left;
  771. startOffset = startIndex - current->left;
  772. if ((endIndex >= endSeg->left) && (endOffset < endSeg->size))
  773. {
  774. // endIndex is within endSeg
  775. if (endSeg->length - 1 > endOffset)
  776. {
  777. if (startSeg != endSeg)
  778. {
  779. // we have some leftover items on endseg
  780. growby = (endSeg->length - endOffset - 1);
  781. current = ((Js::SparseArraySegment<T>*)current)->GrowByMin(recycler, growby);
  782. js_memcpy_s(((Js::SparseArraySegment<T>*)current)->elements + startOffset + length, sizeof(T)* growby, ((Js::SparseArraySegment<T>*)endSeg)->elements + endOffset + 1, sizeof(T)* growby);
  783. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  784. current->length = startOffset + length + growby;
  785. }
  786. if (current == head && HasNoMissingValues())
  787. {
  788. if (ScanForMissingValues<T>(startOffset + length, current->length))
  789. {
  790. SetHasNoMissingValues(false);
  791. }
  792. }
  793. }
  794. current->next = endSeg->next;
  795. }
  796. else if ((endIndex + 1) <= endSeg->left)
  797. {
  798. // endIndex is between endSeg and the segment before
  799. if (endIndex + 1 == endSeg->left && current == head)
  800. {
  801. // extend current to hold endSeg
  802. growby = endSeg->length;
  803. current = ((Js::SparseArraySegment<T>*)current)->GrowByMin(recycler, growby);
  804. js_memcpy_s(((Js::SparseArraySegment<T>*)current)->elements + endIndex + 1, sizeof(T)* endSeg->length, ((Js::SparseArraySegment<T>*)endSeg)->elements, sizeof(T)* endSeg->length);
  805. LinkSegments((Js::SparseArraySegment<T>*)startPrev, current);
  806. if (HasNoMissingValues())
  807. {
  808. if (ScanForMissingValues<T>(endIndex + 1, endIndex + growby))
  809. {
  810. SetHasNoMissingValues(false);
  811. }
  812. }
  813. current->length = endIndex + growby + 1;
  814. current->next = endSeg->next;
  815. }
  816. else
  817. {
  818. current->next = endSeg;
  819. }
  820. }
  821. else
  822. {
  823. //endIndex is at the boundary of endSeg segment at the left + size
  824. Assert(endIndex == endSeg->left + endSeg->size);
  825. current->next = endSeg->next;
  826. }
  827. }
  828. };
  829. FindStartAndEndSegment();
  830. if (startSeg == nullptr)
  831. {
  832. // if start index is greater than array length then we can add a new segment (or extend the last segment based on some heuristics)
  833. ResizeArrayIfStartIsOutsideArrayLength();
  834. }
  835. else
  836. {
  837. // once we found the start segment we extend the start segment until startIndex+length . We don't care about what was there
  838. // as they will be overwritten by the memset/ memcopy. Then we need to append items from the (startIndex+length) to array.length
  839. // from the end segment to the new array
  840. ExtendStartSegmentForMemOp();
  841. AppendLeftOverItemsFromEndSegment();
  842. }
  843. Assert(current);
  844. Assert(current->left <= startIndex);
  845. Assert((startIndex - current->left) < current->size);
  846. return current;
  847. }
  848. template<typename T>
  849. void JavascriptArray::DirectSetItemAtRangeFromArray(uint32 toStartIndex, uint32 length, JavascriptArray *fromArray, uint32 fromStartIndex)
  850. {
  851. if (length == 0)
  852. {
  853. return;
  854. }
  855. bool isBtree = false;
  856. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  857. isBtree = Js::Configuration::Global.flags.ForceArrayBTree;
  858. #endif
  859. if (GetSegmentMap() || fromArray->GetSegmentMap() || isBtree)
  860. {
  861. for (uint i = 0; i < length; i++)
  862. {
  863. T val;
  864. if (fromArray->DirectGetItemAt(fromStartIndex + i, &val))
  865. {
  866. DirectSetItem_Full(toStartIndex + i, val);
  867. }
  868. }
  869. return;
  870. }
  871. SparseArraySegment<T> *toSegment = PrepareSegmentForMemOp<T>(toStartIndex, length);
  872. Assert(fromArray->head);
  873. Assert(fromArray->length >= (fromStartIndex + length));
  874. //Find the segment where itemIndex is present or is at the boundary
  875. SparseArraySegmentBase* current = fromArray->GetBeginLookupSegment(fromStartIndex, false);
  876. Assert(current);
  877. Assert(GetSegmentMap() == nullptr && fromArray->GetSegmentMap() == nullptr);
  878. while (current && length)
  879. {
  880. int memcopySize = length;
  881. int startOffset;
  882. if (fromStartIndex >= current->left && fromStartIndex < (current->left + current->length))
  883. {
  884. startOffset = fromStartIndex - current->left;
  885. if ((startOffset + length) > current->length)
  886. {
  887. memcopySize = current->length - startOffset;
  888. }
  889. js_memcpy_s(toSegment->elements + toStartIndex, memcopySize * sizeof(T), (((Js::SparseArraySegment<T>*)current)->elements + startOffset), memcopySize * sizeof(T));
  890. fromArray->SetLastUsedSegment(current);
  891. fromStartIndex = fromStartIndex + memcopySize;
  892. toStartIndex = toStartIndex + memcopySize;
  893. length = length - memcopySize;
  894. }
  895. current = current->next;
  896. }
  897. Assert(length == 0);
  898. this->SetLastUsedSegment(toSegment);
  899. #if DBG
  900. if (Js::Configuration::Global.flags.MemOpMissingValueValidate)
  901. {
  902. if (toSegment == head)
  903. {
  904. Assert(ScanForMissingValues<T>(0, this->length) != HasNoMissingValues());
  905. }
  906. }
  907. #endif
  908. }
  909. template<typename T>
  910. void JavascriptArray::DirectSetItemAtRange(uint32 startIndex, uint32 length, T newValue)
  911. {
  912. if (startIndex == 0 && head != EmptySegment && length < head->size)
  913. {
  914. if (newValue == (T)0 || newValue == (T)(-1))
  915. {
  916. memset(((Js::SparseArraySegment<T>*)head)->elements, ((int)(intptr_t)newValue), sizeof(T)* length);
  917. }
  918. else
  919. {
  920. Js::SparseArraySegment<T>* headSegment = ((Js::SparseArraySegment<T>*)head);
  921. for (uint32 i = 0; i < length; i++)
  922. {
  923. headSegment->elements[i] = newValue;
  924. }
  925. }
  926. if (length > this->length)
  927. {
  928. this->length = length;
  929. }
  930. if (length > head->length)
  931. {
  932. head->length = length;
  933. }
  934. if (!HasNoMissingValues())
  935. {
  936. if (ScanForMissingValues<T>(length, head->length) == false)
  937. {
  938. SetHasNoMissingValues(true);
  939. }
  940. }
  941. this->SetLastUsedSegment(head);
  942. }
  943. else if (startIndex == 0 && length > this->length && (head == EmptySegment || length > head->size))
  944. {
  945. Recycler *recycler = GetRecycler();
  946. this->length = length;
  947. this->EnsureHead<T>();
  948. SparseArraySegmentBase* current = nullptr;
  949. Assert(head->size < length);
  950. current = SparseArraySegment<T>::AllocateSegment(recycler, 0, length, (SparseArraySegment<T> *)nullptr);
  951. this->SetHeadAndLastUsedSegment(current);
  952. Assert(!HasSegmentMap());
  953. SetHasNoMissingValues(true);
  954. if (newValue == (T)0 || newValue == (T)(-1))
  955. {
  956. memset(((Js::SparseArraySegment<T>*)current)->elements, ((int)(intptr_t)newValue), sizeof(T)* length);
  957. }
  958. else
  959. {
  960. for (uint32 i = 0; i < length; i++)
  961. {
  962. ((Js::SparseArraySegment<T>*)current)->elements[i] = newValue;
  963. }
  964. }
  965. this->SetLastUsedSegment(current);
  966. }
  967. else
  968. {
  969. DirectSetItemAtRangeFull<T>(startIndex, length, newValue);
  970. }
  971. }
  972. template<typename T>
  973. void JavascriptArray::DirectSetItemAtRangeFull(uint32 startIndex, uint32 length, T newValue)
  974. {
  975. if (length == 0)
  976. {
  977. return;
  978. }
  979. bool isBtree = false;
  980. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  981. isBtree = Js::Configuration::Global.flags.ForceArrayBTree;
  982. #endif
  983. if (GetSegmentMap() || isBtree)
  984. {
  985. for (uint i = startIndex; i < startIndex + length; i++)
  986. {
  987. DirectSetItem_Full<T>(i, newValue);
  988. }
  989. return;
  990. }
  991. SparseArraySegment<T> *current = PrepareSegmentForMemOp<T>(startIndex, length);
  992. if (newValue == (T)0 || newValue == (T)(-1))
  993. {
  994. memset((((Js::SparseArraySegment<T>*)current)->elements + (startIndex - current->left)), ((int)(intptr_t)newValue), sizeof(T)* length);
  995. }
  996. else
  997. {
  998. for (uint32 i = 0; i < length; i++)
  999. {
  1000. ((Js::SparseArraySegment<T>*)current)->elements[startIndex - current->left + i] = newValue;
  1001. }
  1002. }
  1003. this->SetLastUsedSegment(current);
  1004. #if DBG
  1005. if (Js::Configuration::Global.flags.MemOpMissingValueValidate)
  1006. {
  1007. if (current == head)
  1008. {
  1009. Assert(ScanForMissingValues<T>(0, this->length) != HasNoMissingValues());
  1010. }
  1011. }
  1012. #endif
  1013. }
  1014. template<typename T>
  1015. void JavascriptArray::DirectSetItem_Full(uint32 itemIndex, T newValue)
  1016. {
  1017. DebugOnly(VerifyNotNeedMarshal(newValue));
  1018. this->EnsureHead<T>();
  1019. AnalysisAssert(head);
  1020. #ifdef VALIDATE_ARRAY
  1021. ValidateArray();
  1022. #endif
  1023. if (itemIndex >= this->length)
  1024. {
  1025. if (itemIndex != JavascriptArray::InvalidIndex)
  1026. {
  1027. this->length = itemIndex + 1;
  1028. }
  1029. else
  1030. {
  1031. JavascriptError::ThrowRangeError(this->GetScriptContext(), JSERR_ArrayLengthAssignIncorrect);
  1032. }
  1033. }
  1034. Recycler* recycler = GetRecycler();
  1035. //Find the segment where itemIndex is present or is at the boundary
  1036. SparseArraySegment<T>* current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(itemIndex, false);
  1037. // If it doesn't fit in current chunk (watch for overflow), start from beginning as we'll
  1038. // need the prev
  1039. if (current->left + current->size > current->left || itemIndex >= current->left + current->size)
  1040. {
  1041. current = (SparseArraySegment<T>*)head;
  1042. }
  1043. SparseArraySegmentBase* prev = nullptr;
  1044. #ifdef VALIDATE_ARRAY
  1045. SparseArraySegmentBase* current_btree = nullptr;
  1046. SparseArraySegmentBase* prev_btree = nullptr;
  1047. bool first_pass = true;
  1048. #endif
  1049. SegmentBTreeRoot * segmentMap = GetSegmentMap();
  1050. if (segmentMap)
  1051. {
  1052. SparseArraySegmentBase* prevSeg = nullptr;
  1053. SparseArraySegmentBase* currentBase = current;
  1054. segmentMap->Find(itemIndex, prevSeg, currentBase);
  1055. current = (SparseArraySegment<T>*)currentBase;
  1056. Assert(!prevSeg || prevSeg->next == current);
  1057. if (prevSeg)
  1058. {
  1059. bool noExactMatch = !current || itemIndex < current->left;
  1060. Assert(prevSeg->left + prevSeg->size >= prevSeg->left);
  1061. bool extendPrevSeg = itemIndex <= prevSeg->left + prevSeg->size;
  1062. if (noExactMatch && extendPrevSeg)
  1063. {
  1064. current = (SparseArraySegment<T>*)head;
  1065. prev = nullptr;
  1066. if (prevSeg != head)
  1067. {
  1068. // Since we are going to extend prevSeg we need the
  1069. // address of it's left neighbor's next pointer
  1070. currentBase = current;
  1071. segmentMap->Find(prevSeg->left, prevSeg, currentBase);
  1072. current = (SparseArraySegment<T>*)currentBase;
  1073. Assert(prevSeg && prevSeg->next == current);
  1074. prev = prevSeg;
  1075. }
  1076. }
  1077. else
  1078. {
  1079. prev = prevSeg;
  1080. }
  1081. }
  1082. else
  1083. {
  1084. Assert(current == head);
  1085. }
  1086. #ifdef VALIDATE_ARRAY
  1087. SECOND_PASS:
  1088. if (!first_pass)
  1089. {
  1090. current = (SparseArraySegment<T>*)this->GetBeginLookupSegment(itemIndex, false);
  1091. // If it doesn't fit in current chunk (watch for overflow), start from beginning as we'll
  1092. // need the prev
  1093. if (current->left + current->size > current->left || itemIndex >= current->left + current->size)
  1094. {
  1095. current = (SparseArraySegment<T>*)head;
  1096. }
  1097. prev = nullptr;
  1098. }
  1099. #endif
  1100. }
  1101. uint probeCost = 0;
  1102. while(current != nullptr)
  1103. {
  1104. uint32 offset = itemIndex - current->left;
  1105. if (itemIndex < current->left)
  1106. {
  1107. break;
  1108. }
  1109. else if (offset <= current->size)
  1110. {
  1111. if ((nullptr == current->next) || (itemIndex < current->next->left))
  1112. {
  1113. break;
  1114. }
  1115. }
  1116. prev = current;
  1117. current = (SparseArraySegment<T>*)current->next;
  1118. Assert(segmentMap == GetSegmentMap());
  1119. if (!segmentMap)
  1120. {
  1121. probeCost++;
  1122. if (probeCost > SegmentBTree::GetLazyCrossOverLimit())
  1123. {
  1124. // Build a SegmentMap
  1125. segmentMap = BuildSegmentMap();
  1126. SparseArraySegmentBase* prevSeg = nullptr;
  1127. SparseArraySegmentBase* currentBase = current;
  1128. segmentMap->Find(itemIndex, prevSeg, currentBase);
  1129. current = (SparseArraySegment<T>*)currentBase;
  1130. Assert(prevSeg->next == current);
  1131. if (prevSeg)
  1132. {
  1133. bool noExactMatch = !current || itemIndex < current->left;
  1134. Assert(prevSeg->left + prevSeg->size >= prevSeg->left);
  1135. bool extendPrevSeg = itemIndex <= prevSeg->left + prevSeg->size;
  1136. if (noExactMatch && extendPrevSeg)
  1137. {
  1138. current = (SparseArraySegment<T>*)head;
  1139. prev = nullptr;
  1140. if (prevSeg != head)
  1141. {
  1142. // Since we are going to extend prevSeg we need the
  1143. // address of its left neighbor's next pointer
  1144. currentBase = current;
  1145. segmentMap->Find(prevSeg->left, prevSeg, currentBase);
  1146. current = (SparseArraySegment<T>*)currentBase;
  1147. Assert(prevSeg->next == current);
  1148. prev = prevSeg;
  1149. }
  1150. }
  1151. else
  1152. {
  1153. prev = prevSeg;
  1154. }
  1155. }
  1156. else
  1157. {
  1158. Assert(current == head);
  1159. }
  1160. }
  1161. }
  1162. }
  1163. #ifdef VALIDATE_ARRAY
  1164. Assert(segmentMap == GetSegmentMap());
  1165. if (segmentMap && first_pass)
  1166. {
  1167. current_btree = current;
  1168. prev_btree = prev;
  1169. first_pass = false;
  1170. goto SECOND_PASS;
  1171. }
  1172. else if (segmentMap)
  1173. {
  1174. Assert(current_btree == current && prev_btree == prev);
  1175. }
  1176. #endif
  1177. if (current != nullptr)
  1178. {
  1179. uint32 offset = itemIndex - current->left;
  1180. if ((itemIndex >= current->left) && (offset < current->size))
  1181. {
  1182. //itemIndex lies in the segment
  1183. Assert(!(HasNoMissingValues() &&
  1184. offset < current->length &&
  1185. SparseArraySegment<T>::IsMissingItem(&current->elements[offset]) &&
  1186. current == head));
  1187. if(offset > current->length && current == head)
  1188. {
  1189. SetHasNoMissingValues(false);
  1190. }
  1191. const bool scanForMissingValues = NeedScanForMissingValuesUponSetItem(current, offset);
  1192. ((SparseArraySegment<T>*)current)->SetElement(recycler, itemIndex, newValue);
  1193. if(scanForMissingValues)
  1194. {
  1195. ScanForMissingValues<T>();
  1196. }
  1197. }
  1198. else if ((itemIndex + 1) < current->left)
  1199. {
  1200. //itemIndex lies in between current and previous segment
  1201. SparseArraySegment<T>* newSeg = SparseArraySegment<T>::AllocateSegment(recycler, prev, itemIndex);
  1202. newSeg->SetElement(recycler, itemIndex, newValue);
  1203. newSeg->next = current;
  1204. LinkSegments((SparseArraySegment<T>*)prev, newSeg);
  1205. current = newSeg;
  1206. TryAddToSegmentMap(recycler, newSeg);
  1207. Assert(current != head);
  1208. }
  1209. else
  1210. {
  1211. //itemIndex is at boundary of current segment either at the left + size or at left - 1;
  1212. Assert((itemIndex == current->left + current->size) || (itemIndex + 1 == current->left));
  1213. SparseArraySegment<T>* next = (SparseArraySegment<T>*)current->next;
  1214. Assert(segmentMap == GetSegmentMap());
  1215. if (!segmentMap && next != nullptr && (itemIndex + 1) == next->left)
  1216. {
  1217. // Don't merge segments if we are using a segmentMap
  1218. //Special case where we need to merge two segments. itemIndex is on the size boundary
  1219. //of the current segment & left boundary of the next
  1220. const bool currentWasFull = current->length == current->size;
  1221. Assert(itemIndex == current->left + current->size);
  1222. current = SparseArraySegment<T>::CopySegment(recycler, (SparseArraySegment<T>*)current, next->left, next, next->left, next->length);
  1223. current->next = next->next;
  1224. current->SetElement(recycler, itemIndex, newValue);
  1225. LinkSegments((SparseArraySegment<T>*)prev, current);
  1226. if(HasNoMissingValues() && current == head)
  1227. {
  1228. // We just merged the head segment and its next segment and filled the only missing value in-between the
  1229. // two segments. We already know that the previous head segment does not have any missing values. If the
  1230. // previous head segment was full, scan the new head segment starting from the merge point for missing
  1231. // values. If the previous head segment was not full, then merging the segments would have created
  1232. // missing values.
  1233. SetHasNoMissingValues(false);
  1234. if(currentWasFull)
  1235. {
  1236. ScanForMissingValues<T>(offset + 1);
  1237. }
  1238. }
  1239. }
  1240. else
  1241. {
  1242. if(offset > current->length && current == head)
  1243. {
  1244. SetHasNoMissingValues(false);
  1245. }
  1246. const bool currentWasHead = current == head;
  1247. SparseArraySegmentBase* oldSegment = current;
  1248. uint originalKey = oldSegment->left;
  1249. current = current->SetElementGrow(recycler, prev, itemIndex, newValue);
  1250. Assert(segmentMap == GetSegmentMap());
  1251. if (segmentMap)
  1252. {
  1253. segmentMap->SwapSegment(originalKey, oldSegment, current);
  1254. }
  1255. LinkSegments((SparseArraySegment<T>*)prev, current);
  1256. // Scan for missing values when the current segment was grown at the beginning and made the head segment
  1257. if(!currentWasHead && current == head)
  1258. {
  1259. ScanForMissingValues<T>();
  1260. }
  1261. }
  1262. }
  1263. }
  1264. else
  1265. {
  1266. // Reallocate head if need it meets a heuristics
  1267. Assert(itemIndex >= head->size);
  1268. if (prev == head // prev segment is the head segment
  1269. && !head->next // There is only one head segment in the array
  1270. && !segmentMap // There is no segmentMap which makes sure that array is not highly fragmented.
  1271. && itemIndex - head->size <= MergeSegmentsLengthHeuristics // Distance to next index is relatively small
  1272. )
  1273. {
  1274. current = ((Js::SparseArraySegment<T>*)head)->GrowByMin(recycler, itemIndex + 1 - head->size);
  1275. current->elements[itemIndex] = newValue;
  1276. current->length = itemIndex + 1;
  1277. head = current;
  1278. SetHasNoMissingValues(false);
  1279. }
  1280. else
  1281. {
  1282. //itemIndex is greater than the (left + size) of last segment in the linked list
  1283. current = SparseArraySegment<T>::AllocateSegment(recycler, itemIndex, 1, (SparseArraySegment<T> *)nullptr);
  1284. current->SetElement(recycler, itemIndex, newValue);
  1285. LinkSegments((SparseArraySegment<T>*)prev, current);
  1286. TryAddToSegmentMap(recycler, current);
  1287. if(current == head)
  1288. {
  1289. Assert(itemIndex == 0);
  1290. Assert(current->length == 1);
  1291. SetHasNoMissingValues();
  1292. }
  1293. }
  1294. }
  1295. this->SetLastUsedSegment(current);
  1296. #ifdef VALIDATE_ARRAY
  1297. ValidateArray();
  1298. #endif
  1299. }
  1300. template<typename T>
  1301. bool JavascriptArray::NeedScanForMissingValuesUponSetItem(SparseArraySegment<T> *const segment, const uint32 offset) const
  1302. {
  1303. Assert(segment);
  1304. // Scan for missing values upon SetItem when a missing value is being filled and the surrounding values are not missing,
  1305. // as this could be the last missing value that is being filled
  1306. return
  1307. offset < segment->length &&
  1308. SparseArraySegment<T>::IsMissingItem(&segment->elements[offset]) &&
  1309. (offset == 0 || !SparseArraySegment<T>::IsMissingItem(&segment->elements[offset - 1])) &&
  1310. (offset == segment->length - 1 || !SparseArraySegment<T>::IsMissingItem(&segment->elements[offset + 1])) &&
  1311. segment == head;
  1312. }
  1313. template<typename T>
  1314. void JavascriptArray::ScanForMissingValues(const uint startIndex)
  1315. {
  1316. Assert(head);
  1317. Assert(!HasNoMissingValues());
  1318. SparseArraySegment<T> *const segment = (SparseArraySegment<T>*)head;
  1319. const uint segmentLength = segment->length;
  1320. const T *const segmentElements = segment->elements;
  1321. for(uint i = startIndex; i < segmentLength; ++i)
  1322. {
  1323. if(SparseArraySegment<T>::IsMissingItem(&segmentElements[i]))
  1324. {
  1325. return;
  1326. }
  1327. }
  1328. SetHasNoMissingValues();
  1329. }
  1330. template<typename T>
  1331. bool JavascriptArray::ScanForMissingValues(const uint startIndex, const uint endIndex)
  1332. {
  1333. Assert(head);
  1334. //Assert(!HasNoMissingValues());
  1335. SparseArraySegment<T> *const segment = (SparseArraySegment<T>*)head;
  1336. const T *const segmentElements = segment->elements;
  1337. for (uint i = startIndex; i < endIndex; ++i)
  1338. {
  1339. if (SparseArraySegment<T>::IsMissingItem(&segmentElements[i]))
  1340. {
  1341. return true;
  1342. }
  1343. }
  1344. return false;
  1345. }
  1346. inline void JavascriptArray::DirectSetItemIfNotExist(uint32 index, Var newValue)
  1347. {
  1348. Assert(VirtualTableInfo<JavascriptArray>::HasVirtualTable(this));
  1349. Var oldValue;
  1350. if (!DirectGetItemAt(index, &oldValue))
  1351. {
  1352. DirectSetItemAt(index, newValue);
  1353. }
  1354. }
  1355. //Grow the array head and try to set at the boundary
  1356. template<typename unitType, typename classname>
  1357. inline BOOL JavascriptArray::TryGrowHeadSegmentAndSetItem(uint32 indexInt, unitType iValue)
  1358. {
  1359. SparseArraySegment<unitType> *current = (SparseArraySegment<unitType> *)this->head;
  1360. if (indexInt == current->length // index is at the boundary of size & length
  1361. && current->size // Make sure its not empty segment.
  1362. && !current->next // There is only head segment.
  1363. && current->length == current->size // Why did we miss the fastpath?
  1364. && !SparseArraySegment<unitType>::IsMissingItem(&iValue)) // value to set is not a missing value.
  1365. {
  1366. current= current->GrowByMin(this->GetRecycler(), indexInt + 1);
  1367. DebugOnly(VerifyNotNeedMarshal(iValue));
  1368. current->elements[indexInt] = iValue;
  1369. current->length = indexInt + 1;
  1370. // There is only a head segment in this condition A segment map is not necessary
  1371. // and most likely invalid at this point. Also we are setting the head and lastUsedSegment
  1372. // to the same segment. Precedent in the rest of the code base dictates the use of
  1373. // SetHeadAndLastUsedSegment which asserts if a segment map exists.
  1374. ClearSegmentMap();
  1375. SetHeadAndLastUsedSegment(current);
  1376. if (this->length <= indexInt)
  1377. {
  1378. this->length = indexInt + 1;
  1379. }
  1380. #ifdef VALIDATE_ARRAY
  1381. ValidateArray();
  1382. #endif
  1383. return true;
  1384. }
  1385. return false;
  1386. }
  1387. //
  1388. // JavascriptArray::IndexTrace specialized on uint32 (small index)
  1389. //
  1390. template<>
  1391. inline Var JavascriptArray::IndexTrace<uint32>::ToNumber(const uint32& index, ScriptContext* scriptContext)
  1392. {
  1393. return JavascriptNumber::ToVar(index, scriptContext);
  1394. }
  1395. template<>
  1396. inline BOOL JavascriptArray::IndexTrace<uint32>::GetItem(JavascriptArray* arr, const uint32& index, Var* outVal)
  1397. {
  1398. return arr->DirectGetItemAt(index, outVal);
  1399. }
  1400. template<>
  1401. inline BOOL JavascriptArray::IndexTrace<uint32>::SetItem(JavascriptArray* arr, const uint32& index, Var newValue)
  1402. {
  1403. return arr->SetItem(index, newValue, PropertyOperation_None);
  1404. }
  1405. template<>
  1406. inline void JavascriptArray::IndexTrace<uint32>::SetItemIfNotExist(JavascriptArray* arr, const uint32& index, Var newValue)
  1407. {
  1408. arr->DirectSetItemIfNotExist(index, newValue);
  1409. }
  1410. template<>
  1411. inline BOOL JavascriptArray::IndexTrace<uint32>::DeleteItem(JavascriptArray* arr, const uint32& index)
  1412. {
  1413. switch (arr->GetTypeId())
  1414. {
  1415. case TypeIds_Array:
  1416. return arr->DirectDeleteItemAt<Var>(index);
  1417. case TypeIds_NativeIntArray:
  1418. return arr->DirectDeleteItemAt<int32>(index);
  1419. case TypeIds_NativeFloatArray:
  1420. return arr->DirectDeleteItemAt<double>(index);
  1421. default:
  1422. Assert(FALSE);
  1423. return FALSE;
  1424. }
  1425. }
  1426. template<>
  1427. inline BOOL JavascriptArray::IndexTrace<uint32>::SetItem(RecyclableObject* obj, const uint32& index, Var newValue, PropertyOperationFlags flags)
  1428. {
  1429. ScriptContext* requestContext = obj->GetScriptContext();
  1430. return JavascriptOperators::SetItem(obj, obj, index, newValue, requestContext, flags);
  1431. }
  1432. template<>
  1433. inline BOOL JavascriptArray::IndexTrace<uint32>::DeleteItem(RecyclableObject* obj, const uint32& index, PropertyOperationFlags flags)
  1434. {
  1435. return JavascriptOperators::DeleteItem(obj, index, flags);
  1436. }
  1437. //
  1438. // JavascriptArray::IndexTrace specialized on BigIndex
  1439. //
  1440. template<>
  1441. inline Var JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::ToNumber(const JavascriptArray::BigIndex& index, ScriptContext* scriptContext)
  1442. {
  1443. return index.ToNumber(scriptContext);
  1444. }
  1445. template<>
  1446. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::GetItem(JavascriptArray* arr, const JavascriptArray::BigIndex& index, Var* outVal)
  1447. {
  1448. return index.GetItem(arr, outVal);
  1449. }
  1450. template<>
  1451. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::SetItem(JavascriptArray* arr, const JavascriptArray::BigIndex& index, Var newValue)
  1452. {
  1453. return index.SetItem(arr, newValue);
  1454. }
  1455. template<>
  1456. inline void JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::SetItemIfNotExist(JavascriptArray* arr, const JavascriptArray::BigIndex& index, Var newValue)
  1457. {
  1458. index.SetItemIfNotExist(arr, newValue);
  1459. }
  1460. template<>
  1461. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::DeleteItem(JavascriptArray* arr, const JavascriptArray::BigIndex& index)
  1462. {
  1463. return index.DeleteItem(arr);
  1464. }
  1465. template<>
  1466. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::SetItem(RecyclableObject* obj, const JavascriptArray::BigIndex& index, Var newValue, PropertyOperationFlags flags)
  1467. {
  1468. return index.SetItem(obj, newValue, flags);
  1469. }
  1470. template<>
  1471. inline BOOL JavascriptArray::IndexTrace<JavascriptArray::BigIndex>::DeleteItem(RecyclableObject* obj, const JavascriptArray::BigIndex& index, PropertyOperationFlags flags)
  1472. {
  1473. return index.DeleteItem(obj, flags);
  1474. }
  1475. template<class T, uint InlinePropertySlots>
  1476. __inline size_t JavascriptArray::DetermineAllocationSize(
  1477. const uint inlineElementSlots,
  1478. size_t *const allocationPlusSizeRef,
  1479. uint *const alignedInlineElementSlotsRef)
  1480. {
  1481. CompileAssert(static_cast<PropertyIndex>(InlinePropertySlots) == InlinePropertySlots);
  1482. Assert(
  1483. DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(InlinePropertySlots)) ==
  1484. InlinePropertySlots);
  1485. CompileAssert(
  1486. InlinePropertySlots <=
  1487. (UINT_MAX - (sizeof(T) + sizeof(SparseArraySegment<typename T::TElement>))) / sizeof(Var));
  1488. const uint objectSize =
  1489. sizeof(T) + sizeof(SparseArraySegment<typename T::TElement>) + InlinePropertySlots * sizeof(Var);
  1490. size_t totalSize = UInt32Math::MulAdd<sizeof(typename T::TElement), objectSize>(inlineElementSlots);
  1491. #if defined(_M_X64_OR_ARM64)
  1492. // On x64, the total size won't be anywhere near AllocSizeMath::MaxMemory on x64, so no need to check
  1493. totalSize = HeapInfo::GetAlignedSizeNoCheck(totalSize);
  1494. #else
  1495. totalSize = HeapInfo::GetAlignedSize(totalSize);
  1496. #endif
  1497. if(allocationPlusSizeRef)
  1498. {
  1499. *allocationPlusSizeRef = totalSize - sizeof(T);
  1500. }
  1501. if(alignedInlineElementSlotsRef)
  1502. {
  1503. const size_t alignedInlineElementSlots = (totalSize - objectSize) / sizeof(typename T::TElement);
  1504. *alignedInlineElementSlotsRef = static_cast<uint>(alignedInlineElementSlots);
  1505. Assert(*alignedInlineElementSlotsRef == alignedInlineElementSlots); // ensure no truncation above
  1506. }
  1507. return totalSize;
  1508. }
  1509. template<class T, uint InlinePropertySlots>
  1510. __inline uint JavascriptArray::DetermineAvailableInlineElementSlots(
  1511. const size_t allocationSize,
  1512. bool *const isSufficientSpaceForInlinePropertySlotsRef)
  1513. {
  1514. CompileAssert(static_cast<PropertyIndex>(InlinePropertySlots) == InlinePropertySlots);
  1515. Assert(
  1516. DynamicTypeHandler::RoundUpInlineSlotCapacity(static_cast<PropertyIndex>(InlinePropertySlots)) ==
  1517. InlinePropertySlots);
  1518. Assert(isSufficientSpaceForInlinePropertySlotsRef);
  1519. CompileAssert(
  1520. InlinePropertySlots <=
  1521. (UINT_MAX - (sizeof(T) + sizeof(SparseArraySegment<typename T::TElement>))) / sizeof(Var));
  1522. *isSufficientSpaceForInlinePropertySlotsRef =
  1523. sizeof(T) + InlinePropertySlots * sizeof(Var) + sizeof(SparseArraySegment<typename T::TElement>) <= allocationSize;
  1524. const size_t availableInlineElementSlots =
  1525. (
  1526. allocationSize -
  1527. (sizeof(T) + InlinePropertySlots * sizeof(Var) + sizeof(SparseArraySegment<typename T::TElement>))
  1528. ) / sizeof(typename T::TElement);
  1529. const uint availableInlineElementSlotsUint = static_cast<uint>(availableInlineElementSlots);
  1530. Assert(availableInlineElementSlotsUint == availableInlineElementSlots); // ensure no truncation above
  1531. return availableInlineElementSlotsUint;
  1532. }
  1533. template<class T, uint ConstInlinePropertySlots, bool UseDynamicInlinePropertySlots>
  1534. __inline SparseArraySegment<typename T::TElement> *JavascriptArray::DetermineInlineHeadSegmentPointer(T *const array)
  1535. {
  1536. Assert(array);
  1537. Assert(VirtualTableInfo<T>::HasVirtualTable(array) || VirtualTableInfo<CrossSiteObject<T>>::HasVirtualTable(array));
  1538. Assert(!UseDynamicInlinePropertySlots || ConstInlinePropertySlots == 0);
  1539. Assert(
  1540. UseDynamicInlinePropertySlots ||
  1541. ConstInlinePropertySlots == array->GetTypeHandler()->GetInlineSlotCapacity());
  1542. const uint inlinePropertySlots =
  1543. UseDynamicInlinePropertySlots ? array->GetTypeHandler()->GetInlineSlotCapacity() : ConstInlinePropertySlots;
  1544. Assert(inlinePropertySlots == 0 || array->GetTypeHandler()->GetOffsetOfInlineSlots() == sizeof(T));
  1545. return
  1546. reinterpret_cast<SparseArraySegment<typename T::TElement> *>(
  1547. reinterpret_cast<Var *>(array + 1) + inlinePropertySlots);
  1548. }
  1549. //
  1550. // ItemTrace<T> specializations
  1551. //
  1552. template<>
  1553. inline uint32 JavascriptArray::ItemTrace<JavascriptArray>::GetLength(JavascriptArray* obj, ScriptContext* scriptContext)
  1554. {
  1555. return obj->GetLength();
  1556. }
  1557. template<>
  1558. inline BOOL JavascriptArray::ItemTrace<JavascriptArray>::GetItem(JavascriptArray* obj, uint32 index, Var* outVal, ScriptContext* scriptContext)
  1559. {
  1560. Assert(JavascriptArray::IsDirectAccessArray(obj));
  1561. return obj->DirectGetItemAtFull(index, outVal); // Note this does prototype lookup
  1562. }
  1563. template<>
  1564. inline uint32 JavascriptArray::ItemTrace<RecyclableObject>::GetLength(RecyclableObject* obj, ScriptContext* scriptContext)
  1565. {
  1566. return JavascriptConversion::ToUInt32(JavascriptOperators::OP_GetLength(obj, scriptContext), scriptContext);
  1567. }
  1568. template<>
  1569. inline BOOL JavascriptArray::ItemTrace<RecyclableObject>::GetItem(RecyclableObject* obj, uint32 index, Var* outVal, ScriptContext* scriptContext)
  1570. {
  1571. return JavascriptOperators::GetItem(obj, index, outVal, scriptContext);
  1572. }
  1573. } // namespace Js