1 #include "../includes/ghcconfig.h"
3 module PositionIndependentCode (
4 cmmMakeDynamicReference,
12 This module handles generation of position independent code and
13 dynamic-linking related issues for the native code generator.
15 Things outside this module which are related to this:
18 - PIC base label (pretty printed as local label 1)
19 - DynamicLinkerLabels - several kinds:
20 CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset
21 - labelDynamic predicate
23 - The CmmExpr datatype has a CmmPicBaseReg constructor
24 - The CmmLit datatype has a CmmLabelDiffOff constructor
26 - When tablesNextToCode, no absolute addresses are stored in info tables
27 any more. Instead, offsets from the info label are used.
28 - For Win32 only, SRTs might contain addresses of __imp_ symbol pointers
29 because Win32 doesn't support external references in data sections.
30 TODO: make sure this still works, it might be bitrotted
32 - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all
34 - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output
35 all the necessary stuff for imported symbols.
36 - The NCG monad keeps track of a list of imported symbols.
37 - MachCodeGen invokes initializePicBase to generate code to initialize
38 the PIC base register when needed.
39 - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel
40 that wasn't in the original Cmm code (e.g. floating point literals).
42 - The mangler converts absolure refs to relative refs in info tables
43 - Symbol pointers, stub code and PIC calculations that are generated
44 by GCC are left intact by the mangler (so far only on ppc-darwin
48 #include "HsVersions.h"
49 #include "nativeGen/NCG.h"
52 import MachOp ( MachOp(MO_Add), wordRep )
53 import CLabel ( CLabel, pprCLabel,
54 mkDynamicLinkerLabel, DynamicLinkerLabelInfo(..),
55 dynamicLinkerLabelInfo, mkPicBaseLabel,
56 labelDynamic, externallyVisibleCLabel )
60 import NCGMonad ( NatM, getNewRegNat, getNewLabelNat )
62 import CmdLineOpts ( opt_PIC )
65 import qualified Outputable
67 import Panic ( panic )
70 -- The most important function here is cmmMakeDynamicReference.
72 -- It gets called by the cmmToCmm pass for every CmmLabel in the Cmm
73 -- code. It does The Right Thing(tm) to convert the CmmLabel into a
74 -- position-independent, dynamic-linking-aware reference to the thing
76 -- Note that this also has to be called from MachCodeGen in order to
77 -- access static data like floating point literals (labels that were
78 -- created after the cmmToCmm pass).
79 -- The function must run in a monad that can keep track of imported symbols
80 -- A function for recording an imported symbol must be passed in:
81 -- - addImportCmmOpt for the CmmOptM monad
82 -- - addImportNat for the NatM monad.
84 cmmMakeDynamicReference
85 :: Monad m => (CLabel -> m ()) -- a monad & a function
86 -- used for recording imported symbols
87 -> Bool -- whether this is the target of a jump
88 -> CLabel -- the label
91 cmmMakeDynamicReference addImport isJumpTarget lbl
92 | Just _ <- dynamicLinkerLabelInfo lbl
93 = return $ CmmLit $ CmmLabel lbl -- already processed it, pass through
94 | otherwise = case howToAccessLabel isJumpTarget lbl of
96 let stub = mkDynamicLinkerLabel CodeStub lbl
98 return $ CmmLit $ CmmLabel stub
99 AccessViaSymbolPtr -> do
100 let symbolPtr = mkDynamicLinkerLabel SymbolPtr lbl
102 return $ CmmLoad (cmmMakePicReference symbolPtr) wordRep
104 -- all currently supported processors support
105 -- a PC-relative branch instruction, so just jump there
106 | isJumpTarget -> return $ CmmLit $ CmmLabel lbl
107 -- for data, we might have to make some calculations:
108 | otherwise -> return $ cmmMakePicReference lbl
110 -- -------------------------------------------------------------------
112 -- Create a position independent reference to a label.
113 -- (but do not bother with dynamic linking).
114 -- We calculate the label's address by adding some (platform-dependent)
115 -- offset to our base register; this offset is calculated by
116 -- the function picRelative in the platform-dependent part below.
118 cmmMakePicReference :: CLabel -> CmmExpr
120 #if !mingw32_TARGET_OS
121 -- Windows doesn't need PIC,
122 -- everything gets relocated at runtime
124 cmmMakePicReference lbl
125 | opt_PIC && absoluteLabel lbl = CmmMachOp (MO_Add wordRep) [
127 CmmLit $ picRelative lbl
130 absoluteLabel lbl = case dynamicLinkerLabelInfo lbl of
131 Just (GotSymbolPtr, _) -> False
132 Just (GotSymbolOffset, _) -> False
136 cmmMakePicReference lbl = CmmLit $ CmmLabel lbl
138 -- ===================================================================
139 -- Platform dependent stuff
140 -- ===================================================================
142 -- Knowledge about how special dynamic linker labels like symbol
143 -- pointers, code stubs and GOT offsets look like is located in the
146 -- -------------------------------------------------------------------
148 -- We have to decide which labels need to be accessed
149 -- indirectly or via a piece of stub code.
151 data LabelAccessStyle = AccessViaStub
155 howToAccessLabel :: Bool -> CLabel -> LabelAccessStyle
157 #if mingw32_TARGET_OS
160 -- We need to use access *exactly* those things that
161 -- are imported from a DLL via an __imp_* label.
162 -- There are no stubs for imported code.
164 howToAccessLabel _ lbl | labelDynamic lbl = AccessViaSymbolPtr
165 | otherwise = AccessDirectly
167 #elif darwin_TARGET_OS
168 -- Mach-O (Darwin, Mac OS X)
170 -- Indirect access is required in the following cases:
171 -- * things imported from a dynamic library
172 -- * things from a different module, if we're generating PIC code
173 -- It is always possible to access something indirectly,
174 -- even when it's not necessary.
176 howToAccessLabel True lbl
177 -- jumps to a dynamic library go via a symbol stub
178 | labelDynamic lbl = AccessViaStub
179 -- when generating PIC code, all cross-module references must
180 -- must go via a symbol pointer, too.
181 -- Unfortunately, we don't know whether it's cross-module,
182 -- so we do it for all externally visible labels.
183 -- This is a slight waste of time and space, but otherwise
184 -- we'd need to pass the current Module all the way in to
186 | opt_PIC && externallyVisibleCLabel lbl = AccessViaStub
187 howToAccessLabel False lbl
188 -- data access to a dynamic library goes via a symbol pointer
189 | labelDynamic lbl = AccessViaSymbolPtr
190 -- cross-module PIC references: same as above
191 | opt_PIC && externallyVisibleCLabel lbl = AccessViaSymbolPtr
192 howToAccessLabel _ _ = AccessDirectly
194 #elif linux_TARGET_OS && powerpc_TARGET_ARCH
197 -- PowerPC Linux is just plain broken.
198 -- While it's theoretically possible to use GOT offsets larger
199 -- than 16 bit, the standard crt*.o files don't, which leads to
200 -- linker errors as soon as the GOT size exceeds 16 bit.
201 -- Also, the assembler doesn't support @gotoff labels.
202 -- In order to be able to use a larger GOT, we circumvent the
203 -- entire GOT mechanism and do it ourselves (this is what GCC does).
205 -- In this scheme, we need to do _all data references_ (even refs
206 -- to static data) via a SymbolPtr when we are generating PIC.
207 -- Luckily, the PLT works as expected, so we can simply access
208 -- dynamically linked code via the PLT.
210 howToAccessLabel _ _ | not opt_PIC = AccessDirectly
211 howToAccessLabel True lbl
212 = if labelDynamic lbl then AccessViaStub
214 howToAccessLabel False lbl
217 #elif linux_TARGET_OS
220 -- Indirect access is required for references to imported symbols
221 -- from position independent code.
222 -- It is always possible to access something indirectly,
223 -- even when it's not necessary.
225 -- For code, we can use a relative jump to a piece of
226 -- stub code instead (this allows lazy binding of imported symbols).
228 howToAccessLabel isJump lbl
229 -- no PIC -> the dynamic linker does everything for us
230 | not opt_PIC = AccessDirectly
231 -- if it's not imported, we need no indirection
232 -- ("foo" will end up being accessed as "foo@GOTOFF")
233 | not (labelDynamic lbl) = AccessDirectly
234 #if !i386_TARGET_ARCH
235 -- for Intel, we temporarily disable the use of the
236 -- Procedure Linkage Table, because PLTs on intel require the
237 -- address of the GOT to be loaded into register %ebx before
238 -- a jump through the PLT is made.
239 -- TODO: make the i386 NCG ensure this before jumping to a
240 -- CodeStub label, so we can remove this special case.
241 | isJump = AccessViaStub
243 | otherwise = AccessViaSymbolPtr
246 -- -------------------------------------------------------------------
248 -- What do we have to add to our 'PIC base register' in order to
249 -- get the address of a label?
251 picRelative :: CLabel -> CmmLit
254 -- The PIC base register points to the PIC base label at the beginning
255 -- of the current CmmTop. We just have to use a label difference to
257 -- We have already made sure that all labels that are not from the current
258 -- module are accessed indirectly ('as' can't calculate differences between
259 -- undefined labels).
262 = CmmLabelDiffOff lbl mkPicBaseLabel 0
264 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
266 -- The PIC base register points to our fake GOT. Use a label difference
267 -- to get the offset.
268 -- We have made sure that *everything* is accessed indirectly, so this
269 -- is only used for offsets from the GOT to symbol pointers inside the
272 = CmmLabelDiffOff lbl gotLabel 0
274 #elif linux_TARGET_OS
275 -- Other Linux versions:
276 -- The PIC base register points to the GOT. Use foo@got for symbol
277 -- pointers, and foo@gotoff for everything else.
280 | Just (SymbolPtr, lbl') <- dynamicLinkerLabelInfo lbl
281 = CmmLabel $ mkDynamicLinkerLabel GotSymbolPtr lbl'
283 = CmmLabel $ mkDynamicLinkerLabel GotSymbolOffset lbl
286 picRelative lbl = panic "PositionIndependentCode.picRelative"
289 -- -------------------------------------------------------------------
291 -- What do we have to add to every assembly file we generate?
293 -- utility function for pretty-printing asm-labels,
294 -- copied from PprMach
295 asmSDoc d = Outputable.withPprStyleDoc (
296 Outputable.mkCodeStyle Outputable.AsmStyle) d
297 pprCLabel_asm l = asmSDoc (pprCLabel l)
302 needImportedSymbols = True
304 -- We don't need to declare any offset tables
305 pprGotDeclaration = Pretty.empty
307 -- On Darwin, we have to generate our own stub code for lazy binding..
308 -- There are two versions, one for PIC and one for non-PIC.
309 pprImportedSymbol importedLbl
310 | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl
314 ptext SLIT(".symbol_stub"),
315 ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$stub:"),
316 ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
317 ptext SLIT("\tlis r11,ha16(L") <> pprCLabel_asm lbl
318 <> ptext SLIT("$lazy_ptr)"),
319 ptext SLIT("\tlwz r12,lo16(L") <> pprCLabel_asm lbl
320 <> ptext SLIT("$lazy_ptr)(r11)"),
321 ptext SLIT("\tmtctr r12"),
322 ptext SLIT("\taddi r11,r11,lo16(L") <> pprCLabel_asm lbl
323 <> ptext SLIT("$lazy_ptr)"),
328 ptext SLIT(".section __TEXT,__picsymbolstub1,")
329 <> ptext SLIT("symbol_stubs,pure_instructions,32"),
330 ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$stub:"),
331 ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
332 ptext SLIT("\tmflr r0"),
333 ptext SLIT("\tbcl 20,31,L0$") <> pprCLabel_asm lbl,
334 ptext SLIT("L0$") <> pprCLabel_asm lbl <> char ':',
335 ptext SLIT("\tmflr r11"),
336 ptext SLIT("\taddis r11,r11,ha16(L") <> pprCLabel_asm lbl
337 <> ptext SLIT("$lazy_ptr-L0$") <> pprCLabel_asm lbl <> char ')',
338 ptext SLIT("\tmtlr r0"),
339 ptext SLIT("\tlwzu r12,lo16(L") <> pprCLabel_asm lbl
340 <> ptext SLIT("$lazy_ptr-L0$") <> pprCLabel_asm lbl
341 <> ptext SLIT(")(r11)"),
342 ptext SLIT("\tmtctr r12"),
346 ptext SLIT(".lazy_symbol_pointer"),
347 ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$lazy_ptr:"),
348 ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
349 ptext SLIT("\t.long dyld_stub_binding_helper")
352 -- We also have to declare our symbol pointers ourselves:
353 | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl
355 ptext SLIT(".non_lazy_symbol_pointer"),
356 char 'L' <> pprCLabel_asm lbl <> ptext SLIT("$non_lazy_ptr:"),
357 ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
358 ptext SLIT("\t.long\t0")
363 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
365 -- For PowerPC linux, we don't do anything unless we're generating PIC.
366 needImportedSymbols = opt_PIC
368 -- If we're generating PIC, we need to create our own "fake GOT".
370 gotLabel = mkForeignLabel -- HACK: it's not really foreign
371 FSLIT(".LCTOC1") Nothing False
373 -- The .LCTOC1 label is defined to point 32768 bytes into the table,
374 -- to make the most of the PPC's 16-bit displacements.
376 pprGotDeclaration = vcat [
377 ptext SLIT(".section \".got2\",\"aw\""),
378 ptext SLIT(".LCTOC1 = .+32768")
381 -- We generate one .long literal for every symbol we import;
382 -- the dynamic linker will relocate those addresses.
384 pprImportedSymbol importedLbl
385 | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl
387 ptext SLIT(".section \".got2\", \"aw\""),
388 ptext SLIT(".LC_") <> pprCLabel_asm lbl <> char ':',
389 ptext SLIT("\t.long") <+> pprCLabel_asm lbl
392 -- PLT code stubs are generated automatically be the dynamic linker.
397 -- For all other currently supported platforms, we don't need to do
400 needImportedSymbols = False
401 pprGotDeclaration = Pretty.empty
402 pprImportedSymbol _ = empty
405 -- -------------------------------------------------------------------
407 -- Generate code to calculate the address that should be put in the
408 -- PIC base register.
409 -- This is called by MachCodeGen for every CmmProc that accessed the
410 -- PIC base register. It adds the appropriate instructions to the
411 -- top of the CmmProc.
413 -- It is assumed that the first NatCmmTop in the input list is a Proc
414 -- and the rest are CmmDatas.
416 initializePicBase :: Reg -> [NatCmmTop] -> NatM [NatCmmTop]
418 #if powerpc_TARGET_ARCH && darwin_TARGET_OS
420 -- Darwin is simple: just fetch the address of a local label.
421 initializePicBase picReg (CmmProc info lab params blocks : statics)
422 = return (CmmProc info lab params (b':tail blocks) : statics)
423 where BasicBlock bID insns = head blocks
424 b' = BasicBlock bID (FETCHPC picReg : insns)
426 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
428 -- Get a pointer to our own fake GOT, which is defined on a per-module basis.
429 -- This is exactly how GCC does it, and it's quite horrible:
430 -- We first fetch the address of a local label (mkPicBaseLabel).
431 -- Then we add a 16-bit offset to that to get the address of a .long that we
432 -- define in .text space right next to the proc. This .long literal contains
433 -- the (32-bit) offset from our local label to our global offset table
434 -- (.LCTOC1 aka gotOffLabel).
435 initializePicBase picReg
436 (CmmProc info lab params blocks : statics)
438 gotOffLabel <- getNewLabelNat
439 tmp <- getNewRegNat wordRep
441 gotOffset = CmmData Text [
442 CmmDataLabel gotOffLabel,
443 CmmStaticLit (CmmLabelDiffOff gotLabel
447 offsetToOffset = ImmConstantDiff (ImmCLbl gotOffLabel)
448 (ImmCLbl mkPicBaseLabel)
449 BasicBlock bID insns = head blocks
450 b' = BasicBlock bID (FETCHPC picReg
452 (AddrRegImm picReg offsetToOffset)
453 : ADD picReg picReg (RIReg tmp)
455 return (CmmProc info lab params (b' : tail blocks) : gotOffset : statics)
457 initializePicBase picReg proc = panic "initializePicBase"
460 -- i386_TARGET_ARCH && linux_TARGET_OS:
461 -- generate something like:
464 -- addl __GLOBAL_OFFSET_TABLE__+.-1b, %picReg
465 -- It might be a good idea to use a FETCHPC pseudo-instruction (like for PowerPC)
466 -- in order to avoid having to create a new basic block.
467 -- ((FETCHPC reg) should pretty-print as call 1f; 1: popl reg)
469 -- mingw32_TARGET_OS: not needed, won't be called
471 -- i386_TARGET_ARCH && darwin_TARGET_OS:
472 -- (just for completeness ;-)