-
Notifications
You must be signed in to change notification settings - Fork 43
/
Instruction.hs
1629 lines (1416 loc) · 65.8 KB
/
Instruction.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-----------------------------------------------------------------------
-- |
-- Module : Lang.Crucible.LLVM.Translation.Instruction
-- Description : Translation of LLVM instructions
-- Copyright : (c) Galois, Inc 2018
-- License : BSD3
-- Maintainer : Rob Dockins <rdockins@galois.com>
-- Stability : provisional
--
-- This module represents the workhorse of the LLVM translation. It
-- is responsable for interpreting the LLVM instruction set into
-- corresponding crucible statements.
-----------------------------------------------------------------------
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
module Lang.Crucible.LLVM.Translation.Instruction
( instrResultType
, generateInstr
, definePhiBlock
, assignLLVMReg
) where
import Control.Monad.Except
import Control.Monad.State.Strict
import Control.Monad.Trans.Maybe
import Control.Lens hiding (op, (:>) )
import Data.Foldable (toList)
import Data.Int
import qualified Data.List as List
import Data.Maybe
import qualified Data.Map.Strict as Map
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.String
import qualified Data.Vector as V
import qualified Data.Text as Text
import Numeric.Natural
import qualified Text.LLVM.AST as L
import qualified Data.Parameterized.Context as Ctx
import Data.Parameterized.Context ( pattern (:>) )
import Data.Parameterized.NatRepr as NatRepr
import Data.Parameterized.Some
import Text.PrettyPrint.ANSI.Leijen (pretty)
import Lang.Crucible.CFG.Expr
import Lang.Crucible.CFG.Generator
import Lang.Crucible.LLVM.DataLayout
import Lang.Crucible.LLVM.Extension
import Lang.Crucible.LLVM.MemType
import qualified Lang.Crucible.LLVM.Bytes as G
import Lang.Crucible.LLVM.MemModel
import Lang.Crucible.LLVM.Translation.Constant
import Lang.Crucible.LLVM.Translation.Expr
import Lang.Crucible.LLVM.Translation.Monad
import Lang.Crucible.LLVM.Translation.Types
import Lang.Crucible.LLVM.TypeContext
import Lang.Crucible.Syntax
import Lang.Crucible.Types
-- | Get the return type of an LLVM instruction
-- See <https://llvm.org/docs/LangRef.html#instruction-reference the language reference>.
instrResultType ::
(?lc :: TypeContext, MonadError String m, HasPtrWidth wptr) =>
L.Instr ->
m MemType
instrResultType instr =
case instr of
L.Arith _ x _ -> liftMemType (L.typedType x)
L.Bit _ x _ -> liftMemType (L.typedType x)
L.Conv _ _ ty -> liftMemType ty
L.Call _ (L.PtrTo (L.FunTy ty _ _)) _ _ -> liftMemType ty
L.Call _ ty _ _ -> fail $ unwords ["unexpected function type in call:", show ty]
L.Invoke (L.FunTy ty _ _) _ _ _ _ -> liftMemType ty
L.Invoke ty _ _ _ _ -> fail $ unwords ["unexpected function type in invoke:", show ty]
L.Alloca ty _ _ -> liftMemType (L.PtrTo ty)
L.Load x _ _ -> case L.typedType x of
L.PtrTo ty -> liftMemType ty
_ -> fail $ unwords ["load through non-pointer type", show (L.typedType x)]
L.ICmp _ _ _ -> liftMemType (L.PrimType (L.Integer 1))
L.FCmp _ _ _ -> liftMemType (L.PrimType (L.Integer 1))
L.Phi tp _ -> liftMemType tp
L.GEP inbounds base elts ->
do gepRes <- runExceptT (translateGEP inbounds base elts)
case gepRes of
Left err -> fail err
Right (GEPResult lanes tp _gep) ->
let n = fromInteger (natValue lanes) in
if n == 1 then
return (PtrType (MemType tp))
else
return (VecType n (PtrType (MemType tp)))
L.Select _ x _ -> liftMemType (L.typedType x)
L.ExtractValue x idxes -> liftMemType (L.typedType x) >>= go idxes
where go [] tp = return tp
go (i:is) (ArrayType n tp')
| i < fromIntegral n = go is tp'
| otherwise = fail $ unwords ["invalid index into array type", showInstr instr]
go (i:is) (StructType si) =
case siFields si V.!? (fromIntegral i) of
Just fi -> go is (fiType fi)
Nothing -> error $ unwords ["invalid index into struct type", showInstr instr]
go _ _ = fail $ unwords ["invalid type in extract value instruction", showInstr instr]
L.InsertValue x _ _ -> liftMemType (L.typedType x)
L.ExtractElt x _ ->
do tp <- liftMemType (L.typedType x)
case tp of
VecType _n tp' -> return tp'
_ -> fail $ unwords ["extract element of non-vector type", showInstr instr]
L.InsertElt x _ _ -> liftMemType (L.typedType x)
L.ShuffleVector x _ i ->
do xtp <- liftMemType (L.typedType x)
itp <- liftMemType (L.typedType i)
case (xtp, itp) of
(VecType _n ty, VecType m _) -> return (VecType m ty)
_ -> fail $ unwords ["invalid shufflevector:", showInstr instr]
L.LandingPad x _ _ _ -> liftMemType x
-- LLVM Language Reference: "The original value at the location is returned."
L.AtomicRW _ _ x _ _ _ -> liftMemType (L.typedType x)
L.CmpXchg _weak _volatile _ptr _old new _ _ _ ->
do let dl = llvmDataLayout ?lc
tp <- liftMemType (L.typedType new)
return (StructType (mkStructInfo dl False [tp, i1]))
_ -> fail $ unwords ["instrResultType, unsupported instruction:", showInstr instr]
liftMemType' :: (?lc::TypeContext, Monad m) => L.Type -> m MemType
liftMemType' = either fail return . liftMemType
-- | Given an LLVM expression of vector type, select out the ith element.
extractElt
:: forall h s arch ret.
L.Instr
-> MemType -- ^ type contained in the vector
-> Integer -- ^ size of the vector
-> LLVMExpr s arch -- ^ vector expression
-> LLVMExpr s arch -- ^ index expression
-> LLVMGenerator h s arch ret (LLVMExpr s arch)
extractElt _instr ty _n (UndefExpr _) _i =
return $ UndefExpr ty
extractElt _instr ty _n (ZeroExpr _) _i =
return $ ZeroExpr ty
extractElt _ ty _ _ (UndefExpr _) =
return $ UndefExpr ty
extractElt instr ty n v (ZeroExpr zty) =
let ?err = fail in
zeroExpand zty $ \tyr ex -> extractElt instr ty n v (BaseExpr tyr ex)
extractElt instr _ n (VecExpr _ vs) i
| Scalar (LLVMPointerRepr _) (BitvectorAsPointerExpr _ x) <- asScalar i
, App (BVLit _ x') <- x
= constantExtract x'
where
constantExtract :: Integer -> LLVMGenerator h s arch ret (LLVMExpr s arch)
constantExtract idx =
if (fromInteger idx < Seq.length vs) && (fromInteger idx < n)
then return $ Seq.index vs (fromInteger idx)
else fail (unlines ["invalid extractelement instruction (index out of bounds)", showInstr instr])
extractElt instr ty n (VecExpr _ vs) i = do
let ?err = fail
llvmTypeAsRepr ty $ \tyr -> unpackVec tyr (toList vs) $
\ex -> extractElt instr ty n (BaseExpr (VectorRepr tyr) ex) i
extractElt instr _ n (BaseExpr (VectorRepr tyr) v) i =
do idx <- case asScalar i of
Scalar (LLVMPointerRepr w) x ->
do bv <- pointerAsBitvectorExpr w x
assertExpr (App (BVUlt w bv (App (BVLit w n)))) "extract element index out of bounds!"
return $ App (BvToNat w bv)
_ ->
fail (unlines ["invalid extractelement instruction", showInstr instr])
return $ BaseExpr tyr (App (VectorGetEntry tyr v idx))
extractElt instr _ _ _ _ = fail (unlines ["invalid extractelement instruction", showInstr instr])
-- | Given an LLVM expression of vector type, insert a new element at location ith element.
insertElt :: forall h s arch ret.
L.Instr -- ^ Actual instruction
-> MemType -- ^ type contained in the vector
-> Integer -- ^ size of the vector
-> LLVMExpr s arch -- ^ vector expression
-> LLVMExpr s arch -- ^ element to insert
-> LLVMExpr s arch -- ^ index expression
-> LLVMGenerator h s arch ret (LLVMExpr s arch)
insertElt _ ty _ _ _ (UndefExpr _) = do
return $ UndefExpr ty
insertElt instr ty n v a (ZeroExpr zty) = do
let ?err = fail
zeroExpand zty $ \tyr ex -> insertElt instr ty n v a (BaseExpr tyr ex)
insertElt instr ty n (UndefExpr _) a i = do
insertElt instr ty n (VecExpr ty (Seq.replicate (fromInteger n) (UndefExpr ty))) a i
insertElt instr ty n (ZeroExpr _) a i = do
insertElt instr ty n (VecExpr ty (Seq.replicate (fromInteger n) (ZeroExpr ty))) a i
insertElt instr _ n (VecExpr ty vs) a i
| Scalar (LLVMPointerRepr _) (BitvectorAsPointerExpr _ x) <- asScalar i
, App (BVLit _ x') <- x
= constantInsert x'
where
constantInsert :: Integer -> LLVMGenerator h s arch ret (LLVMExpr s arch)
constantInsert idx =
if (fromInteger idx < Seq.length vs) && (fromInteger idx < n)
then return $ VecExpr ty $ Seq.adjust (\_ -> a) (fromIntegral idx) vs
else fail (unlines ["invalid insertelement instruction (index out of bounds)", showInstr instr])
insertElt instr ty n (VecExpr _ vs) a i = do
let ?err = fail
llvmTypeAsRepr ty $ \tyr -> unpackVec tyr (toList vs) $
\ex -> insertElt instr ty n (BaseExpr (VectorRepr tyr) ex) a i
insertElt instr _ n (BaseExpr (VectorRepr tyr) v) a i =
do (idx :: Expr (LLVM arch) s NatType)
<- case asScalar i of
Scalar (LLVMPointerRepr w) x ->
do bv <- pointerAsBitvectorExpr w x
assertExpr (App (BVUlt w bv (App (BVLit w n)))) "insert element index out of bounds!"
return $ App (BvToNat w bv)
_ ->
fail (unlines ["invalid insertelement instruction", showInstr instr, show i])
let ?err = fail
unpackOne a $ \tyra a' ->
case testEquality tyr tyra of
Just Refl ->
return $ BaseExpr (VectorRepr tyr) (App (VectorSetEntry tyr v idx a'))
Nothing -> fail (unlines ["type mismatch in insertelement instruction", showInstr instr])
insertElt instr _tp n v a i = fail (unlines ["invalid insertelement instruction", showInstr instr, show n, show v, show a, show i])
-- Given an LLVM expression of vector or structure type, select out the
-- element indicated by the sequence of given concrete indices.
extractValue
:: LLVMExpr s arch -- ^ aggregate expression
-> [Int32] -- ^ sequence of indices
-> LLVMGenerator h s arch ret (LLVMExpr s arch)
extractValue v [] = return v
extractValue (UndefExpr (StructType si)) is =
extractValue (StructExpr $ Seq.fromList $ map (\tp -> (tp, UndefExpr tp)) tps) is
where tps = map fiType $ toList $ siFields si
extractValue (UndefExpr (ArrayType n tp)) is =
extractValue (VecExpr tp $ Seq.replicate (fromIntegral n) (UndefExpr tp)) is
extractValue (ZeroExpr (StructType si)) is =
extractValue (StructExpr $ Seq.fromList $ map (\tp -> (tp, ZeroExpr tp)) tps) is
where tps = map fiType $ toList $ siFields si
extractValue (ZeroExpr (ArrayType n tp)) is =
extractValue (VecExpr tp $ Seq.replicate (fromIntegral n) (ZeroExpr tp)) is
extractValue (BaseExpr (StructRepr ctx) x) (i:is)
| Just (Some idx) <- Ctx.intIndex (fromIntegral i) (Ctx.size ctx) = do
let tpr = ctx Ctx.! idx
extractValue (BaseExpr tpr (getStruct idx x)) is
extractValue (StructExpr vs) (i:is)
| fromIntegral i < Seq.length vs = extractValue (snd $ Seq.index vs $ fromIntegral i) is
extractValue (VecExpr _ vs) (i:is)
| fromIntegral i < Seq.length vs = extractValue (Seq.index vs $ fromIntegral i) is
extractValue _ _ = fail "invalid extractValue instruction"
-- Given an LLVM expression of vector or structure type, insert a new element in the posistion
-- given by the concrete indices.
insertValue
:: LLVMExpr s arch -- ^ aggregate expression
-> LLVMExpr s arch -- ^ element to insert
-> [Int32] -- ^ sequence of concrete indices
-> LLVMGenerator h s arch ret (LLVMExpr s arch)
insertValue _ v [] = return v
insertValue (UndefExpr (StructType si)) v is =
insertValue (StructExpr $ Seq.fromList $ map (\tp -> (tp, UndefExpr tp)) tps) v is
where tps = map fiType $ toList $ siFields si
insertValue (UndefExpr (ArrayType n tp)) v is =
insertValue (VecExpr tp $ Seq.replicate (fromIntegral n) (UndefExpr tp)) v is
insertValue (ZeroExpr (StructType si)) v is =
insertValue (StructExpr $ Seq.fromList $ map (\tp -> (tp, ZeroExpr tp)) tps) v is
where tps = map fiType $ toList $ siFields si
insertValue (ZeroExpr (ArrayType n tp)) v is =
insertValue (VecExpr tp $ Seq.replicate (fromIntegral n) (ZeroExpr tp)) v is
insertValue (BaseExpr (StructRepr ctx) x) v (i:is)
| Just (Some idx) <- Ctx.intIndex (fromIntegral i) (Ctx.size ctx) = do
let tpr = ctx Ctx.! idx
x' <- insertValue (BaseExpr tpr (getStruct idx x)) v is
case x' of
BaseExpr tpr' x''
| Just Refl <- testEquality tpr tpr' ->
return $ BaseExpr (StructRepr ctx) (setStruct ctx x idx x'')
_ -> fail "insertValue was expected to return base value of same type"
insertValue (StructExpr vs) v (i:is)
| fromIntegral i < Seq.length vs = do
let (xtp, x) = Seq.index vs (fromIntegral i)
x' <- insertValue x v is
return (StructExpr (Seq.adjust (\_ -> (xtp,x')) (fromIntegral i) vs))
insertValue (VecExpr tp vs) v (i:is)
| fromIntegral i < Seq.length vs = do
let x = Seq.index vs (fromIntegral i)
x' <- insertValue x v is
return (VecExpr tp (Seq.adjust (\_ -> x') (fromIntegral i) vs))
insertValue _ _ _ = fail "invalid insertValue instruction"
evalGEP :: forall h s arch ret wptr.
wptr ~ ArchWidth arch =>
L.Instr ->
GEPResult (LLVMExpr s arch) ->
LLVMGenerator h s arch ret (LLVMExpr s arch)
evalGEP instr (GEPResult _lanes finalMemType gep0) = finish =<< go gep0
where
finish xs =
case Seq.viewl xs of
x Seq.:< (Seq.null -> True) -> return (BaseExpr PtrRepr x)
_ -> return (VecExpr (PtrType (MemType finalMemType)) (fmap (BaseExpr PtrRepr) xs))
badGEP :: LLVMGenerator h s arch ret a
badGEP = fail $ unlines ["Unexpected failure when evaluating GEP", showInstr instr]
asPtr :: LLVMExpr s arch -> LLVMGenerator h s arch ret (Expr (LLVM arch) s (LLVMPointerType wptr))
asPtr x =
case asScalar x of
Scalar PtrRepr p -> return p
_ -> badGEP
go :: GEP n (LLVMExpr s arch) -> LLVMGenerator h s arch ret (Seq (Expr (LLVM arch) s (LLVMPointerType wptr)))
go (GEP_scalar_base x) =
do p <- asPtr x
return (Seq.singleton p)
go (GEP_vector_base n x) =
do xs <- maybe badGEP (traverse asPtr) (asVector x)
unless (toInteger (Seq.length xs) == natValue n) badGEP
return xs
go (GEP_scatter n gep) =
do xs <- go gep
unless (Seq.length xs == 1) badGEP
return (Seq.cycleTaking (fromInteger (natValue n)) xs)
go (GEP_field fi gep) =
do xs <- go gep
traverse (\x -> calcGEP_struct fi x) xs
go (GEP_index_each mt' gep idx) =
do xs <- go gep
traverse (\x -> calcGEP_array mt' x idx) xs
go (GEP_index_vector mt' gep idx) =
do xs <- go gep
idxs <- maybe badGEP return (asVector idx)
unless (Seq.length idxs == Seq.length xs) badGEP
traverse (\(x,i) -> calcGEP_array mt' x i) (Seq.zip xs idxs)
calcGEP_array :: forall wptr arch h s ret.
wptr ~ ArchWidth arch =>
MemType {- ^ Type of the array elements -} ->
Expr (LLVM arch) s (LLVMPointerType wptr) {- ^ Base pointer -} ->
LLVMExpr s arch {- ^ index value -} ->
LLVMGenerator h s arch ret (Expr (LLVM arch) s (LLVMPointerType wptr))
calcGEP_array typ base idx =
do -- sign-extend the index value if necessary to make it
-- the same width as a pointer
(idx' :: Expr (LLVM arch) s (BVType wptr))
<- case asScalar idx of
Scalar (LLVMPointerRepr w) x
| Just Refl <- testEquality w PtrWidth ->
pointerAsBitvectorExpr PtrWidth x
| Just LeqProof <- testLeq (incNat w) PtrWidth ->
do x' <- pointerAsBitvectorExpr w x
return $ app (BVSext PtrWidth w x')
_ -> fail $ unwords ["Invalid index value in GEP", show idx]
-- Calculate the size of the element memtype and check that it fits
-- in the pointer width
let dl = llvmDataLayout ?lc
let isz = G.bytesToInteger $ memTypeSize dl typ
unless (isz <= maxSigned PtrWidth)
(fail $ unwords ["Type size too large for pointer width:", show typ])
unless (isz == 0) $ do
-- Compute safe upper and lower bounds for the index value to prevent multiplication
-- overflow. Note that `minidx <= idx <= maxidx` iff `MININT <= (isz * idx) <= MAXINT`
-- when `isz` and `idx` are considered as infinite precision integers.
-- This property holds only if we use `quot` (which rounds toward 0) for the
-- divisions in the following definitions.
-- maximum and minimum indices to prevent multiplication overflow
let maxidx = maxSigned PtrWidth `quot` (max isz 1)
let minidx = minSigned PtrWidth `quot` (max isz 1)
-- Assert the necessary range condition
assertExpr ((app $ BVSle PtrWidth (app $ BVLit PtrWidth minidx) idx') .&&
(app $ BVSle PtrWidth idx' (app $ BVLit PtrWidth maxidx)))
(litExpr "Multiplication overflow in getelementpointer")
-- Perform the multiply
let off = app $ BVMul PtrWidth (app $ BVLit PtrWidth isz) idx'
-- Perform the pointer offset arithmetic
callPtrAddOffset base off
calcGEP_struct ::
wptr ~ ArchWidth arch =>
FieldInfo ->
Expr (LLVM arch) s (LLVMPointerType wptr) ->
LLVMGenerator h s arch ret (Expr (LLVM arch) s (LLVMPointerType wptr))
calcGEP_struct fi base =
do -- Get the field offset and check that it fits
-- in the pointer width
let ioff = G.bytesToInteger $ fiOffset fi
unless (ioff <= maxSigned PtrWidth)
(fail $ unwords ["Field offset too large for pointer width in structure:", show ioff])
let off = app $ BVLit PtrWidth $ ioff
-- Perform the pointer arithmetic and continue
callPtrAddOffset base off
translateConversion
:: L.Instr
-> L.ConvOp
-> L.Typed L.Value
-> L.Type
-> LLVMGenerator h s arch ret (LLVMExpr s arch)
translateConversion instr op x outty =
let showI = showInstr instr in
case op of
L.IntToPtr -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (LLVMPointerRepr w) _, LLVMPointerRepr w')
| Just Refl <- testEquality w PtrWidth
, Just Refl <- testEquality w' PtrWidth -> return x'
(Scalar t v, a) ->
fail (unlines ["integer-to-pointer conversion failed: "
, showI
, show v ++ " : " ++ show (pretty t) ++ " -to- " ++ show (pretty a)
])
(NotScalar, _) -> fail (unlines ["integer-to-pointer conversion failed: non scalar", showI])
L.PtrToInt -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (LLVMPointerRepr w) _, LLVMPointerRepr w')
| Just Refl <- testEquality w PtrWidth
, Just Refl <- testEquality w' PtrWidth -> return x'
_ -> fail (unlines ["pointer-to-integer conversion failed", showI])
L.Trunc -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (LLVMPointerRepr w) x'', (LLVMPointerRepr w'))
| Just LeqProof <- isPosNat w'
, Just LeqProof <- testLeq (incNat w') w ->
do x_bv <- pointerAsBitvectorExpr w x''
let bv' = App (BVTrunc w' w x_bv)
return (BaseExpr outty'' (BitvectorAsPointerExpr w' bv'))
_ -> fail (unlines [unwords ["invalid truncation:", show x, show outty], showI])
L.ZExt -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (LLVMPointerRepr w) x'', (LLVMPointerRepr w'))
| Just LeqProof <- isPosNat w
, Just LeqProof <- testLeq (incNat w) w' ->
do x_bv <- pointerAsBitvectorExpr w x''
let bv' = App (BVZext w' w x_bv)
return (BaseExpr outty'' (BitvectorAsPointerExpr w' bv'))
_ -> fail (unlines [unwords ["invalid zero extension:", show x, show outty], showI])
L.SExt -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (LLVMPointerRepr w) x'', (LLVMPointerRepr w'))
| Just LeqProof <- isPosNat w
, Just LeqProof <- testLeq (incNat w) w' -> do
do x_bv <- pointerAsBitvectorExpr w x''
let bv' = App (BVSext w' w x_bv)
return (BaseExpr outty'' (BitvectorAsPointerExpr w' bv'))
_ -> fail (unlines [unwords ["invalid sign extension", show x, show outty], showI])
L.BitCast -> do
tp <- either fail return $ liftMemType $ L.typedType x
outty' <- liftMemType' outty
x' <- transValue tp (L.typedValue x)
bitCast tp x' outty'
L.UiToFp -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (LLVMPointerRepr w) x'', FloatRepr fi) -> do
bv <- pointerAsBitvectorExpr w x''
return $ BaseExpr (FloatRepr fi) $ App $ FloatFromBV fi RNE bv
_ -> fail (unlines [unwords ["Invalid uitofp:", show op, show x, show outty], showI])
L.SiToFp -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (LLVMPointerRepr w) x'', FloatRepr fi) -> do
bv <- pointerAsBitvectorExpr w x''
return $ BaseExpr (FloatRepr fi) $ App $ FloatFromSBV fi RNE bv
_ -> fail (unlines [unwords ["Invalid sitofp:", show op, show x, show outty], showI])
L.FpToUi -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
let demoteToInt :: (1 <= w) => NatRepr w -> Expr (LLVM arch) s (FloatType fi) -> LLVMExpr s arch
demoteToInt w v = BaseExpr (LLVMPointerRepr w) (BitvectorAsPointerExpr w $ App $ FloatToBV w RNE v)
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (FloatRepr _) x'', LLVMPointerRepr w) -> return $ demoteToInt w x''
_ -> fail (unlines [unwords ["Invalid fptoui:", show op, show x, show outty], showI])
L.FpToSi -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
let demoteToInt :: (1 <= w) => NatRepr w -> Expr (LLVM arch) s (FloatType fi) -> LLVMExpr s arch
demoteToInt w v = BaseExpr (LLVMPointerRepr w) (BitvectorAsPointerExpr w $ App $ FloatToSBV w RNE v)
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (FloatRepr _) x'', LLVMPointerRepr w) -> return $ demoteToInt w x''
_ -> fail (unlines [unwords ["Invalid fptosi:", show op, show x, show outty], showI])
L.FpTrunc -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (FloatRepr _) x'', FloatRepr fi) -> do
return $ BaseExpr (FloatRepr fi) $ App $ FloatCast fi RNE x''
_ -> fail (unlines [unwords ["Invalid fptrunc:", show op, show x, show outty], showI])
L.FpExt -> do
outty' <- liftMemType' outty
x' <- transTypedValue x
llvmTypeAsRepr outty' $ \outty'' ->
case (asScalar x', outty'') of
(Scalar (FloatRepr _) x'', FloatRepr fi) -> do
return $ BaseExpr (FloatRepr fi) $ App $ FloatCast fi RNE x''
_ -> fail (unlines [unwords ["Invalid fpext:", show op, show x, show outty], showI])
--------------------------------------------------------------------------------
-- Bit Cast
bitCast :: (?lc::TypeContext,HasPtrWidth wptr, wptr ~ ArchWidth arch) =>
MemType {- ^ starting type of the expression -} ->
LLVMExpr s arch {- ^ expression to cast -} ->
MemType {- ^ target type -} ->
LLVMGenerator h s arch ret (LLVMExpr s arch)
bitCast _ (ZeroExpr _) tgtT = return (ZeroExpr tgtT)
bitCast _ (UndefExpr _) tgtT = return (UndefExpr tgtT)
-- pointer casts always succeed
bitCast (PtrType _) expr (PtrType _) = return expr
-- casts between vectors of the same length can just be done pointwise
bitCast (VecType n srcT) (explodeVector n -> Just xs) (VecType n' tgtT)
| n == n' = VecExpr tgtT <$> traverse (\x -> bitCast srcT x tgtT) xs
-- otherwise, cast via an intermediate integer type of common width
bitCast srcT expr tgtT = mb =<< runMaybeT (
case (memTypeBitwidth srcT, memTypeBitwidth tgtT) of
(Just w1, Just w2) | w1 == w2 -> castToInt srcT expr >>= castFromInt tgtT w2
_ -> mzero)
where
mb = maybe (err [ "*** Invalid coercion of expression"
, indent (show expr)
, "of type"
, indent (show srcT)
, "to type"
, indent (show tgtT)
]) return
err msg = reportError $ fromString $ unlines ("[bitCast] Failed to perform cast:" : msg)
indent msg = " " ++ msg
castToInt :: (?lc::TypeContext,HasPtrWidth w, w ~ ArchWidth arch) =>
MemType -> LLVMExpr s arch -> MaybeT (LLVMGenerator' h s arch ret) (LLVMExpr s arch)
castToInt (IntType w) (BaseExpr (LLVMPointerRepr wrepr) x)
| toInteger w == natValue wrepr
= lift (BaseExpr (BVRepr wrepr) <$> pointerAsBitvectorExpr wrepr x)
castToInt (VecType n tp) (explodeVector n -> Just xs) =
do xs' <- traverse (castToInt tp) (toList xs)
MaybeT (return (vecJoin xs'))
castToInt _ _ = mzero
castFromInt :: (?lc::TypeContext,HasPtrWidth w, w ~ ArchWidth arch) =>
MemType -> Natural -> LLVMExpr s arch -> MaybeT (LLVMGenerator' h s arch ret) (LLVMExpr s arch)
castFromInt (IntType w1) w2 (BaseExpr (BVRepr w) x)
| w1 == w2, toInteger w1 == natValue w
= return (BaseExpr (LLVMPointerRepr w) (BitvectorAsPointerExpr w x))
castFromInt (VecType n tp) w expr
| (w',0) <- w `divMod` n
, Just (Some wrepr') <- someNat (toInteger w')
, Just LeqProof <- isPosNat wrepr'
= do xs <- MaybeT (return (vecSplit wrepr' expr))
VecExpr tp . Seq.fromList <$> traverse (castFromInt tp w') xs
castFromInt _ _ _ = mzero
-- | Join the elements of a vector into a single bit-vector value.
-- The resulting bit-vector would be of length at least one.
vecJoin :: (?lc::TypeContext,HasPtrWidth w, w ~ ArchWidth arch) =>
[LLVMExpr s arch] {- ^ Join these vector elements -} ->
Maybe (LLVMExpr s arch)
vecJoin exprs =
do (a,ys) <- List.uncons exprs
Scalar (BVRepr n) e1 <- return (asScalar a)
if null ys
then do LeqProof <- testLeq (knownNat @1) n
return (BaseExpr (BVRepr n) e1)
else do BaseExpr (BVRepr m) e2 <- vecJoin ys
let p1 = leqProof (knownNat @0) n
p2 = leqProof (knownNat @1) m
(LeqProof,LeqProof) <- return (leqAdd2 p1 p2, leqAdd2 p2 p1)
let bits u v x y = bitVal (addNat u v) (BVConcat u v x y)
return $! case llvmDataLayout ?lc ^. intLayout of
LittleEndian -> bits m n e2 e1
BigEndian -> bits n m e1 e2
bitVal :: (1 <= n) => NatRepr n ->
App (LLVM arch) (Expr (LLVM arch) s) (BVType n) ->
LLVMExpr s arch
bitVal n e = BaseExpr (BVRepr n) (App e)
-- | Split a single bit-vector value into a vector of value of the given width.
vecSplit :: forall s n w arch. (?lc::TypeContext,HasPtrWidth w, w ~ ArchWidth arch, 1 <= n) =>
NatRepr n {- ^ Length of a single element -} ->
LLVMExpr s arch {- ^ Bit-vector value -} ->
Maybe [ LLVMExpr s arch ]
vecSplit elLen expr =
do Scalar (BVRepr totLen) e <- return (asScalar expr)
let getEl :: NatRepr offset -> Maybe [ LLVMExpr s arch ]
getEl offset = let end = addNat offset elLen
in case testLeq end totLen of
Just LeqProof ->
do rest <- getEl end
let x = bitVal elLen
(BVSelect offset elLen totLen e)
return (x : rest)
Nothing ->
do Refl <- testEquality offset totLen
return []
els <- getEl (knownNat @0)
-- in `els` the least significant chunk is first
return $! case lay ^. intLayout of
LittleEndian -> els
BigEndian -> reverse els
where
lay = llvmDataLayout ?lc
bitop ::
L.BitOp ->
MemType ->
LLVMExpr s arch ->
LLVMExpr s arch ->
LLVMGenerator h s arch ret (LLVMExpr s arch)
bitop op (VecType n tp) (explodeVector n -> Just xs) (explodeVector n -> Just ys) =
VecExpr tp <$> sequence (Seq.zipWith (bitop op tp) xs ys)
bitop op _ x y =
case (asScalar x, asScalar y) of
(Scalar (LLVMPointerRepr w) x',
Scalar (LLVMPointerRepr w') y')
| Just Refl <- testEquality w w'
, Just LeqProof <- isPosNat w -> do
xbv <- pointerAsBitvectorExpr w x'
ybv <- pointerAsBitvectorExpr w y'
ex <- raw_bitop op w xbv ybv
return (BaseExpr (LLVMPointerRepr w) (BitvectorAsPointerExpr w ex))
_ -> fail $ unwords ["bitwise operation on unsupported values", show x, show y]
raw_bitop :: (1 <= w) =>
L.BitOp ->
NatRepr w ->
Expr (LLVM arch) s (BVType w) ->
Expr (LLVM arch) s (BVType w) ->
LLVMGenerator h s arch ret (Expr (LLVM arch) s (BVType w))
raw_bitop op w a b =
case op of
L.And -> return $ App (BVAnd w a b)
L.Or -> return $ App (BVOr w a b)
L.Xor -> return $ App (BVXor w a b)
L.Shl nuw nsw -> do
let wlit = App (BVLit w (natValue w))
assertExpr (App (BVUlt w b wlit))
(litExpr "shift amount too large in shl")
res <- AtomExpr <$> mkAtom (App (BVShl w a b))
let nuwCond expr
| nuw = do
m <- AtomExpr <$> mkAtom (App (BVLshr w res b))
return $ App $ AddSideCondition (BaseBVRepr w)
(App (BVEq w a m))
"unsigned overflow on shl"
expr
| otherwise = return expr
let nswCond expr
| nsw = do
m <- AtomExpr <$> mkAtom (App (BVAshr w res b))
return $ App $ AddSideCondition (BaseBVRepr w)
(App (BVEq w a m))
"signed overflow on shl"
expr
| otherwise = return expr
nuwCond =<< nswCond =<< return res
L.Lshr exact -> do
let wlit = App (BVLit w (natValue w))
assertExpr (App (BVUlt w b wlit))
(litExpr "shift amount too large in lshr")
res <- AtomExpr <$> mkAtom (App (BVLshr w a b))
let exactCond expr
| exact = do
m <- AtomExpr <$> mkAtom (App (BVShl w res b))
return $ App $ AddSideCondition (BaseBVRepr w)
(App (BVEq w a m))
"inexact logical right shift"
expr
| otherwise = return expr
exactCond res
L.Ashr exact
| Just LeqProof <- isPosNat w -> do
let wlit = App (BVLit w (natValue w))
assertExpr (App (BVUlt w b wlit))
(litExpr "shift amount too large in ashr")
res <- AtomExpr <$> mkAtom (App (BVAshr w a b))
let exactCond expr
| exact = do
m <- AtomExpr <$> mkAtom (App (BVShl w res b))
return $ App $ AddSideCondition (BaseBVRepr w)
(App (BVEq w a m))
"inexact arithmetic right shift"
expr
| otherwise = return expr
exactCond res
| otherwise -> fail "cannot arithmetic right shift a 0-width integer"
intop :: (1 <= w)
=> L.ArithOp
-> NatRepr w
-> Expr (LLVM arch) s (BVType w)
-> Expr (LLVM arch) s (BVType w)
-> LLVMGenerator h s arch ret (Expr (LLVM arch) s (BVType w))
intop op w a b =
case op of
L.Add nuw nsw -> do
let nuwCond expr
| nuw = return $ App $ AddSideCondition (BaseBVRepr w)
(notExpr (App (BVCarry w a b)))
"unsigned overflow on addition"
expr
| otherwise = return expr
let nswCond expr
| nsw = return $ App $ AddSideCondition (BaseBVRepr w)
(notExpr (App (BVSCarry w a b)))
"signed overflow on addition"
expr
| otherwise = return expr
nuwCond =<< nswCond (App (BVAdd w a b))
L.Sub nuw nsw -> do
let nuwCond expr
| nuw = return $ App $ AddSideCondition (BaseBVRepr w)
(notExpr (App (BVUlt w a b)))
"unsigned overflow on subtraction"
expr
| otherwise = return expr
let nusCond expr
| nsw = return $ App $ AddSideCondition (BaseBVRepr w)
(notExpr (App (BVSBorrow w a b)))
"signed overflow on subtraction"
expr
| otherwise = return expr
nuwCond =<< nusCond (App (BVSub w a b))
L.Mul nuw nsw -> do
let w' = addNat w w
Just LeqProof <- return $ isPosNat w'
Just LeqProof <- return $ testLeq (incNat w) w'
prod <- AtomExpr <$> mkAtom (App (BVMul w a b))
let nuwCond expr
| nuw = do
az <- AtomExpr <$> mkAtom (App (BVZext w' w a))
bz <- AtomExpr <$> mkAtom (App (BVZext w' w b))
wideprod <- AtomExpr <$> mkAtom (App (BVMul w' az bz))
prodz <- AtomExpr <$> mkAtom (App (BVZext w' w prod))
return $ App $ AddSideCondition (BaseBVRepr w)
(App (BVEq w' wideprod prodz))
"unsigned overflow on multiplication"
expr
| otherwise = return expr
let nswCond expr
| nsw = do
as <- AtomExpr <$> mkAtom (App (BVSext w' w a))
bs <- AtomExpr <$> mkAtom (App (BVSext w' w b))
wideprod <- AtomExpr <$> mkAtom (App (BVMul w' as bs))
prods <- AtomExpr <$> mkAtom (App (BVSext w' w prod))
return $ App $ AddSideCondition (BaseBVRepr w)
(App (BVEq w' wideprod prods))
"signed overflow on multiplication"
expr
| otherwise = return expr
nuwCond =<< nswCond prod
L.UDiv exact -> do
let z = App (BVLit w 0)
assertExpr (notExpr (App (BVEq w z b)))
(litExpr "unsigned division-by-0")
q <- AtomExpr <$> mkAtom (App (BVUdiv w a b))
let exactCond expr
| exact = do
m <- AtomExpr <$> mkAtom (App (BVMul w q b))
return $ App $ AddSideCondition (BaseBVRepr w)
(App (BVEq w a m))
"inexact result of unsigned division"
expr
| otherwise = return expr
exactCond q
L.SDiv exact
| Just LeqProof <- isPosNat w -> do
let z = App (BVLit w 0)
let neg1 = App (BVLit w (-1))
let minInt = App (BVLit w (minSigned w))
assertExpr (notExpr (App (BVEq w z b)))
(litExpr "signed division-by-0")
assertExpr (notExpr ((App (BVEq w neg1 b))
.&&
(App (BVEq w minInt a)) ))
(litExpr "signed division overflow (yes, really)")
q <- AtomExpr <$> mkAtom (App (BVSdiv w a b))
let exactCond expr
| exact = do
m <- AtomExpr <$> mkAtom (App (BVMul w q b))
return $ App $ AddSideCondition (BaseBVRepr w)
(App (BVEq w a m))
"inexact result of signed division"
expr
| otherwise = return expr
exactCond q
| otherwise -> fail "cannot take the signed quotient of a 0-width bitvector"
L.URem -> do
let z = App (BVLit w 0)
assertExpr (notExpr (App (BVEq w z b)))
(litExpr "unsigned division-by-0 in urem")
return $ App (BVUrem w a b)
L.SRem
| Just LeqProof <- isPosNat w -> do
let z = App (BVLit w 0)
let neg1 = App (BVLit w (-1))
let minInt = App (BVLit w (minSigned w))
assertExpr (notExpr (App (BVEq w z b)))
(litExpr "signed division-by-0 in srem")
assertExpr (notExpr ((App (BVEq w neg1 b))
.&&
(App (BVEq w minInt a)) ))
(litExpr "signed division overflow in srem (yes, really)")
return $ App (BVSrem w a b)
| otherwise -> fail "cannot take the signed remainder of a 0-width bitvector"
_ -> fail $ unwords ["unsupported integer arith operation", show op]
caseptr
:: (1 <= w)
=> NatRepr w
-> TypeRepr a
-> (Expr (LLVM arch) s (BVType w) ->
LLVMGenerator h s arch ret (Expr (LLVM arch) s a))
-> (Expr (LLVM arch) s NatType -> Expr (LLVM arch) s (BVType w) ->
LLVMGenerator h s arch ret (Expr (LLVM arch) s a))
-> Expr (LLVM arch) s (LLVMPointerType w)
-> LLVMGenerator h s arch ret (Expr (LLVM arch) s a)
caseptr w tpr bvCase ptrCase x =
case x of
PointerExpr _ blk off ->
case asApp blk of
Just (NatLit 0) -> bvCase off
Just (NatLit _) -> ptrCase blk off
_ -> ptrSwitch blk off
_ -> do a_x <- forceEvaluation x
blk <- forceEvaluation (App (ExtensionApp (LLVM_PointerBlock w a_x)))
off <- forceEvaluation (App (ExtensionApp (LLVM_PointerOffset w a_x)))
ptrSwitch blk off
where
ptrSwitch blk off =
do let cond = (blk .== litExpr 0)
c_label <- newLambdaLabel' tpr
bv_label <- defineBlockLabel (bvCase off >>= jumpToLambda c_label)
ptr_label <- defineBlockLabel (ptrCase blk off >>= jumpToLambda c_label)
continueLambda c_label (branch cond bv_label ptr_label)
intcmp :: (1 <= w)
=> NatRepr w
-> L.ICmpOp
-> Expr (LLVM arch) s (BVType w)
-> Expr (LLVM arch) s (BVType w)
-> Expr (LLVM arch) s BoolType
intcmp w op a b =
case op of
L.Ieq -> App (BVEq w a b)
L.Ine -> App (Not (App (BVEq w a b)))
L.Iult -> App (BVUlt w a b)
L.Iule -> App (BVUle w a b)
L.Iugt -> App (BVUlt w b a)
L.Iuge -> App (BVUle w b a)
L.Islt -> App (BVSlt w a b)
L.Isle -> App (BVSle w a b)
L.Isgt -> App (BVSlt w b a)
L.Isge -> App (BVSle w b a)