75e0d642fdf510cc9b670947f2f8aca710f707fd
[ghc-hetmet.git] / compiler / iface / BinIface.hs
1
2 {-# OPTIONS_GHC -O #-}
3 -- We always optimise this, otherwise performance of a non-optimised
4 -- compiler is severely affected
5
6 --
7 --  (c) The University of Glasgow 2002-2006
8 --
9 -- Binary interface file support.
10
11 module BinIface ( writeBinIface, readBinIface,
12                   CheckHiWay(..), TraceBinIFaceReading(..) ) where
13
14 #include "HsVersions.h"
15
16 import TcRnMonad
17 import IfaceEnv
18 import HscTypes
19 import BasicTypes
20 import NewDemand
21 import IfaceSyn
22 import Module
23 import Name
24 import OccName
25 import VarEnv
26 import InstEnv
27 import Class
28 import DynFlags
29 import UniqFM
30 import UniqSupply
31 import CostCentre
32 import StaticFlags
33 import Panic
34 import Binary
35 import SrcLoc
36 import ErrUtils
37 import Config
38 import FastMutInt
39 import Unique
40 import Outputable
41 import FastString
42
43 import Data.List
44 import Data.Word
45 import Data.Array
46 import Data.IORef
47 import Control.Exception
48 import Control.Monad
49
50 data CheckHiWay = CheckHiWay | IgnoreHiWay
51     deriving Eq
52
53 data TraceBinIFaceReading = TraceBinIFaceReading | QuietBinIFaceReading
54     deriving Eq
55
56 -- ---------------------------------------------------------------------------
57 -- Reading and writing binary interface files
58
59 readBinIface :: CheckHiWay -> TraceBinIFaceReading -> FilePath
60              -> TcRnIf a b ModIface
61 readBinIface checkHiWay traceBinIFaceReading hi_path = do
62   nc <- getNameCache
63   (new_nc, iface) <- liftIO $
64     readBinIface_ checkHiWay traceBinIFaceReading hi_path nc
65   setNameCache new_nc
66   return iface
67
68 readBinIface_ :: CheckHiWay -> TraceBinIFaceReading -> FilePath -> NameCache
69               -> IO (NameCache, ModIface)
70 readBinIface_ checkHiWay traceBinIFaceReading hi_path nc = do
71   let printer :: SDoc -> IO ()
72       printer = case traceBinIFaceReading of
73                 TraceBinIFaceReading -> \sd -> printSDoc sd defaultDumpStyle
74                 QuietBinIFaceReading -> \_ -> return ()
75       wantedGot :: Outputable a => String -> a -> a -> IO ()
76       wantedGot what wanted got
77           = printer (text what <> text ": " <>
78                      vcat [text "Wanted " <> ppr wanted <> text ",",
79                            text "got    " <> ppr got])
80
81       errorOnMismatch :: (Eq a, Show a) => String -> a -> a -> IO ()
82       errorOnMismatch what wanted got
83             -- This will be caught by readIface which will emit an error
84             -- msg containing the iface module name.
85           = when (wanted /= got) $ throwDyn $ ProgramError
86                         (what ++ " (wanted " ++ show wanted
87                               ++ ", got "    ++ show got ++ ")")
88   bh <- Binary.readBinMem hi_path
89
90         -- Read the magic number to check that this really is a GHC .hi file
91         -- (This magic number does not change when we change
92         --  GHC interface file format)
93   magic <- get bh
94   wantedGot "Magic" binaryInterfaceMagic magic
95   errorOnMismatch "magic number mismatch: old/corrupt interface file?"
96       binaryInterfaceMagic magic
97
98         -- Get the dictionary pointer.  We won't attempt to actually
99         -- read the dictionary until we've done the version checks below,
100         -- just in case this isn't a valid interface.  In retrospect the
101         -- version should have come before the dictionary pointer, but this
102         -- is the way it was done originally, and we can't change it now.
103   dict_p <- Binary.get bh       -- Get the dictionary ptr
104
105         -- Check the interface file version and ways.
106   check_ver  <- get bh
107   let our_ver = show opt_HiVersion
108   wantedGot "Version" our_ver check_ver
109   errorOnMismatch "mismatched interface file versions" our_ver check_ver
110
111   check_way <- get bh
112   way_descr <- getWayDescr
113   wantedGot "Way" way_descr check_way
114   when (checkHiWay == CheckHiWay) $
115        errorOnMismatch "mismatched interface file ways" way_descr check_way
116
117         -- Read the dictionary
118         -- The next word in the file is a pointer to where the dictionary is
119         -- (probably at the end of the file)
120   data_p <- tellBin bh          -- Remember where we are now
121   seekBin bh dict_p
122   dict <- getDictionary bh
123   seekBin bh data_p             -- Back to where we were before
124
125         -- Initialise the user-data field of bh
126   ud <- newReadState dict
127   bh <- return (setUserData bh ud)
128         
129   symtab_p <- Binary.get bh     -- Get the symtab ptr
130   data_p <- tellBin bh          -- Remember where we are now
131   seekBin bh symtab_p
132   (nc', symtab) <- getSymbolTable bh nc
133   seekBin bh data_p             -- Back to where we were before
134   let ud = getUserData bh
135   bh <- return $! setUserData bh ud{ud_symtab = symtab}
136   iface <- get bh
137   return (nc', iface)
138
139
140 writeBinIface :: DynFlags -> FilePath -> ModIface -> IO ()
141 writeBinIface dflags hi_path mod_iface = do
142   bh <- openBinMem initBinMemSize
143   put_ bh binaryInterfaceMagic
144
145         -- Remember where the dictionary pointer will go
146   dict_p_p <- tellBin bh
147   put_ bh dict_p_p      -- Placeholder for ptr to dictionary
148
149         -- The version and way descriptor go next
150   put_ bh (show opt_HiVersion)
151   way_descr <- getWayDescr
152   put  bh way_descr
153
154         -- Remember where the symbol table pointer will go
155   symtab_p_p <- tellBin bh
156   put_ bh symtab_p_p
157
158         -- Make some intial state
159   symtab_next <- newFastMutInt
160   writeFastMutInt symtab_next 0
161   symtab_map <- newIORef emptyUFM
162   let bin_symtab = BinSymbolTable {
163                       bin_symtab_next = symtab_next,
164                       bin_symtab_map  = symtab_map }
165   dict_next_ref <- newFastMutInt
166   writeFastMutInt dict_next_ref 0
167   dict_map_ref <- newIORef emptyUFM
168   let bin_dict = BinDictionary {
169                       bin_dict_next = dict_next_ref,
170                       bin_dict_map  = dict_map_ref }
171   ud <- newWriteState (putName bin_symtab) (putFastString bin_dict)
172
173         -- Put the main thing, 
174   bh <- return $ setUserData bh ud
175   put_ bh mod_iface
176
177         -- Write the symtab pointer at the fornt of the file
178   symtab_p <- tellBin bh                -- This is where the symtab will start
179   putAt bh symtab_p_p symtab_p  -- Fill in the placeholder
180   seekBin bh symtab_p           -- Seek back to the end of the file
181
182         -- Write the symbol table itself
183   symtab_next <- readFastMutInt symtab_next
184   symtab_map  <- readIORef symtab_map
185   putSymbolTable bh symtab_next symtab_map
186   debugTraceMsg dflags 3 (text "writeBinIface:" <+> int symtab_next 
187                                 <+> text "Names")
188
189         -- NB. write the dictionary after the symbol table, because
190         -- writing the symbol table may create more dictionary entries.
191
192         -- Write the dictionary pointer at the fornt of the file
193   dict_p <- tellBin bh          -- This is where the dictionary will start
194   putAt bh dict_p_p dict_p      -- Fill in the placeholder
195   seekBin bh dict_p             -- Seek back to the end of the file
196
197         -- Write the dictionary itself
198   dict_next <- readFastMutInt dict_next_ref
199   dict_map  <- readIORef dict_map_ref
200   putDictionary bh dict_next dict_map
201   debugTraceMsg dflags 3 (text "writeBinIface:" <+> int dict_next
202                                  <+> text "dict entries")
203
204         -- And send the result to the file
205   writeBinMem bh hi_path
206
207 initBinMemSize :: Int
208 initBinMemSize = 1024 * 1024
209
210 -- The *host* architecture version:
211 #include "MachDeps.h"
212
213 binaryInterfaceMagic :: Word32
214 #if   WORD_SIZE_IN_BITS == 32
215 binaryInterfaceMagic = 0x1face
216 #elif WORD_SIZE_IN_BITS == 64
217 binaryInterfaceMagic = 0x1face64
218 #endif
219   
220 -- -----------------------------------------------------------------------------
221 -- The symbol table
222
223 putSymbolTable :: BinHandle -> Int -> UniqFM (Int,Name) -> IO ()
224 putSymbolTable bh next_off symtab = do
225   put_ bh next_off
226   let names = elems (array (0,next_off-1) (eltsUFM symtab))
227   mapM_ (\n -> serialiseName bh n symtab) names
228
229 getSymbolTable :: BinHandle -> NameCache -> IO (NameCache, Array Int Name)
230 getSymbolTable bh namecache = do
231   sz <- get bh
232   od_names <- sequence (replicate sz (get bh))
233   let 
234         arr = listArray (0,sz-1) names
235         (namecache', names) =    
236                 mapAccumR (fromOnDiskName arr) namecache od_names
237   --
238   return (namecache', arr)
239
240 type OnDiskName = (PackageId, ModuleName, OccName)
241
242 fromOnDiskName
243    :: Array Int Name
244    -> NameCache
245    -> OnDiskName
246    -> (NameCache, Name)
247 fromOnDiskName _ nc (pid, mod_name, occ) =
248   let 
249         mod   = mkModule pid mod_name
250         cache = nsNames nc
251   in
252   case lookupOrigNameCache cache  mod occ of
253      Just name -> (nc, name)
254      Nothing   -> 
255         let 
256                 us        = nsUniqs nc
257                 uniq      = uniqFromSupply us
258                 name      = mkExternalName uniq mod occ noSrcSpan
259                 new_cache = extendNameCache cache mod occ name
260         in        
261         case splitUniqSupply us of { (us',_) -> 
262         ( nc{ nsUniqs = us', nsNames = new_cache }, name )
263         }
264
265 serialiseName :: BinHandle -> Name -> UniqFM (Int,Name) -> IO ()
266 serialiseName bh name _ = do
267   let mod = nameModule name
268   put_ bh (modulePackageId mod, moduleName mod, nameOccName name)
269
270
271 putName :: BinSymbolTable -> BinHandle -> Name -> IO ()
272 putName BinSymbolTable{ 
273             bin_symtab_map = symtab_map_ref,
274             bin_symtab_next = symtab_next }    bh name
275   = do
276     symtab_map <- readIORef symtab_map_ref
277     case lookupUFM symtab_map name of
278       Just (off,_) -> put_ bh off
279       Nothing -> do
280          off <- readFastMutInt symtab_next
281          writeFastMutInt symtab_next (off+1)
282          writeIORef symtab_map_ref
283              $! addToUFM symtab_map name (off,name)
284          put_ bh off          
285
286
287 data BinSymbolTable = BinSymbolTable {
288         bin_symtab_next :: !FastMutInt, -- The next index to use
289         bin_symtab_map  :: !(IORef (UniqFM (Int,Name)))
290                                 -- indexed by Name
291   }
292
293
294 putFastString :: BinDictionary -> BinHandle -> FastString -> IO ()
295 putFastString BinDictionary { bin_dict_next = j_r,
296                               bin_dict_map  = out_r}  bh f
297   = do
298     out <- readIORef out_r
299     let uniq = getUnique f
300     case lookupUFM out uniq of
301         Just (j, _)  -> put_ bh j
302         Nothing -> do
303            j <- readFastMutInt j_r
304            put_ bh j
305            writeFastMutInt j_r (j + 1)
306            writeIORef out_r $! addToUFM out uniq (j, f)
307
308
309 data BinDictionary = BinDictionary {
310         bin_dict_next :: !FastMutInt, -- The next index to use
311         bin_dict_map  :: !(IORef (UniqFM (Int,FastString)))
312                                 -- indexed by FastString
313   }
314
315 -- -----------------------------------------------------------------------------
316 -- All the binary instances
317
318 -- BasicTypes
319 {-! for IPName derive: Binary !-}
320 {-! for Fixity derive: Binary !-}
321 {-! for FixityDirection derive: Binary !-}
322 {-! for Boxity derive: Binary !-}
323 {-! for StrictnessMark derive: Binary !-}
324 {-! for Activation derive: Binary !-}
325
326 -- NewDemand
327 {-! for Demand derive: Binary !-}
328 {-! for Demands derive: Binary !-}
329 {-! for DmdResult derive: Binary !-}
330 {-! for StrictSig derive: Binary !-}
331
332 -- Class
333 {-! for DefMeth derive: Binary !-}
334
335 -- HsTypes
336 {-! for HsPred derive: Binary !-}
337 {-! for HsType derive: Binary !-}
338 {-! for TupCon derive: Binary !-}
339 {-! for HsTyVarBndr derive: Binary !-}
340
341 -- HsCore
342 {-! for UfExpr derive: Binary !-}
343 {-! for UfConAlt derive: Binary !-}
344 {-! for UfBinding derive: Binary !-}
345 {-! for UfBinder derive: Binary !-}
346 {-! for HsIdInfo derive: Binary !-}
347 {-! for UfNote derive: Binary !-}
348
349 -- HsDecls
350 {-! for ConDetails derive: Binary !-}
351 {-! for BangType derive: Binary !-}
352
353 -- CostCentre
354 {-! for IsCafCC derive: Binary !-}
355 {-! for IsDupdCC derive: Binary !-}
356 {-! for CostCentre derive: Binary !-}
357
358
359
360 -- ---------------------------------------------------------------------------
361 -- Reading a binary interface into ParsedIface
362
363 instance Binary ModIface where
364    put_ bh (ModIface {
365                  mi_module    = mod,
366                  mi_boot      = is_boot,
367                  mi_iface_hash= iface_hash,
368                  mi_mod_hash  = mod_hash,
369                  mi_orphan    = orphan,
370                  mi_finsts    = hasFamInsts,
371                  mi_deps      = deps,
372                  mi_usages    = usages,
373                  mi_exports   = exports,
374                  mi_exp_hash  = exp_hash,
375                  mi_fixities  = fixities,
376                  mi_deprecs   = deprecs,
377                  mi_decls     = decls,
378                  mi_insts     = insts,
379                  mi_fam_insts = fam_insts,
380                  mi_rules     = rules,
381                  mi_orphan_hash = orphan_hash,
382                  mi_vect_info = vect_info,
383                  mi_hpc       = hpc_info }) = do
384         put_ bh mod
385         put_ bh is_boot
386         put_ bh iface_hash
387         put_ bh mod_hash
388         put_ bh orphan
389         put_ bh hasFamInsts
390         lazyPut bh deps
391         lazyPut bh usages
392         put_ bh exports
393         put_ bh exp_hash
394         put_ bh fixities
395         lazyPut bh deprecs
396         put_ bh decls
397         put_ bh insts
398         put_ bh fam_insts
399         lazyPut bh rules
400         put_ bh orphan_hash
401         put_ bh vect_info
402         put_ bh hpc_info
403
404    get bh = do
405         mod_name  <- get bh
406         is_boot   <- get bh
407         iface_hash <- get bh
408         mod_hash  <- get bh
409         orphan    <- get bh
410         hasFamInsts <- get bh
411         deps      <- lazyGet bh
412         usages    <- {-# SCC "bin_usages" #-} lazyGet bh
413         exports   <- {-# SCC "bin_exports" #-} get bh
414         exp_hash  <- get bh
415         fixities  <- {-# SCC "bin_fixities" #-} get bh
416         deprecs   <- {-# SCC "bin_deprecs" #-} lazyGet bh
417         decls     <- {-# SCC "bin_tycldecls" #-} get bh
418         insts     <- {-# SCC "bin_insts" #-} get bh
419         fam_insts <- {-# SCC "bin_fam_insts" #-} get bh
420         rules     <- {-# SCC "bin_rules" #-} lazyGet bh
421         orphan_hash <- get bh
422         vect_info <- get bh
423         hpc_info  <- get bh
424         return (ModIface {
425                  mi_module    = mod_name,
426                  mi_boot      = is_boot,
427                  mi_iface_hash = iface_hash,
428                  mi_mod_hash  = mod_hash,
429                  mi_orphan    = orphan,
430                  mi_finsts    = hasFamInsts,
431                  mi_deps      = deps,
432                  mi_usages    = usages,
433                  mi_exports   = exports,
434                  mi_exp_hash  = exp_hash,
435                  mi_fixities  = fixities,
436                  mi_deprecs   = deprecs,
437                  mi_decls     = decls,
438                  mi_globals   = Nothing,
439                  mi_insts     = insts,
440                  mi_fam_insts = fam_insts,
441                  mi_rules     = rules,
442                  mi_orphan_hash = orphan_hash,
443                  mi_vect_info = vect_info,
444                  mi_hpc       = hpc_info,
445                         -- And build the cached values
446                  mi_dep_fn    = mkIfaceDepCache deprecs,
447                  mi_fix_fn    = mkIfaceFixCache fixities,
448                  mi_hash_fn   = mkIfaceHashCache decls })
449
450 getWayDescr :: IO String
451 getWayDescr = do
452   tag <- readIORef v_Build_tag
453   if cGhcUnregisterised == "YES" then return ('u':tag) else return tag
454         -- if this is an unregisterised build, make sure our interfaces
455         -- can't be used by a registerised build.
456
457 -------------------------------------------------------------------------
458 --              Types from: HscTypes
459 -------------------------------------------------------------------------
460
461 instance Binary Dependencies where
462     put_ bh deps = do put_ bh (dep_mods deps)
463                       put_ bh (dep_pkgs deps)
464                       put_ bh (dep_orphs deps)
465                       put_ bh (dep_finsts deps)
466
467     get bh = do ms <- get bh 
468                 ps <- get bh
469                 os <- get bh
470                 fis <- get bh
471                 return (Deps { dep_mods = ms, dep_pkgs = ps, dep_orphs = os,
472                                dep_finsts = fis })
473
474 instance (Binary name) => Binary (GenAvailInfo name) where
475     put_ bh (Avail aa) = do
476             putByte bh 0
477             put_ bh aa
478     put_ bh (AvailTC ab ac) = do
479             putByte bh 1
480             put_ bh ab
481             put_ bh ac
482     get bh = do
483             h <- getByte bh
484             case h of
485               0 -> do aa <- get bh
486                       return (Avail aa)
487               _ -> do ab <- get bh
488                       ac <- get bh
489                       return (AvailTC ab ac)
490
491 instance Binary Usage where
492     put_ bh usg@UsagePackageModule{} = do 
493         putByte bh 0
494         put_ bh (usg_mod usg)
495         put_ bh (usg_mod_hash usg)
496     put_ bh usg@UsageHomeModule{} = do 
497         putByte bh 1
498         put_ bh (usg_mod_name usg)
499         put_ bh (usg_mod_hash usg)
500         put_ bh (usg_exports  usg)
501         put_ bh (usg_entities usg)
502
503     get bh = do
504         h <- getByte bh
505         case h of
506           0 -> do
507             nm    <- get bh
508             mod   <- get bh
509             return UsagePackageModule { usg_mod = nm, usg_mod_hash = mod }
510           _ -> do
511             nm    <- get bh
512             mod   <- get bh
513             exps  <- get bh
514             ents  <- get bh
515             return UsageHomeModule { usg_mod_name = nm, usg_mod_hash = mod,
516                             usg_exports = exps, usg_entities = ents }
517
518 instance Binary Deprecations where
519     put_ bh NoDeprecs     = putByte bh 0
520     put_ bh (DeprecAll t) = do
521             putByte bh 1
522             put_ bh t
523     put_ bh (DeprecSome ts) = do
524             putByte bh 2
525             put_ bh ts
526
527     get bh = do
528             h <- getByte bh
529             case h of
530               0 -> return NoDeprecs
531               1 -> do aa <- get bh
532                       return (DeprecAll aa)
533               _ -> do aa <- get bh
534                       return (DeprecSome aa)
535
536 -------------------------------------------------------------------------
537 --              Types from: BasicTypes
538 -------------------------------------------------------------------------
539
540 instance Binary Activation where
541     put_ bh NeverActive = do
542             putByte bh 0
543     put_ bh AlwaysActive = do
544             putByte bh 1
545     put_ bh (ActiveBefore aa) = do
546             putByte bh 2
547             put_ bh aa
548     put_ bh (ActiveAfter ab) = do
549             putByte bh 3
550             put_ bh ab
551     get bh = do
552             h <- getByte bh
553             case h of
554               0 -> do return NeverActive
555               1 -> do return AlwaysActive
556               2 -> do aa <- get bh
557                       return (ActiveBefore aa)
558               _ -> do ab <- get bh
559                       return (ActiveAfter ab)
560
561 instance Binary StrictnessMark where
562     put_ bh MarkedStrict = do
563             putByte bh 0
564     put_ bh MarkedUnboxed = do
565             putByte bh 1
566     put_ bh NotMarkedStrict = do
567             putByte bh 2
568     get bh = do
569             h <- getByte bh
570             case h of
571               0 -> do return MarkedStrict
572               1 -> do return MarkedUnboxed
573               _ -> do return NotMarkedStrict
574
575 instance Binary Boxity where
576     put_ bh Boxed = do
577             putByte bh 0
578     put_ bh Unboxed = do
579             putByte bh 1
580     get bh = do
581             h <- getByte bh
582             case h of
583               0 -> do return Boxed
584               _ -> do return Unboxed
585
586 instance Binary TupCon where
587     put_ bh (TupCon ab ac) = do
588             put_ bh ab
589             put_ bh ac
590     get bh = do
591           ab <- get bh
592           ac <- get bh
593           return (TupCon ab ac)
594
595 instance Binary RecFlag where
596     put_ bh Recursive = do
597             putByte bh 0
598     put_ bh NonRecursive = do
599             putByte bh 1
600     get bh = do
601             h <- getByte bh
602             case h of
603               0 -> do return Recursive
604               _ -> do return NonRecursive
605
606 instance Binary DefMeth where
607     put_ bh NoDefMeth  = putByte bh 0
608     put_ bh DefMeth    = putByte bh 1
609     put_ bh GenDefMeth = putByte bh 2
610     get bh = do
611             h <- getByte bh
612             case h of
613               0 -> return NoDefMeth
614               1 -> return DefMeth
615               _ -> return GenDefMeth
616
617 instance Binary FixityDirection where
618     put_ bh InfixL = do
619             putByte bh 0
620     put_ bh InfixR = do
621             putByte bh 1
622     put_ bh InfixN = do
623             putByte bh 2
624     get bh = do
625             h <- getByte bh
626             case h of
627               0 -> do return InfixL
628               1 -> do return InfixR
629               _ -> do return InfixN
630
631 instance Binary Fixity where
632     put_ bh (Fixity aa ab) = do
633             put_ bh aa
634             put_ bh ab
635     get bh = do
636           aa <- get bh
637           ab <- get bh
638           return (Fixity aa ab)
639
640 instance (Binary name) => Binary (IPName name) where
641     put_ bh (IPName aa) = put_ bh aa
642     get bh = do aa <- get bh
643                 return (IPName aa)
644
645 -------------------------------------------------------------------------
646 --              Types from: Demand
647 -------------------------------------------------------------------------
648
649 instance Binary DmdType where
650         -- Ignore DmdEnv when spitting out the DmdType
651   put bh (DmdType _ ds dr) = do p <- put bh ds; put bh dr; return (castBin p)
652   get bh = do ds <- get bh; dr <- get bh; return (DmdType emptyVarEnv ds dr)
653
654 instance Binary Demand where
655     put_ bh Top = do
656             putByte bh 0
657     put_ bh Abs = do
658             putByte bh 1
659     put_ bh (Call aa) = do
660             putByte bh 2
661             put_ bh aa
662     put_ bh (Eval ab) = do
663             putByte bh 3
664             put_ bh ab
665     put_ bh (Defer ac) = do
666             putByte bh 4
667             put_ bh ac
668     put_ bh (Box ad) = do
669             putByte bh 5
670             put_ bh ad
671     put_ bh Bot = do
672             putByte bh 6
673     get bh = do
674             h <- getByte bh
675             case h of
676               0 -> do return Top
677               1 -> do return Abs
678               2 -> do aa <- get bh
679                       return (Call aa)
680               3 -> do ab <- get bh
681                       return (Eval ab)
682               4 -> do ac <- get bh
683                       return (Defer ac)
684               5 -> do ad <- get bh
685                       return (Box ad)
686               _ -> do return Bot
687
688 instance Binary Demands where
689     put_ bh (Poly aa) = do
690             putByte bh 0
691             put_ bh aa
692     put_ bh (Prod ab) = do
693             putByte bh 1
694             put_ bh ab
695     get bh = do
696             h <- getByte bh
697             case h of
698               0 -> do aa <- get bh
699                       return (Poly aa)
700               _ -> do ab <- get bh
701                       return (Prod ab)
702
703 instance Binary DmdResult where
704     put_ bh TopRes = do
705             putByte bh 0
706     put_ bh RetCPR = do
707             putByte bh 1
708     put_ bh BotRes = do
709             putByte bh 2
710     get bh = do
711             h <- getByte bh
712             case h of
713               0 -> do return TopRes
714               1 -> do return RetCPR     -- Really use RetCPR even if -fcpr-off
715                                         -- The wrapper was generated for CPR in 
716                                         -- the imported module!
717               _ -> do return BotRes
718
719 instance Binary StrictSig where
720     put_ bh (StrictSig aa) = do
721             put_ bh aa
722     get bh = do
723           aa <- get bh
724           return (StrictSig aa)
725
726
727 -------------------------------------------------------------------------
728 --              Types from: CostCentre
729 -------------------------------------------------------------------------
730
731 instance Binary IsCafCC where
732     put_ bh CafCC = do
733             putByte bh 0
734     put_ bh NotCafCC = do
735             putByte bh 1
736     get bh = do
737             h <- getByte bh
738             case h of
739               0 -> do return CafCC
740               _ -> do return NotCafCC
741
742 instance Binary IsDupdCC where
743     put_ bh OriginalCC = do
744             putByte bh 0
745     put_ bh DupdCC = do
746             putByte bh 1
747     get bh = do
748             h <- getByte bh
749             case h of
750               0 -> do return OriginalCC
751               _ -> do return DupdCC
752
753 instance Binary CostCentre where
754     put_ bh NoCostCentre = do
755             putByte bh 0
756     put_ bh (NormalCC aa ab ac ad) = do
757             putByte bh 1
758             put_ bh aa
759             put_ bh ab
760             put_ bh ac
761             put_ bh ad
762     put_ bh (AllCafsCC ae) = do
763             putByte bh 2
764             put_ bh ae
765     get bh = do
766             h <- getByte bh
767             case h of
768               0 -> do return NoCostCentre
769               1 -> do aa <- get bh
770                       ab <- get bh
771                       ac <- get bh
772                       ad <- get bh
773                       return (NormalCC aa ab ac ad)
774               _ -> do ae <- get bh
775                       return (AllCafsCC ae)
776
777 -------------------------------------------------------------------------
778 --              IfaceTypes and friends
779 -------------------------------------------------------------------------
780
781 instance Binary IfaceBndr where
782     put_ bh (IfaceIdBndr aa) = do
783             putByte bh 0
784             put_ bh aa
785     put_ bh (IfaceTvBndr ab) = do
786             putByte bh 1
787             put_ bh ab
788     get bh = do
789             h <- getByte bh
790             case h of
791               0 -> do aa <- get bh
792                       return (IfaceIdBndr aa)
793               _ -> do ab <- get bh
794                       return (IfaceTvBndr ab)
795
796 instance Binary IfaceLetBndr where
797     put_ bh (IfLetBndr a b c) = do
798             put_ bh a
799             put_ bh b
800             put_ bh c
801     get bh = do a <- get bh
802                 b <- get bh
803                 c <- get bh
804                 return (IfLetBndr a b c)           
805
806 instance Binary IfaceType where
807     put_ bh (IfaceForAllTy aa ab) = do
808             putByte bh 0
809             put_ bh aa
810             put_ bh ab
811     put_ bh (IfaceTyVar ad) = do
812             putByte bh 1
813             put_ bh ad
814     put_ bh (IfaceAppTy ae af) = do
815             putByte bh 2
816             put_ bh ae
817             put_ bh af
818     put_ bh (IfaceFunTy ag ah) = do
819             putByte bh 3
820             put_ bh ag
821             put_ bh ah
822     put_ bh (IfacePredTy aq) = do
823             putByte bh 5
824             put_ bh aq
825
826         -- Simple compression for common cases of TyConApp
827     put_ bh (IfaceTyConApp IfaceIntTc  [])   = putByte bh 6
828     put_ bh (IfaceTyConApp IfaceCharTc [])   = putByte bh 7
829     put_ bh (IfaceTyConApp IfaceBoolTc [])   = putByte bh 8
830     put_ bh (IfaceTyConApp IfaceListTc [ty]) = do { putByte bh 9; put_ bh ty }
831         -- Unit tuple and pairs
832     put_ bh (IfaceTyConApp (IfaceTupTc Boxed 0) [])      = putByte bh 10
833     put_ bh (IfaceTyConApp (IfaceTupTc Boxed 2) [t1,t2]) = do { putByte bh 11; put_ bh t1; put_ bh t2 }
834         -- Kind cases
835     put_ bh (IfaceTyConApp IfaceLiftedTypeKindTc [])   = putByte bh 12
836     put_ bh (IfaceTyConApp IfaceOpenTypeKindTc [])     = putByte bh 13
837     put_ bh (IfaceTyConApp IfaceUnliftedTypeKindTc []) = putByte bh 14
838     put_ bh (IfaceTyConApp IfaceUbxTupleKindTc [])     = putByte bh 15
839     put_ bh (IfaceTyConApp IfaceArgTypeKindTc [])      = putByte bh 16
840
841         -- Generic cases
842
843     put_ bh (IfaceTyConApp (IfaceTc tc) tys) = do { putByte bh 18; put_ bh tc; put_ bh tys }
844     put_ bh (IfaceTyConApp tc tys)           = do { putByte bh 19; put_ bh tc; put_ bh tys }
845
846     get bh = do
847             h <- getByte bh
848             case h of
849               0 -> do aa <- get bh
850                       ab <- get bh
851                       return (IfaceForAllTy aa ab)
852               1 -> do ad <- get bh
853                       return (IfaceTyVar ad)
854               2 -> do ae <- get bh
855                       af <- get bh
856                       return (IfaceAppTy ae af)
857               3 -> do ag <- get bh
858                       ah <- get bh
859                       return (IfaceFunTy ag ah)
860               5 -> do ap <- get bh
861                       return (IfacePredTy ap)
862
863                 -- Now the special cases for TyConApp
864               6 -> return (IfaceTyConApp IfaceIntTc [])
865               7 -> return (IfaceTyConApp IfaceCharTc [])
866               8 -> return (IfaceTyConApp IfaceBoolTc [])
867               9 -> do { ty <- get bh; return (IfaceTyConApp IfaceListTc [ty]) }
868               10 -> return (IfaceTyConApp (IfaceTupTc Boxed 0) [])
869               11 -> do { t1 <- get bh; t2 <- get bh; return (IfaceTyConApp (IfaceTupTc Boxed 2) [t1,t2]) }
870               12 -> return (IfaceTyConApp IfaceLiftedTypeKindTc [])
871               13 -> return (IfaceTyConApp IfaceOpenTypeKindTc [])
872               14 -> return (IfaceTyConApp IfaceUnliftedTypeKindTc [])
873               15 -> return (IfaceTyConApp IfaceUbxTupleKindTc [])
874               16 -> return (IfaceTyConApp IfaceArgTypeKindTc [])
875
876               18 -> do { tc <- get bh; tys <- get bh; return (IfaceTyConApp (IfaceTc tc) tys) }
877               _  -> do { tc <- get bh; tys <- get bh; return (IfaceTyConApp tc tys) }
878
879 instance Binary IfaceTyCon where
880         -- Int,Char,Bool can't show up here because they can't not be saturated
881
882    put_ bh IfaceIntTc         = putByte bh 1
883    put_ bh IfaceBoolTc        = putByte bh 2
884    put_ bh IfaceCharTc        = putByte bh 3
885    put_ bh IfaceListTc        = putByte bh 4
886    put_ bh IfacePArrTc        = putByte bh 5
887    put_ bh IfaceLiftedTypeKindTc   = putByte bh 6
888    put_ bh IfaceOpenTypeKindTc     = putByte bh 7
889    put_ bh IfaceUnliftedTypeKindTc = putByte bh 8
890    put_ bh IfaceUbxTupleKindTc     = putByte bh 9
891    put_ bh IfaceArgTypeKindTc      = putByte bh 10
892    put_ bh (IfaceTupTc bx ar) = do { putByte bh 11; put_ bh bx; put_ bh ar }
893    put_ bh (IfaceTc ext)      = do { putByte bh 12; put_ bh ext }
894
895    get bh = do
896         h <- getByte bh
897         case h of
898           1 -> return IfaceIntTc
899           2 -> return IfaceBoolTc
900           3 -> return IfaceCharTc
901           4 -> return IfaceListTc
902           5 -> return IfacePArrTc
903           6 -> return IfaceLiftedTypeKindTc 
904           7 -> return IfaceOpenTypeKindTc 
905           8 -> return IfaceUnliftedTypeKindTc
906           9 -> return IfaceUbxTupleKindTc
907           10 -> return IfaceArgTypeKindTc
908           11 -> do { bx <- get bh; ar <- get bh; return (IfaceTupTc bx ar) }
909           _ -> do { ext <- get bh; return (IfaceTc ext) }
910
911 instance Binary IfacePredType where
912     put_ bh (IfaceClassP aa ab) = do
913             putByte bh 0
914             put_ bh aa
915             put_ bh ab
916     put_ bh (IfaceIParam ac ad) = do
917             putByte bh 1
918             put_ bh ac
919             put_ bh ad
920     put_ bh (IfaceEqPred ac ad) = do
921             putByte bh 2
922             put_ bh ac
923             put_ bh ad
924     get bh = do
925             h <- getByte bh
926             case h of
927               0 -> do aa <- get bh
928                       ab <- get bh
929                       return (IfaceClassP aa ab)
930               1 -> do ac <- get bh
931                       ad <- get bh
932                       return (IfaceIParam ac ad)
933               2 -> do ac <- get bh
934                       ad <- get bh
935                       return (IfaceEqPred ac ad)
936               _ -> panic ("get IfacePredType " ++ show h)
937
938 -------------------------------------------------------------------------
939 --              IfaceExpr and friends
940 -------------------------------------------------------------------------
941
942 instance Binary IfaceExpr where
943     put_ bh (IfaceLcl aa) = do
944             putByte bh 0
945             put_ bh aa
946     put_ bh (IfaceType ab) = do
947             putByte bh 1
948             put_ bh ab
949     put_ bh (IfaceTuple ac ad) = do
950             putByte bh 2
951             put_ bh ac
952             put_ bh ad
953     put_ bh (IfaceLam ae af) = do
954             putByte bh 3
955             put_ bh ae
956             put_ bh af
957     put_ bh (IfaceApp ag ah) = do
958             putByte bh 4
959             put_ bh ag
960             put_ bh ah
961 -- gaw 2004
962     put_ bh (IfaceCase ai aj al ak) = do
963             putByte bh 5
964             put_ bh ai
965             put_ bh aj
966 -- gaw 2004
967             put_ bh al
968             put_ bh ak
969     put_ bh (IfaceLet al am) = do
970             putByte bh 6
971             put_ bh al
972             put_ bh am
973     put_ bh (IfaceNote an ao) = do
974             putByte bh 7
975             put_ bh an
976             put_ bh ao
977     put_ bh (IfaceLit ap) = do
978             putByte bh 8
979             put_ bh ap
980     put_ bh (IfaceFCall as at) = do
981             putByte bh 9
982             put_ bh as
983             put_ bh at
984     put_ bh (IfaceExt aa) = do
985             putByte bh 10
986             put_ bh aa
987     put_ bh (IfaceCast ie ico) = do
988             putByte bh 11
989             put_ bh ie
990             put_ bh ico
991     put_ bh (IfaceTick m ix) = do
992             putByte bh 12
993             put_ bh m
994             put_ bh ix
995     get bh = do
996             h <- getByte bh
997             case h of
998               0 -> do aa <- get bh
999                       return (IfaceLcl aa)
1000               1 -> do ab <- get bh
1001                       return (IfaceType ab)
1002               2 -> do ac <- get bh
1003                       ad <- get bh
1004                       return (IfaceTuple ac ad)
1005               3 -> do ae <- get bh
1006                       af <- get bh
1007                       return (IfaceLam ae af)
1008               4 -> do ag <- get bh
1009                       ah <- get bh
1010                       return (IfaceApp ag ah)
1011               5 -> do ai <- get bh
1012                       aj <- get bh
1013 -- gaw 2004
1014                       al <- get bh                   
1015                       ak <- get bh
1016 -- gaw 2004
1017                       return (IfaceCase ai aj al ak)
1018               6 -> do al <- get bh
1019                       am <- get bh
1020                       return (IfaceLet al am)
1021               7 -> do an <- get bh
1022                       ao <- get bh
1023                       return (IfaceNote an ao)
1024               8 -> do ap <- get bh
1025                       return (IfaceLit ap)
1026               9 -> do as <- get bh
1027                       at <- get bh
1028                       return (IfaceFCall as at)
1029               10 -> do aa <- get bh
1030                        return (IfaceExt aa)
1031               11 -> do ie <- get bh
1032                        ico <- get bh
1033                        return (IfaceCast ie ico)
1034               12 -> do m <- get bh
1035                        ix <- get bh
1036                        return (IfaceTick m ix)
1037               _ -> panic ("get IfaceExpr " ++ show h)
1038
1039 instance Binary IfaceConAlt where
1040     put_ bh IfaceDefault = do
1041             putByte bh 0
1042     put_ bh (IfaceDataAlt aa) = do
1043             putByte bh 1
1044             put_ bh aa
1045     put_ bh (IfaceTupleAlt ab) = do
1046             putByte bh 2
1047             put_ bh ab
1048     put_ bh (IfaceLitAlt ac) = do
1049             putByte bh 3
1050             put_ bh ac
1051     get bh = do
1052             h <- getByte bh
1053             case h of
1054               0 -> do return IfaceDefault
1055               1 -> do aa <- get bh
1056                       return (IfaceDataAlt aa)
1057               2 -> do ab <- get bh
1058                       return (IfaceTupleAlt ab)
1059               _ -> do ac <- get bh
1060                       return (IfaceLitAlt ac)
1061
1062 instance Binary IfaceBinding where
1063     put_ bh (IfaceNonRec aa ab) = do
1064             putByte bh 0
1065             put_ bh aa
1066             put_ bh ab
1067     put_ bh (IfaceRec ac) = do
1068             putByte bh 1
1069             put_ bh ac
1070     get bh = do
1071             h <- getByte bh
1072             case h of
1073               0 -> do aa <- get bh
1074                       ab <- get bh
1075                       return (IfaceNonRec aa ab)
1076               _ -> do ac <- get bh
1077                       return (IfaceRec ac)
1078
1079 instance Binary IfaceIdInfo where
1080     put_ bh NoInfo = putByte bh 0
1081     put_ bh (HasInfo i) = do
1082             putByte bh 1
1083             lazyPut bh i                        -- NB lazyPut
1084
1085     get bh = do
1086             h <- getByte bh
1087             case h of
1088               0 -> return NoInfo
1089               _ -> do info <- lazyGet bh        -- NB lazyGet
1090                       return (HasInfo info)
1091
1092 instance Binary IfaceInfoItem where
1093     put_ bh (HsArity aa) = do
1094             putByte bh 0
1095             put_ bh aa
1096     put_ bh (HsStrictness ab) = do
1097             putByte bh 1
1098             put_ bh ab
1099     put_ bh (HsUnfold ad) = do
1100             putByte bh 2
1101             put_ bh ad
1102     put_ bh (HsInline ad) = do
1103             putByte bh 3
1104             put_ bh ad
1105     put_ bh HsNoCafRefs = do
1106             putByte bh 4
1107     put_ bh (HsWorker ae af) = do
1108             putByte bh 5
1109             put_ bh ae
1110             put_ bh af
1111     get bh = do
1112             h <- getByte bh
1113             case h of
1114               0 -> do aa <- get bh
1115                       return (HsArity aa)
1116               1 -> do ab <- get bh
1117                       return (HsStrictness ab)
1118               2 -> do ad <- get bh
1119                       return (HsUnfold ad)
1120               3 -> do ad <- get bh
1121                       return (HsInline ad)
1122               4 -> do return HsNoCafRefs
1123               _ -> do ae <- get bh
1124                       af <- get bh
1125                       return (HsWorker ae af)
1126
1127 instance Binary IfaceNote where
1128     put_ bh (IfaceSCC aa) = do
1129             putByte bh 0
1130             put_ bh aa
1131     put_ bh IfaceInlineMe = do
1132             putByte bh 3
1133     put_ bh (IfaceCoreNote s) = do
1134             putByte bh 4
1135             put_ bh s
1136     get bh = do
1137             h <- getByte bh
1138             case h of
1139               0 -> do aa <- get bh
1140                       return (IfaceSCC aa)
1141               3 -> do return IfaceInlineMe
1142               4 -> do ac <- get bh
1143                       return (IfaceCoreNote ac)
1144               _ -> panic ("get IfaceNote " ++ show h)
1145
1146 -------------------------------------------------------------------------
1147 --              IfaceDecl and friends
1148 -------------------------------------------------------------------------
1149
1150 -- A bit of magic going on here: there's no need to store the OccName
1151 -- for a decl on the disk, since we can infer the namespace from the
1152 -- context; however it is useful to have the OccName in the IfaceDecl
1153 -- to avoid re-building it in various places.  So we build the OccName
1154 -- when de-serialising.
1155
1156 instance Binary IfaceDecl where
1157     put_ bh (IfaceId name ty idinfo) = do
1158             putByte bh 0
1159             put_ bh (occNameFS name)
1160             put_ bh ty
1161             put_ bh idinfo
1162     put_ _ (IfaceForeign _ _) = 
1163         error "Binary.put_(IfaceDecl): IfaceForeign"
1164     put_ bh (IfaceData a1 a2 a3 a4 a5 a6 a7 a8) = do
1165             putByte bh 2
1166             put_ bh (occNameFS a1)
1167             put_ bh a2
1168             put_ bh a3
1169             put_ bh a4
1170             put_ bh a5
1171             put_ bh a6
1172             put_ bh a7
1173             put_ bh a8
1174     put_ bh (IfaceSyn a1 a2 a3 a4 a5) = do
1175             putByte bh 3
1176             put_ bh (occNameFS a1)
1177             put_ bh a2
1178             put_ bh a3
1179             put_ bh a4
1180             put_ bh a5
1181     put_ bh (IfaceClass a1 a2 a3 a4 a5 a6 a7) = do
1182             putByte bh 4
1183             put_ bh a1
1184             put_ bh (occNameFS a2)
1185             put_ bh a3
1186             put_ bh a4
1187             put_ bh a5
1188             put_ bh a6
1189             put_ bh a7
1190     get bh = do
1191             h <- getByte bh
1192             case h of
1193               0 -> do name   <- get bh
1194                       ty     <- get bh
1195                       idinfo <- get bh
1196                       occ <- return $! mkOccNameFS varName name
1197                       return (IfaceId occ ty idinfo)
1198               1 -> error "Binary.get(TyClDecl): ForeignType"
1199               2 -> do
1200                     a1 <- get bh
1201                     a2 <- get bh
1202                     a3 <- get bh
1203                     a4 <- get bh
1204                     a5 <- get bh
1205                     a6 <- get bh
1206                     a7 <- get bh
1207                     a8 <- get bh
1208                     occ <- return $! mkOccNameFS tcName a1
1209                     return (IfaceData occ a2 a3 a4 a5 a6 a7 a8)
1210               3 -> do
1211                     a1 <- get bh
1212                     a2 <- get bh
1213                     a3 <- get bh
1214                     a4 <- get bh
1215                     a5 <- get bh
1216                     occ <- return $! mkOccNameFS tcName a1
1217                     return (IfaceSyn occ a2 a3 a4 a5)
1218               _ -> do
1219                     a1 <- get bh
1220                     a2 <- get bh
1221                     a3 <- get bh
1222                     a4 <- get bh
1223                     a5 <- get bh
1224                     a6 <- get bh
1225                     a7 <- get bh
1226                     occ <- return $! mkOccNameFS clsName a2
1227                     return (IfaceClass a1 occ a3 a4 a5 a6 a7)
1228
1229 instance Binary IfaceInst where
1230     put_ bh (IfaceInst cls tys dfun flag orph) = do
1231             put_ bh cls
1232             put_ bh tys
1233             put_ bh dfun
1234             put_ bh flag
1235             put_ bh orph
1236     get bh = do cls  <- get bh
1237                 tys  <- get bh
1238                 dfun <- get bh
1239                 flag <- get bh
1240                 orph <- get bh
1241                 return (IfaceInst cls tys dfun flag orph)
1242
1243 instance Binary IfaceFamInst where
1244     put_ bh (IfaceFamInst fam tys tycon) = do
1245             put_ bh fam
1246             put_ bh tys
1247             put_ bh tycon
1248     get bh = do fam   <- get bh
1249                 tys   <- get bh
1250                 tycon <- get bh
1251                 return (IfaceFamInst fam tys tycon)
1252
1253 instance Binary OverlapFlag where
1254     put_ bh NoOverlap  = putByte bh 0
1255     put_ bh OverlapOk  = putByte bh 1
1256     put_ bh Incoherent = putByte bh 2
1257     get bh = do h <- getByte bh
1258                 case h of
1259                   0 -> return NoOverlap
1260                   1 -> return OverlapOk
1261                   2 -> return Incoherent
1262                   _ -> panic ("get OverlapFlag " ++ show h)
1263
1264 instance Binary IfaceConDecls where
1265     put_ bh IfAbstractTyCon = putByte bh 0
1266     put_ bh IfOpenDataTyCon = putByte bh 1
1267     put_ bh (IfDataTyCon cs) = do { putByte bh 2
1268                                   ; put_ bh cs }
1269     put_ bh (IfNewTyCon c)  = do { putByte bh 3
1270                                   ; put_ bh c }
1271     get bh = do
1272             h <- getByte bh
1273             case h of
1274               0 -> return IfAbstractTyCon
1275               1 -> return IfOpenDataTyCon
1276               2 -> do cs <- get bh
1277                       return (IfDataTyCon cs)
1278               _ -> do aa <- get bh
1279                       return (IfNewTyCon aa)
1280
1281 instance Binary IfaceConDecl where
1282     put_ bh (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9) = do
1283             put_ bh a1
1284             put_ bh a2
1285             put_ bh a3
1286             put_ bh a4
1287             put_ bh a5
1288             put_ bh a6
1289             put_ bh a7
1290             put_ bh a8
1291             put_ bh a9
1292     get bh = do a1 <- get bh
1293                 a2 <- get bh
1294                 a3 <- get bh          
1295                 a4 <- get bh
1296                 a5 <- get bh
1297                 a6 <- get bh
1298                 a7 <- get bh
1299                 a8 <- get bh
1300                 a9 <- get bh
1301                 return (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9)
1302
1303 instance Binary IfaceClassOp where
1304    put_ bh (IfaceClassOp n def ty) = do 
1305         put_ bh (occNameFS n)
1306         put_ bh def     
1307         put_ bh ty
1308    get bh = do
1309         n <- get bh
1310         def <- get bh
1311         ty <- get bh
1312         occ <- return $! mkOccNameFS varName n
1313         return (IfaceClassOp occ def ty)
1314
1315 instance Binary IfaceRule where
1316     put_ bh (IfaceRule a1 a2 a3 a4 a5 a6 a7) = do
1317             put_ bh a1
1318             put_ bh a2
1319             put_ bh a3
1320             put_ bh a4
1321             put_ bh a5
1322             put_ bh a6
1323             put_ bh a7
1324     get bh = do
1325             a1 <- get bh
1326             a2 <- get bh
1327             a3 <- get bh
1328             a4 <- get bh
1329             a5 <- get bh
1330             a6 <- get bh
1331             a7 <- get bh
1332             return (IfaceRule a1 a2 a3 a4 a5 a6 a7)
1333
1334 instance Binary IfaceVectInfo where
1335     put_ bh (IfaceVectInfo a1 a2 a3) = do
1336             put_ bh a1
1337             put_ bh a2
1338             put_ bh a3
1339     get bh = do
1340             a1 <- get bh
1341             a2 <- get bh
1342             a3 <- get bh
1343             return (IfaceVectInfo a1 a2 a3)
1344
1345