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 )
58 #if powerpc_TARGET_ARCH && linux_TARGET_OS
59 import CLabel ( mkForeignLabel )
64 import NCGMonad ( NatM, getNewRegNat, getNewLabelNat )
66 import CmdLineOpts ( opt_PIC )
69 import qualified Outputable
71 import Panic ( panic )
74 -- The most important function here is cmmMakeDynamicReference.
76 -- It gets called by the cmmToCmm pass for every CmmLabel in the Cmm
77 -- code. It does The Right Thing(tm) to convert the CmmLabel into a
78 -- position-independent, dynamic-linking-aware reference to the thing
80 -- Note that this also has to be called from MachCodeGen in order to
81 -- access static data like floating point literals (labels that were
82 -- created after the cmmToCmm pass).
83 -- The function must run in a monad that can keep track of imported symbols
84 -- A function for recording an imported symbol must be passed in:
85 -- - addImportCmmOpt for the CmmOptM monad
86 -- - addImportNat for the NatM monad.
88 cmmMakeDynamicReference
89 :: Monad m => (CLabel -> m ()) -- a monad & a function
90 -- used for recording imported symbols
91 -> Bool -- whether this is the target of a jump
92 -> CLabel -- the label
95 cmmMakeDynamicReference addImport isJumpTarget lbl
96 | Just _ <- dynamicLinkerLabelInfo lbl
97 = return $ CmmLit $ CmmLabel lbl -- already processed it, pass through
98 | otherwise = case howToAccessLabel isJumpTarget lbl of
100 let stub = mkDynamicLinkerLabel CodeStub lbl
102 return $ CmmLit $ CmmLabel stub
103 AccessViaSymbolPtr -> do
104 let symbolPtr = mkDynamicLinkerLabel SymbolPtr lbl
106 return $ CmmLoad (cmmMakePicReference symbolPtr) wordRep
108 -- all currently supported processors support
109 -- a PC-relative branch instruction, so just jump there
110 | isJumpTarget -> return $ CmmLit $ CmmLabel lbl
111 -- for data, we might have to make some calculations:
112 | otherwise -> return $ cmmMakePicReference lbl
114 -- -------------------------------------------------------------------
116 -- Create a position independent reference to a label.
117 -- (but do not bother with dynamic linking).
118 -- We calculate the label's address by adding some (platform-dependent)
119 -- offset to our base register; this offset is calculated by
120 -- the function picRelative in the platform-dependent part below.
122 cmmMakePicReference :: CLabel -> CmmExpr
124 #if !mingw32_TARGET_OS
125 -- Windows doesn't need PIC,
126 -- everything gets relocated at runtime
128 cmmMakePicReference lbl
129 | opt_PIC && absoluteLabel lbl = CmmMachOp (MO_Add wordRep) [
131 CmmLit $ picRelative lbl
134 absoluteLabel lbl = case dynamicLinkerLabelInfo lbl of
135 Just (GotSymbolPtr, _) -> False
136 Just (GotSymbolOffset, _) -> False
140 cmmMakePicReference lbl = CmmLit $ CmmLabel lbl
142 -- ===================================================================
143 -- Platform dependent stuff
144 -- ===================================================================
146 -- Knowledge about how special dynamic linker labels like symbol
147 -- pointers, code stubs and GOT offsets look like is located in the
150 -- -------------------------------------------------------------------
152 -- We have to decide which labels need to be accessed
153 -- indirectly or via a piece of stub code.
155 data LabelAccessStyle = AccessViaStub
159 howToAccessLabel :: Bool -> CLabel -> LabelAccessStyle
161 #if mingw32_TARGET_OS
164 -- We need to use access *exactly* those things that
165 -- are imported from a DLL via an __imp_* label.
166 -- There are no stubs for imported code.
168 howToAccessLabel _ lbl | labelDynamic lbl = AccessViaSymbolPtr
169 | otherwise = AccessDirectly
171 #elif darwin_TARGET_OS
172 -- Mach-O (Darwin, Mac OS X)
174 -- Indirect access is required in the following cases:
175 -- * things imported from a dynamic library
176 -- * things from a different module, if we're generating PIC code
177 -- It is always possible to access something indirectly,
178 -- even when it's not necessary.
180 howToAccessLabel True lbl
181 -- jumps to a dynamic library go via a symbol stub
182 | labelDynamic lbl = AccessViaStub
183 -- when generating PIC code, all cross-module references must
184 -- must go via a symbol pointer, too.
185 -- Unfortunately, we don't know whether it's cross-module,
186 -- so we do it for all externally visible labels.
187 -- This is a slight waste of time and space, but otherwise
188 -- we'd need to pass the current Module all the way in to
190 | opt_PIC && externallyVisibleCLabel lbl = AccessViaStub
191 howToAccessLabel False lbl
192 -- data access to a dynamic library goes via a symbol pointer
193 | labelDynamic lbl = AccessViaSymbolPtr
194 -- cross-module PIC references: same as above
195 | opt_PIC && externallyVisibleCLabel lbl = AccessViaSymbolPtr
196 howToAccessLabel _ _ = AccessDirectly
198 #elif linux_TARGET_OS && powerpc_TARGET_ARCH
201 -- PowerPC Linux is just plain broken.
202 -- While it's theoretically possible to use GOT offsets larger
203 -- than 16 bit, the standard crt*.o files don't, which leads to
204 -- linker errors as soon as the GOT size exceeds 16 bit.
205 -- Also, the assembler doesn't support @gotoff labels.
206 -- In order to be able to use a larger GOT, we circumvent the
207 -- entire GOT mechanism and do it ourselves (this is what GCC does).
209 -- In this scheme, we need to do _all data references_ (even refs
210 -- to static data) via a SymbolPtr when we are generating PIC.
211 -- Luckily, the PLT works as expected, so we can simply access
212 -- dynamically linked code via the PLT.
214 howToAccessLabel _ _ | not opt_PIC = AccessDirectly
215 howToAccessLabel True lbl
216 = if labelDynamic lbl then AccessViaStub
218 howToAccessLabel False lbl
221 #elif linux_TARGET_OS
224 -- Indirect access is required for references to imported symbols
225 -- from position independent code.
226 -- It is always possible to access something indirectly,
227 -- even when it's not necessary.
229 -- For code, we can use a relative jump to a piece of
230 -- stub code instead (this allows lazy binding of imported symbols).
232 howToAccessLabel isJump lbl
233 -- no PIC -> the dynamic linker does everything for us
234 | not opt_PIC = AccessDirectly
235 -- if it's not imported, we need no indirection
236 -- ("foo" will end up being accessed as "foo@GOTOFF")
237 | not (labelDynamic lbl) = AccessDirectly
238 #if !i386_TARGET_ARCH
239 -- for Intel, we temporarily disable the use of the
240 -- Procedure Linkage Table, because PLTs on intel require the
241 -- address of the GOT to be loaded into register %ebx before
242 -- a jump through the PLT is made.
243 -- TODO: make the i386 NCG ensure this before jumping to a
244 -- CodeStub label, so we can remove this special case.
245 | isJump = AccessViaStub
247 | otherwise = AccessViaSymbolPtr
251 -- all other platforms
254 | not opt_PIC = AccessDirectly
255 | otherwise = panic "howToAccessLabel: PIC not defined for this platform"
258 -- -------------------------------------------------------------------
260 -- What do we have to add to our 'PIC base register' in order to
261 -- get the address of a label?
263 picRelative :: CLabel -> CmmLit
266 -- The PIC base register points to the PIC base label at the beginning
267 -- of the current CmmTop. We just have to use a label difference to
269 -- We have already made sure that all labels that are not from the current
270 -- module are accessed indirectly ('as' can't calculate differences between
271 -- undefined labels).
274 = CmmLabelDiffOff lbl mkPicBaseLabel 0
276 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
278 -- The PIC base register points to our fake GOT. Use a label difference
279 -- to get the offset.
280 -- We have made sure that *everything* is accessed indirectly, so this
281 -- is only used for offsets from the GOT to symbol pointers inside the
284 = CmmLabelDiffOff lbl gotLabel 0
286 #elif linux_TARGET_OS
287 -- Other Linux versions:
288 -- The PIC base register points to the GOT. Use foo@got for symbol
289 -- pointers, and foo@gotoff for everything else.
292 | Just (SymbolPtr, lbl') <- dynamicLinkerLabelInfo lbl
293 = CmmLabel $ mkDynamicLinkerLabel GotSymbolPtr lbl'
295 = CmmLabel $ mkDynamicLinkerLabel GotSymbolOffset lbl
298 picRelative lbl = panic "PositionIndependentCode.picRelative"
301 -- -------------------------------------------------------------------
303 -- What do we have to add to every assembly file we generate?
305 -- utility function for pretty-printing asm-labels,
306 -- copied from PprMach
307 asmSDoc d = Outputable.withPprStyleDoc (
308 Outputable.mkCodeStyle Outputable.AsmStyle) d
309 pprCLabel_asm l = asmSDoc (pprCLabel l)
314 needImportedSymbols = True
316 -- We don't need to declare any offset tables
317 pprGotDeclaration = Pretty.empty
319 -- On Darwin, we have to generate our own stub code for lazy binding..
320 -- There are two versions, one for PIC and one for non-PIC.
321 pprImportedSymbol importedLbl
322 | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl
326 ptext SLIT(".symbol_stub"),
327 ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$stub:"),
328 ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
329 ptext SLIT("\tlis r11,ha16(L") <> pprCLabel_asm lbl
330 <> ptext SLIT("$lazy_ptr)"),
331 ptext SLIT("\tlwz r12,lo16(L") <> pprCLabel_asm lbl
332 <> ptext SLIT("$lazy_ptr)(r11)"),
333 ptext SLIT("\tmtctr r12"),
334 ptext SLIT("\taddi r11,r11,lo16(L") <> pprCLabel_asm lbl
335 <> ptext SLIT("$lazy_ptr)"),
340 ptext SLIT(".section __TEXT,__picsymbolstub1,")
341 <> ptext SLIT("symbol_stubs,pure_instructions,32"),
342 ptext SLIT("\t.align 2"),
343 ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$stub:"),
344 ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
345 ptext SLIT("\tmflr r0"),
346 ptext SLIT("\tbcl 20,31,L0$") <> pprCLabel_asm lbl,
347 ptext SLIT("L0$") <> pprCLabel_asm lbl <> char ':',
348 ptext SLIT("\tmflr r11"),
349 ptext SLIT("\taddis r11,r11,ha16(L") <> pprCLabel_asm lbl
350 <> ptext SLIT("$lazy_ptr-L0$") <> pprCLabel_asm lbl <> char ')',
351 ptext SLIT("\tmtlr r0"),
352 ptext SLIT("\tlwzu r12,lo16(L") <> pprCLabel_asm lbl
353 <> ptext SLIT("$lazy_ptr-L0$") <> pprCLabel_asm lbl
354 <> ptext SLIT(")(r11)"),
355 ptext SLIT("\tmtctr r12"),
359 ptext SLIT(".lazy_symbol_pointer"),
360 ptext SLIT("L") <> pprCLabel_asm lbl <> ptext SLIT("$lazy_ptr:"),
361 ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
362 ptext SLIT("\t.long dyld_stub_binding_helper")
365 -- We also have to declare our symbol pointers ourselves:
366 | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl
368 ptext SLIT(".non_lazy_symbol_pointer"),
369 char 'L' <> pprCLabel_asm lbl <> ptext SLIT("$non_lazy_ptr:"),
370 ptext SLIT("\t.indirect_symbol") <+> pprCLabel_asm lbl,
371 ptext SLIT("\t.long\t0")
376 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
378 -- For PowerPC linux, we don't do anything unless we're generating PIC.
379 needImportedSymbols = opt_PIC
381 -- If we're generating PIC, we need to create our own "fake GOT".
383 gotLabel = mkForeignLabel -- HACK: it's not really foreign
384 FSLIT(".LCTOC1") Nothing False
386 -- The .LCTOC1 label is defined to point 32768 bytes into the table,
387 -- to make the most of the PPC's 16-bit displacements.
389 pprGotDeclaration = vcat [
390 ptext SLIT(".section \".got2\",\"aw\""),
391 ptext SLIT(".LCTOC1 = .+32768")
394 -- We generate one .long literal for every symbol we import;
395 -- the dynamic linker will relocate those addresses.
397 pprImportedSymbol importedLbl
398 | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl
400 ptext SLIT(".section \".got2\", \"aw\""),
401 ptext SLIT(".LC_") <> pprCLabel_asm lbl <> char ':',
402 ptext SLIT("\t.long") <+> pprCLabel_asm lbl
405 -- PLT code stubs are generated automatically be the dynamic linker.
410 -- For all other currently supported platforms, we don't need to do
413 needImportedSymbols = False
414 pprGotDeclaration = Pretty.empty
415 pprImportedSymbol _ = empty
418 -- -------------------------------------------------------------------
420 -- Generate code to calculate the address that should be put in the
421 -- PIC base register.
422 -- This is called by MachCodeGen for every CmmProc that accessed the
423 -- PIC base register. It adds the appropriate instructions to the
424 -- top of the CmmProc.
426 -- It is assumed that the first NatCmmTop in the input list is a Proc
427 -- and the rest are CmmDatas.
429 initializePicBase :: Reg -> [NatCmmTop] -> NatM [NatCmmTop]
431 #if powerpc_TARGET_ARCH && darwin_TARGET_OS
433 -- Darwin is simple: just fetch the address of a local label.
434 initializePicBase picReg (CmmProc info lab params blocks : statics)
435 = return (CmmProc info lab params (b':tail blocks) : statics)
436 where BasicBlock bID insns = head blocks
437 b' = BasicBlock bID (FETCHPC picReg : insns)
439 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
441 -- Get a pointer to our own fake GOT, which is defined on a per-module basis.
442 -- This is exactly how GCC does it, and it's quite horrible:
443 -- We first fetch the address of a local label (mkPicBaseLabel).
444 -- Then we add a 16-bit offset to that to get the address of a .long that we
445 -- define in .text space right next to the proc. This .long literal contains
446 -- the (32-bit) offset from our local label to our global offset table
447 -- (.LCTOC1 aka gotOffLabel).
448 initializePicBase picReg
449 (CmmProc info lab params blocks : statics)
451 gotOffLabel <- getNewLabelNat
452 tmp <- getNewRegNat wordRep
454 gotOffset = CmmData Text [
455 CmmDataLabel gotOffLabel,
456 CmmStaticLit (CmmLabelDiffOff gotLabel
460 offsetToOffset = ImmConstantDiff (ImmCLbl gotOffLabel)
461 (ImmCLbl mkPicBaseLabel)
462 BasicBlock bID insns = head blocks
463 b' = BasicBlock bID (FETCHPC picReg
465 (AddrRegImm picReg offsetToOffset)
466 : ADD picReg picReg (RIReg tmp)
468 return (CmmProc info lab params (b' : tail blocks) : gotOffset : statics)
470 initializePicBase picReg proc = panic "initializePicBase"
473 -- i386_TARGET_ARCH && linux_TARGET_OS:
474 -- generate something like:
477 -- addl __GLOBAL_OFFSET_TABLE__+.-1b, %picReg
478 -- It might be a good idea to use a FETCHPC pseudo-instruction (like for PowerPC)
479 -- in order to avoid having to create a new basic block.
480 -- ((FETCHPC reg) should pretty-print as call 1f; 1: popl reg)
482 -- mingw32_TARGET_OS: not needed, won't be called
484 -- i386_TARGET_ARCH && darwin_TARGET_OS:
485 -- (just for completeness ;-)