Add support for parameter attributes to the llvm BE binding
[ghc-hetmet.git] / compiler / llvmGen / Llvm / Types.hs
1 --------------------------------------------------------------------------------
2 -- | The LLVM Type System.
3 --
4
5 module Llvm.Types where
6
7 #include "HsVersions.h"
8 #include "ghcconfig.h"
9
10 import Data.Char
11 import Numeric
12
13 import Constants
14 import FastString
15 import Unique
16
17 -- from NCG
18 import PprBase
19
20 -- -----------------------------------------------------------------------------
21 -- * LLVM Basic Types and Variables
22 --
23
24 -- | A global mutable variable. Maybe defined or external
25 type LMGlobal   = (LlvmVar, Maybe LlvmStatic)
26 -- | A String in LLVM
27 type LMString   = FastString
28
29
30 -- | Llvm Types.
31 data LlvmType
32   = LMInt Int                 -- ^ An integer with a given width in bits.
33   | LMFloat                   -- ^ 32 bit floating point
34   | LMDouble                  -- ^ 64 bit floating point
35   | LMFloat80                 -- ^ 80 bit (x86 only) floating point
36   | LMFloat128                -- ^ 128 bit floating point
37   | LMPointer LlvmType        -- ^ A pointer to a 'LlvmType'
38   | LMArray Int LlvmType      -- ^ An array of 'LlvmType'
39   | LMLabel                   -- ^ A 'LlvmVar' can represent a label (address)
40   | LMVoid                    -- ^ Void type
41   | LMStruct [LlvmType]       -- ^ Structure type
42   | LMAlias LMString LlvmType -- ^ A type alias
43
44   -- | Function type, used to create pointers to functions
45   | LMFunction LlvmFunctionDecl
46   deriving (Eq)
47
48 instance Show LlvmType where
49   show (LMInt size    ) = "i" ++ show size
50   show (LMFloat       ) = "float"
51   show (LMDouble      ) = "double"
52   show (LMFloat80     ) = "x86_fp80"
53   show (LMFloat128    ) = "fp128"
54   show (LMPointer x   ) = show x ++ "*"
55   show (LMArray nr tp ) = "[" ++ show nr ++ " x " ++ show tp ++ "]"
56   show (LMLabel       ) = "label"
57   show (LMVoid        ) = "void"
58   show (LMStruct tys  ) = "{" ++ (commaCat tys) ++ "}"
59
60   show (LMFunction (LlvmFunctionDecl _ _ _ r varg p _))
61     = let varg' = if varg == VarArgs then ", ..." else ""
62           args = (tail.concat) $
63                   map (\(t,a) -> "," ++ show t ++ " " ++ spaceCat a) p
64     in show r ++ " (" ++ args ++ varg' ++ ")"
65
66   show (LMAlias s _   ) = "%" ++ unpackFS s
67
68 -- | An LLVM section defenition. If Nothing then let LLVM decide the section
69 type LMSection = Maybe LMString
70 type LMAlign = Maybe Int
71 type LMConst = Bool -- ^ is a variable constant or not
72
73 -- | Llvm Variables
74 data LlvmVar
75   -- | Variables with a global scope.
76   = LMGlobalVar LMString LlvmType LlvmLinkageType LMSection LMAlign LMConst
77   -- | Variables local to a function or parameters.
78   | LMLocalVar Unique LlvmType
79   -- | Named local variables. Sometimes we need to be able to explicitly name
80   -- variables (e.g for function arguments).
81   | LMNLocalVar LMString LlvmType
82   -- | A constant variable
83   | LMLitVar LlvmLit
84   deriving (Eq)
85
86 instance Show LlvmVar where
87   show (LMLitVar x) = show x
88   show (x         ) = show (getVarType x) ++ " " ++ getName x
89
90
91 -- | Llvm Literal Data.
92 --
93 -- These can be used inline in expressions.
94 data LlvmLit
95   -- | Refers to an integer constant (i64 42).
96   = LMIntLit Integer LlvmType
97   -- | Floating point literal
98   | LMFloatLit Double LlvmType
99   deriving (Eq)
100
101 instance Show LlvmLit where
102   show l = show (getLitType l) ++ " " ++ getLit l
103
104
105 -- | Llvm Static Data.
106 --
107 -- These represent the possible global level variables and constants.
108 data LlvmStatic
109   = LMComment LMString                  -- ^ A comment in a static section
110   | LMStaticLit LlvmLit                 -- ^ A static variant of a literal value
111   | LMUninitType LlvmType               -- ^ For uninitialised data
112   | LMStaticStr LMString LlvmType       -- ^ Defines a static 'LMString'
113   | LMStaticArray [LlvmStatic] LlvmType -- ^ A static array
114   | LMStaticStruc [LlvmStatic] LlvmType -- ^ A static structure type
115   | LMStaticPointer LlvmVar             -- ^ A pointer to other data
116
117   -- static expressions, could split out but leave
118   -- for moment for ease of use. Not many of them.
119
120   | LMBitc LlvmStatic LlvmType         -- ^ Pointer to Pointer conversion
121   | LMPtoI LlvmStatic LlvmType         -- ^ Pointer to Integer conversion
122   | LMAdd LlvmStatic LlvmStatic        -- ^ Constant addition operation
123   | LMSub LlvmStatic LlvmStatic        -- ^ Constant subtraction operation
124
125 instance Show LlvmStatic where
126   show (LMComment       s) = "; " ++ unpackFS s
127   show (LMStaticLit   l  ) = show l
128   show (LMUninitType    t) = show t ++ " undef"
129   show (LMStaticStr   s t) = show t ++ " c\"" ++ unpackFS s ++ "\\00\""
130
131   show (LMStaticArray d t)
132       = let struc = case d of
133               [] -> "[]"
134               ts -> "[" ++ show (head ts) ++
135                       concat (map (\x -> "," ++ show x) (tail ts)) ++ "]"
136         in show t ++ " " ++ struc
137
138   show (LMStaticStruc d t)
139       = let struc = case d of
140               [] -> "{}"
141               ts -> "{" ++ show (head ts) ++
142                       concat (map (\x -> "," ++ show x) (tail ts)) ++ "}"
143         in show t ++ " " ++ struc
144
145   show (LMStaticPointer v) = show v
146
147   show (LMBitc v t)
148       = show t ++ " bitcast (" ++ show v ++ " to " ++ show t ++ ")"
149
150   show (LMPtoI v t)
151       = show t ++ " ptrtoint (" ++ show v ++ " to " ++ show t ++ ")"
152
153   show (LMAdd s1 s2)
154       = let ty1 = getStatType s1
155         in if ty1 == getStatType s2
156                 then show ty1 ++ " add (" ++ show s1 ++ "," ++ show s2 ++ ")"
157                 else error $ "LMAdd with different types! s1: "
158                         ++ show s1 ++ ", s2: " ++ show s2
159   show (LMSub s1 s2)
160       = let ty1 = getStatType s1
161         in if ty1 == getStatType s2
162                 then show ty1 ++ " sub (" ++ show s1 ++ "," ++ show s2 ++ ")"
163                 else error $ "LMSub with different types! s1: "
164                         ++ show s1 ++ ", s2: " ++ show s2
165
166
167 -- | Concatenate an array together, separated by commas
168 commaCat :: Show a => [a] -> String
169 commaCat [] = ""
170 commaCat x  = show (head x) ++ (concat $ map (\y -> "," ++ show y) (tail x))
171
172 -- | Concatenate an array together, separated by commas
173 spaceCat :: Show a => [a] -> String
174 spaceCat [] = ""
175 spaceCat x  = show (head x) ++ (concat $ map (\y -> " " ++ show y) (tail x))
176
177 -- -----------------------------------------------------------------------------
178 -- ** Operations on LLVM Basic Types and Variables
179 --
180
181 -- | Return the variable name or value of the 'LlvmVar'
182 -- in Llvm IR textual representation (e.g. @\@x@, @%y@ or @42@).
183 getName :: LlvmVar -> String
184 getName v@(LMGlobalVar _ _ _ _ _ _) = "@" ++ getPlainName v
185 getName v@(LMLocalVar  _ _        ) = "%" ++ getPlainName v
186 getName v@(LMNLocalVar _ _        ) = "%" ++ getPlainName v
187 getName v@(LMLitVar    _          ) = getPlainName v
188
189 -- | Return the variable name or value of the 'LlvmVar'
190 -- in a plain textual representation (e.g. @x@, @y@ or @42@).
191 getPlainName :: LlvmVar -> String
192 getPlainName (LMGlobalVar x _ _ _ _ _) = unpackFS x
193 getPlainName (LMLocalVar  x _        ) = show x
194 getPlainName (LMNLocalVar x _        ) = unpackFS x
195 getPlainName (LMLitVar    x          ) = getLit x
196
197 -- | Print a literal value. No type.
198 getLit :: LlvmLit -> String
199 getLit (LMIntLit   i _) = show ((fromInteger i)::Int)
200 getLit (LMFloatLit r LMFloat ) = fToStr $ realToFrac r
201 getLit (LMFloatLit r LMDouble) = dToStr r
202 getLit f@(LMFloatLit _ _) = error $ "Can't print this float literal!" ++ show f
203
204 -- | Return the 'LlvmType' of the 'LlvmVar'
205 getVarType :: LlvmVar -> LlvmType
206 getVarType (LMGlobalVar _ y _ _ _ _) = y
207 getVarType (LMLocalVar  _ y        ) = y
208 getVarType (LMNLocalVar _ y        ) = y
209 getVarType (LMLitVar    l          ) = getLitType l
210
211 -- | Return the 'LlvmType' of a 'LlvmLit'
212 getLitType :: LlvmLit -> LlvmType
213 getLitType (LMIntLit   _ t) = t
214 getLitType (LMFloatLit _ t) = t
215
216 -- | Return the 'LlvmType' of the 'LlvmStatic'
217 getStatType :: LlvmStatic -> LlvmType
218 getStatType (LMStaticLit   l  ) = getLitType l
219 getStatType (LMUninitType    t) = t
220 getStatType (LMStaticStr   _ t) = t
221 getStatType (LMStaticArray _ t) = t
222 getStatType (LMStaticStruc _ t) = t
223 getStatType (LMStaticPointer v) = getVarType v
224 getStatType (LMBitc        _ t) = t
225 getStatType (LMPtoI        _ t) = t
226 getStatType (LMAdd         t _) = getStatType t
227 getStatType (LMSub         t _) = getStatType t
228 getStatType (LMComment       _) = error "Can't call getStatType on LMComment!"
229
230 -- | Return the 'LlvmType' of the 'LMGlobal'
231 getGlobalType :: LMGlobal -> LlvmType
232 getGlobalType (v, _) = getVarType v
233
234 -- | Return the 'LlvmVar' part of a 'LMGlobal'
235 getGlobalVar :: LMGlobal -> LlvmVar
236 getGlobalVar (v, _) = v
237
238 -- | Return the 'LlvmLinkageType' for a 'LlvmVar'
239 getLink :: LlvmVar -> LlvmLinkageType
240 getLink (LMGlobalVar _ _ l _ _ _) = l
241 getLink _                         = Internal
242
243 -- | Add a pointer indirection to the supplied type. 'LMLabel' and 'LMVoid'
244 -- cannot be lifted.
245 pLift :: LlvmType -> LlvmType
246 pLift (LMLabel) = error "Labels are unliftable"
247 pLift (LMVoid)  = error "Voids are unliftable"
248 pLift x         = LMPointer x
249
250 -- | Lower a variable of 'LMPointer' type.
251 pVarLift :: LlvmVar -> LlvmVar
252 pVarLift (LMGlobalVar s t l x a c) = LMGlobalVar s (pLift t) l x a c
253 pVarLift (LMLocalVar  s t        ) = LMLocalVar  s (pLift t)
254 pVarLift (LMNLocalVar s t        ) = LMNLocalVar s (pLift t)
255 pVarLift (LMLitVar    _          ) = error $ "Can't lower a literal type!"
256
257 -- | Remove the pointer indirection of the supplied type. Only 'LMPointer'
258 -- constructors can be lowered.
259 pLower :: LlvmType -> LlvmType
260 pLower (LMPointer x) = x
261 pLower x  = error $ show x ++ " is a unlowerable type, need a pointer"
262
263 -- | Lower a variable of 'LMPointer' type.
264 pVarLower :: LlvmVar -> LlvmVar
265 pVarLower (LMGlobalVar s t l x a c) = LMGlobalVar s (pLower t) l x a c
266 pVarLower (LMLocalVar  s t        ) = LMLocalVar  s (pLower t)
267 pVarLower (LMNLocalVar s t        ) = LMNLocalVar s (pLower t)
268 pVarLower (LMLitVar    _          ) = error $ "Can't lower a literal type!"
269
270 -- | Test if the given 'LlvmType' is an integer
271 isInt :: LlvmType -> Bool
272 isInt (LMInt _) = True
273 isInt _         = False
274
275 -- | Test if the given 'LlvmType' is a floating point type
276 isFloat :: LlvmType -> Bool
277 isFloat LMFloat    = True
278 isFloat LMDouble   = True
279 isFloat LMFloat80  = True
280 isFloat LMFloat128 = True
281 isFloat _          = False
282
283 -- | Test if the given 'LlvmType' is an 'LMPointer' construct
284 isPointer :: LlvmType -> Bool
285 isPointer (LMPointer _) = True
286 isPointer _             = False
287
288 -- | Test if a 'LlvmVar' is global.
289 isGlobal :: LlvmVar -> Bool
290 isGlobal (LMGlobalVar _ _ _ _ _ _) = True
291 isGlobal _                         = False
292
293 -- | Width in bits of an 'LlvmType', returns 0 if not applicable
294 llvmWidthInBits :: LlvmType -> Int
295 llvmWidthInBits (LMInt n)       = n
296 llvmWidthInBits (LMFloat)       = 32
297 llvmWidthInBits (LMDouble)      = 64
298 llvmWidthInBits (LMFloat80)     = 80
299 llvmWidthInBits (LMFloat128)    = 128
300 -- Could return either a pointer width here or the width of what
301 -- it points to. We will go with the former for now.
302 llvmWidthInBits (LMPointer _)   = llvmWidthInBits llvmWord
303 llvmWidthInBits (LMArray _ _)   = llvmWidthInBits llvmWord
304 llvmWidthInBits LMLabel         = 0
305 llvmWidthInBits LMVoid          = 0
306 llvmWidthInBits (LMStruct tys)  = sum $ map llvmWidthInBits tys
307 llvmWidthInBits (LMFunction  _) = 0
308 llvmWidthInBits (LMAlias _ t)   = llvmWidthInBits t
309
310
311 -- -----------------------------------------------------------------------------
312 -- ** Shortcut for Common Types
313 --
314
315 i128, i64, i32, i16, i8, i1, i8Ptr :: LlvmType
316 i128  = LMInt 128
317 i64   = LMInt  64
318 i32   = LMInt  32
319 i16   = LMInt  16
320 i8    = LMInt   8
321 i1    = LMInt   1
322 i8Ptr = pLift i8
323
324 -- | The target architectures word size
325 llvmWord, llvmWordPtr :: LlvmType
326 llvmWord    = LMInt (wORD_SIZE * 8)
327 llvmWordPtr = pLift llvmWord
328
329 -- -----------------------------------------------------------------------------
330 -- * LLVM Function Types
331 --
332
333 -- | An LLVM Function
334 data LlvmFunctionDecl = LlvmFunctionDecl {
335         -- | Unique identifier of the function
336         decName       :: LMString,
337         -- | LinkageType of the function
338         funcLinkage   :: LlvmLinkageType,
339         -- | The calling convention of the function
340         funcCc        :: LlvmCallConvention,
341         -- | Type of the returned value
342         decReturnType :: LlvmType,
343         -- | Indicates if this function uses varargs
344         decVarargs    :: LlvmParameterListType,
345         -- | Parameter types and attributes
346         decParams     :: [LlvmParameter],
347         -- | Function align value, must be power of 2
348         funcAlign     :: LMAlign
349   }
350   deriving (Eq)
351
352 instance Show LlvmFunctionDecl where
353   show (LlvmFunctionDecl n l c r varg p a)
354     = let varg' = if varg == VarArgs then ", ..." else ""
355           align = case a of
356                        Just a' -> " align " ++ show a'
357                        Nothing -> ""
358           args = (tail.concat) $
359                   map (\(t,a) -> "," ++ show t ++ " " ++ spaceCat a) p
360     in show l ++ " " ++ show c ++ " " ++ show r ++ " @" ++ unpackFS n ++
361         "(" ++ args ++ varg' ++ ")" ++ align
362
363 type LlvmFunctionDecls = [LlvmFunctionDecl]
364
365 type LlvmParameter = (LlvmType, [LlvmParamAttr])
366
367 -- | LLVM Parameter Attributes.
368 --
369 -- Parameter attributes are used to communicate additional information about
370 -- the result or parameters of a function
371 data LlvmParamAttr
372   -- | This indicates to the code generator that the parameter or return value
373   -- should be zero-extended to a 32-bit value by the caller (for a parameter)
374   -- or the callee (for a return value).
375   = ZeroExt
376   -- | This indicates to the code generator that the parameter or return value
377   -- should be sign-extended to a 32-bit value by the caller (for a parameter)
378   -- or the callee (for a return value).
379   | SignExt
380   -- | This indicates that this parameter or return value should be treated in
381   -- a special target-dependent fashion during while emitting code for a
382   -- function call or return (usually, by putting it in a register as opposed
383   -- to memory).
384   | InReg
385   -- | This indicates that the pointer parameter should really be passed by
386   -- value to the function.
387   | ByVal
388   -- | This indicates that the pointer parameter specifies the address of a
389   -- structure that is the return value of the function in the source program.
390   | SRet
391   -- | This indicates that the pointer does not alias any global or any other
392   -- parameter.
393   | NoAlias
394   -- | This indicates that the callee does not make any copies of the pointer
395   -- that outlive the callee itself
396   | NoCapture
397   -- | This indicates that the pointer parameter can be excised using the
398   -- trampoline intrinsics.
399   | Nest
400   deriving (Eq)
401
402 instance Show LlvmParamAttr where
403   show ZeroExt   = "zeroext"
404   show SignExt   = "signext"
405   show InReg     = "inreg"
406   show ByVal     = "byval"
407   show SRet      = "sret"
408   show NoAlias   = "noalias"
409   show NoCapture = "nocapture"
410   show Nest      = "nest"
411
412 -- | Llvm Function Attributes.
413 --
414 -- Function attributes are set to communicate additional information about a
415 -- function. Function attributes are considered to be part of the function,
416 -- not of the function type, so functions with different parameter attributes
417 -- can have the same function type. Functions can have multiple attributes.
418 --
419 -- Descriptions taken from <http://llvm.org/docs/LangRef.html#fnattrs>
420 data LlvmFuncAttr
421   -- | This attribute indicates that the inliner should attempt to inline this
422   -- function into callers whenever possible, ignoring any active inlining
423   -- size threshold for this caller.
424   = AlwaysInline
425   -- | This attribute indicates that the source code contained a hint that
426   -- inlining this function is desirable (such as the \"inline\" keyword in
427   -- C/C++). It is just a hint; it imposes no requirements on the inliner.
428   | InlineHint
429   -- | This attribute indicates that the inliner should never inline this
430   -- function in any situation. This attribute may not be used together
431   -- with the alwaysinline attribute.
432   | NoInline
433   -- | This attribute suggests that optimization passes and code generator
434   -- passes make choices that keep the code size of this function low, and
435   -- otherwise do optimizations specifically to reduce code size.
436   | OptSize
437   -- | This function attribute indicates that the function never returns
438   -- normally. This produces undefined behavior at runtime if the function
439   -- ever does dynamically return.
440   | NoReturn
441   -- | This function attribute indicates that the function never returns with
442   -- an unwind or exceptional control flow. If the function does unwind, its
443   -- runtime behavior is undefined.
444   | NoUnwind
445   -- | This attribute indicates that the function computes its result (or
446   -- decides to unwind an exception) based strictly on its arguments, without
447   -- dereferencing any pointer arguments or otherwise accessing any mutable
448   -- state (e.g. memory, control registers, etc) visible to caller functions.
449   -- It does not write through any pointer arguments (including byval
450   -- arguments) and never changes any state visible to callers. This means
451   -- that it cannot unwind exceptions by calling the C++ exception throwing
452   -- methods, but could use the unwind instruction.
453   | ReadNone
454   -- | This attribute indicates that the function does not write through any
455   -- pointer arguments (including byval arguments) or otherwise modify any
456   -- state (e.g. memory, control registers, etc) visible to caller functions.
457   -- It may dereference pointer arguments and read state that may be set in
458   -- the caller. A readonly function always returns the same value (or unwinds
459   -- an exception identically) when called with the same set of arguments and
460   -- global state. It cannot unwind an exception by calling the C++ exception
461   -- throwing methods, but may use the unwind instruction.
462   | ReadOnly
463   -- | This attribute indicates that the function should emit a stack smashing
464   -- protector. It is in the form of a \"canary\"—a random value placed on the
465   -- stack before the local variables that's checked upon return from the
466   -- function to see if it has been overwritten. A heuristic is used to
467   -- determine if a function needs stack protectors or not.
468   --
469   -- If a function that has an ssp attribute is inlined into a function that
470   -- doesn't have an ssp attribute, then the resulting function will have an
471   -- ssp attribute.
472   | Ssp
473   -- | This attribute indicates that the function should always emit a stack
474   -- smashing protector. This overrides the ssp function attribute.
475   --
476   -- If a function that has an sspreq attribute is inlined into a function
477   -- that doesn't have an sspreq attribute or which has an ssp attribute,
478   -- then the resulting function will have an sspreq attribute.
479   | SspReq
480   -- | This attribute indicates that the code generator should not use a red
481   -- zone, even if the target-specific ABI normally permits it.
482   | NoRedZone
483   -- | This attributes disables implicit floating point instructions.
484   | NoImplicitFloat
485   -- | This attribute disables prologue / epilogue emission for the function.
486   -- This can have very system-specific consequences.
487   | Naked
488   deriving (Eq)
489
490 instance Show LlvmFuncAttr where
491   show AlwaysInline       = "alwaysinline"
492   show InlineHint         = "inlinehint"
493   show NoInline           = "noinline"
494   show OptSize            = "optsize"
495   show NoReturn           = "noreturn"
496   show NoUnwind           = "nounwind"
497   show ReadNone           = "readnon"
498   show ReadOnly           = "readonly"
499   show Ssp                = "ssp"
500   show SspReq             = "ssqreq"
501   show NoRedZone          = "noredzone"
502   show NoImplicitFloat    = "noimplicitfloat"
503   show Naked              = "naked"
504
505
506 -- | Different types to call a function.
507 data LlvmCallType
508   -- | Normal call, allocate a new stack frame.
509   = StdCall
510   -- | Tail call, perform the call in the current stack frame.
511   | TailCall
512   deriving (Eq,Show)
513
514 -- | Different calling conventions a function can use.
515 data LlvmCallConvention
516   -- | The C calling convention.
517   -- This calling convention (the default if no other calling convention is
518   -- specified) matches the target C calling conventions. This calling
519   -- convention supports varargs function calls and tolerates some mismatch in
520   -- the declared prototype and implemented declaration of the function (as
521   -- does normal C).
522   = CC_Ccc
523   -- | This calling convention attempts to make calls as fast as possible
524   -- (e.g. by passing things in registers). This calling convention allows
525   -- the target to use whatever tricks it wants to produce fast code for the
526   -- target, without having to conform to an externally specified ABI
527   -- (Application Binary Interface). Implementations of this convention should
528   -- allow arbitrary tail call optimization to be supported. This calling
529   -- convention does not support varargs and requires the prototype of al
530   -- callees to exactly match the prototype of the function definition.
531   | CC_Fastcc
532   -- | This calling convention attempts to make code in the caller as efficient
533   -- as possible under the assumption that the call is not commonly executed.
534   -- As such, these calls often preserve all registers so that the call does
535   -- not break any live ranges in the caller side. This calling convention
536   -- does not support varargs and requires the prototype of all callees to
537   -- exactly match the prototype of the function definition.
538   | CC_Coldcc
539   -- | Any calling convention may be specified by number, allowing
540   -- target-specific calling conventions to be used. Target specific calling
541   -- conventions start at 64.
542   | CC_Ncc Int
543   -- | X86 Specific 'StdCall' convention. LLVM includes a specific alias for it
544   -- rather than just using CC_Ncc.
545   | CC_X86_Stdcc
546   deriving (Eq)
547
548 instance Show LlvmCallConvention where
549   show CC_Ccc       = "ccc"
550   show CC_Fastcc    = "fastcc"
551   show CC_Coldcc    = "coldcc"
552   show (CC_Ncc i)   = "cc " ++ show i
553   show CC_X86_Stdcc = "x86_stdcallcc"
554
555
556 -- | Functions can have a fixed amount of parameters, or a variable amount.
557 data LlvmParameterListType
558   -- Fixed amount of arguments.
559   = FixedArgs
560   -- Variable amount of arguments.
561   | VarArgs
562   deriving (Eq,Show)
563
564
565 -- | Linkage type of a symbol.
566 --
567 -- The description of the constructors is copied from the Llvm Assembly Language
568 -- Reference Manual <http://www.llvm.org/docs/LangRef.html#linkage>, because
569 -- they correspond to the Llvm linkage types.
570 data LlvmLinkageType
571   -- | Global values with internal linkage are only directly accessible by
572   -- objects in the current module. In particular, linking code into a module
573   -- with an internal global value may cause the internal to be renamed as
574   -- necessary to avoid collisions. Because the symbol is internal to the
575   -- module, all references can be updated. This corresponds to the notion
576   -- of the @static@ keyword in C.
577   = Internal
578   -- | Globals with @linkonce@ linkage are merged with other globals of the
579   -- same name when linkage occurs. This is typically used to implement
580   -- inline functions, templates, or other code which must be generated
581   -- in each translation unit that uses it. Unreferenced linkonce globals are
582   -- allowed to be discarded.
583   | LinkOnce
584   -- | @weak@ linkage is exactly the same as linkonce linkage, except that
585   -- unreferenced weak globals may not be discarded. This is used for globals
586   -- that may be emitted in multiple translation units, but that are not
587   -- guaranteed to be emitted into every translation unit that uses them. One
588   -- example of this are common globals in C, such as @int X;@ at global
589   -- scope.
590   | Weak
591   -- | @appending@ linkage may only be applied to global variables of pointer
592   -- to array type. When two global variables with appending linkage are
593   -- linked together, the two global arrays are appended together. This is
594   -- the Llvm, typesafe, equivalent of having the system linker append
595   -- together @sections@ with identical names when .o files are linked.
596   | Appending
597   -- | The semantics of this linkage follow the ELF model: the symbol is weak
598   -- until linked, if not linked, the symbol becomes null instead of being an
599   -- undefined reference.
600   | ExternWeak
601   -- | The symbol participates in linkage and can be used to resolve external
602   --  symbol references.
603   | ExternallyVisible
604   -- | Alias for 'ExternallyVisible' but with explicit textual form in LLVM
605   --  assembly.
606   | External
607   deriving (Eq)
608
609 instance Show LlvmLinkageType where
610   show Internal          = "internal"
611   show LinkOnce          = "linkonce"
612   show Weak              = "weak"
613   show Appending         = "appending"
614   show ExternWeak        = "extern_weak"
615   -- ExternallyVisible does not have a textual representation, it is
616   -- the linkage type a function resolves to if no other is specified
617   -- in Llvm.
618   show ExternallyVisible = ""
619   show External          = "external"
620
621
622 -- -----------------------------------------------------------------------------
623 -- * LLVM Operations
624 --
625
626 -- | Llvm binary operators machine operations.
627 data LlvmMachOp
628   = LM_MO_Add  -- ^ add two integer, floating point or vector values.
629   | LM_MO_Sub  -- ^ subtract two ...
630   | LM_MO_Mul  -- ^ multiply ..
631   | LM_MO_UDiv -- ^ unsigned integer or vector division.
632   | LM_MO_SDiv -- ^ signed integer ..
633   | LM_MO_FDiv -- ^ floating point ..
634   | LM_MO_URem -- ^ unsigned integer or vector remainder (mod)
635   | LM_MO_SRem -- ^ signed ...
636   | LM_MO_FRem -- ^ floating point ...
637
638   -- | Left shift
639   | LM_MO_Shl
640   -- | Logical shift right
641   -- Shift right, filling with zero
642   | LM_MO_LShr
643   -- | Arithmetic shift right
644   -- The most significant bits of the result will be equal to the sign bit of
645   -- the left operand.
646   | LM_MO_AShr
647
648   | LM_MO_And -- ^ AND bitwise logical operation.
649   | LM_MO_Or  -- ^ OR bitwise logical operation.
650   | LM_MO_Xor -- ^ XOR bitwise logical operation.
651   deriving (Eq)
652
653 instance Show LlvmMachOp where
654   show LM_MO_Add  = "add"
655   show LM_MO_Sub  = "sub"
656   show LM_MO_Mul  = "mul"
657   show LM_MO_UDiv = "udiv"
658   show LM_MO_SDiv = "sdiv"
659   show LM_MO_FDiv = "fdiv"
660   show LM_MO_URem = "urem"
661   show LM_MO_SRem = "srem"
662   show LM_MO_FRem = "frem"
663   show LM_MO_Shl  = "shl"
664   show LM_MO_LShr = "lshr"
665   show LM_MO_AShr = "ashr"
666   show LM_MO_And  = "and"
667   show LM_MO_Or   = "or"
668   show LM_MO_Xor  = "xor"
669
670
671 -- | Llvm compare operations.
672 data LlvmCmpOp
673   = LM_CMP_Eq  -- ^ Equal (Signed and Unsigned)
674   | LM_CMP_Ne  -- ^ Not equal (Signed and Unsigned)
675   | LM_CMP_Ugt -- ^ Unsigned greater than
676   | LM_CMP_Uge -- ^ Unsigned greater than or equal
677   | LM_CMP_Ult -- ^ Unsigned less than
678   | LM_CMP_Ule -- ^ Unsigned less than or equal
679   | LM_CMP_Sgt -- ^ Signed greater than
680   | LM_CMP_Sge -- ^ Signed greater than or equal
681   | LM_CMP_Slt -- ^ Signed less than
682   | LM_CMP_Sle -- ^ Signed less than or equal
683
684   -- Float comparisons. GHC uses a mix of ordered and unordered float
685   -- comparisons.
686   | LM_CMP_Feq -- ^ Float equal
687   | LM_CMP_Fne -- ^ Float not equal
688   | LM_CMP_Fgt -- ^ Float greater than
689   | LM_CMP_Fge -- ^ Float greater than or equal
690   | LM_CMP_Flt -- ^ Float less than
691   | LM_CMP_Fle -- ^ Float less than or equal
692   deriving (Eq)
693
694 instance Show LlvmCmpOp where
695   show LM_CMP_Eq  = "eq"
696   show LM_CMP_Ne  = "ne"
697   show LM_CMP_Ugt = "ugt"
698   show LM_CMP_Uge = "uge"
699   show LM_CMP_Ult = "ult"
700   show LM_CMP_Ule = "ule"
701   show LM_CMP_Sgt = "sgt"
702   show LM_CMP_Sge = "sge"
703   show LM_CMP_Slt = "slt"
704   show LM_CMP_Sle = "sle"
705   show LM_CMP_Feq = "oeq"
706   show LM_CMP_Fne = "une"
707   show LM_CMP_Fgt = "ogt"
708   show LM_CMP_Fge = "oge"
709   show LM_CMP_Flt = "olt"
710   show LM_CMP_Fle = "ole"
711
712
713 -- | Llvm cast operations.
714 data LlvmCastOp
715   = LM_Trunc    -- ^ Integer truncate
716   | LM_Zext     -- ^ Integer extend (zero fill)
717   | LM_Sext     -- ^ Integer extend (sign fill)
718   | LM_Fptrunc  -- ^ Float truncate
719   | LM_Fpext    -- ^ Float extend
720   | LM_Fptoui   -- ^ Float to unsigned Integer
721   | LM_Fptosi   -- ^ Float to signed Integer
722   | LM_Uitofp   -- ^ Unsigned Integer to Float
723   | LM_Sitofp   -- ^ Signed Int to Float
724   | LM_Ptrtoint -- ^ Pointer to Integer
725   | LM_Inttoptr -- ^ Integer to Pointer
726   | LM_Bitcast  -- ^ Cast between types where no bit manipulation is needed
727   deriving (Eq)
728
729 instance Show LlvmCastOp where
730   show LM_Trunc    = "trunc"
731   show LM_Zext     = "zext"
732   show LM_Sext     = "sext"
733   show LM_Fptrunc  = "fptrunc"
734   show LM_Fpext    = "fpext"
735   show LM_Fptoui   = "fptoui"
736   show LM_Fptosi   = "fptosi"
737   show LM_Uitofp   = "uitofp"
738   show LM_Sitofp   = "sitofp"
739   show LM_Ptrtoint = "ptrtoint"
740   show LM_Inttoptr = "inttoptr"
741   show LM_Bitcast  = "bitcast"
742
743
744 -- -----------------------------------------------------------------------------
745 -- * Floating point conversion
746 --
747
748 -- | Convert a Haskell Double to an LLVM hex encoded floating point form. In
749 -- Llvm float literals can be printed in a big-endian hexadecimal format,
750 -- regardless of underlying architecture.
751 dToStr :: Double -> String
752 dToStr d
753   = let bs     = doubleToBytes d
754         hex d' = case showHex d' "" of
755                      []    -> error "dToStr: too few hex digits for float"
756                      [x]   -> ['0',x]
757                      [x,y] -> [x,y]
758                      _     -> error "dToStr: too many hex digits for float"
759
760         str  = map toUpper $ concat . fixEndian . (map hex) $ bs
761     in  "0x" ++ str
762
763 -- | Convert a Haskell Float to an LLVM hex encoded floating point form.
764 -- LLVM uses the same encoding for both floats and doubles (16 digit hex
765 -- string) but floats must have the last half all zeroes so it can fit into
766 -- a float size type.
767 {-# NOINLINE fToStr #-}
768 fToStr :: Float -> String
769 fToStr = (dToStr . realToFrac)
770
771 -- | Reverse or leave byte data alone to fix endianness on this target.
772 fixEndian :: [a] -> [a]
773 #ifdef WORDS_BIGENDIAN
774 fixEndian = id
775 #else
776 fixEndian = reverse
777 #endif
778