Another round of External Core fixes
[ghc-hetmet.git] / compiler / main / CodeOutput.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
3 %
4 \section{Code output phase}
5
6 \begin{code}
7 module CodeOutput( codeOutput, outputForeignStubs ) where
8
9 #include "HsVersions.h"
10
11 #ifndef OMIT_NATIVE_CODEGEN
12 import UniqSupply       ( mkSplitUniqSupply )
13 import AsmCodeGen       ( nativeCodeGen )
14 #endif
15
16 #ifdef JAVA
17 import JavaGen          ( javaGen )
18 import qualified PrintJava
19 import OccurAnal        ( occurAnalyseBinds )
20 #endif
21
22 import Finder           ( mkStubPaths )
23 import PprC             ( writeCs )
24 import CmmLint          ( cmmLint )
25 import Packages
26 import Util
27 import Cmm              ( RawCmm )
28 import HscTypes
29 import DynFlags
30
31 import ErrUtils         ( dumpIfSet_dyn, showPass, ghcExit )
32 import Outputable
33 import Module
34 import Maybes           ( firstJust )
35
36 import Distribution.Package     ( showPackageId )
37 import Directory        ( doesFileExist )
38 import Monad            ( when )
39 import IO
40 import System.FilePath
41 \end{code}
42
43 %************************************************************************
44 %*                                                                      *
45 \subsection{Steering}
46 %*                                                                      *
47 %************************************************************************
48
49 \begin{code}
50 codeOutput :: DynFlags
51            -> Module
52            -> ModLocation
53            -> ForeignStubs
54            -> [PackageId]
55            -> [RawCmm]                  -- Compiled C--
56            -> IO (Bool{-stub_h_exists-}, Bool{-stub_c_exists-})
57
58 codeOutput dflags this_mod location foreign_stubs pkg_deps flat_abstractC
59   = 
60     -- You can have C (c_output) or assembly-language (ncg_output),
61     -- but not both.  [Allowing for both gives a space leak on
62     -- flat_abstractC.  WDP 94/10]
63
64     -- Dunno if the above comment is still meaningful now.  JRS 001024.
65
66     do  { when (dopt Opt_DoCmmLinting dflags) $ do
67                 { showPass dflags "CmmLint"
68                 ; let lints = map cmmLint flat_abstractC
69                 ; case firstJust lints of
70                         Just err -> do { printDump err
71                                        ; ghcExit dflags 1
72                                        }
73                         Nothing  -> return ()
74                 }
75
76         ; showPass dflags "CodeOutput"
77         ; let filenm = hscOutName dflags 
78         ; stubs_exist <- outputForeignStubs dflags this_mod location foreign_stubs
79         ; case hscTarget dflags of {
80              HscInterpreted -> return ();
81              HscAsm         -> outputAsm dflags filenm flat_abstractC;
82              HscC           -> outputC dflags filenm flat_abstractC pkg_deps;
83              HscJava        -> 
84 #ifdef JAVA
85                                outputJava dflags filenm mod_name tycons core_binds;
86 #else
87                                panic "Java support not compiled into this ghc";
88 #endif
89              HscNothing     -> panic "codeOutput: HscNothing"
90           }
91         ; return stubs_exist
92         }
93
94 doOutput :: String -> (Handle -> IO ()) -> IO ()
95 doOutput filenm io_action = bracket (openFile filenm WriteMode) hClose io_action
96 \end{code}
97
98
99 %************************************************************************
100 %*                                                                      *
101 \subsection{C}
102 %*                                                                      *
103 %************************************************************************
104
105 \begin{code}
106 outputC :: DynFlags
107         -> FilePath
108         -> [RawCmm]
109         -> [PackageId]
110         -> IO ()
111
112 outputC dflags filenm flat_absC packages
113   = do 
114        -- figure out which header files to #include in the generated .hc file:
115        --
116        --   * extra_includes from packages
117        --   * -#include options from the cmdline and OPTIONS pragmas
118        --   * the _stub.h file, if there is one.
119        --
120        let rts = getPackageDetails (pkgState dflags) rtsPackageId
121                        
122        let cc_injects = unlines (map mk_include (includes rts))
123            mk_include h_file = 
124             case h_file of 
125                '"':_{-"-} -> "#include "++h_file
126                '<':_      -> "#include "++h_file
127                _          -> "#include \""++h_file++"\""
128
129        pkg_configs <- getPreloadPackagesAnd dflags packages
130        let pkg_names = map (showPackageId.package) pkg_configs
131
132        doOutput filenm $ \ h -> do
133           hPutStr h ("/* GHC_PACKAGES " ++ unwords pkg_names ++ "\n*/\n")
134           hPutStr h cc_injects
135           writeCs dflags h flat_absC
136 \end{code}
137
138
139 %************************************************************************
140 %*                                                                      *
141 \subsection{Assembler}
142 %*                                                                      *
143 %************************************************************************
144
145 \begin{code}
146 outputAsm :: DynFlags -> FilePath -> [RawCmm] -> IO ()
147 outputAsm dflags filenm flat_absC
148
149 #ifndef OMIT_NATIVE_CODEGEN
150
151   = do ncg_uniqs <- mkSplitUniqSupply 'n'
152
153        {-# SCC "OutputAsm" #-} doOutput filenm $
154            \f -> {-# SCC "NativeCodeGen" #-}
155                  nativeCodeGen dflags f ncg_uniqs flat_absC
156   where
157
158 #else /* OMIT_NATIVE_CODEGEN */
159
160   = pprPanic "This compiler was built without a native code generator"
161              (text "Use -fvia-C instead")
162
163 #endif
164 \end{code}
165
166
167 %************************************************************************
168 %*                                                                      *
169 \subsection{Java}
170 %*                                                                      *
171 %************************************************************************
172
173 \begin{code}
174 #ifdef JAVA
175 outputJava dflags filenm mod tycons core_binds
176   = doOutput filenm (\ f -> printForUser f alwaysQualify pp_java)
177         -- User style printing for now to keep indentation
178   where
179     occ_anal_binds = occurAnalyseBinds core_binds
180         -- Make sure we have up to date dead-var information
181     java_code = javaGen mod [{- Should be imports-}] tycons occ_anal_binds
182     pp_java   = PrintJava.compilationUnit java_code
183 #endif
184 \end{code}
185
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection{Foreign import/export}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 outputForeignStubs :: DynFlags -> Module -> ModLocation -> ForeignStubs
195                    -> IO (Bool,         -- Header file created
196                           Bool)         -- C file created
197 outputForeignStubs dflags mod location stubs
198  = case stubs of
199    NoStubs -> do
200         -- When compiling External Core files, may need to use stub
201         -- files from a previous compilation
202         stub_c_exists <- doesFileExist stub_c
203         stub_h_exists <- doesFileExist stub_h
204         return (stub_h_exists, stub_c_exists)
205
206    ForeignStubs h_code c_code -> do
207         let
208             stub_c_output_d = pprCode CStyle c_code
209             stub_c_output_w = showSDoc stub_c_output_d
210         
211             -- Header file protos for "foreign export"ed functions.
212             stub_h_output_d = pprCode CStyle h_code
213             stub_h_output_w = showSDoc stub_h_output_d
214         -- in
215
216         createDirectoryHierarchy (takeDirectory stub_c)
217
218         dumpIfSet_dyn dflags Opt_D_dump_foreign
219                       "Foreign export header file" stub_h_output_d
220
221         -- we need the #includes from the rts package for the stub files
222         let rts_includes = 
223                let rts_pkg = getPackageDetails (pkgState dflags) rtsPackageId in
224                concatMap mk_include (includes rts_pkg)
225             mk_include i = "#include \"" ++ i ++ "\"\n"
226
227         stub_h_file_exists
228            <- outputForeignStubs_help stub_h stub_h_output_w
229                 ("#include \"HsFFI.h\"\n" ++ cplusplus_hdr) cplusplus_ftr
230
231         dumpIfSet_dyn dflags Opt_D_dump_foreign
232                       "Foreign export stubs" stub_c_output_d
233
234         stub_c_file_exists
235            <- outputForeignStubs_help stub_c stub_c_output_w
236                 ("#define IN_STG_CODE 0\n" ++ 
237                  "#include \"Rts.h\"\n" ++
238                  rts_includes ++
239                  cplusplus_hdr)
240                  cplusplus_ftr
241            -- We're adding the default hc_header to the stub file, but this
242            -- isn't really HC code, so we need to define IN_STG_CODE==0 to
243            -- avoid the register variables etc. being enabled.
244
245         return (stub_h_file_exists, stub_c_file_exists)
246   where
247    (stub_c, stub_h, _) = mkStubPaths dflags (moduleName mod) location
248
249    cplusplus_hdr = "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"
250    cplusplus_ftr = "#ifdef __cplusplus\n}\n#endif\n"
251
252
253 -- Don't use doOutput for dumping the f. export stubs
254 -- since it is more than likely that the stubs file will
255 -- turn out to be empty, in which case no file should be created.
256 outputForeignStubs_help :: FilePath -> String -> String -> String -> IO Bool
257 outputForeignStubs_help _fname ""      _header _footer = return False
258 outputForeignStubs_help fname doc_str header footer
259    = do writeFile fname (header ++ doc_str ++ '\n':footer ++ "\n")
260         return True
261 \end{code}
262