Fix the build on amd64/Linux
[ghc-hetmet.git] / compiler / nativeGen / PositionIndependentCode.hs
1 {-# OPTIONS -w #-}
2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
6 -- for details
7
8 module PositionIndependentCode (
9         cmmMakeDynamicReference,
10         ReferenceKind(..),
11         needImportedSymbols,
12         pprImportedSymbol,
13         pprGotDeclaration,
14         initializePicBase
15      ) where
16
17 #include "HsVersions.h"
18
19 {-
20   This module handles generation of position independent code and
21   dynamic-linking related issues for the native code generator.
22   
23   Things outside this module which are related to this:
24   
25   + module CLabel
26     - PIC base label (pretty printed as local label 1)
27     - DynamicLinkerLabels - several kinds:
28         CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset
29     - labelDynamic predicate
30   + module Cmm
31     - The GlobalReg datatype has a PicBaseReg constructor
32     - The CmmLit datatype has a CmmLabelDiffOff constructor
33   + codeGen & RTS
34     - When tablesNextToCode, no absolute addresses are stored in info tables
35       any more. Instead, offsets from the info label are used.
36     - For Win32 only, SRTs might contain addresses of __imp_ symbol pointers
37       because Win32 doesn't support external references in data sections.
38       TODO: make sure this still works, it might be bitrotted
39   + NCG
40     - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all
41       labels.
42     - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output
43       all the necessary stuff for imported symbols.
44     - The NCG monad keeps track of a list of imported symbols.
45     - MachCodeGen invokes initializePicBase to generate code to initialize
46       the PIC base register when needed.
47     - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel
48       that wasn't in the original Cmm code (e.g. floating point literals).
49   + The Mangler
50     - The mangler converts absolure refs to relative refs in info tables
51     - Symbol pointers, stub code and PIC calculations that are generated
52       by GCC are left intact by the mangler (so far only on ppc-darwin
53       and ppc-linux).
54 -}
55
56 #include "nativeGen/NCG.h"
57
58 import Cmm
59 import CLabel           ( CLabel, pprCLabel,
60                           mkDynamicLinkerLabel, DynamicLinkerLabelInfo(..),
61                           dynamicLinkerLabelInfo, mkPicBaseLabel,
62                           labelDynamic, externallyVisibleCLabel )
63
64 #if linux_TARGET_OS
65 import CLabel           ( mkForeignLabel )
66 #endif
67
68 import Regs
69 import Instrs
70 import NCGMonad         ( NatM, getNewRegNat, getNewLabelNat )
71
72 import StaticFlags      ( opt_PIC, opt_Static )
73 import BasicTypes
74
75 import Pretty
76 import qualified Outputable
77
78 import Panic            ( panic )
79 import DynFlags
80 import FastString
81
82
83 -- The most important function here is cmmMakeDynamicReference.
84
85 -- It gets called by the cmmToCmm pass for every CmmLabel in the Cmm
86 -- code. It does The Right Thing(tm) to convert the CmmLabel into a
87 -- position-independent, dynamic-linking-aware reference to the thing
88 -- in question.
89 -- Note that this also has to be called from MachCodeGen in order to
90 -- access static data like floating point literals (labels that were
91 -- created after the cmmToCmm pass).
92 -- The function must run in a monad that can keep track of imported symbols
93 -- A function for recording an imported symbol must be passed in:
94 -- - addImportCmmOpt for the CmmOptM monad
95 -- - addImportNat for the NatM monad.
96
97 data ReferenceKind = DataReference
98                    | CallReference
99                    | JumpReference
100                    deriving(Eq)
101
102 cmmMakeDynamicReference
103   :: Monad m => DynFlags
104              -> (CLabel -> m ())  -- a monad & a function
105                                   -- used for recording imported symbols
106              -> ReferenceKind     -- whether this is the target of a jump
107              -> CLabel            -- the label
108              -> m CmmExpr
109   
110 cmmMakeDynamicReference dflags addImport referenceKind lbl
111   | Just _ <- dynamicLinkerLabelInfo lbl
112   = return $ CmmLit $ CmmLabel lbl   -- already processed it, pass through
113   | otherwise = case howToAccessLabel dflags referenceKind lbl of
114         AccessViaStub -> do
115               let stub = mkDynamicLinkerLabel CodeStub lbl
116               addImport stub
117               return $ CmmLit $ CmmLabel stub
118         AccessViaSymbolPtr -> do
119               let symbolPtr = mkDynamicLinkerLabel SymbolPtr lbl
120               addImport symbolPtr
121               return $ CmmLoad (cmmMakePicReference symbolPtr) bWord
122         AccessDirectly -> case referenceKind of
123                 -- for data, we might have to make some calculations:
124               DataReference -> return $ cmmMakePicReference lbl  
125                 -- all currently supported processors support
126                 -- PC-relative branch and call instructions,
127                 -- so just jump there if it's a call or a jump
128               _ -> return $ CmmLit $ CmmLabel lbl
129   
130 -- -------------------------------------------------------------------
131   
132 -- Create a position independent reference to a label.
133 -- (but do not bother with dynamic linking).
134 -- We calculate the label's address by adding some (platform-dependent)
135 -- offset to our base register; this offset is calculated by
136 -- the function picRelative in the platform-dependent part below.
137
138 cmmMakePicReference :: CLabel -> CmmExpr
139   
140 #if !mingw32_TARGET_OS
141         -- Windows doesn't need PIC,
142         -- everything gets relocated at runtime
143
144 cmmMakePicReference lbl
145     | (opt_PIC || not opt_Static) && absoluteLabel lbl = CmmMachOp (MO_Add wordWidth) [
146             CmmReg (CmmGlobal PicBaseReg),
147             CmmLit $ picRelative lbl
148         ]
149     where
150         absoluteLabel lbl = case dynamicLinkerLabelInfo lbl of
151                                 Just (GotSymbolPtr, _) -> False
152                                 Just (GotSymbolOffset, _) -> False
153                                 _ -> True
154
155 #endif
156 cmmMakePicReference lbl = CmmLit $ CmmLabel lbl
157
158 -- ===================================================================
159 -- Platform dependent stuff
160 -- ===================================================================
161
162 -- Knowledge about how special dynamic linker labels like symbol
163 -- pointers, code stubs and GOT offsets look like is located in the
164 -- module CLabel.
165
166 -- -------------------------------------------------------------------
167
168 -- We have to decide which labels need to be accessed
169 -- indirectly or via a piece of stub code.
170
171 data LabelAccessStyle = AccessViaStub
172                       | AccessViaSymbolPtr
173                       | AccessDirectly
174
175 howToAccessLabel :: DynFlags -> ReferenceKind -> CLabel -> LabelAccessStyle
176
177 #if mingw32_TARGET_OS
178 -- Windows
179 -- 
180 -- We need to use access *exactly* those things that
181 -- are imported from a DLL via an __imp_* label.
182 -- There are no stubs for imported code.
183
184 howToAccessLabel dflags _ lbl | labelDynamic (thisPackage dflags) lbl = AccessViaSymbolPtr
185                               | otherwise        = AccessDirectly
186 #elif darwin_TARGET_OS
187 -- Mach-O (Darwin, Mac OS X)
188 --
189 -- Indirect access is required in the following cases:
190 --  * things imported from a dynamic library
191 --  * (not on x86_64) data from a different module, if we're generating PIC code
192 -- It is always possible to access something indirectly,
193 -- even when it's not necessary.
194
195 howToAccessLabel dflags DataReference lbl
196       -- data access to a dynamic library goes via a symbol pointer
197     | labelDynamic (thisPackage dflags) lbl = AccessViaSymbolPtr
198     
199 #if !x86_64_TARGET_ARCH
200       -- when generating PIC code, all cross-module data references must
201       -- must go via a symbol pointer, too, because the assembler
202       -- cannot generate code for a label difference where one
203       -- label is undefined. Doesn't apply t x86_64.
204       -- Unfortunately, we don't know whether it's cross-module,
205       -- so we do it for all externally visible labels.
206       -- This is a slight waste of time and space, but otherwise
207       -- we'd need to pass the current Module all the way in to
208       -- this function.
209     | opt_PIC && externallyVisibleCLabel lbl = AccessViaSymbolPtr
210 #endif
211     | otherwise = AccessDirectly
212
213
214 #if i386_TARGET_ARCH || x86_64_TARGET_ARCH
215     -- dyld code stubs don't work for tailcalls because the
216     -- stack alignment is only right for regular calls.
217     -- Therefore, we have to go via a symbol pointer:
218 howToAccessLabel dflags JumpReference lbl
219     | labelDynamic (thisPackage dflags) lbl
220     = AccessViaSymbolPtr
221 #endif
222
223 howToAccessLabel dflags _ lbl
224 #if !x86_64_TARGET_ARCH
225     -- Code stubs are the usual method of choice for imported code;
226     -- not needed on x86_64 because Apple's new linker, ld64, generates
227     -- them automatically.
228     | labelDynamic (thisPackage dflags) lbl
229     = AccessViaStub
230 #endif
231     | otherwise
232     = AccessDirectly
233
234
235 #elif linux_TARGET_OS && powerpc64_TARGET_ARCH
236 -- ELF PPC64 (powerpc64-linux), AIX, MacOS 9, BeOS/PPC
237
238 howToAccessLabel _ DataReference lbl = AccessViaSymbolPtr
239 howToAccessLabel _ _ lbl = AccessDirectly -- actually, .label instead of label
240
241 #elif linux_TARGET_OS
242 -- ELF (Linux)
243 --
244 -- ELF tries to pretend to the main application code that dynamic linking does 
245 -- not exist. While this may sound convenient, it tends to mess things up in
246 -- very bad ways, so we have to be careful when we generate code for the main
247 -- program (-dynamic but no -fPIC).
248 --
249 -- Indirect access is required for references to imported symbols
250 -- from position independent code. It is also required from the main program
251 -- when dynamic libraries containing Haskell code are used.
252
253 howToAccessLabel _ _ lbl
254         -- no PIC -> the dynamic linker does everything for us;
255         --           if we don't dynamically link to Haskell code,
256         --           it actually manages to do so without messing thins up.
257     | not opt_PIC && opt_Static = AccessDirectly
258    
259 howToAccessLabel dflags DataReference lbl
260         -- A dynamic label needs to be accessed via a symbol pointer.
261     | labelDynamic (thisPackage dflags) lbl = AccessViaSymbolPtr
262 #if powerpc_TARGET_ARCH
263         -- For PowerPC32 -fPIC, we have to access even static data
264         -- via a symbol pointer (see below for an explanation why
265         -- PowerPC32 Linux is especially broken).
266     | opt_PIC = AccessViaSymbolPtr
267 #endif
268     | otherwise = AccessDirectly
269
270
271 -- In most cases, we have to avoid symbol stubs on ELF, for the following reasons:
272 -- * on i386, the position-independent symbol stubs in the Procedure Linkage Table
273 --   require the address of the GOT to be loaded into register %ebx on entry.
274 -- * The linker will take any reference to the symbol stub as a hint that
275 --   the label in question is a code label. When linking executables, this
276 --   will cause the linker to replace even data references to the label with
277 --   references to the symbol stub.
278
279 -- This leaves calling a (foreign) function from non-PIC code
280 -- (AccessDirectly, because we get an implicit symbol stub)
281 -- and calling functions from PIC code on non-i386 platforms (via a symbol stub) 
282
283 howToAccessLabel dflags CallReference lbl
284     | labelDynamic (thisPackage dflags) lbl && not opt_PIC
285     = AccessDirectly
286 #if !i386_TARGET_ARCH
287     | labelDynamic (thisPackage dflags) lbl && opt_PIC
288     = AccessViaStub
289 #endif
290
291 howToAccessLabel dflags _ lbl
292     | labelDynamic (thisPackage dflags) lbl = AccessViaSymbolPtr
293     | otherwise = AccessDirectly
294 #else
295 --
296 -- all other platforms
297 --
298 howToAccessLabel _ _ _
299         | not opt_PIC = AccessDirectly
300         | otherwise   = panic "howToAccessLabel: PIC not defined for this platform"
301 #endif
302
303 -- -------------------------------------------------------------------
304
305 -- What do we have to add to our 'PIC base register' in order to
306 -- get the address of a label?
307
308 picRelative :: CLabel -> CmmLit
309 #if darwin_TARGET_OS && !x86_64_TARGET_ARCH
310 -- Darwin, but not x86_64:
311 -- The PIC base register points to the PIC base label at the beginning
312 -- of the current CmmTop. We just have to use a label difference to
313 -- get the offset.
314 -- We have already made sure that all labels that are not from the current
315 -- module are accessed indirectly ('as' can't calculate differences between
316 -- undefined labels).
317
318 picRelative lbl
319   = CmmLabelDiffOff lbl mkPicBaseLabel 0
320
321 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
322 -- PowerPC Linux:
323 -- The PIC base register points to our fake GOT. Use a label difference
324 -- to get the offset.
325 -- We have made sure that *everything* is accessed indirectly, so this
326 -- is only used for offsets from the GOT to symbol pointers inside the
327 -- GOT.
328 picRelative lbl
329   = CmmLabelDiffOff lbl gotLabel 0
330
331 #elif linux_TARGET_OS || (darwin_TARGET_OS && x86_64_TARGET_ARCH)
332 -- Most Linux versions:
333 -- The PIC base register points to the GOT. Use foo@got for symbol
334 -- pointers, and foo@gotoff for everything else.
335 -- Linux and Darwin on x86_64:
336 -- The PIC base register is %rip, we use foo@gotpcrel for symbol pointers,
337 -- and a GotSymbolOffset label for other things.
338 -- For reasons of tradition, the symbol offset label is written as a plain label.
339
340 picRelative lbl
341   | Just (SymbolPtr, lbl') <- dynamicLinkerLabelInfo lbl
342   = CmmLabel $ mkDynamicLinkerLabel GotSymbolPtr lbl'
343   | otherwise
344   = CmmLabel $ mkDynamicLinkerLabel GotSymbolOffset lbl
345
346 #else
347 picRelative lbl = panic "PositionIndependentCode.picRelative"
348 #endif
349
350 -- -------------------------------------------------------------------
351
352 -- What do we have to add to every assembly file we generate?
353
354 -- utility function for pretty-printing asm-labels,
355 -- copied from PprMach
356 asmSDoc d = Outputable.withPprStyleDoc (
357               Outputable.mkCodeStyle Outputable.AsmStyle) d
358 pprCLabel_asm l = asmSDoc (pprCLabel l)
359
360
361 #if darwin_TARGET_OS && !x86_64_TARGET_ARCH
362
363 needImportedSymbols = True
364
365 -- We don't need to declare any offset tables.
366 -- However, for PIC on x86, we need a small helper function.
367 #if i386_TARGET_ARCH
368 pprGotDeclaration
369     | opt_PIC
370     = vcat [
371         ptext (sLit ".section __TEXT,__textcoal_nt,coalesced,no_toc"),
372         ptext (sLit ".weak_definition ___i686.get_pc_thunk.ax"),
373         ptext (sLit ".private_extern ___i686.get_pc_thunk.ax"),
374         ptext (sLit "___i686.get_pc_thunk.ax:"),
375             ptext (sLit "\tmovl (%esp), %eax"),
376             ptext (sLit "\tret")
377     ]
378     | otherwise = Pretty.empty
379 #else
380 pprGotDeclaration = Pretty.empty
381 #endif
382
383 -- On Darwin, we have to generate our own stub code for lazy binding..
384 -- For each processor architecture, there are two versions, one for PIC
385 -- and one for non-PIC.
386 --
387 -- Whenever you change something in this assembler output, make sure
388 -- the splitter in driver/split/ghc-split.lprl recognizes the new output
389 pprImportedSymbol importedLbl
390 #if powerpc_TARGET_ARCH
391     | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl
392     = case opt_PIC of
393         False ->
394             vcat [
395                 ptext (sLit ".symbol_stub"),
396                 ptext (sLit "L") <> pprCLabel_asm lbl <> ptext (sLit "$stub:"),
397                     ptext (sLit "\t.indirect_symbol") <+> pprCLabel_asm lbl,
398                     ptext (sLit "\tlis r11,ha16(L") <> pprCLabel_asm lbl
399                         <> ptext (sLit "$lazy_ptr)"),
400                     ptext (sLit "\tlwz r12,lo16(L") <> pprCLabel_asm lbl
401                         <> ptext (sLit "$lazy_ptr)(r11)"),
402                     ptext (sLit "\tmtctr r12"),
403                     ptext (sLit "\taddi r11,r11,lo16(L") <> pprCLabel_asm lbl
404                         <> ptext (sLit "$lazy_ptr)"),
405                     ptext (sLit "\tbctr")
406             ]
407         True ->
408             vcat [
409                 ptext (sLit ".section __TEXT,__picsymbolstub1,")
410                   <> ptext (sLit "symbol_stubs,pure_instructions,32"),
411                 ptext (sLit "\t.align 2"),
412                 ptext (sLit "L") <> pprCLabel_asm lbl <> ptext (sLit "$stub:"),
413                     ptext (sLit "\t.indirect_symbol") <+> pprCLabel_asm lbl,
414                     ptext (sLit "\tmflr r0"),
415                     ptext (sLit "\tbcl 20,31,L0$") <> pprCLabel_asm lbl,
416                 ptext (sLit "L0$") <> pprCLabel_asm lbl <> char ':',
417                     ptext (sLit "\tmflr r11"),
418                     ptext (sLit "\taddis r11,r11,ha16(L") <> pprCLabel_asm lbl
419                         <> ptext (sLit "$lazy_ptr-L0$") <> pprCLabel_asm lbl <> char ')',
420                     ptext (sLit "\tmtlr r0"),
421                     ptext (sLit "\tlwzu r12,lo16(L") <> pprCLabel_asm lbl
422                         <> ptext (sLit "$lazy_ptr-L0$") <> pprCLabel_asm lbl
423                         <> ptext (sLit ")(r11)"),
424                     ptext (sLit "\tmtctr r12"),
425                     ptext (sLit "\tbctr")
426             ]
427     $+$ vcat [
428         ptext (sLit ".lazy_symbol_pointer"),
429         ptext (sLit "L") <> pprCLabel_asm lbl <> ptext (sLit "$lazy_ptr:"),
430             ptext (sLit "\t.indirect_symbol") <+> pprCLabel_asm lbl,
431             ptext (sLit "\t.long dyld_stub_binding_helper")
432     ]
433 #elif i386_TARGET_ARCH
434     | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl
435     = case opt_PIC of
436         False ->
437             vcat [
438                 ptext (sLit ".symbol_stub"),
439                 ptext (sLit "L") <> pprCLabel_asm lbl <> ptext (sLit "$stub:"),
440                     ptext (sLit "\t.indirect_symbol") <+> pprCLabel_asm lbl,
441                     ptext (sLit "\tjmp *L") <> pprCLabel_asm lbl
442                         <> ptext (sLit "$lazy_ptr"),
443                 ptext (sLit "L") <> pprCLabel_asm lbl
444                     <> ptext (sLit "$stub_binder:"),
445                     ptext (sLit "\tpushl $L") <> pprCLabel_asm lbl
446                         <> ptext (sLit "$lazy_ptr"),
447                     ptext (sLit "\tjmp dyld_stub_binding_helper")
448             ]
449         True ->
450             vcat [
451                 ptext (sLit ".section __TEXT,__picsymbolstub2,")
452                     <> ptext (sLit "symbol_stubs,pure_instructions,25"),
453                 ptext (sLit "L") <> pprCLabel_asm lbl <> ptext (sLit "$stub:"),
454                     ptext (sLit "\t.indirect_symbol") <+> pprCLabel_asm lbl,
455                     ptext (sLit "\tcall ___i686.get_pc_thunk.ax"),
456                 ptext (sLit "1:"),
457                     ptext (sLit "\tmovl L") <> pprCLabel_asm lbl
458                         <> ptext (sLit "$lazy_ptr-1b(%eax),%edx"),
459                     ptext (sLit "\tjmp *%edx"),
460                 ptext (sLit "L") <> pprCLabel_asm lbl
461                     <> ptext (sLit "$stub_binder:"),
462                     ptext (sLit "\tlea L") <> pprCLabel_asm lbl
463                         <> ptext (sLit "$lazy_ptr-1b(%eax),%eax"),
464                     ptext (sLit "\tpushl %eax"),
465                     ptext (sLit "\tjmp dyld_stub_binding_helper")
466             ]
467     $+$ vcat [        ptext (sLit ".section __DATA, __la_sym_ptr")
468                     <> (if opt_PIC then int 2 else int 3)
469                     <> ptext (sLit ",lazy_symbol_pointers"),
470         ptext (sLit "L") <> pprCLabel_asm lbl <> ptext (sLit "$lazy_ptr:"),
471             ptext (sLit "\t.indirect_symbol") <+> pprCLabel_asm lbl,
472             ptext (sLit "\t.long L") <> pprCLabel_asm lbl
473                     <> ptext (sLit "$stub_binder")
474     ]
475 #endif
476 -- We also have to declare our symbol pointers ourselves:
477     | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl
478     = vcat [
479         ptext (sLit ".non_lazy_symbol_pointer"),
480         char 'L' <> pprCLabel_asm lbl <> ptext (sLit "$non_lazy_ptr:"),
481             ptext (sLit "\t.indirect_symbol") <+> pprCLabel_asm lbl,
482             ptext (sLit "\t.long\t0")
483     ]
484
485     | otherwise = empty
486
487 #elif linux_TARGET_OS && !powerpc64_TARGET_ARCH
488
489 -- ELF / Linux
490 --
491 -- In theory, we don't need to generate any stubs or symbol pointers
492 -- by hand for Linux.
493 --
494 -- Reality differs from this in two areas.
495 --
496 -- 1) If we just use a dynamically imported symbol directly in a read-only
497 --    section of the main executable (as GCC does), ld generates R_*_COPY
498 --    relocations, which are fundamentally incompatible with reversed info
499 --    tables. Therefore, we need a table of imported addresses in a writable
500 --    section.
501 --    The "official" GOT mechanism (label@got) isn't intended to be used
502 --    in position dependent code, so we have to create our own "fake GOT"
503 --    when not opt_PCI && not opt_Static.
504 --
505 -- 2) PowerPC Linux is just plain broken.
506 --    While it's theoretically possible to use GOT offsets larger
507 --    than 16 bit, the standard crt*.o files don't, which leads to
508 --    linker errors as soon as the GOT size exceeds 16 bit.
509 --    Also, the assembler doesn't support @gotoff labels.
510 --    In order to be able to use a larger GOT, we have to circumvent the
511 --    entire GOT mechanism and do it ourselves (this is also what GCC does).
512
513
514 -- When needImportedSymbols is defined,
515 -- the NCG will keep track of all DynamicLinkerLabels it uses
516 -- and output each of them using pprImportedSymbol.
517 #if powerpc_TARGET_ARCH
518     -- PowerPC Linux: -fPIC or -dynamic
519 needImportedSymbols = opt_PIC || not opt_Static
520 #else
521     -- i386 (and others?): -dynamic but not -fPIC
522 needImportedSymbols = not opt_Static && not opt_PIC
523 #endif
524
525 -- gotLabel
526 -- The label used to refer to our "fake GOT" from
527 -- position-independent code.
528 gotLabel = mkForeignLabel -- HACK: it's not really foreign
529                            (fsLit ".LCTOC1") Nothing False IsData
530
531 -- pprGotDeclaration
532 -- Output whatever needs to be output once per .s file.
533 -- The .LCTOC1 label is defined to point 32768 bytes into the table,
534 -- to make the most of the PPC's 16-bit displacements.
535 -- Only needed for PIC.
536
537 pprGotDeclaration
538     | not opt_PIC = Pretty.empty
539     | otherwise = vcat [
540         ptext (sLit ".section \".got2\",\"aw\""),
541         ptext (sLit ".LCTOC1 = .+32768")
542     ]
543
544 -- We generate one .long/.quad literal for every symbol we import;
545 -- the dynamic linker will relocate those addresses.
546
547 pprImportedSymbol importedLbl
548     | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl
549     = vcat [
550         ptext (sLit ".section \".got2\", \"aw\""),
551         ptext (sLit ".LC_") <> pprCLabel_asm lbl <> char ':',
552         ptext symbolSize <+> pprCLabel_asm lbl
553     ]
554
555 -- PLT code stubs are generated automatically by the dynamic linker.
556     | otherwise = empty
557     where
558       symbolSize = case wordWidth of
559                      W32 -> sLit "\t.long"
560                      W64 -> sLit "\t.quad"
561                      _ -> panic "Unknown wordRep in pprImportedSymbol"
562
563 #else
564
565 -- For all other currently supported platforms, we don't need to do
566 -- anything at all.
567
568 needImportedSymbols = False
569 pprGotDeclaration = Pretty.empty
570 pprImportedSymbol _ = empty
571 #endif
572
573 -- -------------------------------------------------------------------
574
575 -- Generate code to calculate the address that should be put in the
576 -- PIC base register.
577 -- This is called by MachCodeGen for every CmmProc that accessed the
578 -- PIC base register. It adds the appropriate instructions to the
579 -- top of the CmmProc.
580
581 -- It is assumed that the first NatCmmTop in the input list is a Proc
582 -- and the rest are CmmDatas.
583
584 initializePicBase :: Reg -> [NatCmmTop] -> NatM [NatCmmTop]
585
586 #if darwin_TARGET_OS
587
588 -- Darwin is simple: just fetch the address of a local label.
589 -- The FETCHPC pseudo-instruction is expanded to multiple instructions
590 -- during pretty-printing so that we don't have to deal with the
591 -- local label:
592
593 -- PowerPC version:
594 --          bcl 20,31,1f.
595 --      1:  mflr picReg
596
597 -- i386 version:
598 --          call 1f
599 --      1:  popl %picReg
600
601 initializePicBase picReg (CmmProc info lab params (ListGraph blocks) : statics)
602     = return (CmmProc info lab params (ListGraph (b':tail blocks)) : statics)
603     where BasicBlock bID insns = head blocks
604           b' = BasicBlock bID (FETCHPC picReg : insns)
605
606 #elif powerpc_TARGET_ARCH && linux_TARGET_OS
607
608 -- Get a pointer to our own fake GOT, which is defined on a per-module basis.
609 -- This is exactly how GCC does it, and it's quite horrible:
610 -- We first fetch the address of a local label (mkPicBaseLabel).
611 -- Then we add a 16-bit offset to that to get the address of a .long that we
612 -- define in .text space right next to the proc. This .long literal contains
613 -- the (32-bit) offset from our local label to our global offset table
614 -- (.LCTOC1 aka gotOffLabel).
615 initializePicBase picReg
616     (CmmProc info lab params (ListGraph blocks) : statics)
617     = do
618         gotOffLabel <- getNewLabelNat
619         tmp <- getNewRegNat $ intSize wordWidth
620         let 
621             gotOffset = CmmData Text [
622                             CmmDataLabel gotOffLabel,
623                             CmmStaticLit (CmmLabelDiffOff gotLabel
624                                                           mkPicBaseLabel
625                                                           0)
626                         ]
627             offsetToOffset = ImmConstantDiff (ImmCLbl gotOffLabel)
628                                              (ImmCLbl mkPicBaseLabel)
629             BasicBlock bID insns = head blocks
630             b' = BasicBlock bID (FETCHPC picReg
631                                : LD wordSize tmp
632                                     (AddrRegImm picReg offsetToOffset)
633                                : ADD picReg picReg (RIReg tmp)
634                                : insns)
635         return (CmmProc info lab params (ListGraph (b' : tail blocks)) : gotOffset : statics)
636 #elif i386_TARGET_ARCH && linux_TARGET_OS
637
638 -- We cheat a bit here by defining a pseudo-instruction named FETCHGOT
639 -- which pretty-prints as:
640 --              call 1f
641 -- 1:           popl %picReg
642 --              addl __GLOBAL_OFFSET_TABLE__+.-1b, %picReg
643 -- (See PprMach.lhs)
644
645 initializePicBase picReg (CmmProc info lab params (ListGraph blocks) : statics)
646     = return (CmmProc info lab params (ListGraph (b':tail blocks)) : statics)
647     where BasicBlock bID insns = head blocks
648           b' = BasicBlock bID (FETCHGOT picReg : insns)
649
650 #else
651 initializePicBase picReg proc = panic "initializePicBase"
652
653 -- mingw32_TARGET_OS: not needed, won't be called
654 #endif