Simon Jakobi pushed to branch wip/sjakobi/udfm-placement at Glasgow Haskell Compiler / GHC

Commits:

5 changed files:

Changes:

  • compiler/GHC/Data/Word64Map/Internal.hs
    ... ... @@ -72,6 +72,7 @@ module GHC.Data.Word64Map.Internal (
    72 72
         -- * Query
    
    73 73
         , null
    
    74 74
         , size
    
    75
    +    , compareSize
    
    75 76
         , member
    
    76 77
         , notMember
    
    77 78
         , lookup
    
    ... ... @@ -169,6 +170,7 @@ module GHC.Data.Word64Map.Internal (
    169 170
         , map
    
    170 171
         , mapWithKey
    
    171 172
         , traverseWithKey
    
    173
    +    , traverseWithKey_
    
    172 174
         , traverseMaybeWithKey
    
    173 175
         , mapAccum
    
    174 176
         , mapAccumWithKey
    
    ... ... @@ -522,6 +524,8 @@ null _ = False
    522 524
     -- > size empty                                   == 0
    
    523 525
     -- > size (singleton 1 'a')                       == 1
    
    524 526
     -- > size (fromList([(1,'a'), (2,'c'), (3,'b')])) == 3
    
    527
    +--
    
    528
    +-- See also: 'compareSize'
    
    525 529
     size :: Word64Map a -> Int
    
    526 530
     size = go 0
    
    527 531
       where
    
    ... ... @@ -529,6 +533,23 @@ size = go 0
    529 533
         go acc (Tip _ _) = 1 + acc
    
    530 534
         go acc Nil = acc
    
    531 535
     
    
    536
    +-- | \(O(\min(n,c))\). Compare the number of entries in the map to an @Int@.
    
    537
    +--
    
    538
    +-- @compareSize m c@ returns the same result as @compare ('size' m) c@ but is
    
    539
    +-- more efficient when @c@ is smaller than the size of the map.
    
    540
    +compareSize :: Word64Map a -> Int -> Ordering
    
    541
    +compareSize Nil c0 = compare 0 c0
    
    542
    +compareSize _ c0 | c0 <= 0 = GT
    
    543
    +compareSize t c0 = compare 0 (go t (c0 - 1))
    
    544
    +  where
    
    545
    +    go (Bin _ _ _ _) 0 = -1
    
    546
    +    go (Bin _ _ l r) c
    
    547
    +      | c' < 0 = c'
    
    548
    +      | otherwise = go r c'
    
    549
    +      where
    
    550
    +        c' = go l (c - 1)
    
    551
    +    go _ c = c -- Must be Tip (Nil is never a child of Bin)
    
    552
    +
    
    532 553
     -- | \(O(\min(n,W))\). Is the key a member of the map?
    
    533 554
     --
    
    534 555
     -- > member 5 (fromList [(5,'a'), (3,'b')]) == True
    
    ... ... @@ -2500,6 +2521,18 @@ traverseWithKey f = go
    2500 2521
           | otherwise = liftA2 (Bin p m) (go l) (go r)
    
    2501 2522
     {-# INLINE traverseWithKey #-}
    
    2502 2523
     
    
    2524
    +-- | \(O(n)\). Visit each key\/value pair in ascending key order, discarding
    
    2525
    +-- the results.
    
    2526
    +--
    
    2527
    +-- Unlike @traverse_ . toList@, this builds no intermediate structure.
    
    2528
    +traverseWithKey_ :: Applicative t => (Key -> a -> t ()) -> Word64Map a -> t ()
    
    2529
    +traverseWithKey_ f = go
    
    2530
    +  where
    
    2531
    +    go Nil = pure ()
    
    2532
    +    go (Tip k v) = f k v
    
    2533
    +    go (Bin _ _ l r) = go l *> go r
    
    2534
    +{-# INLINE traverseWithKey_ #-}
    
    2535
    +
    
    2503 2536
     -- | \(O(n)\). The function @'mapAccum'@ threads an accumulating
    
    2504 2537
     -- argument through the map in ascending order of keys.
    
    2505 2538
     --
    

  • compiler/GHC/Data/Word64Map/Lazy.hs
    ... ... @@ -113,6 +113,7 @@ module GHC.Data.Word64Map.Lazy (
    113 113
         -- ** Size
    
    114 114
         , WM.null
    
    115 115
         , size
    
    116
    +    , compareSize
    
    116 117
     
    
    117 118
         -- * Combine
    
    118 119
     
    
    ... ... @@ -148,6 +149,7 @@ module GHC.Data.Word64Map.Lazy (
    148 149
         , WM.map
    
    149 150
         , mapWithKey
    
    150 151
         , traverseWithKey
    
    152
    +    , traverseWithKey_
    
    151 153
         , traverseMaybeWithKey
    
    152 154
         , mapAccum
    
    153 155
         , mapAccumWithKey
    

  • compiler/GHC/Data/Word64Map/Strict.hs
    ... ... @@ -130,6 +130,7 @@ module GHC.Data.Word64Map.Strict (
    130 130
         -- ** Size
    
    131 131
         , null
    
    132 132
         , size
    
    133
    +    , compareSize
    
    133 134
     
    
    134 135
         -- * Combine
    
    135 136
     
    
    ... ... @@ -165,6 +166,7 @@ module GHC.Data.Word64Map.Strict (
    165 166
         , map
    
    166 167
         , mapWithKey
    
    167 168
         , traverseWithKey
    
    169
    +    , traverseWithKey_
    
    168 170
         , traverseMaybeWithKey
    
    169 171
         , mapAccum
    
    170 172
         , mapAccumWithKey
    

  • compiler/GHC/Data/Word64Map/Strict/Internal.hs
    ... ... @@ -132,6 +132,7 @@ module GHC.Data.Word64Map.Strict.Internal (
    132 132
         -- ** Size
    
    133 133
         , null
    
    134 134
         , size
    
    135
    +    , compareSize
    
    135 136
     
    
    136 137
         -- * Combine
    
    137 138
     
    
    ... ... @@ -167,6 +168,7 @@ module GHC.Data.Word64Map.Strict.Internal (
    167 168
         , map
    
    168 169
         , mapWithKey
    
    169 170
         , traverseWithKey
    
    171
    +    , traverseWithKey_
    
    170 172
         , traverseMaybeWithKey
    
    171 173
         , mapAccum
    
    172 174
         , mapAccumWithKey
    
    ... ... @@ -322,12 +324,14 @@ import GHC.Data.Word64Map.Internal
    322 324
       , spanAntitone
    
    323 325
       , restrictKeys
    
    324 326
       , size
    
    327
    +  , compareSize
    
    325 328
       , split
    
    326 329
       , splitLookup
    
    327 330
       , splitRoot
    
    328 331
       , toAscList
    
    329 332
       , toDescList
    
    330 333
       , toList
    
    334
    +  , traverseWithKey_
    
    331 335
       , union
    
    332 336
       , unions
    
    333 337
       , withoutKeys
    

  • compiler/GHC/Types/Unique/DFM.hs
    ... ... @@ -97,9 +97,9 @@ import qualified GHC.Data.Word64Set as W
    97 97
     -- If the client of the map performs operations on the map in deterministic
    
    98 98
     -- order then `udfmToList` returns them in deterministic order.
    
    99 99
     --
    
    100
    --- There is an implementation cost: each element is given a serial number
    
    100
    +-- There is an implementation cost: each element is given an insertion tag
    
    101 101
     -- as it is added, and functions like `udfmToList` or `eltsUDFM` order their
    
    102
    --- results by this serial number (see
    
    102
    +-- results by this tag (see
    
    103 103
     -- Note [Cost of deterministic iteration]). So you should only use `UniqDFM`
    
    104 104
     -- if you need the deterministic property.
    
    105 105
     --
    
    ... ... @@ -114,7 +114,7 @@ import qualified GHC.Data.Word64Set as W
    114 114
     --
    
    115 115
     --
    
    116 116
     -- There's more than one way to implement this. The implementation here tags
    
    117
    --- every value with the insertion time that can later be used to sort the
    
    117
    +-- every value with its insertion tag that can later be used to sort the
    
    118 118
     -- values when asked to convert to a list.
    
    119 119
     --
    
    120 120
     -- An alternative would be to have
    
    ... ... @@ -133,11 +133,11 @@ import qualified GHC.Data.Word64Set as W
    133 133
     --
    
    134 134
     -- may also be worth considering. Compare Dhall.Map in the dhall package.
    
    135 135
     
    
    136
    --- | A type of values tagged with insertion time
    
    136
    +-- | A type of values carrying an insertion tag
    
    137 137
     data TaggedVal val =
    
    138 138
       TaggedVal
    
    139 139
         !val
    
    140
    -    {-# UNPACK #-} !Int -- ^ insertion time
    
    140
    +    {-# UNPACK #-} !Int -- ^ insertion tag
    
    141 141
       deriving stock (Data, Functor, Foldable, Traversable)
    
    142 142
     
    
    143 143
     taggedFst :: TaggedVal val -> val
    
    ... ... @@ -159,13 +159,25 @@ instance Eq val => Eq (TaggedVal val) where
    159 159
     data UniqDFM key ele =
    
    160 160
       UDFM
    
    161 161
         !(M.Word64Map (TaggedVal ele)) -- A map where keys are Unique's values and
    
    162
    -                                -- values are tagged with insertion time.
    
    163
    -                                -- The invariant is that all the tags will
    
    164
    -                                -- be distinct within a single map
    
    162
    +                                -- values carry an insertion tag.
    
    165 163
         {-# UNPACK #-} !Int         -- Upper bound on the values' insertion
    
    166
    -                                -- time. See Note [Overflow on plusUDFM]
    
    164
    +                                -- tags. See Note [Overflow on plusUDFM]
    
    165
    +  -- See Note [UDFM invariants]
    
    167 166
       deriving (Data, Functor)
    
    168 167
     
    
    168
    +{- Note [UDFM invariants]
    
    169
    +~~~~~~~~~~~~~~~~~~~~~~~~~
    
    170
    +In a map (UDFM m ub):
    
    171
    +
    
    172
    + (a) The insertion tags of the elements of m are distinct.
    
    173
    + (b) Every tag lies in [0, ub).
    
    174
    +
    
    175
    +Consequently ub >= size m.
    
    176
    +
    
    177
    +The tags determine the order of deterministic iteration (eltsUDFM,
    
    178
    +udfmToList); see Note [Sorting a UDFM].
    
    179
    +-}
    
    180
    +
    
    169 181
     -- | Deterministic.
    
    170 182
     --
    
    171 183
     -- See Note [Cost of deterministic iteration].
    
    ... ... @@ -266,8 +278,8 @@ plusUDFM_CK f udfml@(UDFM _ i) udfmr@(UDFM _ j)
    266 278
     -- Note [Overflow on plusUDFM]
    
    267 279
     -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    268 280
     -- There are multiple ways of implementing plusUDFM.
    
    269
    --- The main problem that needs to be solved is overlap on times of
    
    270
    --- insertion between different keys in two maps.
    
    281
    +-- The main problem that needs to be solved is overlap on insertion
    
    282
    +-- tags between different keys in two maps.
    
    271 283
     -- Consider:
    
    272 284
     --
    
    273 285
     -- A = fromList [(a, (x, 1))]
    
    ... ... @@ -355,84 +367,108 @@ nonDetStrictFoldUDFM k z (UDFM m _i) = foldl' k' z m
    355 367
       where
    
    356 368
         k' acc (TaggedVal v _) = k v acc
    
    357 369
     
    
    358
    --- Note [Cost of deterministic iteration]
    
    359
    --- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    360
    --- Deterministic iteration orders elements by insertion tag, and any such
    
    361
    --- ordering must inspect every element's tag before it can emit the first
    
    362
    --- element. So even the head of the result costs a full traversal of the map
    
    363
    --- plus -- on the main path -- the allocation of an O(n)-sized array (see
    
    364
    --- Note [Sorting a UDFM]). Laziness in the result list only avoids allocating
    
    365
    --- for elements that are never demanded; it does not make the iteration
    
    366
    --- incremental. #27459 shows this cost biting in consumers that demanded only
    
    367
    --- the head.
    
    368
    ---
    
    369
    --- So: to test for emptiness, use isNullUDFM rather than null on eltsUDFM;
    
    370
    --- for order-oblivious queries, prefer short-circuiting anyUDFM/allUDFM; and
    
    371
    --- if you don't need the deterministic order at all, use the nonDet functions.
    
    370
    +{- Note [Cost of deterministic iteration]
    
    371
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    372
    +Deterministic iteration -- eltsUDFM, udfmToList, and everything built on
    
    373
    +them, such as foldUDFM and UniqDFM's Foldable instance -- orders elements
    
    374
    +by insertion tag, and any such ordering must inspect every element's tag
    
    375
    +before it can emit the first element. So even the head of the result costs
    
    376
    +a full traversal of the map plus -- on the main path -- the allocation of
    
    377
    +an O(n)-sized array (see Note [Sorting a UDFM]). Laziness in the result
    
    378
    +list only avoids allocating for elements that are never demanded; it does
    
    379
    +not make the iteration incremental. #27459 shows this cost biting in
    
    380
    +consumers that demanded only the head.
    
    381
    +
    
    382
    +So: to test for emptiness, use isNullUDFM rather than null on eltsUDFM;
    
    383
    +for order-oblivious queries, prefer short-circuiting anyUDFM/allUDFM; and
    
    384
    +if you don't need the deterministic order at all, use the nonDet functions.
    
    385
    +-}
    
    372 386
     
    
    373 387
     -- | Deterministic, in order of insertion.
    
    374 388
     --
    
    375 389
     -- See Note [Sorting a UDFM] and Note [Cost of deterministic iteration].
    
    376 390
     eltsUDFM :: UniqDFM key elt -> [elt]
    
    377
    -eltsUDFM (UDFM m i)
    
    378
    -  | n <= 1            = map taggedFst (M.elems m)
    
    379
    -  | usePlacement n i  = placementSort i (M.elems m)
    
    380
    -  | otherwise         = map taggedFst (sort_it m)
    
    381
    -  where n = M.size m
    
    391
    +eltsUDFM (UDFM m ub)
    
    392
    +  | M.compareSize m 1 /= GT = map taggedFst (M.elems m)
    
    393
    +  | usePlacement m ub       = placementSort ub (\_ tv -> tv) m
    
    394
    +  | otherwise               = map taggedFst (sort_it m)
    
    382 395
     
    
    383 396
     sort_it :: M.Word64Map (TaggedVal elt) -> [TaggedVal elt]
    
    384 397
     sort_it m = sortBy (compare `on` taggedSnd) (M.elems m)
    
    385 398
     
    
    386 399
     
    
    387
    --- Note [Sorting a UDFM]
    
    388
    --- ~~~~~~~~~~~~~~~~~~~~~
    
    389
    --- Deterministic iteration must order elements by insertion tag. Instead of a
    
    390
    --- comparison sort -- the list mergesort behind sortBy allocates ~n*log n cons
    
    391
    --- cells -- we exploit the invariant that in (UDFM m i) all tags are distinct
    
    392
    --- Ints in [0, i): allocate an array of size i, write each element at
    
    393
    --- @index = tag@, freeze, and read out in index order. That's O(i) work (which
    
    394
    --- subsumes the O(n) fill, since distinct tags force n <= i), no comparisons,
    
    395
    --- and the readout is lazy, so consumers that demand only a prefix pay almost
    
    396
    --- nothing beyond the fill (but the fill itself is unavoidable; see
    
    397
    --- Note [Cost of deterministic iteration]).
    
    398
    ---
    
    399
    --- Holes: slots whose tag never occurs keep the initial sentinel, a TaggedVal
    
    400
    --- with tag -1. Real tags are non-negative, so the readout skips on tag < 0;
    
    401
    --- the sentinel's value field is never touched (it is unsafeCoerced ()).
    
    402
    ---
    
    403
    --- This sorting method loses when i is much larger than n: i never shrinks
    
    404
    --- (overwrites keep bumping it, delete/filter shrink n but not i). We compute
    
    405
    --- n = M.size m (O(n), cheap next to either sort) and fall back to the
    
    406
    --- mergesort when i > 4 * n. Maps built by plain insertion -- the common
    
    407
    --- case -- have i == n. The guard also caps the fast path's O(i) at O(n).
    
    408
    -
    
    409
    -usePlacement :: Int -> Int -> Bool
    
    410
    -usePlacement n i = i <= 4 * n
    
    411
    -
    
    412
    --- | Order a list of 'TaggedVal's by tag, by placing each at array index =
    
    413
    --- its tag.
    
    414
    ---
    
    415
    --- The tags must be distinct and in @[0, i)@.
    
    416
    --- See Note [Sorting a UDFM].
    
    417
    -placementSort :: forall r. Int -> [TaggedVal r] -> [r]
    
    418
    -placementSort i tvs = runST (ST (\s0 ->
    
    419
    -  case newSmallArray i hole s0 of
    
    420
    -    (# s1, marr #) -> case fill marr tvs s1 of
    
    421
    -      s2 -> case unsafeFreezeSmallArray marr s2 of
    
    400
    +{- Note [Sorting a UDFM]
    
    401
    +~~~~~~~~~~~~~~~~~~~~~~~~
    
    402
    +Deterministic iteration must order elements by insertion tag. A comparison
    
    403
    +sort is needlessly expensive: the list mergesort behind sortBy allocates
    
    404
    +~n*log n cons cells, and in #27459 those allocations made up a large share
    
    405
    +of the compiler's total allocation on the InstanceMatching perf tests.
    
    406
    +
    
    407
    +Instead we exploit the UDFM invariants (all tags in (UDFM m ub) are distinct
    
    408
    +Ints in [0, ub); see Note [UDFM invariants]): allocate an array of size ub,
    
    409
    +write each element at
    
    410
    +@index = tag@, freeze, and read out in index order. The fill is O(n) work,
    
    411
    +where n = size m; the readout is O(ub); and since ub >= n, the whole sort is
    
    412
    +O(ub) -- with no comparisons. The readout is lazy, so consumers that demand
    
    413
    +only a prefix pay almost nothing beyond the fill (but the fill itself is
    
    414
    +unavoidable; see Note [Cost of deterministic iteration]).
    
    415
    +
    
    416
    +Holes: slots whose tag never occurs keep the initial sentinel, a TaggedVal
    
    417
    +with tag -1. Real tags are non-negative, so the readout skips on tag < 0.
    
    418
    +The sentinel's value field is never read, but something must fill it: not a
    
    419
    +panic thunk -- TaggedVal's strict value field would force it as soon as the
    
    420
    +readout inspects a hole's tag -- so we borrow the value of an arbitrary map
    
    421
    +element. (Safe: the callers' guards send maps of size < 2 down a different
    
    422
    +path, so the map is never empty here.)
    
    423
    +
    
    424
    +This sorting method loses when ub is much larger than n = M.size m: ub never
    
    425
    +shrinks (overwrites keep bumping it, delete/filter shrink n but not ub). We
    
    426
    +fall back to the mergesort when ub > 4 * n; the decision about which sort to
    
    427
    +use is made by usePlacement. It checks the threshold with M.compareSize,
    
    428
    +which stops traversing the map as soon as the outcome is decided (so the
    
    429
    +guard costs O(min(n, ub)), not a full O(n) size computation). Maps built by
    
    430
    +plain insertion -- the common case -- have ub == n. The guard also caps the
    
    431
    +fast path's O(ub) at O(n).
    
    432
    +-}
    
    433
    +
    
    434
    +-- | @ub <= 4 * size m@, computed without a full 'M.size' traversal.
    
    435
    +usePlacement :: M.Word64Map a -> Int -> Bool
    
    436
    +usePlacement m ub = M.compareSize m ceil_ub_div_4 /= LT
    
    437
    +  where
    
    438
    +    ceil_ub_div_4 = (ub + 3) `div` 4  -- ceil(ub/4): ub <= 4*n iff n >= ceil(ub/4)
    
    439
    +
    
    440
    +-- | Order the map's elements by tag, by placing @mk key elt@ at array index =
    
    441
    +-- the tag of @elt@.
    
    442
    +--
    
    443
    +-- The map must be non-empty, its tags distinct and in @[0, ub)@; @mk@ must
    
    444
    +-- preserve the tag. See Note [Sorting a UDFM].
    
    445
    +placementSort :: forall e r. Int
    
    446
    +              -> (M.Key -> TaggedVal e -> TaggedVal r)
    
    447
    +              -> M.Word64Map (TaggedVal e)
    
    448
    +              -> [r]
    
    449
    +{-# INLINE placementSort #-}  -- specializes mk into the fill loop
    
    450
    +placementSort ub mk m = runST (ST (\s0 ->
    
    451
    +  case newSmallArray ub hole s0 of
    
    452
    +    (# s1, marr #) -> case fill marr s1 of
    
    453
    +      (# s2, () #) -> case unsafeFreezeSmallArray marr s2 of
    
    422 454
             (# s3, arr #) -> (# s3, readout arr 0 #)))
    
    423 455
       where
    
    456
    +    -- The tag -1 marks unfilled slots; the value field is never read, but
    
    457
    +    -- it is strict, so it needs a real value of type r -- borrow one from
    
    458
    +    -- the map. See Note [Sorting a UDFM].
    
    424 459
         hole :: TaggedVal r
    
    425
    -    hole = TaggedVal (unsafeCoerce ()) (-1)
    
    460
    +    hole = case M.findMin m of
    
    461
    +      (k, tv) -> TaggedVal (taggedFst (mk k tv)) (-1)
    
    426 462
     
    
    427
    -    fill :: SmallMutableArray s (TaggedVal r) -> [TaggedVal r] -> State# s -> State# s
    
    428
    -    fill _    []          s = s
    
    429
    -    fill marr (tv : tvs') s =
    
    430
    -      case writeSmallArray marr (taggedSnd tv) tv s of
    
    431
    -        s' -> fill marr tvs' s'
    
    463
    +    fill :: SmallMutableArray s (TaggedVal r) -> State# s -> (# State# s, () #)
    
    464
    +    fill marr s = case M.traverseWithKey_ write m of ST st -> st s
    
    465
    +      where
    
    466
    +        write k tv = ST (\s' ->
    
    467
    +          (# writeSmallArray marr (taggedSnd tv) (mk k tv) s', () #))
    
    432 468
     
    
    433 469
         readout :: SmallArray (TaggedVal r) -> Int -> [r]
    
    434 470
         readout arr j
    
    435
    -      | j >= i    = []
    
    471
    +      | j >= ub   = []
    
    436 472
           | t < 0     = readout arr (j + 1)
    
    437 473
           | otherwise = v : readout arr (j + 1)
    
    438 474
           where TaggedVal v t = indexSmallArray arr j
    
    ... ... @@ -461,19 +497,17 @@ udfmRestrictKeysSet (UDFM val_set i) set =
    461 497
     -- as this already incurs most of the cost of returning the full list.
    
    462 498
     -- See Note [Cost of deterministic iteration].
    
    463 499
     udfmToList :: UniqDFM key elt -> [(Unique, elt)]
    
    464
    -udfmToList (UDFM m i)
    
    465
    -  | n <= 1           = [ (mkUniqueGrimily k, taggedFst v) | (k, v) <- M.toList m ]
    
    500
    +udfmToList (UDFM m ub)
    
    501
    +  | M.compareSize m 1 /= GT =
    
    502
    +      [ (mkUniqueGrimily k, taggedFst v) | (k, v) <- M.toList m ]
    
    466 503
     
    
    467 504
       -- Unlike eltsUDFM, this allocates a fresh TaggedVal + pair per element
    
    468
    -  -- before the sort. If it ever matters, a parallel Word64 array of
    
    469
    -  -- keys filled in the same pass would avoid the eager boxes.
    
    470
    -  | usePlacement n i = placementSort i
    
    471
    -      (M.foldrWithKey (\k tv rest ->
    
    472
    -         TaggedVal (mkUniqueGrimily k, taggedFst tv) (taggedSnd tv) : rest) [] m)
    
    505
    +  -- (they make up the result).
    
    506
    +  | usePlacement m ub = placementSort ub
    
    507
    +      (\k tv -> TaggedVal (mkUniqueGrimily k, taggedFst tv) (taggedSnd tv)) m
    
    473 508
       | otherwise =
    
    474 509
           [ (mkUniqueGrimily k, taggedFst v)
    
    475 510
           | (k, v) <- sortBy (compare `on` (taggedSnd . snd)) $ M.toList m ]
    
    476
    -  where n = M.size m
    
    477 511
     
    
    478 512
     -- Determines whether two 'UniqDFM's contain the same keys.
    
    479 513
     equalKeysUDFM :: UniqDFM key a -> UniqDFM key b -> Bool