如何通过getElementPtr获取struct中的数据指针? (在llvm包中)

时间:2012-04-27 22:30:28

标签: haskell llvm

我正在尝试通过ghc 7.4.1上的llvm-3.0.0.0包在llvm中创建一个struct和access元素,并且遇到了一些毛茸茸的类型。这是一个示例代码,我正在尝试获取结构的第二个元素(即TestStruct中的Word32

{-# LANGUAGE TypeOperators #-}
import LLVM.Core
import Data.Word

type TestStruct = Struct (Word16 :& Word32 :& Word64)
getTestPtr :: Value (Ptr TestStruct) -> CodeGenFunction r (Value (Ptr Word32))
getTestPtr u = getElementPtr u (0 :: Word32, (1  :: Word32, ()))

但是我在ghc 7.4.1上遇到以下错误:

Test.hs:8:16:
    Overlapping instances for llvm-3.0.0.0:LLVM.Core.Instructions.GetField
                                (Word32, Word64) i Word32
      arising from a use of `getElementPtr'
    Matching instances:
      instance [overlap ok] (llvm-3.0.0.0:LLVM.Core.Instructions.GetField
                               as i b,
                             Succ i i') =>
                            llvm-3.0.0.0:LLVM.Core.Instructions.GetField (a, as) i' b
        -- Defined in `llvm-3.0.0.0:LLVM.Core.Instructions'
      instance [overlap ok] llvm-3.0.0.0:LLVM.Core.Instructions.GetField
                              (a, as) D0 a
        -- Defined in `llvm-3.0.0.0:LLVM.Core.Instructions'
    (The choice depends on the instantiation of `i'
     To pick the first instance above, use -XIncoherentInstances
     when compiling the other instance declarations)
    In the expression: getElementPtr u (0 :: Word32, (0 :: Word32, ()))
    In an equation for `getTestPtr':
        getTestPtr u = getElementPtr u (0 :: Word32, (0 :: Word32, ()))

Test.hs:8:16:
    No instances for (Data.TypeLevel.Num.Sets.PosI Word32,
                      Data.TypeLevel.Num.Ops.IsZero Word32 yz,
                      DivMod10 Word32 yi yl)
      arising from a use of `getElementPtr'
    Possible fix:
      add instance declarations for
      (Data.TypeLevel.Num.Sets.PosI Word32,
       Data.TypeLevel.Num.Ops.IsZero Word32 yz,
       DivMod10 Word32 yi yl)
    In the expression: getElementPtr u (0 :: Word32, (0 :: Word32, ()))
    In an equation for `getTestPtr':
        getTestPtr u = getElementPtr u (0 :: Word32, (0 :: Word32, ()))

1 个答案:

答案 0 :(得分:1)

索引到Struct包中的llvm需要类型级别编号,以便可以静态计算字段类型。这就是描述记录字段的嵌套元组的原因。如果您使用getElementPtr,则第一个索引值必须是常规整数(Word32或其他),或者只使用getElementPtr0

{-# LANGUAGE TypeOperators #-}
import LLVM.Core
import Data.TypeLevel
import Data.Word

type TestStruct = Struct (Word16 :& Word32 :& Word64)
getTestPtr :: Value (Ptr TestStruct) -> CodeGenFunction r (Value (Ptr Word32))
-- getTestPtr u = getElementPtr u ((0 :: Word32) & d1 & ())
getTestPtr u = getElementPtr0 u (d1 & ())