-
Notifications
You must be signed in to change notification settings - Fork 9
/
malloc.go
43 lines (39 loc) · 1.03 KB
/
malloc.go
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
package main
import "github.com/llir/llvm/ir"
func fixMalloc(f *ir.Func) {
var idx Index
idx.Add(f)
for _, b := range f.Blocks {
for _, inst := range b.Insts {
switch inst := inst.(type) {
case *ir.InstCall:
callee, err := FormatValue(inst.Callee)
if err != nil {
continue
}
switch callee {
case "malloc", "calloc":
users := idx.Users(inst)
if len(users) == 1 {
// If the return value of malloc was immediately cast to another type,
// tell our Malloc function to allocate that type instead of bytes.
if bc, ok := users[0].(*ir.InstBitCast); ok {
inst.Typ = bc.To
idx.ReplaceValue(bc, inst)
idx.DeleteInstruction(bc)
}
}
case "free":
if len(inst.Args) == 1 {
if bc, ok := inst.Args[0].(*ir.InstBitCast); ok && len(idx.Users(bc)) == 1 {
// If the parameter needed a cast to *byte before calling free,
// delete the cast too.
idx.DeleteInstruction(bc)
}
}
idx.DeleteInstruction(inst)
}
}
}
}
}