Second working draft of a CPS algorithm for C--.
[ghc-hetmet.git] / compiler / cmm / Cmm.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Cmm data types
4 --
5 -- (c) The University of Glasgow 2004-2006
6 --
7 -----------------------------------------------------------------------------
8
9 module Cmm ( 
10         GenCmm(..), Cmm,
11         GenCmmTop(..), CmmTop,
12         GenBasicBlock(..), CmmBasicBlock, blockId, blockStmts,
13         CmmStmt(..), CmmActuals, CmmFormals,
14         CmmCallTarget(..),
15         CmmStatic(..), Section(..),
16         CmmExpr(..), cmmExprRep, 
17         CmmReg(..), cmmRegRep,
18         CmmLit(..), cmmLitRep,
19         LocalReg(..), localRegRep,
20         BlockId(..),
21         GlobalReg(..), globalRegRep,
22
23         node, nodeReg, spReg, hpReg, spLimReg
24   ) where
25
26 #include "HsVersions.h"
27
28 import MachOp
29 import CLabel
30 import ForeignCall
31 import Unique
32 import FastString
33
34 import Data.Word
35
36 -----------------------------------------------------------------------------
37 --              Cmm, CmmTop, CmmBasicBlock
38 -----------------------------------------------------------------------------
39
40 -- A file is a list of top-level chunks.  These may be arbitrarily
41 -- re-orderd during code generation.
42
43 -- GenCmm is abstracted over
44 --   (a) the type of static data elements
45 --   (b) the contents of a basic block.
46 -- We expect there to be two main instances of this type:
47 --   (a) Plain C--, i.e. populated with CmmLit and CmmExpr respectively,
48 --   (b) Native code, populated with instructions
49 --
50 newtype GenCmm d i = Cmm [GenCmmTop d i]
51
52 type Cmm = GenCmm CmmStatic CmmStmt
53
54 -- A top-level chunk, abstracted over the type of the contents of
55 -- the basic blocks (Cmm or instructions are the likely instantiations).
56 data GenCmmTop d i
57   = CmmProc
58      [d]               -- Info table, may be empty
59      CLabel            -- Used to generate both info & entry labels
60      [LocalReg]        -- Argument locals live on entry (C-- procedure params)
61      [GenBasicBlock i] -- Code, may be empty.  The first block is
62                        -- the entry point.  The order is otherwise initially 
63                        -- unimportant, but at some point the code gen will
64                        -- fix the order.
65
66                        -- the BlockId of the first block does not give rise
67                        -- to a label.  To jump to the first block in a Proc,
68                        -- use the appropriate CLabel.
69
70   -- some static data.
71   | CmmData Section [d] -- constant values only
72
73 type CmmTop = GenCmmTop CmmStatic CmmStmt
74
75 -- A basic block containing a single label, at the beginning.
76 -- The list of basic blocks in a top-level code block may be re-ordered.
77 -- Fall-through is not allowed: there must be an explicit jump at the
78 -- end of each basic block, but the code generator might rearrange basic
79 -- blocks in order to turn some jumps into fallthroughs.
80
81 data GenBasicBlock i = BasicBlock BlockId [i]
82   -- ToDo: Julian suggests that we might need to annotate this type
83   -- with the out & in edges in the graph, i.e. two * [BlockId].  This
84   -- information can be derived from the contents, but it might be
85   -- helpful to cache it here.
86
87 type CmmBasicBlock = GenBasicBlock CmmStmt
88
89 blockId :: GenBasicBlock i -> BlockId
90 -- The branch block id is that of the first block in 
91 -- the branch, which is that branch's entry point
92 blockId (BasicBlock blk_id _ ) = blk_id
93
94 blockStmts :: GenBasicBlock i -> [i]
95 blockStmts (BasicBlock _ stmts) = stmts
96
97
98 -----------------------------------------------------------------------------
99 --              CmmStmt
100 -- A "statement".  Note that all branches are explicit: there are no
101 -- control transfers to computed addresses, except when transfering
102 -- control to a new function.
103 -----------------------------------------------------------------------------
104
105 data CmmStmt
106   = CmmNop
107   | CmmComment FastString
108
109   | CmmAssign CmmReg CmmExpr     -- Assign to register
110
111   | CmmStore CmmExpr CmmExpr     -- Assign to memory location.  Size is
112                                  -- given by cmmExprRep of the rhs.
113
114   | CmmCall                      -- A foreign call, with 
115      CmmCallTarget
116      CmmFormals                  -- zero or more results
117      CmmActuals                  -- zero or more arguments
118      (Maybe [GlobalReg])         -- Global regs that may need to be saved
119                                  -- if they will be clobbered by the call.
120                                  -- Nothing <=> save *all* globals that
121                                  -- might be clobbered.
122
123   | CmmBranch BlockId             -- branch to another BB in this fn
124
125   | CmmCondBranch CmmExpr BlockId -- conditional branch
126
127   | CmmSwitch CmmExpr [Maybe BlockId]   -- Table branch
128         -- The scrutinee is zero-based; 
129         --      zero -> first block
130         --      one  -> second block etc
131         -- Undefined outside range, and when there's a Nothing
132
133   | CmmJump CmmExpr               -- Jump to another function,
134     CmmActuals                    -- with these parameters.
135
136   | CmmReturn                     -- Return from a function,
137     CmmActuals                    -- with these return values.
138
139 type CmmActuals = [(CmmExpr,MachHint)]
140 type CmmFormals = [(CmmReg,MachHint)]
141
142 {-
143 Discussion
144 ~~~~~~~~~~
145
146 One possible problem with the above type is that the only way to do a
147 non-local conditional jump is to encode it as a branch to a block that
148 contains a single jump.  This leads to inefficient code in the back end.
149
150 One possible way to fix this would be:
151
152 data CmmStat = 
153   ...
154   | CmmJump CmmBranchDest
155   | CmmCondJump CmmExpr CmmBranchDest
156   ...
157
158 data CmmBranchDest
159   = Local BlockId
160   | NonLocal CmmExpr [LocalReg]
161
162 In favour:
163
164 + one fewer constructors in CmmStmt
165 + allows both cond branch and switch to jump to non-local destinations
166
167 Against:
168
169 - not strictly necessary: can already encode as branch+jump
170 - not always possible to implement any better in the back end
171 - could do the optimisation in the back end (but then plat-specific?)
172 - C-- doesn't have it
173 - back-end optimisation might be more general (jump shortcutting)
174
175 So we'll stick with the way it is, and add the optimisation to the NCG.
176 -}
177
178 -----------------------------------------------------------------------------
179 --              CmmCallTarget
180 --
181 -- The target of a CmmCall.
182 -----------------------------------------------------------------------------
183
184 data CmmCallTarget
185   = CmmForeignCall              -- Call to a foreign function
186         CmmExpr                 -- literal label <=> static call
187                                 -- other expression <=> dynamic call
188         CCallConv               -- The calling convention
189
190   | CmmPrim                     -- Call to a "primitive" (eg. sin, cos)
191         CallishMachOp           -- These might be implemented as inline
192                                 -- code by the backend.
193
194 -----------------------------------------------------------------------------
195 --              CmmExpr
196 -- An expression.  Expressions have no side effects.
197 -----------------------------------------------------------------------------
198
199 data CmmExpr
200   = CmmLit CmmLit               -- Literal
201   | CmmLoad CmmExpr MachRep     -- Read memory location
202   | CmmReg CmmReg               -- Contents of register
203   | CmmMachOp MachOp [CmmExpr]  -- Machine operation (+, -, *, etc.)
204   | CmmRegOff CmmReg Int        
205         -- CmmRegOff reg i
206         --        ** is shorthand only, meaning **
207         -- CmmMachOp (MO_S_Add rep (CmmReg reg) (CmmLit (CmmInt i rep)))
208         --      where rep = cmmRegRep reg
209   deriving Eq
210
211 cmmExprRep :: CmmExpr -> MachRep
212 cmmExprRep (CmmLit lit)      = cmmLitRep lit
213 cmmExprRep (CmmLoad _ rep)   = rep
214 cmmExprRep (CmmReg reg)      = cmmRegRep reg
215 cmmExprRep (CmmMachOp op _)  = resultRepOfMachOp op
216 cmmExprRep (CmmRegOff reg _) = cmmRegRep reg
217
218 data CmmReg 
219   = CmmLocal  LocalReg
220   | CmmGlobal GlobalReg
221   deriving( Eq )
222
223 cmmRegRep :: CmmReg -> MachRep
224 cmmRegRep (CmmLocal  reg)       = localRegRep reg
225 cmmRegRep (CmmGlobal reg)       = globalRegRep reg
226
227 data LocalReg
228   = LocalReg !Unique MachRep
229
230 instance Eq LocalReg where
231   (LocalReg u1 _) == (LocalReg u2 _) = u1 == u2
232
233 instance Uniquable LocalReg where
234   getUnique (LocalReg uniq _) = uniq
235
236 localRegRep :: LocalReg -> MachRep
237 localRegRep (LocalReg _ rep) = rep
238
239 data CmmLit
240   = CmmInt Integer  MachRep
241         -- Interpretation: the 2's complement representation of the value
242         -- is truncated to the specified size.  This is easier than trying
243         -- to keep the value within range, because we don't know whether
244         -- it will be used as a signed or unsigned value (the MachRep doesn't
245         -- distinguish between signed & unsigned).
246   | CmmFloat  Rational MachRep
247   | CmmLabel    CLabel                  -- Address of label
248   | CmmLabelOff CLabel Int              -- Address of label + byte offset
249   
250         -- Due to limitations in the C backend, the following
251         -- MUST ONLY be used inside the info table indicated by label2
252         -- (label2 must be the info label), and label1 must be an
253         -- SRT, a slow entrypoint or a large bitmap (see the Mangler)
254         -- Don't use it at all unless tablesNextToCode.
255         -- It is also used inside the NCG during when generating
256         -- position-independent code. 
257   | CmmLabelDiffOff CLabel CLabel Int   -- label1 - label2 + offset
258   deriving Eq
259
260 cmmLitRep :: CmmLit -> MachRep
261 cmmLitRep (CmmInt _ rep)    = rep
262 cmmLitRep (CmmFloat _ rep)  = rep
263 cmmLitRep (CmmLabel _)      = wordRep
264 cmmLitRep (CmmLabelOff _ _) = wordRep
265 cmmLitRep (CmmLabelDiffOff _ _ _) = wordRep
266
267 -----------------------------------------------------------------------------
268 -- A local label.
269
270 -- Local labels must be unique within a single compilation unit.
271
272 newtype BlockId = BlockId Unique
273   deriving (Eq,Ord)
274
275 instance Uniquable BlockId where
276   getUnique (BlockId u) = u
277
278 type BlockEnv a = UniqFM {- BlockId -} a
279
280 -----------------------------------------------------------------------------
281 --              Static Data
282 -----------------------------------------------------------------------------
283
284 data Section
285   = Text
286   | Data
287   | ReadOnlyData
288   | RelocatableReadOnlyData
289   | UninitialisedData
290   | ReadOnlyData16      -- .rodata.cst16 on x86_64, 16-byte aligned
291   | OtherSection String
292
293 data CmmStatic
294   = CmmStaticLit CmmLit 
295         -- a literal value, size given by cmmLitRep of the literal.
296   | CmmUninitialised Int
297         -- uninitialised data, N bytes long
298   | CmmAlign Int
299         -- align to next N-byte boundary (N must be a power of 2).
300   | CmmDataLabel CLabel
301         -- label the current position in this section.
302   | CmmString [Word8]
303         -- string of 8-bit values only, not zero terminated.
304
305 -----------------------------------------------------------------------------
306 --              Global STG registers
307 -----------------------------------------------------------------------------
308
309 data GlobalReg
310   -- Argument and return registers
311   = VanillaReg                  -- pointers, unboxed ints and chars
312         {-# UNPACK #-} !Int     -- its number
313
314   | FloatReg            -- single-precision floating-point registers
315         {-# UNPACK #-} !Int     -- its number
316
317   | DoubleReg           -- double-precision floating-point registers
318         {-# UNPACK #-} !Int     -- its number
319
320   | LongReg             -- long int registers (64-bit, really)
321         {-# UNPACK #-} !Int     -- its number
322
323   -- STG registers
324   | Sp                  -- Stack ptr; points to last occupied stack location.
325   | SpLim               -- Stack limit
326   | Hp                  -- Heap ptr; points to last occupied heap location.
327   | HpLim               -- Heap limit register
328   | CurrentTSO          -- pointer to current thread's TSO
329   | CurrentNursery      -- pointer to allocation area
330   | HpAlloc             -- allocation count for heap check failure
331
332                 -- We keep the address of some commonly-called 
333                 -- functions in the register table, to keep code
334                 -- size down:
335   | GCEnter1            -- stg_gc_enter_1
336   | GCFun               -- stg_gc_fun
337
338   -- Base offset for the register table, used for accessing registers
339   -- which do not have real registers assigned to them.  This register
340   -- will only appear after we have expanded GlobalReg into memory accesses
341   -- (where necessary) in the native code generator.
342   | BaseReg
343
344   -- Base Register for PIC (position-independent code) calculations
345   -- Only used inside the native code generator. It's exact meaning differs
346   -- from platform to platform (see module PositionIndependentCode).
347   | PicBaseReg
348
349   deriving( Eq
350 #ifdef DEBUG
351         , Show
352 #endif
353          )
354
355 -- convenient aliases
356 spReg, hpReg, spLimReg, nodeReg :: CmmReg
357 spReg = CmmGlobal Sp
358 hpReg = CmmGlobal Hp
359 spLimReg = CmmGlobal SpLim
360 nodeReg = CmmGlobal node
361
362 node :: GlobalReg
363 node = VanillaReg 1
364
365 globalRegRep :: GlobalReg -> MachRep
366 globalRegRep (VanillaReg _)     = wordRep
367 globalRegRep (FloatReg _)       = F32
368 globalRegRep (DoubleReg _)      = F64
369 globalRegRep (LongReg _)        = I64
370 globalRegRep _                  = wordRep