optimisation: shortcut branches when possible (x86/x86_64 only for now)
[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(..),  
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,
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      [(CmmReg,MachHint)]         -- zero or more results
117      [(CmmExpr,MachHint)]        -- 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 [LocalReg]    -- Jump to another function, with these 
134                                   -- parameters.
135
136 {-
137 Discussion
138 ~~~~~~~~~~
139
140 One possible problem with the above type is that the only way to do a
141 non-local conditional jump is to encode it as a branch to a block that
142 contains a single jump.  This leads to inefficient code in the back end.
143
144 One possible way to fix this would be:
145
146 data CmmStat = 
147   ...
148   | CmmJump CmmBranchDest
149   | CmmCondJump CmmExpr CmmBranchDest
150   ...
151
152 data CmmBranchDest
153   = Local BlockId
154   | NonLocal CmmExpr [LocalReg]
155
156 In favour:
157
158 + one fewer constructors in CmmStmt
159 + allows both cond branch and switch to jump to non-local destinations
160
161 Against:
162
163 - not strictly necessary: can already encode as branch+jump
164 - not always possible to implement any better in the back end
165 - could do the optimisation in the back end (but then plat-specific?)
166 - C-- doesn't have it
167 - back-end optimisation might be more general (jump shortcutting)
168
169 So we'll stick with the way it is, and add the optimisation to the NCG.
170 -}
171
172 -----------------------------------------------------------------------------
173 --              CmmCallTarget
174 --
175 -- The target of a CmmCall.
176 -----------------------------------------------------------------------------
177
178 data CmmCallTarget
179   = CmmForeignCall              -- Call to a foreign function
180         CmmExpr                 -- literal label <=> static call
181                                 -- other expression <=> dynamic call
182         CCallConv               -- The calling convention
183
184   | CmmPrim                     -- Call to a "primitive" (eg. sin, cos)
185         CallishMachOp           -- These might be implemented as inline
186                                 -- code by the backend.
187
188 -----------------------------------------------------------------------------
189 --              CmmExpr
190 -- An expression.  Expressions have no side effects.
191 -----------------------------------------------------------------------------
192
193 data CmmExpr
194   = CmmLit CmmLit               -- Literal
195   | CmmLoad CmmExpr MachRep     -- Read memory location
196   | CmmReg CmmReg               -- Contents of register
197   | CmmMachOp MachOp [CmmExpr]  -- Machine operation (+, -, *, etc.)
198   | CmmRegOff CmmReg Int        
199         -- CmmRegOff reg i
200         --        ** is shorthand only, meaning **
201         -- CmmMachOp (MO_S_Add rep (CmmReg reg) (CmmLit (CmmInt i rep)))
202         --      where rep = cmmRegRep reg
203
204 cmmExprRep :: CmmExpr -> MachRep
205 cmmExprRep (CmmLit lit)      = cmmLitRep lit
206 cmmExprRep (CmmLoad _ rep)   = rep
207 cmmExprRep (CmmReg reg)      = cmmRegRep reg
208 cmmExprRep (CmmMachOp op _)  = resultRepOfMachOp op
209 cmmExprRep (CmmRegOff reg _) = cmmRegRep reg
210
211 data CmmReg 
212   = CmmLocal  LocalReg
213   | CmmGlobal GlobalReg
214   deriving( Eq )
215
216 cmmRegRep :: CmmReg -> MachRep
217 cmmRegRep (CmmLocal  reg)       = localRegRep reg
218 cmmRegRep (CmmGlobal reg)       = globalRegRep reg
219
220 data LocalReg
221   = LocalReg !Unique MachRep
222
223 instance Eq LocalReg where
224   (LocalReg u1 _) == (LocalReg u2 _) = u1 == u2
225
226 instance Uniquable LocalReg where
227   getUnique (LocalReg uniq _) = uniq
228
229 localRegRep :: LocalReg -> MachRep
230 localRegRep (LocalReg _ rep) = rep
231
232 data CmmLit
233   = CmmInt Integer  MachRep
234         -- Interpretation: the 2's complement representation of the value
235         -- is truncated to the specified size.  This is easier than trying
236         -- to keep the value within range, because we don't know whether
237         -- it will be used as a signed or unsigned value (the MachRep doesn't
238         -- distinguish between signed & unsigned).
239   | CmmFloat  Rational MachRep
240   | CmmLabel    CLabel                  -- Address of label
241   | CmmLabelOff CLabel Int              -- Address of label + byte offset
242   
243         -- Due to limitations in the C backend, the following
244         -- MUST ONLY be used inside the info table indicated by label2
245         -- (label2 must be the info label), and label1 must be an
246         -- SRT, a slow entrypoint or a large bitmap (see the Mangler)
247         -- Don't use it at all unless tablesNextToCode.
248         -- It is also used inside the NCG during when generating
249         -- position-independent code. 
250   | CmmLabelDiffOff CLabel CLabel Int   -- label1 - label2 + offset
251
252 cmmLitRep :: CmmLit -> MachRep
253 cmmLitRep (CmmInt _ rep)    = rep
254 cmmLitRep (CmmFloat _ rep)  = rep
255 cmmLitRep (CmmLabel _)      = wordRep
256 cmmLitRep (CmmLabelOff _ _) = wordRep
257 cmmLitRep (CmmLabelDiffOff _ _ _) = wordRep
258
259 -----------------------------------------------------------------------------
260 -- A local label.
261
262 -- Local labels must be unique within a single compilation unit.
263
264 newtype BlockId = BlockId Unique
265   deriving (Eq,Ord)
266
267 instance Uniquable BlockId where
268   getUnique (BlockId u) = u
269
270 -----------------------------------------------------------------------------
271 --              Static Data
272 -----------------------------------------------------------------------------
273
274 data Section
275   = Text
276   | Data
277   | ReadOnlyData
278   | RelocatableReadOnlyData
279   | UninitialisedData
280   | ReadOnlyData16      -- .rodata.cst16 on x86_64, 16-byte aligned
281   | OtherSection String
282
283 data CmmStatic
284   = CmmStaticLit CmmLit 
285         -- a literal value, size given by cmmLitRep of the literal.
286   | CmmUninitialised Int
287         -- uninitialised data, N bytes long
288   | CmmAlign Int
289         -- align to next N-byte boundary (N must be a power of 2).
290   | CmmDataLabel CLabel
291         -- label the current position in this section.
292   | CmmString [Word8]
293         -- string of 8-bit values only, not zero terminated.
294
295 -----------------------------------------------------------------------------
296 --              Global STG registers
297 -----------------------------------------------------------------------------
298
299 data GlobalReg
300   -- Argument and return registers
301   = VanillaReg                  -- pointers, unboxed ints and chars
302         {-# UNPACK #-} !Int     -- its number
303
304   | FloatReg            -- single-precision floating-point registers
305         {-# UNPACK #-} !Int     -- its number
306
307   | DoubleReg           -- double-precision floating-point registers
308         {-# UNPACK #-} !Int     -- its number
309
310   | LongReg             -- long int registers (64-bit, really)
311         {-# UNPACK #-} !Int     -- its number
312
313   -- STG registers
314   | Sp                  -- Stack ptr; points to last occupied stack location.
315   | SpLim               -- Stack limit
316   | Hp                  -- Heap ptr; points to last occupied heap location.
317   | HpLim               -- Heap limit register
318   | CurrentTSO          -- pointer to current thread's TSO
319   | CurrentNursery      -- pointer to allocation area
320   | HpAlloc             -- allocation count for heap check failure
321
322                 -- We keep the address of some commonly-called 
323                 -- functions in the register table, to keep code
324                 -- size down:
325   | GCEnter1            -- stg_gc_enter_1
326   | GCFun               -- stg_gc_fun
327
328   -- Base offset for the register table, used for accessing registers
329   -- which do not have real registers assigned to them.  This register
330   -- will only appear after we have expanded GlobalReg into memory accesses
331   -- (where necessary) in the native code generator.
332   | BaseReg
333
334   -- Base Register for PIC (position-independent code) calculations
335   -- Only used inside the native code generator. It's exact meaning differs
336   -- from platform to platform (see module PositionIndependentCode).
337   | PicBaseReg
338
339   deriving( Eq
340 #ifdef DEBUG
341         , Show
342 #endif
343          )
344
345 -- convenient aliases
346 spReg, hpReg, nodeReg :: CmmReg
347 spReg = CmmGlobal Sp
348 hpReg = CmmGlobal Hp
349 nodeReg = CmmGlobal node
350
351 node :: GlobalReg
352 node = VanillaReg 1
353
354 globalRegRep :: GlobalReg -> MachRep
355 globalRegRep (VanillaReg _)     = wordRep
356 globalRegRep (FloatReg _)       = F32
357 globalRegRep (DoubleReg _)      = F64
358 globalRegRep (LongReg _)        = I64
359 globalRegRep _                  = wordRep