d1b293353acc14ff3291fc867b16ce670c6219f0
[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 ILX
17 import IlxGen           ( ilxGen )
18 #endif
19
20 #ifdef JAVA
21 import JavaGen          ( javaGen )
22 import qualified PrintJava
23 import OccurAnal        ( occurAnalyseBinds )
24 #endif
25
26 import Finder           ( mkStubPaths )
27 import PprC             ( writeCs )
28 import CmmLint          ( cmmLint )
29 import Packages
30 import Util
31 import FastString       ( unpackFS )
32 import Cmm              ( Cmm )
33 import HscTypes
34 import DynFlags
35 import ErrUtils         ( dumpIfSet_dyn, showPass, ghcExit )
36 import Outputable
37 import Pretty           ( Mode(..), printDoc )
38 import Module           ( Module, ModLocation(..) )
39 import List             ( nub )
40 import Maybes           ( firstJust )
41
42 import Distribution.Package     ( showPackageId )
43 import Directory        ( doesFileExist )
44 import Monad            ( when )
45 import IO
46 \end{code}
47
48 %************************************************************************
49 %*                                                                      *
50 \subsection{Steering}
51 %*                                                                      *
52 %************************************************************************
53
54 \begin{code}
55 codeOutput :: DynFlags
56            -> Module
57            -> ModLocation
58            -> ForeignStubs
59            -> [PackageId]
60            -> [Cmm]                     -- Compiled C--
61            -> IO (Bool{-stub_h_exists-}, Bool{-stub_c_exists-})
62
63 codeOutput dflags this_mod location foreign_stubs pkg_deps flat_abstractC
64   = 
65     -- You can have C (c_output) or assembly-language (ncg_output),
66     -- but not both.  [Allowing for both gives a space leak on
67     -- flat_abstractC.  WDP 94/10]
68
69     -- Dunno if the above comment is still meaningful now.  JRS 001024.
70
71     do  { when (dopt Opt_DoCmmLinting dflags) $ do
72                 { showPass dflags "CmmLint"
73                 ; let lints = map cmmLint flat_abstractC
74                 ; case firstJust lints of
75                         Just err -> do { printDump err
76                                        ; ghcExit dflags 1
77                                        }
78                         Nothing  -> return ()
79                 }
80
81         ; showPass dflags "CodeOutput"
82         ; let filenm = hscOutName dflags 
83         ; stubs_exist <- outputForeignStubs dflags this_mod location foreign_stubs
84         ; case hscTarget dflags of {
85              HscInterpreted -> return ();
86              HscAsm         -> outputAsm dflags filenm flat_abstractC;
87              HscC           -> outputC dflags filenm this_mod location 
88                                  flat_abstractC stubs_exist pkg_deps
89                                  foreign_stubs;
90              HscJava        -> 
91 #ifdef JAVA
92                                outputJava dflags filenm mod_name tycons core_binds;
93 #else
94                                panic "Java support not compiled into this ghc";
95 #endif
96              HscILX         -> 
97 #ifdef ILX
98                                let tycons = typeEnvTyCons type_env in
99                                outputIlx dflags filenm mod_name tycons stg_binds;
100 #else
101                                panic "ILX support not compiled into this ghc";
102 #endif
103           }
104         ; return stubs_exist
105         }
106
107 doOutput :: String -> (Handle -> IO ()) -> IO ()
108 doOutput filenm io_action = bracket (openFile filenm WriteMode) hClose io_action
109 \end{code}
110
111
112 %************************************************************************
113 %*                                                                      *
114 \subsection{C}
115 %*                                                                      *
116 %************************************************************************
117
118 \begin{code}
119 outputC dflags filenm mod location flat_absC 
120         (stub_h_exists, _) packages foreign_stubs
121   = do 
122        -- figure out which header files to #include in the generated .hc file:
123        --
124        --   * extra_includes from packages
125        --   * -#include options from the cmdline and OPTIONS pragmas
126        --   * the _stub.h file, if there is one.
127        --
128        pkg_configs <- getExplicitPackagesAnd dflags packages
129        let pkg_names = map (showPackageId.package) pkg_configs
130
131        c_includes <- getPackageCIncludes pkg_configs
132        let cmdline_includes = cmdlineHcIncludes dflags -- -#include options
133        
134            ffi_decl_headers 
135               = case foreign_stubs of
136                   NoStubs                 -> []
137                   ForeignStubs _ _ fdhs _ -> map unpackFS (nub fdhs)
138                         -- Remove duplicates, because distinct foreign import decls
139                         -- may cite the same #include.  Order doesn't matter.
140
141            all_headers =  c_includes
142                        ++ reverse cmdline_includes
143                        ++ ffi_decl_headers
144
145        let cc_injects = unlines (map mk_include all_headers)
146            mk_include h_file = 
147             case h_file of 
148                '"':_{-"-} -> "#include "++h_file
149                '<':_      -> "#include "++h_file
150                _          -> "#include \""++h_file++"\""
151
152        doOutput filenm $ \ h -> do
153           hPutStr h ("/* GHC_PACKAGES " ++ unwords pkg_names ++ "\n*/\n")
154           hPutStr h cc_injects
155           when stub_h_exists $ 
156              hPutStrLn h ("#include \"" ++ (filenameOf stub_h) ++ "\"")
157           writeCs dflags h flat_absC
158   where
159     (_, stub_h) = mkStubPaths dflags mod location
160 \end{code}
161
162
163 %************************************************************************
164 %*                                                                      *
165 \subsection{Assembler}
166 %*                                                                      *
167 %************************************************************************
168
169 \begin{code}
170 outputAsm dflags filenm flat_absC
171
172 #ifndef OMIT_NATIVE_CODEGEN
173
174   = do ncg_uniqs <- mkSplitUniqSupply 'n'
175        ncg_output_d <- _scc_ "NativeCodeGen" 
176                           nativeCodeGen dflags flat_absC ncg_uniqs
177        dumpIfSet_dyn dflags Opt_D_dump_asm "Asm code" (docToSDoc ncg_output_d)
178        _scc_ "OutputAsm" doOutput filenm $
179            \f -> printDoc LeftMode f ncg_output_d
180   where
181
182 #else /* OMIT_NATIVE_CODEGEN */
183
184   = pprPanic "This compiler was built without a native code generator"
185              (text "Use -fvia-C instead")
186
187 #endif
188 \end{code}
189
190
191 %************************************************************************
192 %*                                                                      *
193 \subsection{Java}
194 %*                                                                      *
195 %************************************************************************
196
197 \begin{code}
198 #ifdef JAVA
199 outputJava dflags filenm mod tycons core_binds
200   = doOutput filenm (\ f -> printForUser f alwaysQualify pp_java)
201         -- User style printing for now to keep indentation
202   where
203     occ_anal_binds = occurAnalyseBinds core_binds
204         -- Make sure we have up to date dead-var information
205     java_code = javaGen mod [{- Should be imports-}] tycons occ_anal_binds
206     pp_java   = PrintJava.compilationUnit java_code
207 #endif
208 \end{code}
209
210
211 %************************************************************************
212 %*                                                                      *
213 \subsection{Ilx}
214 %*                                                                      *
215 %************************************************************************
216
217 \begin{code}
218 #ifdef ILX
219 outputIlx dflags filename mod tycons stg_binds
220   =  doOutput filename (\ f -> printForC f pp_ilx)
221   where
222     pp_ilx = ilxGen mod tycons stg_binds
223 #endif
224 \end{code}
225
226
227 %************************************************************************
228 %*                                                                      *
229 \subsection{Foreign import/export}
230 %*                                                                      *
231 %************************************************************************
232
233 \begin{code}
234 outputForeignStubs :: DynFlags -> Module -> ModLocation -> ForeignStubs
235                    -> IO (Bool,         -- Header file created
236                           Bool)         -- C file created
237 outputForeignStubs dflags mod location stubs
238   | NoStubs <- stubs = do
239         -- When compiling External Core files, may need to use stub
240         -- files from a previous compilation
241         stub_c_exists <- doesFileExist stub_c
242         stub_h_exists <- doesFileExist stub_h
243         return (stub_h_exists, stub_c_exists)
244
245   | ForeignStubs h_code c_code _ _ <- stubs
246   = do
247         let
248             stub_c_output_d = pprCode CStyle c_code
249             stub_c_output_w = showSDoc stub_c_output_d
250         
251             -- Header file protos for "foreign export"ed functions.
252             stub_h_output_d = pprCode CStyle h_code
253             stub_h_output_w = showSDoc stub_h_output_d
254         -- in
255
256         createDirectoryHierarchy (directoryOf stub_c)
257
258         dumpIfSet_dyn dflags Opt_D_dump_foreign
259                       "Foreign export header file" stub_h_output_d
260
261         -- we need the #includes from the rts package for the stub files
262         let rtsid = rtsPackageId (pkgState dflags)
263             rts_includes 
264                 | ExtPackage pid <- rtsid = 
265                         let rts_pkg = getPackageDetails (pkgState dflags) pid in
266                         concatMap mk_include (includes rts_pkg)
267                 | otherwise = []
268             mk_include i = "#include \"" ++ i ++ "\"\n"
269
270         stub_h_file_exists
271            <- outputForeignStubs_help stub_h stub_h_output_w
272                 ("#include \"HsFFI.h\"\n" ++ cplusplus_hdr) cplusplus_ftr
273
274         dumpIfSet_dyn dflags Opt_D_dump_foreign
275                       "Foreign export stubs" stub_c_output_d
276
277         stub_c_file_exists
278            <- outputForeignStubs_help stub_c stub_c_output_w
279                 ("#define IN_STG_CODE 0\n" ++ 
280                  "#include \"Rts.h\"\n" ++
281                  rts_includes ++
282                  cplusplus_hdr)
283                  cplusplus_ftr
284            -- We're adding the default hc_header to the stub file, but this
285            -- isn't really HC code, so we need to define IN_STG_CODE==0 to
286            -- avoid the register variables etc. being enabled.
287
288         return (stub_h_file_exists, stub_c_file_exists)
289   where
290    (stub_c, stub_h) = mkStubPaths dflags mod location
291
292 cplusplus_hdr = "#ifdef __cplusplus\nextern \"C\" {\n#endif\n"
293 cplusplus_ftr = "#ifdef __cplusplus\n}\n#endif\n"
294
295 -- Don't use doOutput for dumping the f. export stubs
296 -- since it is more than likely that the stubs file will
297 -- turn out to be empty, in which case no file should be created.
298 outputForeignStubs_help fname ""      header footer = return False
299 outputForeignStubs_help fname doc_str header footer
300    = do writeFile fname (header ++ doc_str ++ '\n':footer ++ "\n")
301         return True
302 \end{code}
303