JavascriptArray.inl 75 KB

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