[project @ 2001-05-28 03:31:19 by sof]
[ghc-hetmet.git] / ghc / compiler / main / DriverPipeline.hs
1 -----------------------------------------------------------------------------
2 -- $Id: DriverPipeline.hs,v 1.71 2001/05/28 03:31:19 sof Exp $
3 --
4 -- GHC Driver
5 --
6 -- (c) Simon Marlow 2000
7 --
8 -----------------------------------------------------------------------------
9
10 #include "../includes/config.h"
11
12 module DriverPipeline (
13
14         -- interfaces for the batch-mode driver
15    GhcMode(..), getGhcMode, v_GhcMode,
16    genPipeline, runPipeline, pipeLoop,
17
18         -- interfaces for the compilation manager (interpreted/batch-mode)
19    preprocess, compile, CompResult(..),
20
21         -- batch-mode linking interface
22    doLink,
23         -- DLL building
24    doMkDLL
25   ) where
26
27 #include "HsVersions.h"
28
29 import CmStaticInfo
30 import CmTypes
31 import GetImports
32 import DriverState
33 import DriverUtil
34 import DriverMkDepend
35 import DriverPhases
36 import DriverFlags
37 import HscMain
38 import TmpFiles
39 import Finder
40 import HscTypes
41 import Outputable
42 import Module
43 import ErrUtils
44 import CmdLineOpts
45 import Config
46 import Panic
47 import Util
48
49 import Time             ( getClockTime )
50 import Directory
51 import System
52 import IOExts
53 import Exception
54
55 import IO
56 import Monad
57 import Maybe
58
59 import PackedString
60 import MatchPS
61
62 -----------------------------------------------------------------------------
63 -- GHC modes of operation
64
65 data GhcMode
66   = DoMkDependHS                        -- ghc -M
67   | DoMkDLL                             -- ghc --mk-dll
68   | StopBefore Phase                    -- ghc -E | -C | -S | -c
69   | DoMake                              -- ghc --make
70   | DoInteractive                       -- ghc --interactive
71   | DoLink                              -- [ the default ]
72   deriving (Eq)
73
74 GLOBAL_VAR(v_GhcMode, error "todo", GhcMode)
75
76 modeFlag :: String -> Maybe GhcMode
77 modeFlag "-M"            = Just $ DoMkDependHS
78 modeFlag "--mk-dll"      = Just $ DoMkDLL
79 modeFlag "-E"            = Just $ StopBefore Hsc
80 modeFlag "-C"            = Just $ StopBefore HCc
81 modeFlag "-S"            = Just $ StopBefore As
82 modeFlag "-c"            = Just $ StopBefore Ln
83 modeFlag "--make"        = Just $ DoMake
84 modeFlag "--interactive" = Just $ DoInteractive
85 modeFlag _               = Nothing
86
87 getGhcMode :: [String]
88          -> IO ( [String]   -- rest of command line
89                , GhcMode
90                , String     -- "GhcMode" flag
91                )
92 getGhcMode flags 
93   = case my_partition modeFlag flags of
94         ([]   , rest) -> return (rest, DoLink,  "") -- default is to do linking
95         ([(flag,one)], rest) -> return (rest, one, flag)
96         (_    , _   ) -> 
97           throwDyn (UsageError 
98                 "only one of the flags -M, -E, -C, -S, -c, --make, --interactive, -mk-dll is allowed")
99
100 -----------------------------------------------------------------------------
101 -- genPipeline
102 --
103 -- Herein is all the magic about which phases to run in which order, whether
104 -- the intermediate files should be in TMPDIR or in the current directory,
105 -- what the suffix of the intermediate files should be, etc.
106
107 -- The following compilation pipeline algorithm is fairly hacky.  A
108 -- better way to do this would be to express the whole compilation as a
109 -- data flow DAG, where the nodes are the intermediate files and the
110 -- edges are the compilation phases.  This framework would also work
111 -- nicely if a haskell dependency generator was included in the
112 -- driver.
113
114 -- It would also deal much more cleanly with compilation phases that
115 -- generate multiple intermediates, (eg. hsc generates .hc, .hi, and
116 -- possibly stub files), where some of the output files need to be
117 -- processed further (eg. the stub files need to be compiled by the C
118 -- compiler).
119
120 -- A cool thing to do would then be to execute the data flow graph
121 -- concurrently, automatically taking advantage of extra processors on
122 -- the host machine.  For example, when compiling two Haskell files
123 -- where one depends on the other, the data flow graph would determine
124 -- that the C compiler from the first compilation can be overlapped
125 -- with the hsc compilation for the second file.
126
127 data IntermediateFileType
128   = Temporary
129   | Persistent
130   deriving (Eq, Show)
131
132 genPipeline
133    :: GhcMode           -- when to stop
134    -> String            -- "stop after" flag (for error messages)
135    -> Bool              -- True => output is persistent
136    -> HscLang           -- preferred output language for hsc
137    -> String            -- original filename
138    -> IO [              -- list of phases to run for this file
139              (Phase,
140               IntermediateFileType,  -- keep the output from this phase?
141               String)                -- output file suffix
142          ]      
143
144 genPipeline todo stop_flag persistent_output lang filename 
145  = do
146    split      <- readIORef v_Split_object_files
147    mangle     <- readIORef v_Do_asm_mangling
148    keep_hc    <- readIORef v_Keep_hc_files
149    keep_raw_s <- readIORef v_Keep_raw_s_files
150    keep_s     <- readIORef v_Keep_s_files
151    osuf       <- readIORef v_Object_suf
152    hcsuf      <- readIORef v_HC_suf
153
154    let
155    ----------- -----  ----   ---   --   --  -  -  -
156     (_basename, suffix) = splitFilename filename
157
158     start = startPhase suffix
159
160       -- special case for mkdependHS: .hspp files go through MkDependHS
161     start_phase | todo == DoMkDependHS && start == Hsc  = MkDependHS
162                 | otherwise = start
163
164     haskellish = haskellish_suffix suffix
165     cish = cish_suffix suffix
166
167        -- for a .hc file we need to force lang to HscC
168     real_lang | start_phase == HCc || start_phase == Mangle = HscC
169               | otherwise                                   = lang
170
171    let
172    ----------- -----  ----   ---   --   --  -  -  -
173     pipeline
174       | todo == DoMkDependHS = [ Unlit, Cpp, MkDependHS ]
175
176       | haskellish = 
177        case real_lang of
178         HscC    | split && mangle -> [ Unlit, Cpp, Hsc, HCc, Mangle, 
179                                         SplitMangle, SplitAs ]
180                 | mangle          -> [ Unlit, Cpp, Hsc, HCc, Mangle, As ]
181                 | split           -> not_valid
182                 | otherwise       -> [ Unlit, Cpp, Hsc, HCc, As ]
183
184         HscAsm  | split           -> [ Unlit, Cpp, Hsc, SplitMangle, SplitAs ]
185                 | otherwise       -> [ Unlit, Cpp, Hsc, As ]
186
187         HscJava | split           -> not_valid
188                 | otherwise       -> error "not implemented: compiling via Java"
189         HscILX  | split           -> not_valid
190                 | otherwise       -> [ Unlit, Cpp, Hsc ]
191
192       | cish      = [ Cc, As ]
193
194       | otherwise = [ ]  -- just pass this file through to the linker
195
196         -- ToDo: this is somewhat cryptic
197
198     not_valid = throwDyn (UsageError ("invalid option combination"))
199    ----------- -----  ----   ---   --   --  -  -  -
200
201         -- this shouldn't happen.
202    if start_phase /= Ln && start_phase `notElem` pipeline
203         then throwDyn (CmdLineError ("can't find starting phase for "
204                                      ++ filename))
205         else do
206
207    let
208         -- .o and .hc suffixes can be overriden by command-line options:
209       myPhaseInputExt Ln  | Just s <- osuf  = s
210       myPhaseInputExt HCc | Just s <- hcsuf = s
211       myPhaseInputExt other                 = phaseInputExt other
212
213       annotatePipeline
214          :: [Phase]             -- raw pipeline
215          -> Phase               -- phase to stop before
216          -> [(Phase, IntermediateFileType, String{-file extension-})]
217       annotatePipeline []     _    = []
218       annotatePipeline (Ln:_) _    = []
219       annotatePipeline (phase:next_phase:ps) stop = 
220           (phase, keep_this_output, myPhaseInputExt next_phase)
221              : annotatePipeline (next_phase:ps) stop
222           where
223                 keep_this_output
224                      | next_phase == stop 
225                      = if persistent_output then Persistent else Temporary
226                      | otherwise
227                      = case next_phase of
228                              Ln -> Persistent
229                              Mangle | keep_raw_s -> Persistent
230                              As     | keep_s     -> Persistent
231                              HCc    | keep_hc    -> Persistent
232                              _other              -> Temporary
233
234         -- add information about output files to the pipeline
235         -- the suffix on an output file is determined by the next phase
236         -- in the pipeline, so we add linking to the end of the pipeline
237         -- to force the output from the final phase to be a .o file.
238       stop_phase = case todo of 
239                         StopBefore As | split -> SplitAs
240                         StopBefore phase      -> phase
241                         DoMkDependHS          -> Ln
242                         DoLink                -> Ln
243
244       annotated_pipeline = annotatePipeline (pipeline ++ [Ln]) stop_phase
245
246       phase_ne p (p1,_,_) = (p1 /= p)
247    ----------- -----  ----   ---   --   --  -  -  -
248
249         -- if we can't find the phase we're supposed to stop before,
250         -- something has gone wrong.  This test carefully avoids the
251         -- case where we aren't supposed to do any compilation, because the file
252         -- is already in linkable form (for example).
253    if start_phase `elem` pipeline && 
254         (stop_phase /= Ln && stop_phase `notElem` pipeline)
255       then throwDyn (UsageError 
256                 ("flag " ++ stop_flag
257                  ++ " is incompatible with source file `" ++ filename ++ "'"))
258       else do
259
260    return (
261      takeWhile (phase_ne stop_phase ) $
262      dropWhile (phase_ne start_phase) $
263      annotated_pipeline
264     )
265
266
267 runPipeline
268   :: [ (Phase, IntermediateFileType, String) ] -- phases to run
269   -> String                     -- input file
270   -> Bool                       -- doing linking afterward?
271   -> Bool                       -- take into account -o when generating output?
272   -> IO String                  -- return final filename
273
274 runPipeline pipeline input_fn do_linking use_ofile
275   = pipeLoop pipeline input_fn do_linking use_ofile basename suffix
276   where (basename, suffix) = splitFilename input_fn
277
278 pipeLoop [] input_fn _ _ _ _ = return input_fn
279 pipeLoop ((phase, keep, o_suffix):phases) 
280         input_fn do_linking use_ofile orig_basename orig_suffix
281   = do
282
283      output_fn <- outputFileName (null phases) keep o_suffix
284
285      carry_on <- run_phase phase orig_basename orig_suffix input_fn output_fn
286         -- sometimes we bail out early, eg. when the compiler's recompilation
287         -- checker has determined that recompilation isn't necessary.
288      if not carry_on 
289         then do let (_,keep,final_suffix) = last phases
290                 ofile <- outputFileName True keep final_suffix
291                 return ofile
292         else do -- carry on ...
293
294      pipeLoop phases output_fn do_linking use_ofile orig_basename orig_suffix
295
296   where
297      outputFileName last_phase keep suffix
298         = do o_file <- readIORef v_Output_file
299              if last_phase && not do_linking && use_ofile && isJust o_file
300                then case o_file of 
301                        Just s  -> return s
302                        Nothing -> error "outputFileName"
303                else if keep == Persistent
304                            then odir_ify (orig_basename ++ '.':suffix)
305                            else newTempName suffix
306
307 -------------------------------------------------------------------------------
308 -- Unlit phase 
309
310 run_phase Unlit _basename _suff input_fn output_fn
311   = do unlit <- readIORef v_Pgm_L
312        unlit_flags <- getOpts opt_L
313        runSomething "Literate pre-processor"
314           (unlit ++ unwords unlit_flags ++ 
315                     " -h " ++ input_fn ++ 
316                     ' ':input_fn ++ 
317                     ' ':output_fn)
318        return True
319
320 -------------------------------------------------------------------------------
321 -- Cpp phase 
322
323 run_phase Cpp basename suff input_fn output_fn
324   = do src_opts <- getOptionsFromSource input_fn
325        unhandled_flags <- processArgs dynamic_flags src_opts []
326        checkProcessArgsResult unhandled_flags basename suff
327
328        do_cpp <- dynFlag cppFlag
329        if do_cpp
330           then do
331             cpp <- readIORef v_Pgm_P >>= prependToolDir
332             hscpp_opts <- getOpts opt_P
333             hs_src_cpp_opts <- readIORef v_Hs_source_cpp_opts
334
335             cmdline_include_paths <- readIORef v_Include_paths
336             pkg_include_dirs <- getPackageIncludePath
337             let include_paths = map (\p -> "-I"++p) (cmdline_include_paths
338                                                         ++ pkg_include_dirs)
339
340             verb <- getVerbFlag
341             (md_c_flags, _) <- machdepCCOpts
342
343             runSomething "C pre-processor" 
344                 (unwords
345                    ([cpp, verb] 
346                     ++ include_paths
347                     ++ hs_src_cpp_opts
348                     ++ hscpp_opts
349                     ++ md_c_flags
350                     ++ [ "-x", "c", input_fn, "-o", output_fn ]
351                    ))
352         -- ToDo: switch away from using 'echo' alltogether (but need
353         -- a faster alternative than what's done below).
354 #if defined(mingw32_TARGET_OS) && defined(MINIMAL_UNIX_DEPS)
355           else (do
356             h <- openFile output_fn WriteMode
357             hPutStrLn h ("{-# LINE 1 \"" ++ input_fn ++ "\" #-}")
358             ls <- readFile input_fn -- inefficient, but it'll do for now.
359                                     -- ToDo: speed up via slurping.
360             hPutStrLn h ls
361             hClose h) `catchAllIO`
362                         (\_ -> throwDyn (PhaseFailed "Ineffective C pre-processor" (ExitFailure 1)))
363 #else
364           else do
365             runSomething "Ineffective C pre-processor"
366                    ("echo '{-# LINE 1 \""  ++ input_fn ++ "\" #-}' > " 
367                     ++ output_fn ++ " && cat " ++ input_fn
368                     ++ " >> " ++ output_fn)
369 #endif
370        return True
371
372 -----------------------------------------------------------------------------
373 -- MkDependHS phase
374
375 run_phase MkDependHS basename suff input_fn _output_fn = do 
376    src <- readFile input_fn
377    let (import_sources, import_normals, module_name) = getImports src
378
379    let orig_fn = basename ++ '.':suff
380    deps_sources <- mapM (findDependency True  orig_fn) import_sources
381    deps_normals <- mapM (findDependency False orig_fn) import_normals
382    let deps = deps_sources ++ deps_normals
383
384    osuf_opt <- readIORef v_Object_suf
385    let osuf = case osuf_opt of
386                         Nothing -> phaseInputExt Ln
387                         Just s  -> s
388
389    extra_suffixes <- readIORef v_Dep_suffixes
390    let suffixes = osuf : map (++ ('_':osuf)) extra_suffixes
391        ofiles = map (\suf -> basename ++ '.':suf) suffixes
392            
393    objs <- mapM odir_ify ofiles
394    
395    hdl <- readIORef v_Dep_tmp_hdl
396
397         -- std dependency of the object(s) on the source file
398    hPutStrLn hdl (unwords objs ++ " : " ++ basename ++ '.':suff)
399
400    let genDep (dep, False {- not an hi file -}) = 
401           hPutStrLn hdl (unwords objs ++ " : " ++ dep)
402        genDep (dep, True  {- is an hi file -}) = do
403           hisuf <- readIORef v_Hi_suf
404           let dep_base = remove_suffix '.' dep
405               deps = (dep_base ++ hisuf)
406                      : map (\suf -> dep_base ++ suf ++ '_':hisuf) extra_suffixes
407                   -- length objs should be == length deps
408           sequence_ (zipWith (\o d -> hPutStrLn hdl (o ++ " : " ++ d)) objs deps)
409
410    mapM genDep [ d | Just d <- deps ]
411
412    return True
413
414 -- add the lines to dep_makefile:
415            -- always:
416                    -- this.o : this.hs
417
418            -- if the dependency is on something other than a .hi file:
419                    -- this.o this.p_o ... : dep
420            -- otherwise
421                    -- if the import is {-# SOURCE #-}
422                            -- this.o this.p_o ... : dep.hi-boot[-$vers]
423                            
424                    -- else
425                            -- this.o ...   : dep.hi
426                            -- this.p_o ... : dep.p_hi
427                            -- ...
428    
429            -- (where .o is $osuf, and the other suffixes come from
430            -- the cmdline -s options).
431    
432 -----------------------------------------------------------------------------
433 -- Hsc phase
434
435 -- Compilation of a single module, in "legacy" mode (_not_ under
436 -- the direction of the compilation manager).
437 run_phase Hsc basename suff input_fn output_fn
438   = do
439         
440   -- we add the current directory (i.e. the directory in which
441   -- the .hs files resides) to the import path, since this is
442   -- what gcc does, and it's probably what you want.
443         let current_dir = getdir basename
444         
445         paths <- readIORef v_Include_paths
446         writeIORef v_Include_paths (current_dir : paths)
447         
448   -- figure out where to put the .hi file
449         ohi    <- readIORef v_Output_hi
450         hisuf  <- readIORef v_Hi_suf
451         let hifile = case ohi of
452                            Nothing -> basename ++ '.':hisuf
453                            Just fn -> fn
454
455   -- figure out which header files to #include in a generated .hc file
456         c_includes <- getPackageCIncludes
457         cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
458
459         let cc_injects = unlines (map mk_include 
460                                  (c_includes ++ reverse cmdline_includes))
461             mk_include h_file = 
462                 case h_file of 
463                    '"':_{-"-} -> "#include "++h_file
464                    '<':_      -> "#include "++h_file
465                    _          -> "#include \""++h_file++"\""
466
467         writeIORef v_HCHeader cc_injects
468
469   -- figure out if the source has changed, for recompilation avoidance.
470   -- only do this if we're eventually going to generate a .o file.
471   -- (ToDo: do when generating .hc files too?)
472   --
473   -- Setting source_unchanged to True means that M.o seems
474   -- to be up to date wrt M.hs; so no need to recompile unless imports have
475   -- changed (which the compiler itself figures out).
476   -- Setting source_unchanged to False tells the compiler that M.o is out of
477   -- date wrt M.hs (or M.o doesn't exist) so we must recompile regardless.
478         do_recomp <- readIORef v_Recomp
479         todo <- readIORef v_GhcMode
480         o_file' <- odir_ify (basename ++ '.':phaseInputExt Ln)
481         o_file <- osuf_ify o_file'
482         source_unchanged <- 
483           if not (do_recomp && ( todo == DoLink || todo == StopBefore Ln ))
484              then return False
485              else do t1 <- getModificationTime (basename ++ '.':suff)
486                      o_file_exists <- doesFileExist o_file
487                      if not o_file_exists
488                         then return False       -- Need to recompile
489                         else do t2 <- getModificationTime o_file
490                                 if t2 > t1
491                                   then return True
492                                   else return False
493
494          -- build a ModuleLocation to pass to hscMain.
495         (srcimps,imps,mod_name) <- getImportsFromFile input_fn
496
497         Just (mod, location)
498            <- mkHomeModuleLocn mod_name basename (basename ++ '.':suff)
499
500   -- get the DynFlags
501         dyn_flags <- readIORef v_DynFlags
502
503         let dyn_flags' = dyn_flags { hscOutName = output_fn,
504                                      hscStubCOutName = basename ++ "_stub.c",
505                                      hscStubHOutName = basename ++ "_stub.h" }
506
507   -- run the compiler!
508         pcs <- initPersistentCompilerState
509         result <- hscMain OneShot
510                           dyn_flags' mod
511                           location{ ml_hspp_file=Just input_fn }
512                           source_unchanged
513                           False
514                           Nothing        -- no iface
515                           emptyModuleEnv -- HomeSymbolTable
516                           emptyModuleEnv -- HomeIfaceTable
517                           pcs
518
519         case result of {
520
521             HscFail pcs -> throwDyn (PhaseFailed "hsc" (ExitFailure 1));
522
523             HscNoRecomp pcs details iface -> 
524                 do {
525 #if defined(mingw32_TARGET_OS) && defined(MINIMAL_UNIX_DEPS)
526                   touch <- readIORef v_Pgm_T;
527                   runSomething "Touching object file" (unwords [dosifyPath touch, dosifyPath o_file]);
528 #else
529                   runSomething "Touching object file" (cTOUCH ++ o_file);
530 #endif
531                   return False;
532                 };
533
534             HscRecomp pcs details iface stub_h_exists stub_c_exists
535                       _maybe_interpreted_code -> do
536
537             -- deal with stubs
538         maybe_stub_o <- compileStub dyn_flags' stub_c_exists
539         case maybe_stub_o of
540                 Nothing -> return ()
541                 Just stub_o -> add v_Ld_inputs stub_o
542
543         return True
544     }
545
546 -----------------------------------------------------------------------------
547 -- Cc phase
548
549 -- we don't support preprocessing .c files (with -E) now.  Doing so introduces
550 -- way too many hacks, and I can't say I've ever used it anyway.
551
552 run_phase cc_phase basename suff input_fn output_fn
553    | cc_phase == Cc || cc_phase == HCc
554    = do cc  <- readIORef v_Pgm_c >>= prependToolDir >>= appendInstallDir
555         cc_opts <- (getOpts opt_c)
556         cmdline_include_dirs <- readIORef v_Include_paths
557
558         let hcc = cc_phase == HCc
559
560                 -- add package include paths even if we're just compiling
561                 -- .c files; this is the Value Add(TM) that using
562                 -- ghc instead of gcc gives you :)
563         pkg_include_dirs <- getPackageIncludePath
564         let include_paths = map (\p -> "-I"++p) (cmdline_include_dirs 
565                                                         ++ pkg_include_dirs)
566
567         mangle <- readIORef v_Do_asm_mangling
568         (md_c_flags, md_regd_c_flags) <- machdepCCOpts
569
570         verb <- getVerbFlag
571
572         o2 <- readIORef v_minus_o2_for_C
573         let opt_flag | o2        = "-O2"
574                      | otherwise = "-O"
575
576         pkg_extra_cc_opts <- getPackageExtraCcOpts
577
578         split_objs <- readIORef v_Split_object_files
579         let split_opt | hcc && split_objs = [ "-DUSE_SPLIT_MARKERS" ]
580                       | otherwise         = [ ]
581
582         excessPrecision <- readIORef v_Excess_precision
583         runSomething "C Compiler"
584          (unwords ([ cc, "-x", "c", input_fn, "-o", output_fn ]
585                    ++ md_c_flags
586                    ++ (if cc_phase == HCc && mangle
587                          then md_regd_c_flags
588                          else [])
589                    ++ [ verb, "-S", "-Wimplicit", opt_flag ]
590                    ++ [ "-D__GLASGOW_HASKELL__="++cProjectVersionInt ]
591                    ++ cc_opts
592                    ++ split_opt
593                    ++ (if excessPrecision then [] else [ "-ffloat-store" ])
594                    ++ include_paths
595                    ++ pkg_extra_cc_opts
596                    ))
597         return True
598
599         -- ToDo: postprocess the output from gcc
600
601 -----------------------------------------------------------------------------
602 -- Mangle phase
603
604 run_phase Mangle _basename _suff input_fn output_fn
605   = do mangler <- readIORef v_Pgm_m
606        mangler_opts <- getOpts opt_m
607        machdep_opts <-
608          if (prefixMatch "i386" cTARGETPLATFORM)
609             then do n_regs <- dynFlag stolen_x86_regs
610                     return [ show n_regs ]
611             else return []
612 #if defined(mingw32_TARGET_OS) && defined(MINIMAL_UNIX_DEPS)
613        perl_path <- prependToolDir ("perl")
614        let real_mangler = unwords [perl_path, mangler]
615 #else
616        let real_mangler = mangler
617 #endif
618        runSomething "Assembly Mangler"
619         (unwords (real_mangler : mangler_opts
620                   ++ [ input_fn, output_fn ]
621                   ++ machdep_opts
622                 ))
623        return True
624
625 -----------------------------------------------------------------------------
626 -- Splitting phase
627
628 run_phase SplitMangle _basename _suff input_fn _output_fn
629   = do  splitter <- readIORef v_Pgm_s
630         -- this is the prefix used for the split .s files
631         tmp_pfx <- readIORef v_TmpDir
632         x <- myGetProcessID
633         let split_s_prefix = tmp_pfx ++ "/ghc" ++ show x
634         writeIORef v_Split_prefix split_s_prefix
635         addFilesToClean [split_s_prefix ++ "__*"] -- d:-)
636
637         -- allocate a tmp file to put the no. of split .s files in (sigh)
638         n_files <- newTempName "n_files"
639
640 #if defined(mingw32_TARGET_OS) && defined(MINIMAL_UNIX_DEPS)
641         perl_path <- prependToolDir ("perl")
642         let real_splitter = unwords [perl_path, splitter]
643 #else
644         let real_splitter = splitter
645 #endif
646         runSomething "Split Assembly File"
647          (unwords [ real_splitter
648                   , input_fn
649                   , split_s_prefix
650                   , n_files ]
651          )
652
653         -- save the number of split files for future references
654         s <- readFile n_files
655         let n = read s :: Int
656         writeIORef v_N_split_files n
657         return True
658
659 -----------------------------------------------------------------------------
660 -- As phase
661
662 run_phase As _basename _suff input_fn output_fn
663   = do  as <- readIORef v_Pgm_a >>= prependToolDir >>= appendInstallDir
664         as_opts <- getOpts opt_a
665
666         cmdline_include_paths <- readIORef v_Include_paths
667         let cmdline_include_flags = map (\p -> "-I"++p) cmdline_include_paths
668         runSomething "Assembler"
669            (unwords (as : as_opts
670                        ++ cmdline_include_flags
671                        ++ [ "-c", input_fn, "-o",  output_fn ]
672                     ))
673         return True
674
675 run_phase SplitAs basename _suff _input_fn _output_fn
676   = do  as <- readIORef v_Pgm_a
677         as_opts <- getOpts opt_a
678
679         split_s_prefix <- readIORef v_Split_prefix
680         n <- readIORef v_N_split_files
681
682         odir <- readIORef v_Output_dir
683         let real_odir = case odir of
684                                 Nothing -> basename
685                                 Just d  -> d
686
687         let assemble_file n = do
688                     let input_s  = split_s_prefix ++ "__" ++ show n ++ ".s"
689                     let output_o = newdir real_odir 
690                                         (basename ++ "__" ++ show n ++ ".o")
691                     real_o <- osuf_ify output_o
692                     runSomething "Assembler" 
693                             (unwords (as : as_opts
694                                       ++ [ "-c", "-o", real_o, input_s ]
695                             ))
696         
697         mapM_ assemble_file [1..n]
698         return True
699
700 -----------------------------------------------------------------------------
701 -- MoveBinary sort-of-phase
702 -- After having produced a binary, move it somewhere else and generate a
703 -- wrapper script calling the binary. Currently, we need this only in 
704 -- a parallel way (i.e. in GUM), because PVM expects the binary in a
705 -- central directory.
706 -- This is called from doLink below, after linking. I haven't made it
707 -- a separate phase to minimise interfering with other modules, and
708 -- we don't need the generality of a phase (MoveBinary is always
709 -- done after linking and makes only sense in a parallel setup)   -- HWL
710
711 run_phase_MoveBinary input_fn
712   = do  
713         top_dir <- readIORef v_TopDir
714         pvm_root <- getEnv "PVM_ROOT"
715         pvm_arch <- getEnv "PVM_ARCH"
716         let 
717            pvm_executable_base = "=" ++ input_fn
718            pvm_executable = pvm_root ++ "/bin/" ++ pvm_arch ++ "/" ++ pvm_executable_base
719            sysMan = top_dir ++ "/ghc/rts/parallel/SysMan";
720         -- nuke old binary; maybe use configur'ed names for cp and rm?
721         system ("rm -f " ++ pvm_executable)
722         -- move the newly created binary into PVM land
723         system ("cp -p " ++ input_fn ++ " " ++ pvm_executable)
724         -- generate a wrapper script for running a parallel prg under PVM
725         writeFile input_fn (mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan)
726         return True
727
728 -- generates a Perl skript starting a parallel prg under PVM
729 mk_pvm_wrapper_script :: String -> String -> String -> String
730 mk_pvm_wrapper_script pvm_executable pvm_executable_base sysMan = unlines $
731  [
732   "eval 'exec perl -S $0 ${1+\"$@\"}'", 
733   "  if $running_under_some_shell;",
734   "# =!=!=!=!=!=!=!=!=!=!=!",
735   "# This script is automatically generated: DO NOT EDIT!!!",
736   "# Generated by Glasgow Haskell Compiler",
737   "# ngoqvam choHbogh vaj' vIHoHnISbej !!!!",
738   "#",
739   "$pvm_executable      = '" ++ pvm_executable ++ "';",
740   "$pvm_executable_base = '" ++ pvm_executable_base ++ "';",
741   "$SysMan = '" ++ sysMan ++ "';",
742   "",
743   {- ToDo: add the magical shortcuts again iff we actually use them -- HWL
744   "# first, some magical shortcuts to run "commands" on the binary",
745   "# (which is hidden)",
746   "if ($#ARGV == 1 && $ARGV[0] eq '+RTS' && $ARGV[1] =~ /^--((size|file|strip|rm|nm).*)/ ) {",
747   "    local($cmd) = $1;",
748   "    system("$cmd $pvm_executable");",
749   "    exit(0); # all done",
750   "}", -}
751   "",
752   "# Now, run the real binary; process the args first",
753   "$ENV{'PE'} = $pvm_executable_base;", --  ++ pvm_executable_base,
754   "$debug = '';",
755   "$nprocessors = 0; # the default: as many PEs as machines in PVM config",
756   "@nonPVM_args = ();",
757   "$in_RTS_args = 0;",
758   "",
759   "args: while ($a = shift(@ARGV)) {",
760   "    if ( $a eq '+RTS' ) {",
761   "     $in_RTS_args = 1;",
762   "    } elsif ( $a eq '-RTS' ) {",
763   "     $in_RTS_args = 0;",
764   "    }",
765   "    if ( $a eq '-d' && $in_RTS_args ) {",
766   "     $debug = '-';",
767   "    } elsif ( $a =~ /^-qN(\\d+)/ && $in_RTS_args ) {",
768   "     $nprocessors = $1;",
769   "    } elsif ( $a =~ /^-qp(\\d+)/ && $in_RTS_args ) {",
770   "     $nprocessors = $1;",
771   "    } else {",
772   "     push(@nonPVM_args, $a);",
773   "    }",
774   "}",
775   "",
776   "local($return_val) = 0;",
777   "# Start the parallel execution by calling SysMan",
778   "system(\"$SysMan $debug $pvm_executable $nprocessors @nonPVM_args\");",
779   "$return_val = $?;",
780   "# ToDo: fix race condition moving files and flushing them!!",
781   "system(\"cp $ENV{'HOME'}/$pvm_executable_base.???.gr .\") if -f \"$ENV{'HOME'}/$pvm_executable_base.002.gr\";",
782   "exit($return_val);"
783  ]
784
785 -----------------------------------------------------------------------------
786 -- Complain about non-dynamic flags in OPTIONS pragmas
787
788 checkProcessArgsResult flags basename suff
789   = do when (not (null flags)) (throwDyn (ProgramError (
790            basename ++ "." ++ suff 
791            ++ ": static flags are not allowed in {-# OPTIONS #-} pragmas:\n\t" 
792            ++ unwords flags)) (ExitFailure 1))
793
794 -----------------------------------------------------------------------------
795 -- Linking
796
797 doLink :: [String] -> IO ()
798 doLink o_files = do
799     ln <- readIORef v_Pgm_l >>= prependToolDir >>= appendInstallDir
800     verb <- getVerbFlag
801     static <- readIORef v_Static
802     let imp = if static then "" else "_imp"
803     no_hs_main <- readIORef v_NoHsMain
804
805     o_file <- readIORef v_Output_file
806     let output_fn = case o_file of { Just s -> s; Nothing -> "a.out"; }
807
808     pkg_lib_paths <- getPackageLibraryPath
809     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
810
811     lib_paths <- readIORef v_Library_paths
812     let lib_path_opts = map ("-L"++) lib_paths
813
814     pkg_libs <- getPackageLibraries
815     let pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
816
817     libs <- readIORef v_Cmdline_libraries
818     let lib_opts = map ("-l"++) (reverse libs)
819          -- reverse because they're added in reverse order from the cmd line
820
821     pkg_extra_ld_opts <- getPackageExtraLdOpts
822
823         -- probably _stub.o files
824     extra_ld_inputs <- readIORef v_Ld_inputs
825
826         -- opts from -optl-<blah>
827     extra_ld_opts <- getStaticOpts v_Opt_l
828
829     rts_pkg <- getPackageDetails ["rts"]
830     std_pkg <- getPackageDetails ["std"]
831 #ifdef mingw32_TARGET_OS
832     let extra_os = if static || no_hs_main
833                    then []
834                    else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
835                           head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
836 #endif
837     (md_c_flags, _) <- machdepCCOpts
838     runSomething "Linker"
839        (unwords
840          ([ ln, verb, "-o", output_fn ]
841          ++ md_c_flags
842          ++ o_files
843 #ifdef mingw32_TARGET_OS
844          ++ extra_os
845 #endif
846          ++ extra_ld_inputs
847          ++ lib_path_opts
848          ++ lib_opts
849          ++ pkg_lib_path_opts
850          ++ pkg_lib_opts
851          ++ pkg_extra_ld_opts
852          ++ extra_ld_opts
853 #ifdef mingw32_TARGET_OS
854          ++ if static then [ "-u _PrelMain_mainIO_closure" , "-u ___init_PrelMain"] else []
855 #else
856          ++ [ "-u PrelMain_mainIO_closure" , "-u __init_PrelMain"]
857 #endif
858         )
859        )
860     -- parallel only: move binary to another dir -- HWL
861     ways_ <- readIORef v_Ways
862     when (WayPar `elem` ways_) (do 
863                                   success <- run_phase_MoveBinary output_fn
864                                   if success then return ()
865                                              else throwDyn (InstallationError ("cannot move binary to PVM dir")))
866
867 -----------------------------------------------------------------------------
868 -- Making a DLL
869
870 -- only for Win32, but bits that are #ifdefed in doLn are still #ifdefed here
871 -- in a vain attempt to aid future portability
872 doMkDLL :: [String] -> IO ()
873 doMkDLL o_files = do
874     ln <- readIORef v_Pgm_dll >>= prependToolDir >>= appendInstallDir
875     verb <- getVerbFlag
876     static <- readIORef v_Static
877     let imp = if static then "" else "_imp"
878     no_hs_main <- readIORef v_NoHsMain
879
880     o_file <- readIORef v_Output_file
881     let output_fn = case o_file of { Just s -> s; Nothing -> "HSdll.dll"; }
882
883     pkg_lib_paths <- getPackageLibraryPath
884     let pkg_lib_path_opts = map ("-L"++) pkg_lib_paths
885
886     lib_paths <- readIORef v_Library_paths
887     let lib_path_opts = map ("-L"++) lib_paths
888
889     pkg_libs <- getPackageLibraries
890     let pkg_lib_opts = map (\lib -> "-l" ++ lib ++ imp) pkg_libs
891
892     libs <- readIORef v_Cmdline_libraries
893     let lib_opts = map ("-l"++) (reverse libs)
894          -- reverse because they're added in reverse order from the cmd line
895
896     pkg_extra_ld_opts <- getPackageExtraLdOpts
897
898         -- probably _stub.o files
899     extra_ld_inputs <- readIORef v_Ld_inputs
900
901         -- opts from -optdll-<blah>
902     extra_ld_opts <- getStaticOpts v_Opt_dll
903
904     rts_pkg <- getPackageDetails ["rts"]
905     std_pkg <- getPackageDetails ["std"]
906 #ifdef mingw32_TARGET_OS
907     let extra_os = if static || no_hs_main
908                    then []
909                    else [ head (library_dirs (head rts_pkg)) ++ "/Main.dll_o",
910                           head (library_dirs (head std_pkg)) ++ "/PrelMain.dll_o" ]
911 #endif
912     (md_c_flags, _) <- machdepCCOpts
913     runSomething "DLL creator"
914        (unwords
915          ([ ln, verb, "-o", output_fn ]
916          ++ md_c_flags
917          ++ o_files
918 #ifdef mingw32_TARGET_OS
919          ++ extra_os
920          ++ [ "--target=i386-mingw32" ]
921 #endif
922          ++ extra_ld_inputs
923          ++ lib_path_opts
924          ++ lib_opts
925          ++ pkg_lib_path_opts
926          ++ pkg_lib_opts
927          ++ pkg_extra_ld_opts
928          ++ (case findPS (packString (concat extra_ld_opts)) (packString "--def") of
929                Nothing -> [ "--export-all" ]
930                Just _  -> [ "" ])
931          ++ extra_ld_opts
932         )
933        )
934
935 -----------------------------------------------------------------------------
936 -- Just preprocess a file, put the result in a temp. file (used by the
937 -- compilation manager during the summary phase).
938
939 preprocess :: FilePath -> IO FilePath
940 preprocess filename =
941   ASSERT(haskellish_src_file filename) 
942   do init_dyn_flags <- readIORef v_InitDynFlags
943      writeIORef v_DynFlags init_dyn_flags
944      pipeline <- genPipeline (StopBefore Hsc) ("preprocess") False 
945                         defaultHscLang filename
946      runPipeline pipeline filename False{-no linking-} False{-no -o flag-}
947
948 -----------------------------------------------------------------------------
949 -- Compile a single module, under the control of the compilation manager.
950 --
951 -- This is the interface between the compilation manager and the
952 -- compiler proper (hsc), where we deal with tedious details like
953 -- reading the OPTIONS pragma from the source file, and passing the
954 -- output of hsc through the C compiler.
955
956 -- The driver sits between 'compile' and 'hscMain', translating calls
957 -- to the former into calls to the latter, and results from the latter
958 -- into results from the former.  It does things like preprocessing
959 -- the .hs file if necessary, and compiling up the .stub_c files to
960 -- generate Linkables.
961
962 -- NB.  No old interface can also mean that the source has changed.
963
964 compile :: GhciMode                -- distinguish batch from interactive
965         -> ModSummary              -- summary, including source
966         -> Bool                    -- True <=> source unchanged
967         -> Bool                    -- True <=> have object
968         -> Maybe ModIface          -- old interface, if available
969         -> HomeSymbolTable         -- for home module ModDetails
970         -> HomeIfaceTable          -- for home module Ifaces
971         -> PersistentCompilerState -- persistent compiler state
972         -> IO CompResult
973
974 data CompResult
975    = CompOK   PersistentCompilerState   -- updated PCS
976               ModDetails  -- new details (HST additions)
977               ModIface    -- new iface   (HIT additions)
978               (Maybe Linkable)
979                        -- new code; Nothing => compilation was not reqd
980                        -- (old code is still valid)
981
982    | CompErrs PersistentCompilerState   -- updated PCS
983
984
985 compile ghci_mode summary source_unchanged have_object 
986         old_iface hst hit pcs = do 
987    init_dyn_flags <- readIORef v_InitDynFlags
988    writeIORef v_DynFlags init_dyn_flags
989
990    showPass init_dyn_flags 
991         (showSDoc (text "Compiling" <+> ppr (name_of_summary summary)))
992
993    let verb = verbosity init_dyn_flags
994    let location   = ms_location summary
995    let input_fn   = unJust "compile:hs" (ml_hs_file location) 
996    let input_fnpp = unJust "compile:hspp" (ml_hspp_file location)
997
998    when (verb >= 2) (hPutStrLn stderr ("compile: input file " ++ input_fnpp))
999
1000    opts <- getOptionsFromSource input_fnpp
1001    processArgs dynamic_flags opts []
1002    dyn_flags <- readIORef v_DynFlags
1003
1004    let hsc_lang = hscLang dyn_flags
1005        (basename, _) = splitFilename input_fn
1006        
1007    output_fn <- case hsc_lang of
1008                     HscAsm         -> newTempName (phaseInputExt As)
1009                     HscC           -> newTempName (phaseInputExt HCc)
1010                     HscJava        -> newTempName "java" -- ToDo
1011                     HscILX         -> return (basename ++ ".ilx")       -- newTempName "ilx"    -- ToDo
1012                     HscInterpreted -> return (error "no output file")
1013
1014    let dyn_flags' = dyn_flags { hscOutName = output_fn,
1015                                 hscStubCOutName = basename ++ "_stub.c",
1016                                 hscStubHOutName = basename ++ "_stub.h" }
1017
1018    -- figure out which header files to #include in a generated .hc file
1019    c_includes <- getPackageCIncludes
1020    cmdline_includes <- dynFlag cmdlineHcIncludes -- -#include options
1021
1022    let cc_injects = unlines (map mk_include 
1023                                  (c_includes ++ reverse cmdline_includes))
1024        mk_include h_file = 
1025         case h_file of 
1026            '"':_{-"-} -> "#include "++h_file
1027            '<':_      -> "#include "++h_file
1028            _          -> "#include \""++h_file++"\""
1029
1030    writeIORef v_HCHeader cc_injects
1031
1032    -- run the compiler
1033    hsc_result <- hscMain ghci_mode dyn_flags'
1034                          (ms_mod summary) location
1035                          source_unchanged have_object old_iface hst hit pcs
1036
1037    case hsc_result of
1038       HscFail pcs -> return (CompErrs pcs)
1039
1040       HscNoRecomp pcs details iface -> return (CompOK pcs details iface Nothing)
1041
1042       HscRecomp pcs details iface
1043         stub_h_exists stub_c_exists maybe_interpreted_code -> do
1044            
1045            let 
1046            maybe_stub_o <- compileStub dyn_flags' stub_c_exists
1047            let stub_unlinked = case maybe_stub_o of
1048                                   Nothing -> []
1049                                   Just stub_o -> [ DotO stub_o ]
1050
1051            (hs_unlinked, unlinked_time) <-
1052              case hsc_lang of
1053
1054                 -- in interpreted mode, just return the compiled code
1055                 -- as our "unlinked" object.
1056                 HscInterpreted -> 
1057                     case maybe_interpreted_code of
1058                        Just (bcos,itbl_env) -> do tm <- getClockTime 
1059                                                   return ([BCOs bcos itbl_env], tm)
1060                        Nothing -> panic "compile: no interpreted code"
1061
1062                 -- we're in batch mode: finish the compilation pipeline.
1063                 _other -> do pipe <- genPipeline (StopBefore Ln) "" True 
1064                                         hsc_lang output_fn
1065                              -- runPipeline takes input_fn so it can split off 
1066                              -- the base name and use it as the base of 
1067                              -- the output object file.
1068                              let (basename, suffix) = splitFilename input_fn
1069                              o_file <- pipeLoop pipe output_fn False False 
1070                                                 basename suffix
1071                              o_time <- getModificationTime o_file
1072                              return ([DotO o_file], o_time)
1073
1074            let linkable = LM unlinked_time (moduleName (ms_mod summary)) 
1075                              (hs_unlinked ++ stub_unlinked)
1076
1077            return (CompOK pcs details iface (Just linkable))
1078
1079
1080 -----------------------------------------------------------------------------
1081 -- stub .h and .c files (for foreign export support)
1082
1083 compileStub dflags stub_c_exists
1084   | not stub_c_exists = return Nothing
1085   | stub_c_exists = do
1086         -- compile the _stub.c file w/ gcc
1087         let stub_c = hscStubCOutName dflags
1088         pipeline <- genPipeline (StopBefore Ln) "" True defaultHscLang stub_c
1089         stub_o <- runPipeline pipeline stub_c False{-no linking-} 
1090                         False{-no -o option-}
1091
1092         return (Just stub_o)