Generate a new unique for each label
[ghc-hetmet.git] / compiler / cmm / CmmParse.y
1 -----------------------------------------------------------------------------
2 --
3 -- (c) The University of Glasgow, 2004
4 --
5 -- Parser for concrete Cmm.
6 --
7 -----------------------------------------------------------------------------
8
9 {
10 module CmmParse ( parseCmmFile ) where
11
12 import CgMonad
13 import CgHeapery
14 import CgUtils
15 import CgProf
16 import CgTicky
17 import CgInfoTbls
18 import CgForeignCall
19 import CgTailCall       ( pushUnboxedTuple )
20 import CgStackery       ( emitPushUpdateFrame )
21 import ClosureInfo      ( C_SRT(..) )
22 import CgCallConv       ( smallLiveness )
23 import CgClosure        ( emitBlackHoleCode )
24 import CostCentre       ( dontCareCCS )
25
26 import Cmm
27 import PprCmm
28 import CmmUtils         ( mkIntCLit )
29 import CmmLex
30 import CLabel
31 import MachOp
32 import SMRep            ( fixedHdrSize, CgRep(..) )
33 import Lexer
34
35 import ForeignCall      ( CCallConv(..), Safety(..) )
36 import Literal          ( mkMachInt )
37 import Unique
38 import UniqFM
39 import SrcLoc
40 import DynFlags         ( DynFlags, DynFlag(..) )
41 import Packages         ( HomeModules )
42 import StaticFlags      ( opt_SccProfilingOn )
43 import ErrUtils         ( printError, dumpIfSet_dyn, showPass )
44 import StringBuffer     ( hGetStringBuffer )
45 import FastString
46 import Panic            ( panic )
47 import Constants        ( wORD_SIZE )
48 import Outputable
49
50 import Monad            ( when )
51 import Data.Char        ( ord )
52
53 #include "HsVersions.h"
54 }
55
56 %token
57         ':'     { L _ (CmmT_SpecChar ':') }
58         ';'     { L _ (CmmT_SpecChar ';') }
59         '{'     { L _ (CmmT_SpecChar '{') }
60         '}'     { L _ (CmmT_SpecChar '}') }
61         '['     { L _ (CmmT_SpecChar '[') }
62         ']'     { L _ (CmmT_SpecChar ']') }
63         '('     { L _ (CmmT_SpecChar '(') }
64         ')'     { L _ (CmmT_SpecChar ')') }
65         '='     { L _ (CmmT_SpecChar '=') }
66         '`'     { L _ (CmmT_SpecChar '`') }
67         '~'     { L _ (CmmT_SpecChar '~') }
68         '/'     { L _ (CmmT_SpecChar '/') }
69         '*'     { L _ (CmmT_SpecChar '*') }
70         '%'     { L _ (CmmT_SpecChar '%') }
71         '-'     { L _ (CmmT_SpecChar '-') }
72         '+'     { L _ (CmmT_SpecChar '+') }
73         '&'     { L _ (CmmT_SpecChar '&') }
74         '^'     { L _ (CmmT_SpecChar '^') }
75         '|'     { L _ (CmmT_SpecChar '|') }
76         '>'     { L _ (CmmT_SpecChar '>') }
77         '<'     { L _ (CmmT_SpecChar '<') }
78         ','     { L _ (CmmT_SpecChar ',') }
79         '!'     { L _ (CmmT_SpecChar '!') }
80
81         '..'    { L _ (CmmT_DotDot) }
82         '::'    { L _ (CmmT_DoubleColon) }
83         '>>'    { L _ (CmmT_Shr) }
84         '<<'    { L _ (CmmT_Shl) }
85         '>='    { L _ (CmmT_Ge) }
86         '<='    { L _ (CmmT_Le) }
87         '=='    { L _ (CmmT_Eq) }
88         '!='    { L _ (CmmT_Ne) }
89         '&&'    { L _ (CmmT_BoolAnd) }
90         '||'    { L _ (CmmT_BoolOr) }
91
92         'CLOSURE'       { L _ (CmmT_CLOSURE) }
93         'INFO_TABLE'    { L _ (CmmT_INFO_TABLE) }
94         'INFO_TABLE_RET'{ L _ (CmmT_INFO_TABLE_RET) }
95         'INFO_TABLE_FUN'{ L _ (CmmT_INFO_TABLE_FUN) }
96         'INFO_TABLE_CONSTR'{ L _ (CmmT_INFO_TABLE_CONSTR) }
97         'INFO_TABLE_SELECTOR'{ L _ (CmmT_INFO_TABLE_SELECTOR) }
98         'else'          { L _ (CmmT_else) }
99         'export'        { L _ (CmmT_export) }
100         'section'       { L _ (CmmT_section) }
101         'align'         { L _ (CmmT_align) }
102         'goto'          { L _ (CmmT_goto) }
103         'if'            { L _ (CmmT_if) }
104         'jump'          { L _ (CmmT_jump) }
105         'foreign'       { L _ (CmmT_foreign) }
106         'import'        { L _ (CmmT_import) }
107         'switch'        { L _ (CmmT_switch) }
108         'case'          { L _ (CmmT_case) }
109         'default'       { L _ (CmmT_default) }
110         'bits8'         { L _ (CmmT_bits8) }
111         'bits16'        { L _ (CmmT_bits16) }
112         'bits32'        { L _ (CmmT_bits32) }
113         'bits64'        { L _ (CmmT_bits64) }
114         'float32'       { L _ (CmmT_float32) }
115         'float64'       { L _ (CmmT_float64) }
116
117         GLOBALREG       { L _ (CmmT_GlobalReg   $$) }
118         NAME            { L _ (CmmT_Name        $$) }
119         STRING          { L _ (CmmT_String      $$) }
120         INT             { L _ (CmmT_Int         $$) }
121         FLOAT           { L _ (CmmT_Float       $$) }
122
123 %monad { P } { >>= } { return }
124 %lexer { cmmlex } { L _ CmmT_EOF }
125 %name cmmParse cmm
126 %tokentype { Located CmmToken }
127
128 -- C-- operator precedences, taken from the C-- spec
129 %right '||'     -- non-std extension, called %disjoin in C--
130 %right '&&'     -- non-std extension, called %conjoin in C--
131 %right '!'
132 %nonassoc '>=' '>' '<=' '<' '!=' '=='
133 %left '|'
134 %left '^'
135 %left '&'
136 %left '>>' '<<'
137 %left '-' '+'
138 %left '/' '*' '%'
139 %right '~'
140
141 %%
142
143 cmm     :: { ExtCode }
144         : {- empty -}                   { return () }
145         | cmmtop cmm                    { do $1; $2 }
146
147 cmmtop  :: { ExtCode }
148         : cmmproc                       { $1 }
149         | cmmdata                       { $1 }
150         | decl                          { $1 } 
151         | 'CLOSURE' '(' NAME ',' NAME lits ')' ';'  
152                 { do lits <- sequence $6;
153                      staticClosure $3 $5 (map getLit lits) }
154
155 -- The only static closures in the RTS are dummy closures like
156 -- stg_END_TSO_QUEUE_closure and stg_dummy_ret.  We don't need
157 -- to provide the full generality of static closures here.
158 -- In particular:
159 --      * CCS can always be CCS_DONT_CARE
160 --      * closure is always extern
161 --      * payload is always empty
162 --      * we can derive closure and info table labels from a single NAME
163
164 cmmdata :: { ExtCode }
165         : 'section' STRING '{' statics '}' 
166                 { do ss <- sequence $4;
167                      code (emitData (section $2) (concat ss)) }
168
169 statics :: { [ExtFCode [CmmStatic]] }
170         : {- empty -}                   { [] }
171         | static statics                { $1 : $2 }
172
173 -- Strings aren't used much in the RTS HC code, so it doesn't seem
174 -- worth allowing inline strings.  C-- doesn't allow them anyway.
175 static  :: { ExtFCode [CmmStatic] }
176         : NAME ':'      { return [CmmDataLabel (mkRtsDataLabelFS $1)] }
177         | type expr ';' { do e <- $2;
178                              return [CmmStaticLit (getLit e)] }
179         | type ';'                      { return [CmmUninitialised
180                                                         (machRepByteWidth $1)] }
181         | 'bits8' '[' ']' STRING ';'    { return [mkString $4] }
182         | 'bits8' '[' INT ']' ';'       { return [CmmUninitialised 
183                                                         (fromIntegral $3)] }
184         | typenot8 '[' INT ']' ';'      { return [CmmUninitialised 
185                                                 (machRepByteWidth $1 * 
186                                                         fromIntegral $3)] }
187         | 'align' INT ';'               { return [CmmAlign (fromIntegral $2)] }
188         | 'CLOSURE' '(' NAME lits ')'
189                 { do lits <- sequence $4;
190                      return $ map CmmStaticLit $
191                        mkStaticClosure (mkRtsInfoLabelFS $3) 
192                          dontCareCCS (map getLit lits) [] [] [] }
193         -- arrays of closures required for the CHARLIKE & INTLIKE arrays
194
195 lits    :: { [ExtFCode CmmExpr] }
196         : {- empty -}           { [] }
197         | ',' expr lits         { $2 : $3 }
198
199 cmmproc :: { ExtCode }
200         : info '{' body '}'
201                 { do  (info_lbl, info1, info2) <- $1;
202                       stmts <- getCgStmtsEC (loopDecls $3)
203                       blks <- code (cgStmtsToBlocks stmts)
204                       code (emitInfoTableAndCode info_lbl info1 info2 [] blks) }
205
206         | info ';'
207                 { do (info_lbl, info1, info2) <- $1;
208                      code (emitInfoTableAndCode info_lbl info1 info2 [] []) }
209
210         | NAME '{' body '}'
211                 { do stmts <- getCgStmtsEC (loopDecls $3);
212                      blks <- code (cgStmtsToBlocks stmts)
213                      code (emitProc [] (mkRtsCodeLabelFS $1) [] blks) }
214
215 info    :: { ExtFCode (CLabel, [CmmLit],[CmmLit]) }
216         : 'INFO_TABLE' '(' NAME ',' INT ',' INT ',' INT ',' STRING ',' STRING ')'
217                 -- ptrs, nptrs, closure type, description, type
218                 { stdInfo $3 $5 $7 0 $9 $11 $13 }
219         
220         | 'INFO_TABLE_FUN' '(' NAME ',' INT ',' INT ',' INT ',' STRING ',' STRING ',' INT ')'
221                 -- ptrs, nptrs, closure type, description, type, fun type
222                 { funInfo $3 $5 $7 $9 $11 $13 $15 }
223         
224         | 'INFO_TABLE_CONSTR' '(' NAME ',' INT ',' INT ',' INT ',' INT ',' STRING ',' STRING ')'
225                 -- ptrs, nptrs, tag, closure type, description, type
226                 { stdInfo $3 $5 $7 $9 $11 $13 $15 }
227         
228         | 'INFO_TABLE_SELECTOR' '(' NAME ',' INT ',' INT ',' STRING ',' STRING ')'
229                 -- selector, closure type, description, type
230                 { basicInfo $3 (mkIntCLit (fromIntegral $5)) 0 $7 $9 $11 }
231
232         | 'INFO_TABLE_RET' '(' NAME ',' INT ',' INT ',' INT maybe_vec ')'
233                 { retInfo $3 $5 $7 $9 $10 }
234
235 maybe_vec :: { [CmmLit] }
236         : {- empty -}                   { [] }
237         | ',' NAME maybe_vec            { CmmLabel (mkRtsCodeLabelFS $2) : $3 }
238
239 body    :: { ExtCode }
240         : {- empty -}                   { return () }
241         | decl body                     { do $1; $2 }
242         | stmt body                     { do $1; $2 }
243
244 decl    :: { ExtCode }
245         : type names ';'                { mapM_ (newLocal $1) $2 }
246         | 'import' names ';'            { return () }  -- ignore imports
247         | 'export' names ';'            { return () }  -- ignore exports
248
249 names   :: { [FastString] }
250         : NAME                  { [$1] }
251         | NAME ',' names        { $1 : $3 }
252
253 stmt    :: { ExtCode }
254         : ';'                                   { nopEC }
255
256         | NAME ':'
257                 { do l <- newLabel $1; code (labelC l) }
258
259         | lreg '=' expr ';'                     
260                 { do reg <- $1; e <- $3; stmtEC (CmmAssign reg e) }
261         | type '[' expr ']' '=' expr ';'
262                 { doStore $1 $3 $6 }
263         | 'foreign' STRING expr '(' hint_exprs0 ')' vols ';'
264                 {% foreignCall $2 [] $3 $5 $7 }
265         | lreg '=' 'foreign' STRING expr '(' hint_exprs0 ')' vols ';'
266                 {% let result = do r <- $1; return (r,NoHint) in
267                    foreignCall $4 [result] $5 $7 $9 }
268         | STRING lreg '=' 'foreign' STRING expr '(' hint_exprs0 ')' vols ';'
269                 {% do h <- parseHint $1;
270                       let result = do r <- $2; return (r,h) in
271                       foreignCall $5 [result] $6 $8 $10 }
272         -- stmt-level macros, stealing syntax from ordinary C-- function calls.
273         -- Perhaps we ought to use the %%-form?
274         | NAME '(' exprs0 ')' ';'
275                 {% stmtMacro $1 $3  }
276         | 'switch' maybe_range expr '{' arms default '}'
277                 { doSwitch $2 $3 $5 $6 }
278         | 'goto' NAME ';'
279                 { do l <- lookupLabel $2; stmtEC (CmmBranch l) }
280         | 'jump' expr {-maybe_actuals-} ';'
281                 { do e <- $2; stmtEC (CmmJump e []) }
282         | 'if' bool_expr '{' body '}' else      
283                 { ifThenElse $2 $4 $6 }
284
285 bool_expr :: { ExtFCode BoolExpr }
286         : bool_op                       { $1 }
287         | expr                          { do e <- $1; return (BoolTest e) }
288
289 bool_op :: { ExtFCode BoolExpr }
290         : bool_expr '&&' bool_expr      { do e1 <- $1; e2 <- $3; 
291                                           return (BoolAnd e1 e2) }
292         | bool_expr '||' bool_expr      { do e1 <- $1; e2 <- $3; 
293                                           return (BoolOr e1 e2)  }
294         | '!' bool_expr                 { do e <- $2; return (BoolNot e) }
295         | '(' bool_op ')'               { $2 }
296
297 -- This is not C-- syntax.  What to do?
298 vols    :: { Maybe [GlobalReg] }
299         : {- empty -}                   { Nothing }
300         | '[' ']'                       { Just [] }
301         | '[' globals ']'               { Just $2 }
302
303 globals :: { [GlobalReg] }
304         : GLOBALREG                     { [$1] }
305         | GLOBALREG ',' globals         { $1 : $3 }
306
307 maybe_range :: { Maybe (Int,Int) }
308         : '[' INT '..' INT ']'  { Just (fromIntegral $2, fromIntegral $4) }
309         | {- empty -}           { Nothing }
310
311 arms    :: { [([Int],ExtCode)] }
312         : {- empty -}                   { [] }
313         | arm arms                      { $1 : $2 }
314
315 arm     :: { ([Int],ExtCode) }
316         : 'case' ints ':' '{' body '}'  { ($2, $5) }
317
318 ints    :: { [Int] }
319         : INT                           { [ fromIntegral $1 ] }
320         | INT ',' ints                  { fromIntegral $1 : $3 }
321
322 default :: { Maybe ExtCode }
323         : 'default' ':' '{' body '}'    { Just $4 }
324         -- taking a few liberties with the C-- syntax here; C-- doesn't have
325         -- 'default' branches
326         | {- empty -}                   { Nothing }
327
328 else    :: { ExtCode }
329         : {- empty -}                   { nopEC }
330         | 'else' '{' body '}'           { $3 }
331
332 -- we have to write this out longhand so that Happy's precedence rules
333 -- can kick in.
334 expr    :: { ExtFCode CmmExpr } 
335         : expr '/' expr                 { mkMachOp MO_U_Quot [$1,$3] }
336         | expr '*' expr                 { mkMachOp MO_Mul [$1,$3] }
337         | expr '%' expr                 { mkMachOp MO_U_Rem [$1,$3] }
338         | expr '-' expr                 { mkMachOp MO_Sub [$1,$3] }
339         | expr '+' expr                 { mkMachOp MO_Add [$1,$3] }
340         | expr '>>' expr                { mkMachOp MO_U_Shr [$1,$3] }
341         | expr '<<' expr                { mkMachOp MO_Shl [$1,$3] }
342         | expr '&' expr                 { mkMachOp MO_And [$1,$3] }
343         | expr '^' expr                 { mkMachOp MO_Xor [$1,$3] }
344         | expr '|' expr                 { mkMachOp MO_Or [$1,$3] }
345         | expr '>=' expr                { mkMachOp MO_U_Ge [$1,$3] }
346         | expr '>' expr                 { mkMachOp MO_U_Gt [$1,$3] }
347         | expr '<=' expr                { mkMachOp MO_U_Le [$1,$3] }
348         | expr '<' expr                 { mkMachOp MO_U_Lt [$1,$3] }
349         | expr '!=' expr                { mkMachOp MO_Ne [$1,$3] }
350         | expr '==' expr                { mkMachOp MO_Eq [$1,$3] }
351         | '~' expr                      { mkMachOp MO_Not [$2] }
352         | '-' expr                      { mkMachOp MO_S_Neg [$2] }
353         | expr0 '`' NAME '`' expr0      {% do { mo <- nameToMachOp $3 ;
354                                                 return (mkMachOp mo [$1,$5]) } }
355         | expr0                         { $1 }
356
357 expr0   :: { ExtFCode CmmExpr }
358         : INT   maybe_ty         { return (CmmLit (CmmInt $1 $2)) }
359         | FLOAT maybe_ty         { return (CmmLit (CmmFloat $1 $2)) }
360         | STRING                 { do s <- code (mkStringCLit $1); 
361                                       return (CmmLit s) }
362         | reg                    { $1 }
363         | type '[' expr ']'      { do e <- $3; return (CmmLoad e $1) }
364         | '%' NAME '(' exprs0 ')' {% exprOp $2 $4 }
365         | '(' expr ')'           { $2 }
366
367
368 -- leaving out the type of a literal gives you the native word size in C--
369 maybe_ty :: { MachRep }
370         : {- empty -}                   { wordRep }
371         | '::' type                     { $2 }
372
373 hint_exprs0 :: { [ExtFCode (CmmExpr, MachHint)] }
374         : {- empty -}                   { [] }
375         | hint_exprs                    { $1 }
376
377 hint_exprs :: { [ExtFCode (CmmExpr, MachHint)] }
378         : hint_expr                     { [$1] }
379         | hint_expr ',' hint_exprs      { $1 : $3 }
380
381 hint_expr :: { ExtFCode (CmmExpr, MachHint) }
382         : expr                          { do e <- $1; return (e, inferHint e) }
383         | expr STRING                   {% do h <- parseHint $2;
384                                               return $ do
385                                                 e <- $1; return (e,h) }
386
387 exprs0  :: { [ExtFCode CmmExpr] }
388         : {- empty -}                   { [] }
389         | exprs                         { $1 }
390
391 exprs   :: { [ExtFCode CmmExpr] }
392         : expr                          { [ $1 ] }
393         | expr ',' exprs                { $1 : $3 }
394
395 reg     :: { ExtFCode CmmExpr }
396         : NAME                  { lookupName $1 }
397         | GLOBALREG             { return (CmmReg (CmmGlobal $1)) }
398
399 lreg    :: { ExtFCode CmmReg }
400         : NAME                  { do e <- lookupName $1;
401                                      return $
402                                        case e of 
403                                         CmmReg r -> r
404                                         other -> pprPanic "CmmParse:" (ftext $1 <> text " not a register") }
405         | GLOBALREG             { return (CmmGlobal $1) }
406
407 type    :: { MachRep }
408         : 'bits8'               { I8 }
409         | typenot8              { $1 }
410
411 typenot8 :: { MachRep }
412         : 'bits16'              { I16 }
413         | 'bits32'              { I32 }
414         | 'bits64'              { I64 }
415         | 'float32'             { F32 }
416         | 'float64'             { F64 }
417 {
418 section :: String -> Section
419 section "text"   = Text
420 section "data"   = Data
421 section "rodata" = ReadOnlyData
422 section "bss"    = UninitialisedData
423 section s        = OtherSection s
424
425 mkString :: String -> CmmStatic
426 mkString s = CmmString (map (fromIntegral.ord) s)
427
428 -- mkMachOp infers the type of the MachOp from the type of its first
429 -- argument.  We assume that this is correct: for MachOps that don't have
430 -- symmetrical args (e.g. shift ops), the first arg determines the type of
431 -- the op.
432 mkMachOp :: (MachRep -> MachOp) -> [ExtFCode CmmExpr] -> ExtFCode CmmExpr
433 mkMachOp fn args = do
434   arg_exprs <- sequence args
435   return (CmmMachOp (fn (cmmExprRep (head arg_exprs))) arg_exprs)
436
437 getLit :: CmmExpr -> CmmLit
438 getLit (CmmLit l) = l
439 getLit (CmmMachOp (MO_S_Neg _) [CmmLit (CmmInt i r)])  = CmmInt (negate i) r
440 getLit _ = panic "invalid literal" -- TODO messy failure
441
442 nameToMachOp :: FastString -> P (MachRep -> MachOp)
443 nameToMachOp name = 
444   case lookupUFM machOps name of
445         Nothing -> fail ("unknown primitive " ++ unpackFS name)
446         Just m  -> return m
447
448 exprOp :: FastString -> [ExtFCode CmmExpr] -> P (ExtFCode CmmExpr)
449 exprOp name args_code =
450   case lookupUFM exprMacros name of
451      Just f  -> return $ do
452         args <- sequence args_code
453         return (f args)
454      Nothing -> do
455         mo <- nameToMachOp name
456         return $ mkMachOp mo args_code
457
458 exprMacros :: UniqFM ([CmmExpr] -> CmmExpr)
459 exprMacros = listToUFM [
460   ( FSLIT("ENTRY_CODE"),   \ [x] -> entryCode x ),
461   ( FSLIT("INFO_PTR"),     \ [x] -> closureInfoPtr x ),
462   ( FSLIT("STD_INFO"),     \ [x] -> infoTable x ),
463   ( FSLIT("FUN_INFO"),     \ [x] -> funInfoTable x ),
464   ( FSLIT("GET_ENTRY"),    \ [x] -> entryCode (closureInfoPtr x) ),
465   ( FSLIT("GET_STD_INFO"), \ [x] -> infoTable (closureInfoPtr x) ),
466   ( FSLIT("GET_FUN_INFO"), \ [x] -> funInfoTable (closureInfoPtr x) ),
467   ( FSLIT("INFO_TYPE"),    \ [x] -> infoTableClosureType x ),
468   ( FSLIT("INFO_PTRS"),    \ [x] -> infoTablePtrs x ),
469   ( FSLIT("INFO_NPTRS"),   \ [x] -> infoTableNonPtrs x ),
470   ( FSLIT("RET_VEC"),      \ [info, conZ] -> retVec info conZ )
471   ]
472
473 -- we understand a subset of C-- primitives:
474 machOps = listToUFM $
475         map (\(x, y) -> (mkFastString x, y)) [
476         ( "add",        MO_Add ),
477         ( "sub",        MO_Sub ),
478         ( "eq",         MO_Eq ),
479         ( "ne",         MO_Ne ),
480         ( "mul",        MO_Mul ),
481         ( "neg",        MO_S_Neg ),
482         ( "quot",       MO_S_Quot ),
483         ( "rem",        MO_S_Rem ),
484         ( "divu",       MO_U_Quot ),
485         ( "modu",       MO_U_Rem ),
486
487         ( "ge",         MO_S_Ge ),
488         ( "le",         MO_S_Le ),
489         ( "gt",         MO_S_Gt ),
490         ( "lt",         MO_S_Lt ),
491
492         ( "geu",        MO_U_Ge ),
493         ( "leu",        MO_U_Le ),
494         ( "gtu",        MO_U_Gt ),
495         ( "ltu",        MO_U_Lt ),
496
497         ( "flt",        MO_S_Lt ),
498         ( "fle",        MO_S_Le ),
499         ( "feq",        MO_Eq ),
500         ( "fne",        MO_Ne ),
501         ( "fgt",        MO_S_Gt ),
502         ( "fge",        MO_S_Ge ),
503         ( "fneg",       MO_S_Neg ),
504
505         ( "and",        MO_And ),
506         ( "or",         MO_Or ),
507         ( "xor",        MO_Xor ),
508         ( "com",        MO_Not ),
509         ( "shl",        MO_Shl ),
510         ( "shrl",       MO_U_Shr ),
511         ( "shra",       MO_S_Shr ),
512
513         ( "lobits8",  flip MO_U_Conv I8  ),
514         ( "lobits16", flip MO_U_Conv I16 ),
515         ( "lobits32", flip MO_U_Conv I32 ),
516         ( "lobits64", flip MO_U_Conv I64 ),
517         ( "sx16",     flip MO_S_Conv I16 ),
518         ( "sx32",     flip MO_S_Conv I32 ),
519         ( "sx64",     flip MO_S_Conv I64 ),
520         ( "zx16",     flip MO_U_Conv I16 ),
521         ( "zx32",     flip MO_U_Conv I32 ),
522         ( "zx64",     flip MO_U_Conv I64 ),
523         ( "f2f32",    flip MO_S_Conv F32 ),  -- TODO; rounding mode
524         ( "f2f64",    flip MO_S_Conv F64 ),  -- TODO; rounding mode
525         ( "f2i8",     flip MO_S_Conv I8 ),
526         ( "f2i16",    flip MO_S_Conv I8 ),
527         ( "f2i32",    flip MO_S_Conv I8 ),
528         ( "f2i64",    flip MO_S_Conv I8 ),
529         ( "i2f32",    flip MO_S_Conv F32 ),
530         ( "i2f64",    flip MO_S_Conv F64 )
531         ]
532
533 parseHint :: String -> P MachHint
534 parseHint "ptr"    = return PtrHint
535 parseHint "signed" = return SignedHint
536 parseHint "float"  = return FloatHint
537 parseHint str      = fail ("unrecognised hint: " ++ str)
538
539 -- labels are always pointers, so we might as well infer the hint
540 inferHint :: CmmExpr -> MachHint
541 inferHint (CmmLit (CmmLabel _)) = PtrHint
542 inferHint (CmmReg (CmmGlobal g)) | isPtrGlobalReg g = PtrHint
543 inferHint _ = NoHint
544
545 isPtrGlobalReg Sp               = True
546 isPtrGlobalReg SpLim            = True
547 isPtrGlobalReg Hp               = True
548 isPtrGlobalReg HpLim            = True
549 isPtrGlobalReg CurrentTSO       = True
550 isPtrGlobalReg CurrentNursery   = True
551 isPtrGlobalReg _                = False
552
553 happyError :: P a
554 happyError = srcParseFail
555
556 -- -----------------------------------------------------------------------------
557 -- Statement-level macros
558
559 stmtMacro :: FastString -> [ExtFCode CmmExpr] -> P ExtCode
560 stmtMacro fun args_code = do
561   case lookupUFM stmtMacros fun of
562     Nothing -> fail ("unknown macro: " ++ unpackFS fun)
563     Just fcode -> return $ do
564         args <- sequence args_code
565         code (fcode args)
566
567 stmtMacros :: UniqFM ([CmmExpr] -> Code)
568 stmtMacros = listToUFM [
569   ( FSLIT("CCS_ALLOC"),            \[words,ccs]  -> profAlloc words ccs ),
570   ( FSLIT("CLOSE_NURSERY"),        \[]  -> emitCloseNursery ),
571   ( FSLIT("ENTER_CCS_PAP_CL"),     \[e] -> enterCostCentrePAP e ),
572   ( FSLIT("ENTER_CCS_THUNK"),      \[e] -> enterCostCentreThunk e ),
573   ( FSLIT("HP_CHK_GEN"),           \[words,liveness,reentry] -> 
574                                       hpChkGen words liveness reentry ),
575   ( FSLIT("HP_CHK_NP_ASSIGN_SP0"), \[e,f] -> hpChkNodePointsAssignSp0 e f ),
576   ( FSLIT("LOAD_THREAD_STATE"),    \[] -> emitLoadThreadState ),
577   ( FSLIT("LDV_ENTER"),            \[e] -> ldvEnter e ),
578   ( FSLIT("LDV_RECORD_CREATE"),    \[e] -> ldvRecordCreate e ),
579   ( FSLIT("OPEN_NURSERY"),         \[]  -> emitOpenNursery ),
580   ( FSLIT("PUSH_UPD_FRAME"),       \[sp,e] -> emitPushUpdateFrame sp e ),
581   ( FSLIT("SAVE_THREAD_STATE"),    \[] -> emitSaveThreadState ),
582   ( FSLIT("SET_HDR"),              \[ptr,info,ccs] -> 
583                                         emitSetDynHdr ptr info ccs ),
584   ( FSLIT("STK_CHK_GEN"),          \[words,liveness,reentry] -> 
585                                       stkChkGen words liveness reentry ),
586   ( FSLIT("STK_CHK_NP"),           \[e] -> stkChkNodePoints e ),
587   ( FSLIT("TICK_ALLOC_PRIM"),      \[hdr,goods,slop] -> 
588                                         tickyAllocPrim hdr goods slop ),
589   ( FSLIT("TICK_ALLOC_PAP"),       \[goods,slop] -> 
590                                         tickyAllocPAP goods slop ),
591   ( FSLIT("TICK_ALLOC_UP_THK"),    \[goods,slop] -> 
592                                         tickyAllocThunk goods slop ),
593   ( FSLIT("UPD_BH_UPDATABLE"),       \[] -> emitBlackHoleCode False ),
594   ( FSLIT("UPD_BH_SINGLE_ENTRY"),    \[] -> emitBlackHoleCode True ),
595
596   ( FSLIT("RET_P"),     \[a] ->       emitRetUT [(PtrArg,a)]),
597   ( FSLIT("RET_N"),     \[a] ->       emitRetUT [(NonPtrArg,a)]),
598   ( FSLIT("RET_PP"),    \[a,b] ->     emitRetUT [(PtrArg,a),(PtrArg,b)]),
599   ( FSLIT("RET_NN"),    \[a,b] ->     emitRetUT [(NonPtrArg,a),(NonPtrArg,b)]),
600   ( FSLIT("RET_NP"),    \[a,b] ->     emitRetUT [(NonPtrArg,a),(PtrArg,b)]),
601   ( FSLIT("RET_PPP"),   \[a,b,c] ->   emitRetUT [(PtrArg,a),(PtrArg,b),(PtrArg,c)]),
602   ( FSLIT("RET_NNP"),   \[a,b,c] ->   emitRetUT [(NonPtrArg,a),(NonPtrArg,b),(PtrArg,c)]),
603   ( FSLIT("RET_NNNP"),  \[a,b,c,d] -> emitRetUT [(NonPtrArg,a),(NonPtrArg,b),(NonPtrArg,c),(PtrArg,d)]),
604   ( FSLIT("RET_NPNP"),  \[a,b,c,d] -> emitRetUT [(NonPtrArg,a),(PtrArg,b),(NonPtrArg,c),(PtrArg,d)])
605
606  ]
607
608 -- -----------------------------------------------------------------------------
609 -- Our extended FCode monad.
610
611 -- We add a mapping from names to CmmExpr, to support local variable names in
612 -- the concrete C-- code.  The unique supply of the underlying FCode monad
613 -- is used to grab a new unique for each local variable.
614
615 -- In C--, a local variable can be declared anywhere within a proc,
616 -- and it scopes from the beginning of the proc to the end.  Hence, we have
617 -- to collect declarations as we parse the proc, and feed the environment
618 -- back in circularly (to avoid a two-pass algorithm).
619
620 data Named = Var CmmExpr | Label BlockId
621 type Decls = [(FastString,Named)]
622 type Env   = UniqFM Named
623
624 newtype ExtFCode a = EC { unEC :: Env -> Decls -> FCode (Decls, a) }
625
626 type ExtCode = ExtFCode ()
627
628 returnExtFC a = EC $ \e s -> return (s, a)
629 thenExtFC (EC m) k = EC $ \e s -> do (s',r) <- m e s; unEC (k r) e s'
630
631 instance Monad ExtFCode where
632   (>>=) = thenExtFC
633   return = returnExtFC
634
635 -- This function takes the variable decarations and imports and makes 
636 -- an environment, which is looped back into the computation.  In this
637 -- way, we can have embedded declarations that scope over the whole
638 -- procedure, and imports that scope over the entire module.
639 loopDecls :: ExtFCode a -> ExtFCode a
640 loopDecls (EC fcode) = 
641    EC $ \e s -> fixC (\ ~(decls,a) -> fcode (addListToUFM e decls) [])
642
643 getEnv :: ExtFCode Env
644 getEnv = EC $ \e s -> return (s, e)
645
646 addVarDecl :: FastString -> CmmExpr -> ExtCode
647 addVarDecl var expr = EC $ \e s -> return ((var, Var expr):s, ())
648
649 addLabel :: FastString -> BlockId -> ExtCode
650 addLabel name block_id = EC $ \e s -> return ((name, Label block_id):s, ())
651
652 newLocal :: MachRep -> FastString -> ExtCode
653 newLocal ty name  = do
654    u <- code newUnique
655    addVarDecl name (CmmReg (CmmLocal (LocalReg u ty)))
656
657 newLabel :: FastString -> ExtFCode BlockId
658 newLabel name = do
659    u <- code newUnique
660    addLabel name (BlockId u)
661    return (BlockId u)
662
663 lookupLabel :: FastString -> ExtFCode BlockId
664 lookupLabel name = do
665   env <- getEnv
666   return $ 
667      case lookupUFM env name of
668         Just (Label l) -> l
669         _other -> BlockId (newTagUnique (getUnique name) 'L')
670
671 -- Unknown names are treated as if they had been 'import'ed.
672 -- This saves us a lot of bother in the RTS sources, at the expense of
673 -- deferring some errors to link time.
674 lookupName :: FastString -> ExtFCode CmmExpr
675 lookupName name = do
676   env <- getEnv
677   return $ 
678      case lookupUFM env name of
679         Just (Var e) -> e
680         _other -> CmmLit (CmmLabel (mkRtsCodeLabelFS name))
681
682 -- Lifting FCode computations into the ExtFCode monad:
683 code :: FCode a -> ExtFCode a
684 code fc = EC $ \e s -> do r <- fc; return (s, r)
685
686 code2 :: (FCode (Decls,b) -> FCode ((Decls,b),c))
687          -> ExtFCode b -> ExtFCode c
688 code2 f (EC ec) = EC $ \e s -> do ((s',b),c) <- f (ec e s); return (s',c)
689
690 nopEC = code nopC
691 stmtEC stmt = code (stmtC stmt)
692 stmtsEC stmts = code (stmtsC stmts)
693 getCgStmtsEC = code2 getCgStmts'
694
695 forkLabelledCodeEC ec = do
696   stmts <- getCgStmtsEC ec
697   code (forkCgStmts stmts)
698
699 retInfo name size live_bits cl_type vector = do
700   let liveness = smallLiveness (fromIntegral size) (fromIntegral live_bits)
701       info_lbl = mkRtsRetInfoLabelFS name
702       (info1,info2) = mkRetInfoTable info_lbl liveness NoC_SRT 
703                                 (fromIntegral cl_type) vector
704   return (info_lbl, info1, info2)
705
706 stdInfo name ptrs nptrs srt_bitmap cl_type desc_str ty_str =
707   basicInfo name (packHalfWordsCLit ptrs nptrs) 
708         srt_bitmap cl_type desc_str ty_str
709
710 basicInfo name layout srt_bitmap cl_type desc_str ty_str = do
711   lit1 <- if opt_SccProfilingOn 
712                    then code $ mkStringCLit desc_str
713                    else return (mkIntCLit 0)
714   lit2 <- if opt_SccProfilingOn 
715                    then code $ mkStringCLit ty_str
716                    else return (mkIntCLit 0)
717   let info1 = mkStdInfoTable lit1 lit2 (fromIntegral cl_type) 
718                         (fromIntegral srt_bitmap)
719                         layout
720   return (mkRtsInfoLabelFS name, info1, [])
721
722 funInfo name ptrs nptrs cl_type desc_str ty_str fun_type = do
723   (label,info1,_) <- stdInfo name ptrs nptrs 0{-srt_bitmap-}
724                          cl_type desc_str ty_str 
725   let info2 = mkFunGenInfoExtraBits (fromIntegral fun_type) 0 zero zero zero
726                 -- we leave most of the fields zero here.  This is only used
727                 -- to generate the BCO info table in the RTS at the moment.
728   return (label,info1,info2)
729  where
730    zero = mkIntCLit 0
731
732
733 staticClosure :: FastString -> FastString -> [CmmLit] -> ExtCode
734 staticClosure cl_label info payload
735   = code $ emitDataLits (mkRtsDataLabelFS cl_label) lits
736   where  lits = mkStaticClosure (mkRtsInfoLabelFS info) dontCareCCS payload [] [] []
737
738 foreignCall
739         :: String
740         -> [ExtFCode (CmmReg,MachHint)]
741         -> ExtFCode CmmExpr
742         -> [ExtFCode (CmmExpr,MachHint)]
743         -> Maybe [GlobalReg] -> P ExtCode
744 foreignCall "C" results_code expr_code args_code vols
745   = return $ do
746         results <- sequence results_code
747         expr <- expr_code
748         args <- sequence args_code
749         code (emitForeignCall' PlayRisky results 
750                  (CmmForeignCall expr CCallConv) args vols)
751 foreignCall conv _ _ _ _
752   = fail ("unknown calling convention: " ++ conv)
753
754 doStore :: MachRep -> ExtFCode CmmExpr  -> ExtFCode CmmExpr -> ExtCode
755 doStore rep addr_code val_code
756   = do addr <- addr_code
757        val <- val_code
758         -- if the specified store type does not match the type of the expr
759         -- on the rhs, then we insert a coercion that will cause the type
760         -- mismatch to be flagged by cmm-lint.  If we don't do this, then
761         -- the store will happen at the wrong type, and the error will not
762         -- be noticed.
763        let coerce_val 
764                 | cmmExprRep val /= rep = CmmMachOp (MO_U_Conv rep rep) [val]
765                 | otherwise             = val
766        stmtEC (CmmStore addr coerce_val)
767
768 -- Return an unboxed tuple.
769 emitRetUT :: [(CgRep,CmmExpr)] -> Code
770 emitRetUT args = do
771   tickyUnboxedTupleReturn (length args)  -- TICK
772   (sp, stmts) <- pushUnboxedTuple 0 args
773   emitStmts stmts
774   when (sp /= 0) $ stmtC (CmmAssign spReg (cmmRegOffW spReg (-sp)))
775   stmtC (CmmJump (entryCode (CmmLoad (cmmRegOffW spReg sp) wordRep)) [])
776
777 -- -----------------------------------------------------------------------------
778 -- If-then-else and boolean expressions
779
780 data BoolExpr
781   = BoolExpr `BoolAnd` BoolExpr
782   | BoolExpr `BoolOr`  BoolExpr
783   | BoolNot BoolExpr
784   | BoolTest CmmExpr
785
786 -- ToDo: smart constructors which simplify the boolean expression.
787
788 ifThenElse cond then_part else_part = do
789      then_id <- code newLabelC
790      join_id <- code newLabelC
791      c <- cond
792      emitCond c then_id
793      else_part
794      stmtEC (CmmBranch join_id)
795      code (labelC then_id)
796      then_part
797      -- fall through to join
798      code (labelC join_id)
799
800 -- 'emitCond cond true_id'  emits code to test whether the cond is true,
801 -- branching to true_id if so, and falling through otherwise.
802 emitCond (BoolTest e) then_id = do
803   stmtEC (CmmCondBranch e then_id)
804 emitCond (BoolNot (BoolTest (CmmMachOp op args))) then_id
805   | Just op' <- maybeInvertComparison op
806   = emitCond (BoolTest (CmmMachOp op' args)) then_id
807 emitCond (BoolNot e) then_id = do
808   else_id <- code newLabelC
809   emitCond e else_id
810   stmtEC (CmmBranch then_id)
811   code (labelC else_id)
812 emitCond (e1 `BoolOr` e2) then_id = do
813   emitCond e1 then_id
814   emitCond e2 then_id
815 emitCond (e1 `BoolAnd` e2) then_id = do
816         -- we'd like to invert one of the conditionals here to avoid an
817         -- extra branch instruction, but we can't use maybeInvertComparison
818         -- here because we can't look too closely at the expression since
819         -- we're in a loop.
820   and_id <- code newLabelC
821   else_id <- code newLabelC
822   emitCond e1 and_id
823   stmtEC (CmmBranch else_id)
824   code (labelC and_id)
825   emitCond e2 then_id
826   code (labelC else_id)
827
828
829 -- -----------------------------------------------------------------------------
830 -- Table jumps
831
832 -- We use a simplified form of C-- switch statements for now.  A
833 -- switch statement always compiles to a table jump.  Each arm can
834 -- specify a list of values (not ranges), and there can be a single
835 -- default branch.  The range of the table is given either by the
836 -- optional range on the switch (eg. switch [0..7] {...}), or by
837 -- the minimum/maximum values from the branches.
838
839 doSwitch :: Maybe (Int,Int) -> ExtFCode CmmExpr -> [([Int],ExtCode)]
840          -> Maybe ExtCode -> ExtCode
841 doSwitch mb_range scrut arms deflt
842    = do 
843         -- Compile code for the default branch
844         dflt_entry <- 
845                 case deflt of
846                   Nothing -> return Nothing
847                   Just e  -> do b <- forkLabelledCodeEC e; return (Just b)
848
849         -- Compile each case branch
850         table_entries <- mapM emitArm arms
851
852         -- Construct the table
853         let
854             all_entries = concat table_entries
855             ixs = map fst all_entries
856             (min,max) 
857                 | Just (l,u) <- mb_range = (l,u)
858                 | otherwise              = (minimum ixs, maximum ixs)
859
860             entries = elems (accumArray (\_ a -> Just a) dflt_entry (min,max)
861                                 all_entries)
862         expr <- scrut
863         -- ToDo: check for out of range and jump to default if necessary
864         stmtEC (CmmSwitch expr entries)
865    where
866         emitArm :: ([Int],ExtCode) -> ExtFCode [(Int,BlockId)]
867         emitArm (ints,code) = do
868            blockid <- forkLabelledCodeEC code
869            return [ (i,blockid) | i <- ints ]
870
871
872 -- -----------------------------------------------------------------------------
873 -- Putting it all together
874
875 -- The initial environment: we define some constants that the compiler
876 -- knows about here.
877 initEnv :: Env
878 initEnv = listToUFM [
879   ( FSLIT("SIZEOF_StgHeader"), 
880     Var (CmmLit (CmmInt (fromIntegral (fixedHdrSize * wORD_SIZE)) wordRep) )),
881   ( FSLIT("SIZEOF_StgInfoTable"),
882     Var (CmmLit (CmmInt (fromIntegral stdInfoTableSizeB) wordRep) ))
883   ]
884
885 parseCmmFile :: DynFlags -> HomeModules -> FilePath -> IO (Maybe Cmm)
886 parseCmmFile dflags hmods filename = do
887   showPass dflags "ParseCmm"
888   buf <- hGetStringBuffer filename
889   let
890         init_loc = mkSrcLoc (mkFastString filename) 1 0
891         init_state = (mkPState buf init_loc dflags) { lex_state = [0] }
892                 -- reset the lex_state: the Lexer monad leaves some stuff
893                 -- in there we don't want.
894   case unP cmmParse init_state of
895     PFailed span err -> do printError span err; return Nothing
896     POk _ code -> do
897         cmm <- initC dflags hmods no_module (getCmm (unEC code initEnv [] >> return ()))
898         dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm" (pprCmms [cmm])
899         return (Just cmm)
900   where
901         no_module = panic "parseCmmFile: no module"
902 }