1 -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2004-2006
5 -- Parser for concrete Cmm.
7 -----------------------------------------------------------------------------
10 module CmmParse ( parseCmmFile ) where
50 import Data.Char ( ord )
53 #include "HsVersions.h"
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 '!') }
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) }
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 'prim' { L _ (CmmT_prim) }
107 'return' { L _ (CmmT_return) }
108 'import' { L _ (CmmT_import) }
109 'switch' { L _ (CmmT_switch) }
110 'case' { L _ (CmmT_case) }
111 'default' { L _ (CmmT_default) }
112 'bits8' { L _ (CmmT_bits8) }
113 'bits16' { L _ (CmmT_bits16) }
114 'bits32' { L _ (CmmT_bits32) }
115 'bits64' { L _ (CmmT_bits64) }
116 'float32' { L _ (CmmT_float32) }
117 'float64' { L _ (CmmT_float64) }
119 GLOBALREG { L _ (CmmT_GlobalReg $$) }
120 NAME { L _ (CmmT_Name $$) }
121 STRING { L _ (CmmT_String $$) }
122 INT { L _ (CmmT_Int $$) }
123 FLOAT { L _ (CmmT_Float $$) }
125 %monad { P } { >>= } { return }
126 %lexer { cmmlex } { L _ CmmT_EOF }
128 %tokentype { Located CmmToken }
130 -- C-- operator precedences, taken from the C-- spec
131 %right '||' -- non-std extension, called %disjoin in C--
132 %right '&&' -- non-std extension, called %conjoin in C--
134 %nonassoc '>=' '>' '<=' '<' '!=' '=='
146 : {- empty -} { return () }
147 | cmmtop cmm { do $1; $2 }
149 cmmtop :: { ExtCode }
153 | 'CLOSURE' '(' NAME ',' NAME lits ')' ';'
154 { do lits <- sequence $6;
155 staticClosure $3 $5 (map getLit lits) }
157 -- The only static closures in the RTS are dummy closures like
158 -- stg_END_TSO_QUEUE_closure and stg_dummy_ret. We don't need
159 -- to provide the full generality of static closures here.
161 -- * CCS can always be CCS_DONT_CARE
162 -- * closure is always extern
163 -- * payload is always empty
164 -- * we can derive closure and info table labels from a single NAME
166 cmmdata :: { ExtCode }
167 : 'section' STRING '{' statics '}'
168 { do ss <- sequence $4;
169 code (emitData (section $2) (concat ss)) }
171 statics :: { [ExtFCode [CmmStatic]] }
173 | static statics { $1 : $2 }
175 -- Strings aren't used much in the RTS HC code, so it doesn't seem
176 -- worth allowing inline strings. C-- doesn't allow them anyway.
177 static :: { ExtFCode [CmmStatic] }
178 : NAME ':' { return [CmmDataLabel (mkRtsDataLabelFS $1)] }
179 | type expr ';' { do e <- $2;
180 return [CmmStaticLit (getLit e)] }
181 | type ';' { return [CmmUninitialised
182 (machRepByteWidth $1)] }
183 | 'bits8' '[' ']' STRING ';' { return [mkString $4] }
184 | 'bits8' '[' INT ']' ';' { return [CmmUninitialised
186 | typenot8 '[' INT ']' ';' { return [CmmUninitialised
187 (machRepByteWidth $1 *
189 | 'align' INT ';' { return [CmmAlign (fromIntegral $2)] }
190 | 'CLOSURE' '(' NAME lits ')'
191 { do lits <- sequence $4;
192 return $ map CmmStaticLit $
193 mkStaticClosure (mkRtsInfoLabelFS $3)
194 dontCareCCS (map getLit lits) [] [] [] }
195 -- arrays of closures required for the CHARLIKE & INTLIKE arrays
197 lits :: { [ExtFCode CmmExpr] }
199 | ',' expr lits { $2 : $3 }
201 cmmproc :: { ExtCode }
202 -- TODO: add real SRT/info tables to parsed Cmm
203 : info maybe_formals '{' body '}'
204 { do (info_lbl, info) <- $1;
205 formals <- sequence $2;
206 stmts <- getCgStmtsEC (loopDecls $4)
207 blks <- code (cgStmtsToBlocks stmts)
208 code (emitInfoTableAndCode info_lbl info formals blks) }
210 | info maybe_formals ';'
211 { do (info_lbl, info) <- $1;
212 formals <- sequence $2;
213 code (emitInfoTableAndCode info_lbl info formals []) }
215 | NAME maybe_formals '{' body '}'
216 { do formals <- sequence $2;
217 stmts <- getCgStmtsEC (loopDecls $4);
218 blks <- code (cgStmtsToBlocks stmts);
219 code (emitProc (CmmNonInfo Nothing) (mkRtsCodeLabelFS $1) formals blks) }
221 info :: { ExtFCode (CLabel, CmmInfo) }
222 : 'INFO_TABLE' '(' NAME ',' INT ',' INT ',' INT ',' STRING ',' STRING ')'
223 -- ptrs, nptrs, closure type, description, type
224 { do prof <- profilingInfo $11 $13
225 return (mkRtsInfoLabelFS $3,
226 CmmInfo prof Nothing (fromIntegral $9)
227 (ThunkInfo (fromIntegral $5, fromIntegral $7) NoC_SRT)) }
229 | 'INFO_TABLE_FUN' '(' NAME ',' INT ',' INT ',' INT ',' STRING ',' STRING ',' INT ')'
230 -- ptrs, nptrs, closure type, description, type, fun type
231 { do prof <- profilingInfo $11 $13
232 return (mkRtsInfoLabelFS $3,
233 CmmInfo prof Nothing (fromIntegral $9)
234 (FunInfo (fromIntegral $5, fromIntegral $7) NoC_SRT (fromIntegral $15) 0
237 -- we leave most of the fields zero here. This is only used
238 -- to generate the BCO info table in the RTS at the moment.
240 | 'INFO_TABLE_CONSTR' '(' NAME ',' INT ',' INT ',' INT ',' INT ',' STRING ',' STRING ')'
241 -- ptrs, nptrs, tag, closure type, description, type
242 { do prof <- profilingInfo $13 $15
243 -- If profiling is on, this string gets duplicated,
244 -- but that's the way the old code did it we can fix it some other time.
245 desc_lit <- code $ mkStringCLit $13
246 return (mkRtsInfoLabelFS $3,
247 CmmInfo prof Nothing (fromIntegral $11)
248 (ConstrInfo (fromIntegral $5, fromIntegral $7) (fromIntegral $9) desc_lit)) }
250 | 'INFO_TABLE_SELECTOR' '(' NAME ',' INT ',' INT ',' STRING ',' STRING ')'
251 -- selector, closure type, description, type
252 { do prof <- profilingInfo $9 $11
253 return (mkRtsInfoLabelFS $3,
254 CmmInfo prof Nothing (fromIntegral $7)
255 (ThunkSelectorInfo (fromIntegral $5) NoC_SRT)) }
257 | 'INFO_TABLE_RET' '(' NAME ',' INT ')'
258 -- closure type (no live regs)
259 { return (mkRtsInfoLabelFS $3,
260 CmmInfo (ProfilingInfo zeroCLit zeroCLit) Nothing (fromIntegral $5)
261 (ContInfo [] NoC_SRT)) }
263 | 'INFO_TABLE_RET' '(' NAME ',' INT ',' formals0 ')'
264 -- closure type, live regs
265 { do live <- sequence (map (liftM Just) $7)
266 return (mkRtsInfoLabelFS $3,
267 CmmInfo (ProfilingInfo zeroCLit zeroCLit) Nothing (fromIntegral $5)
268 (ContInfo live NoC_SRT)) }
271 : {- empty -} { return () }
272 | decl body { do $1; $2 }
273 | stmt body { do $1; $2 }
276 : type names ';' { mapM_ (newLocal defaultKind $1) $2 }
277 | STRING type names ';' {% do k <- parseKind $1;
278 return $ mapM_ (newLocal k $2) $3 }
280 | 'import' names ';' { return () } -- ignore imports
281 | 'export' names ';' { return () } -- ignore exports
283 names :: { [FastString] }
285 | NAME ',' names { $1 : $3 }
291 { do l <- newLabel $1; code (labelC l) }
294 { do reg <- $1; e <- $3; stmtEC (CmmAssign reg e) }
295 | type '[' expr ']' '=' expr ';'
298 -- Gah! We really want to say "maybe_results" but that causes
299 -- a shift/reduce conflict with assignment. We either
300 -- we expand out the no-result and single result cases or
301 -- we tweak the syntax to avoid the conflict. The later
302 -- option is taken here because the other way would require
303 -- multiple levels of expanding and get unwieldy.
304 | maybe_results 'foreign' STRING expr '(' hint_exprs0 ')' vols ';'
305 {% foreignCall $3 $1 $4 $6 $8 NoC_SRT }
306 | maybe_results 'prim' '%' NAME '(' hint_exprs0 ')' vols ';'
307 {% primCall $1 $4 $6 $8 NoC_SRT }
308 -- stmt-level macros, stealing syntax from ordinary C-- function calls.
309 -- Perhaps we ought to use the %%-form?
310 | NAME '(' exprs0 ')' ';'
312 | 'switch' maybe_range expr '{' arms default '}'
313 { doSwitch $2 $3 $5 $6 }
315 { do l <- lookupLabel $2; stmtEC (CmmBranch l) }
316 | 'jump' expr maybe_actuals ';'
317 { do e1 <- $2; e2 <- sequence $3; stmtEC (CmmJump e1 e2) }
318 | 'return' maybe_actuals ';'
319 { do e <- sequence $2; stmtEC (CmmReturn e) }
320 | 'if' bool_expr '{' body '}' else
321 { ifThenElse $2 $4 $6 }
323 bool_expr :: { ExtFCode BoolExpr }
325 | expr { do e <- $1; return (BoolTest e) }
327 bool_op :: { ExtFCode BoolExpr }
328 : bool_expr '&&' bool_expr { do e1 <- $1; e2 <- $3;
329 return (BoolAnd e1 e2) }
330 | bool_expr '||' bool_expr { do e1 <- $1; e2 <- $3;
331 return (BoolOr e1 e2) }
332 | '!' bool_expr { do e <- $2; return (BoolNot e) }
333 | '(' bool_op ')' { $2 }
335 -- This is not C-- syntax. What to do?
336 vols :: { Maybe [GlobalReg] }
337 : {- empty -} { Nothing }
338 | '[' ']' { Just [] }
339 | '[' globals ']' { Just $2 }
341 globals :: { [GlobalReg] }
343 | GLOBALREG ',' globals { $1 : $3 }
345 maybe_range :: { Maybe (Int,Int) }
346 : '[' INT '..' INT ']' { Just (fromIntegral $2, fromIntegral $4) }
347 | {- empty -} { Nothing }
349 arms :: { [([Int],ExtCode)] }
351 | arm arms { $1 : $2 }
353 arm :: { ([Int],ExtCode) }
354 : 'case' ints ':' '{' body '}' { ($2, $5) }
357 : INT { [ fromIntegral $1 ] }
358 | INT ',' ints { fromIntegral $1 : $3 }
360 default :: { Maybe ExtCode }
361 : 'default' ':' '{' body '}' { Just $4 }
362 -- taking a few liberties with the C-- syntax here; C-- doesn't have
363 -- 'default' branches
364 | {- empty -} { Nothing }
367 : {- empty -} { nopEC }
368 | 'else' '{' body '}' { $3 }
370 -- we have to write this out longhand so that Happy's precedence rules
372 expr :: { ExtFCode CmmExpr }
373 : expr '/' expr { mkMachOp MO_U_Quot [$1,$3] }
374 | expr '*' expr { mkMachOp MO_Mul [$1,$3] }
375 | expr '%' expr { mkMachOp MO_U_Rem [$1,$3] }
376 | expr '-' expr { mkMachOp MO_Sub [$1,$3] }
377 | expr '+' expr { mkMachOp MO_Add [$1,$3] }
378 | expr '>>' expr { mkMachOp MO_U_Shr [$1,$3] }
379 | expr '<<' expr { mkMachOp MO_Shl [$1,$3] }
380 | expr '&' expr { mkMachOp MO_And [$1,$3] }
381 | expr '^' expr { mkMachOp MO_Xor [$1,$3] }
382 | expr '|' expr { mkMachOp MO_Or [$1,$3] }
383 | expr '>=' expr { mkMachOp MO_U_Ge [$1,$3] }
384 | expr '>' expr { mkMachOp MO_U_Gt [$1,$3] }
385 | expr '<=' expr { mkMachOp MO_U_Le [$1,$3] }
386 | expr '<' expr { mkMachOp MO_U_Lt [$1,$3] }
387 | expr '!=' expr { mkMachOp MO_Ne [$1,$3] }
388 | expr '==' expr { mkMachOp MO_Eq [$1,$3] }
389 | '~' expr { mkMachOp MO_Not [$2] }
390 | '-' expr { mkMachOp MO_S_Neg [$2] }
391 | expr0 '`' NAME '`' expr0 {% do { mo <- nameToMachOp $3 ;
392 return (mkMachOp mo [$1,$5]) } }
395 expr0 :: { ExtFCode CmmExpr }
396 : INT maybe_ty { return (CmmLit (CmmInt $1 $2)) }
397 | FLOAT maybe_ty { return (CmmLit (CmmFloat $1 $2)) }
398 | STRING { do s <- code (mkStringCLit $1);
401 | type '[' expr ']' { do e <- $3; return (CmmLoad e $1) }
402 | '%' NAME '(' exprs0 ')' {% exprOp $2 $4 }
403 | '(' expr ')' { $2 }
406 -- leaving out the type of a literal gives you the native word size in C--
407 maybe_ty :: { MachRep }
408 : {- empty -} { wordRep }
411 maybe_actuals :: { [ExtFCode (CmmExpr, MachHint)] }
413 | '(' hint_exprs0 ')' { $2 }
415 hint_exprs0 :: { [ExtFCode (CmmExpr, MachHint)] }
419 hint_exprs :: { [ExtFCode (CmmExpr, MachHint)] }
421 | hint_expr ',' hint_exprs { $1 : $3 }
423 hint_expr :: { ExtFCode (CmmExpr, MachHint) }
424 : expr { do e <- $1; return (e, inferHint e) }
425 | expr STRING {% do h <- parseHint $2;
427 e <- $1; return (e,h) }
429 exprs0 :: { [ExtFCode CmmExpr] }
433 exprs :: { [ExtFCode CmmExpr] }
435 | expr ',' exprs { $1 : $3 }
437 reg :: { ExtFCode CmmExpr }
438 : NAME { lookupName $1 }
439 | GLOBALREG { return (CmmReg (CmmGlobal $1)) }
441 maybe_results :: { [ExtFCode (CmmFormal, MachHint)] }
443 | '(' hint_lregs ')' '=' { $2 }
445 hint_lregs :: { [ExtFCode (CmmFormal, MachHint)] }
447 | hint_lreg ',' { [$1] }
448 | hint_lreg ',' hint_lregs { $1 : $3 }
450 hint_lreg :: { ExtFCode (CmmFormal, MachHint) }
451 : local_lreg { do e <- $1; return (e, inferHint (CmmReg (CmmLocal e))) }
452 | STRING local_lreg {% do h <- parseHint $1;
454 e <- $2; return (e,h) }
456 local_lreg :: { ExtFCode LocalReg }
457 : NAME { do e <- lookupName $1;
460 CmmReg (CmmLocal r) -> r
461 other -> pprPanic "CmmParse:" (ftext $1 <> text " not a local register") }
463 lreg :: { ExtFCode CmmReg }
464 : NAME { do e <- lookupName $1;
468 other -> pprPanic "CmmParse:" (ftext $1 <> text " not a register") }
469 | GLOBALREG { return (CmmGlobal $1) }
471 maybe_formals :: { [ExtFCode LocalReg] }
473 | '(' formals0 ')' { $2 }
475 formals0 :: { [ExtFCode LocalReg] }
479 formals :: { [ExtFCode LocalReg] }
480 : formal ',' { [$1] }
482 | formal ',' formals { $1 : $3 }
484 formal :: { ExtFCode LocalReg }
485 : type NAME { newLocal defaultKind $1 $2 }
486 | STRING type NAME {% do k <- parseKind $1;
487 return $ newLocal k $2 $3 }
493 typenot8 :: { MachRep }
500 section :: String -> Section
501 section "text" = Text
502 section "data" = Data
503 section "rodata" = ReadOnlyData
504 section "relrodata" = RelocatableReadOnlyData
505 section "bss" = UninitialisedData
506 section s = OtherSection s
508 mkString :: String -> CmmStatic
509 mkString s = CmmString (map (fromIntegral.ord) s)
511 -- mkMachOp infers the type of the MachOp from the type of its first
512 -- argument. We assume that this is correct: for MachOps that don't have
513 -- symmetrical args (e.g. shift ops), the first arg determines the type of
515 mkMachOp :: (MachRep -> MachOp) -> [ExtFCode CmmExpr] -> ExtFCode CmmExpr
516 mkMachOp fn args = do
517 arg_exprs <- sequence args
518 return (CmmMachOp (fn (cmmExprRep (head arg_exprs))) arg_exprs)
520 getLit :: CmmExpr -> CmmLit
521 getLit (CmmLit l) = l
522 getLit (CmmMachOp (MO_S_Neg _) [CmmLit (CmmInt i r)]) = CmmInt (negate i) r
523 getLit _ = panic "invalid literal" -- TODO messy failure
525 nameToMachOp :: FastString -> P (MachRep -> MachOp)
527 case lookupUFM machOps name of
528 Nothing -> fail ("unknown primitive " ++ unpackFS name)
531 exprOp :: FastString -> [ExtFCode CmmExpr] -> P (ExtFCode CmmExpr)
532 exprOp name args_code =
533 case lookupUFM exprMacros name of
534 Just f -> return $ do
535 args <- sequence args_code
538 mo <- nameToMachOp name
539 return $ mkMachOp mo args_code
541 exprMacros :: UniqFM ([CmmExpr] -> CmmExpr)
542 exprMacros = listToUFM [
543 ( FSLIT("ENTRY_CODE"), \ [x] -> entryCode x ),
544 ( FSLIT("INFO_PTR"), \ [x] -> closureInfoPtr x ),
545 ( FSLIT("STD_INFO"), \ [x] -> infoTable x ),
546 ( FSLIT("FUN_INFO"), \ [x] -> funInfoTable x ),
547 ( FSLIT("GET_ENTRY"), \ [x] -> entryCode (closureInfoPtr x) ),
548 ( FSLIT("GET_STD_INFO"), \ [x] -> infoTable (closureInfoPtr x) ),
549 ( FSLIT("GET_FUN_INFO"), \ [x] -> funInfoTable (closureInfoPtr x) ),
550 ( FSLIT("INFO_TYPE"), \ [x] -> infoTableClosureType x ),
551 ( FSLIT("INFO_PTRS"), \ [x] -> infoTablePtrs x ),
552 ( FSLIT("INFO_NPTRS"), \ [x] -> infoTableNonPtrs x )
555 -- we understand a subset of C-- primitives:
556 machOps = listToUFM $
557 map (\(x, y) -> (mkFastString x, y)) [
564 ( "quot", MO_S_Quot ),
566 ( "divu", MO_U_Quot ),
567 ( "modu", MO_U_Rem ),
585 ( "fneg", MO_S_Neg ),
592 ( "shrl", MO_U_Shr ),
593 ( "shra", MO_S_Shr ),
595 ( "lobits8", flip MO_U_Conv I8 ),
596 ( "lobits16", flip MO_U_Conv I16 ),
597 ( "lobits32", flip MO_U_Conv I32 ),
598 ( "lobits64", flip MO_U_Conv I64 ),
599 ( "sx16", flip MO_S_Conv I16 ),
600 ( "sx32", flip MO_S_Conv I32 ),
601 ( "sx64", flip MO_S_Conv I64 ),
602 ( "zx16", flip MO_U_Conv I16 ),
603 ( "zx32", flip MO_U_Conv I32 ),
604 ( "zx64", flip MO_U_Conv I64 ),
605 ( "f2f32", flip MO_S_Conv F32 ), -- TODO; rounding mode
606 ( "f2f64", flip MO_S_Conv F64 ), -- TODO; rounding mode
607 ( "f2i8", flip MO_S_Conv I8 ),
608 ( "f2i16", flip MO_S_Conv I16 ),
609 ( "f2i32", flip MO_S_Conv I32 ),
610 ( "f2i64", flip MO_S_Conv I64 ),
611 ( "i2f32", flip MO_S_Conv F32 ),
612 ( "i2f64", flip MO_S_Conv F64 )
615 callishMachOps = listToUFM $
616 map (\(x, y) -> (mkFastString x, y)) [
617 ( "write_barrier", MO_WriteBarrier )
618 -- ToDo: the rest, maybe
621 parseHint :: String -> P MachHint
622 parseHint "ptr" = return PtrHint
623 parseHint "signed" = return SignedHint
624 parseHint "float" = return FloatHint
625 parseHint str = fail ("unrecognised hint: " ++ str)
627 parseKind :: String -> P Kind
628 parseKind "ptr" = return KindPtr
629 parseKind str = fail ("unrecognized kin: " ++ str)
632 defaultKind = KindNonPtr
634 -- labels are always pointers, so we might as well infer the hint
635 inferHint :: CmmExpr -> MachHint
636 inferHint (CmmLit (CmmLabel _)) = PtrHint
637 inferHint (CmmReg (CmmGlobal g)) | isPtrGlobalReg g = PtrHint
640 isPtrGlobalReg Sp = True
641 isPtrGlobalReg SpLim = True
642 isPtrGlobalReg Hp = True
643 isPtrGlobalReg HpLim = True
644 isPtrGlobalReg CurrentTSO = True
645 isPtrGlobalReg CurrentNursery = True
646 isPtrGlobalReg _ = False
649 happyError = srcParseFail
651 -- -----------------------------------------------------------------------------
652 -- Statement-level macros
654 stmtMacro :: FastString -> [ExtFCode CmmExpr] -> P ExtCode
655 stmtMacro fun args_code = do
656 case lookupUFM stmtMacros fun of
657 Nothing -> fail ("unknown macro: " ++ unpackFS fun)
658 Just fcode -> return $ do
659 args <- sequence args_code
662 stmtMacros :: UniqFM ([CmmExpr] -> Code)
663 stmtMacros = listToUFM [
664 ( FSLIT("CCS_ALLOC"), \[words,ccs] -> profAlloc words ccs ),
665 ( FSLIT("CLOSE_NURSERY"), \[] -> emitCloseNursery ),
666 ( FSLIT("ENTER_CCS_PAP_CL"), \[e] -> enterCostCentrePAP e ),
667 ( FSLIT("ENTER_CCS_THUNK"), \[e] -> enterCostCentreThunk e ),
668 ( FSLIT("HP_CHK_GEN"), \[words,liveness,reentry] ->
669 hpChkGen words liveness reentry ),
670 ( FSLIT("HP_CHK_NP_ASSIGN_SP0"), \[e,f] -> hpChkNodePointsAssignSp0 e f ),
671 ( FSLIT("LOAD_THREAD_STATE"), \[] -> emitLoadThreadState ),
672 ( FSLIT("LDV_ENTER"), \[e] -> ldvEnter e ),
673 ( FSLIT("LDV_RECORD_CREATE"), \[e] -> ldvRecordCreate e ),
674 ( FSLIT("OPEN_NURSERY"), \[] -> emitOpenNursery ),
675 ( FSLIT("PUSH_UPD_FRAME"), \[sp,e] -> emitPushUpdateFrame sp e ),
676 ( FSLIT("SAVE_THREAD_STATE"), \[] -> emitSaveThreadState ),
677 ( FSLIT("SET_HDR"), \[ptr,info,ccs] ->
678 emitSetDynHdr ptr info ccs ),
679 ( FSLIT("STK_CHK_GEN"), \[words,liveness,reentry] ->
680 stkChkGen words liveness reentry ),
681 ( FSLIT("STK_CHK_NP"), \[e] -> stkChkNodePoints e ),
682 ( FSLIT("TICK_ALLOC_PRIM"), \[hdr,goods,slop] ->
683 tickyAllocPrim hdr goods slop ),
684 ( FSLIT("TICK_ALLOC_PAP"), \[goods,slop] ->
685 tickyAllocPAP goods slop ),
686 ( FSLIT("TICK_ALLOC_UP_THK"), \[goods,slop] ->
687 tickyAllocThunk goods slop ),
688 ( FSLIT("UPD_BH_UPDATABLE"), \[] -> emitBlackHoleCode False ),
689 ( FSLIT("UPD_BH_SINGLE_ENTRY"), \[] -> emitBlackHoleCode True ),
691 ( FSLIT("RET_P"), \[a] -> emitRetUT [(PtrArg,a)]),
692 ( FSLIT("RET_N"), \[a] -> emitRetUT [(NonPtrArg,a)]),
693 ( FSLIT("RET_PP"), \[a,b] -> emitRetUT [(PtrArg,a),(PtrArg,b)]),
694 ( FSLIT("RET_NN"), \[a,b] -> emitRetUT [(NonPtrArg,a),(NonPtrArg,b)]),
695 ( FSLIT("RET_NP"), \[a,b] -> emitRetUT [(NonPtrArg,a),(PtrArg,b)]),
696 ( FSLIT("RET_PPP"), \[a,b,c] -> emitRetUT [(PtrArg,a),(PtrArg,b),(PtrArg,c)]),
697 ( FSLIT("RET_NPP"), \[a,b,c] -> emitRetUT [(NonPtrArg,a),(PtrArg,b),(PtrArg,c)]),
698 ( FSLIT("RET_NNP"), \[a,b,c] -> emitRetUT [(NonPtrArg,a),(NonPtrArg,b),(PtrArg,c)]),
699 ( FSLIT("RET_NNNP"), \[a,b,c,d] -> emitRetUT [(NonPtrArg,a),(NonPtrArg,b),(NonPtrArg,c),(PtrArg,d)]),
700 ( FSLIT("RET_NPNP"), \[a,b,c,d] -> emitRetUT [(NonPtrArg,a),(PtrArg,b),(NonPtrArg,c),(PtrArg,d)])
704 -- -----------------------------------------------------------------------------
705 -- Our extended FCode monad.
707 -- We add a mapping from names to CmmExpr, to support local variable names in
708 -- the concrete C-- code. The unique supply of the underlying FCode monad
709 -- is used to grab a new unique for each local variable.
711 -- In C--, a local variable can be declared anywhere within a proc,
712 -- and it scopes from the beginning of the proc to the end. Hence, we have
713 -- to collect declarations as we parse the proc, and feed the environment
714 -- back in circularly (to avoid a two-pass algorithm).
716 data Named = Var CmmExpr | Label BlockId
717 type Decls = [(FastString,Named)]
718 type Env = UniqFM Named
720 newtype ExtFCode a = EC { unEC :: Env -> Decls -> FCode (Decls, a) }
722 type ExtCode = ExtFCode ()
724 returnExtFC a = EC $ \e s -> return (s, a)
725 thenExtFC (EC m) k = EC $ \e s -> do (s',r) <- m e s; unEC (k r) e s'
727 instance Monad ExtFCode where
731 -- This function takes the variable decarations and imports and makes
732 -- an environment, which is looped back into the computation. In this
733 -- way, we can have embedded declarations that scope over the whole
734 -- procedure, and imports that scope over the entire module.
735 loopDecls :: ExtFCode a -> ExtFCode a
736 loopDecls (EC fcode) =
737 EC $ \e s -> fixC (\ ~(decls,a) -> fcode (addListToUFM e decls) [])
739 getEnv :: ExtFCode Env
740 getEnv = EC $ \e s -> return (s, e)
742 addVarDecl :: FastString -> CmmExpr -> ExtCode
743 addVarDecl var expr = EC $ \e s -> return ((var, Var expr):s, ())
745 addLabel :: FastString -> BlockId -> ExtCode
746 addLabel name block_id = EC $ \e s -> return ((name, Label block_id):s, ())
748 newLocal :: Kind -> MachRep -> FastString -> ExtFCode LocalReg
749 newLocal kind ty name = do
751 let reg = LocalReg u ty kind
752 addVarDecl name (CmmReg (CmmLocal reg))
755 newLabel :: FastString -> ExtFCode BlockId
758 addLabel name (BlockId u)
761 lookupLabel :: FastString -> ExtFCode BlockId
762 lookupLabel name = do
765 case lookupUFM env name of
767 _other -> BlockId (newTagUnique (getUnique name) 'L')
769 -- Unknown names are treated as if they had been 'import'ed.
770 -- This saves us a lot of bother in the RTS sources, at the expense of
771 -- deferring some errors to link time.
772 lookupName :: FastString -> ExtFCode CmmExpr
776 case lookupUFM env name of
778 _other -> CmmLit (CmmLabel (mkRtsCodeLabelFS name))
780 -- Lifting FCode computations into the ExtFCode monad:
781 code :: FCode a -> ExtFCode a
782 code fc = EC $ \e s -> do r <- fc; return (s, r)
784 code2 :: (FCode (Decls,b) -> FCode ((Decls,b),c))
785 -> ExtFCode b -> ExtFCode c
786 code2 f (EC ec) = EC $ \e s -> do ((s',b),c) <- f (ec e s); return (s',c)
789 stmtEC stmt = code (stmtC stmt)
790 stmtsEC stmts = code (stmtsC stmts)
791 getCgStmtsEC = code2 getCgStmts'
793 forkLabelledCodeEC ec = do
794 stmts <- getCgStmtsEC ec
795 code (forkCgStmts stmts)
798 profilingInfo desc_str ty_str = do
799 lit1 <- if opt_SccProfilingOn
800 then code $ mkStringCLit desc_str
801 else return (mkIntCLit 0)
802 lit2 <- if opt_SccProfilingOn
803 then code $ mkStringCLit ty_str
804 else return (mkIntCLit 0)
805 return (ProfilingInfo lit1 lit2)
808 staticClosure :: FastString -> FastString -> [CmmLit] -> ExtCode
809 staticClosure cl_label info payload
810 = code $ emitDataLits (mkRtsDataLabelFS cl_label) lits
811 where lits = mkStaticClosure (mkRtsInfoLabelFS info) dontCareCCS payload [] [] []
815 -> [ExtFCode (CmmFormal,MachHint)]
817 -> [ExtFCode (CmmExpr,MachHint)]
821 foreignCall conv_string results_code expr_code args_code vols srt
822 = do convention <- case conv_string of
823 "C" -> return CCallConv
824 "C--" -> return CmmCallConv
825 _ -> fail ("unknown calling convention: " ++ conv_string)
827 results <- sequence results_code
829 args <- sequence args_code
830 code (emitForeignCall' PlayRisky results
831 (CmmForeignCall expr convention) args vols srt) where
834 :: [ExtFCode (CmmFormal,MachHint)]
836 -> [ExtFCode (CmmExpr,MachHint)]
840 primCall results_code name args_code vols srt
841 = case lookupUFM callishMachOps name of
842 Nothing -> fail ("unknown primitive " ++ unpackFS name)
843 Just p -> return $ do
844 results <- sequence results_code
845 args <- sequence args_code
846 code (emitForeignCall' PlayRisky results (CmmPrim p) args vols srt)
848 doStore :: MachRep -> ExtFCode CmmExpr -> ExtFCode CmmExpr -> ExtCode
849 doStore rep addr_code val_code
850 = do addr <- addr_code
852 -- if the specified store type does not match the type of the expr
853 -- on the rhs, then we insert a coercion that will cause the type
854 -- mismatch to be flagged by cmm-lint. If we don't do this, then
855 -- the store will happen at the wrong type, and the error will not
858 | cmmExprRep val /= rep = CmmMachOp (MO_U_Conv rep rep) [val]
860 stmtEC (CmmStore addr coerce_val)
862 -- Return an unboxed tuple.
863 emitRetUT :: [(CgRep,CmmExpr)] -> Code
865 tickyUnboxedTupleReturn (length args) -- TICK
866 (sp, stmts) <- pushUnboxedTuple 0 args
868 when (sp /= 0) $ stmtC (CmmAssign spReg (cmmRegOffW spReg (-sp)))
869 stmtC (CmmJump (entryCode (CmmLoad (cmmRegOffW spReg sp) wordRep)) [])
870 -- TODO (when using CPS): emitStmt (CmmReturn (map snd args))
872 -- -----------------------------------------------------------------------------
873 -- If-then-else and boolean expressions
876 = BoolExpr `BoolAnd` BoolExpr
877 | BoolExpr `BoolOr` BoolExpr
881 -- ToDo: smart constructors which simplify the boolean expression.
883 ifThenElse cond then_part else_part = do
884 then_id <- code newLabelC
885 join_id <- code newLabelC
889 stmtEC (CmmBranch join_id)
890 code (labelC then_id)
892 -- fall through to join
893 code (labelC join_id)
895 -- 'emitCond cond true_id' emits code to test whether the cond is true,
896 -- branching to true_id if so, and falling through otherwise.
897 emitCond (BoolTest e) then_id = do
898 stmtEC (CmmCondBranch e then_id)
899 emitCond (BoolNot (BoolTest (CmmMachOp op args))) then_id
900 | Just op' <- maybeInvertComparison op
901 = emitCond (BoolTest (CmmMachOp op' args)) then_id
902 emitCond (BoolNot e) then_id = do
903 else_id <- code newLabelC
905 stmtEC (CmmBranch then_id)
906 code (labelC else_id)
907 emitCond (e1 `BoolOr` e2) then_id = do
910 emitCond (e1 `BoolAnd` e2) then_id = do
911 -- we'd like to invert one of the conditionals here to avoid an
912 -- extra branch instruction, but we can't use maybeInvertComparison
913 -- here because we can't look too closely at the expression since
915 and_id <- code newLabelC
916 else_id <- code newLabelC
918 stmtEC (CmmBranch else_id)
921 code (labelC else_id)
924 -- -----------------------------------------------------------------------------
927 -- We use a simplified form of C-- switch statements for now. A
928 -- switch statement always compiles to a table jump. Each arm can
929 -- specify a list of values (not ranges), and there can be a single
930 -- default branch. The range of the table is given either by the
931 -- optional range on the switch (eg. switch [0..7] {...}), or by
932 -- the minimum/maximum values from the branches.
934 doSwitch :: Maybe (Int,Int) -> ExtFCode CmmExpr -> [([Int],ExtCode)]
935 -> Maybe ExtCode -> ExtCode
936 doSwitch mb_range scrut arms deflt
938 -- Compile code for the default branch
941 Nothing -> return Nothing
942 Just e -> do b <- forkLabelledCodeEC e; return (Just b)
944 -- Compile each case branch
945 table_entries <- mapM emitArm arms
947 -- Construct the table
949 all_entries = concat table_entries
950 ixs = map fst all_entries
952 | Just (l,u) <- mb_range = (l,u)
953 | otherwise = (minimum ixs, maximum ixs)
955 entries = elems (accumArray (\_ a -> Just a) dflt_entry (min,max)
958 -- ToDo: check for out of range and jump to default if necessary
959 stmtEC (CmmSwitch expr entries)
961 emitArm :: ([Int],ExtCode) -> ExtFCode [(Int,BlockId)]
962 emitArm (ints,code) = do
963 blockid <- forkLabelledCodeEC code
964 return [ (i,blockid) | i <- ints ]
967 -- -----------------------------------------------------------------------------
968 -- Putting it all together
970 -- The initial environment: we define some constants that the compiler
973 initEnv = listToUFM [
974 ( FSLIT("SIZEOF_StgHeader"),
975 Var (CmmLit (CmmInt (fromIntegral (fixedHdrSize * wORD_SIZE)) wordRep) )),
976 ( FSLIT("SIZEOF_StgInfoTable"),
977 Var (CmmLit (CmmInt (fromIntegral stdInfoTableSizeB) wordRep) ))
980 parseCmmFile :: DynFlags -> FilePath -> IO (Maybe Cmm)
981 parseCmmFile dflags filename = do
982 showPass dflags "ParseCmm"
983 buf <- hGetStringBuffer filename
985 init_loc = mkSrcLoc (mkFastString filename) 1 0
986 init_state = (mkPState buf init_loc dflags) { lex_state = [0] }
987 -- reset the lex_state: the Lexer monad leaves some stuff
988 -- in there we don't want.
989 case unP cmmParse init_state of
990 PFailed span err -> do printError span err; return Nothing
992 cmm <- initC dflags no_module (getCmm (unEC code initEnv [] >> return ()))
993 let ms = getMessages pst
994 printErrorsAndWarnings dflags ms
995 when (errorsFound dflags ms) $ exitWith (ExitFailure 1)
996 dumpIfSet_dyn dflags Opt_D_dump_cmm "Cmm" (pprCmms [cmm])
999 no_module = panic "parseCmmFile: no module"