sanity.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package ssa
  5. // An optional pass for sanity-checking invariants of the SSA representation.
  6. // Currently it checks CFG invariants but little at the instruction level.
  7. import (
  8. "fmt"
  9. "go/types"
  10. "io"
  11. "os"
  12. "strings"
  13. )
  14. type sanity struct {
  15. reporter io.Writer
  16. fn *Function
  17. block *BasicBlock
  18. instrs map[Instruction]struct{}
  19. insane bool
  20. }
  21. // sanityCheck performs integrity checking of the SSA representation
  22. // of the function fn and returns true if it was valid. Diagnostics
  23. // are written to reporter if non-nil, os.Stderr otherwise. Some
  24. // diagnostics are only warnings and do not imply a negative result.
  25. //
  26. // Sanity-checking is intended to facilitate the debugging of code
  27. // transformation passes.
  28. //
  29. func sanityCheck(fn *Function, reporter io.Writer) bool {
  30. if reporter == nil {
  31. reporter = os.Stderr
  32. }
  33. return (&sanity{reporter: reporter}).checkFunction(fn)
  34. }
  35. // mustSanityCheck is like sanityCheck but panics instead of returning
  36. // a negative result.
  37. //
  38. func mustSanityCheck(fn *Function, reporter io.Writer) {
  39. if !sanityCheck(fn, reporter) {
  40. fn.WriteTo(os.Stderr)
  41. panic("SanityCheck failed")
  42. }
  43. }
  44. func (s *sanity) diagnostic(prefix, format string, args ...interface{}) {
  45. fmt.Fprintf(s.reporter, "%s: function %s", prefix, s.fn)
  46. if s.block != nil {
  47. fmt.Fprintf(s.reporter, ", block %s", s.block)
  48. }
  49. io.WriteString(s.reporter, ": ")
  50. fmt.Fprintf(s.reporter, format, args...)
  51. io.WriteString(s.reporter, "\n")
  52. }
  53. func (s *sanity) errorf(format string, args ...interface{}) {
  54. s.insane = true
  55. s.diagnostic("Error", format, args...)
  56. }
  57. func (s *sanity) warnf(format string, args ...interface{}) {
  58. s.diagnostic("Warning", format, args...)
  59. }
  60. // findDuplicate returns an arbitrary basic block that appeared more
  61. // than once in blocks, or nil if all were unique.
  62. func findDuplicate(blocks []*BasicBlock) *BasicBlock {
  63. if len(blocks) < 2 {
  64. return nil
  65. }
  66. if blocks[0] == blocks[1] {
  67. return blocks[0]
  68. }
  69. // Slow path:
  70. m := make(map[*BasicBlock]bool)
  71. for _, b := range blocks {
  72. if m[b] {
  73. return b
  74. }
  75. m[b] = true
  76. }
  77. return nil
  78. }
  79. func (s *sanity) checkInstr(idx int, instr Instruction) {
  80. switch instr := instr.(type) {
  81. case *If, *Jump, *Return, *Panic:
  82. s.errorf("control flow instruction not at end of block")
  83. case *Phi:
  84. if idx == 0 {
  85. // It suffices to apply this check to just the first phi node.
  86. if dup := findDuplicate(s.block.Preds); dup != nil {
  87. s.errorf("phi node in block with duplicate predecessor %s", dup)
  88. }
  89. } else {
  90. prev := s.block.Instrs[idx-1]
  91. if _, ok := prev.(*Phi); !ok {
  92. s.errorf("Phi instruction follows a non-Phi: %T", prev)
  93. }
  94. }
  95. if ne, np := len(instr.Edges), len(s.block.Preds); ne != np {
  96. s.errorf("phi node has %d edges but %d predecessors", ne, np)
  97. } else {
  98. for i, e := range instr.Edges {
  99. if e == nil {
  100. s.errorf("phi node '%s' has no value for edge #%d from %s", instr.Comment, i, s.block.Preds[i])
  101. }
  102. }
  103. }
  104. case *Alloc:
  105. if !instr.Heap {
  106. found := false
  107. for _, l := range s.fn.Locals {
  108. if l == instr {
  109. found = true
  110. break
  111. }
  112. }
  113. if !found {
  114. s.errorf("local alloc %s = %s does not appear in Function.Locals", instr.Name(), instr)
  115. }
  116. }
  117. case *BinOp:
  118. case *Call:
  119. case *ChangeInterface:
  120. case *ChangeType:
  121. case *Convert:
  122. if _, ok := instr.X.Type().Underlying().(*types.Basic); !ok {
  123. if _, ok := instr.Type().Underlying().(*types.Basic); !ok {
  124. s.errorf("convert %s -> %s: at least one type must be basic", instr.X.Type(), instr.Type())
  125. }
  126. }
  127. case *Defer:
  128. case *Extract:
  129. case *Field:
  130. case *FieldAddr:
  131. case *Go:
  132. case *Index:
  133. case *IndexAddr:
  134. case *Lookup:
  135. case *MakeChan:
  136. case *MakeClosure:
  137. numFree := len(instr.Fn.(*Function).FreeVars)
  138. numBind := len(instr.Bindings)
  139. if numFree != numBind {
  140. s.errorf("MakeClosure has %d Bindings for function %s with %d free vars",
  141. numBind, instr.Fn, numFree)
  142. }
  143. if recv := instr.Type().(*types.Signature).Recv(); recv != nil {
  144. s.errorf("MakeClosure's type includes receiver %s", recv.Type())
  145. }
  146. case *MakeInterface:
  147. case *MakeMap:
  148. case *MakeSlice:
  149. case *MapUpdate:
  150. case *Next:
  151. case *Range:
  152. case *RunDefers:
  153. case *Select:
  154. case *Send:
  155. case *Slice:
  156. case *Store:
  157. case *TypeAssert:
  158. case *UnOp:
  159. case *DebugRef:
  160. case *BlankStore:
  161. case *Sigma:
  162. // TODO(adonovan): implement checks.
  163. default:
  164. panic(fmt.Sprintf("Unknown instruction type: %T", instr))
  165. }
  166. if call, ok := instr.(CallInstruction); ok {
  167. if call.Common().Signature() == nil {
  168. s.errorf("nil signature: %s", call)
  169. }
  170. }
  171. // Check that value-defining instructions have valid types
  172. // and a valid referrer list.
  173. if v, ok := instr.(Value); ok {
  174. t := v.Type()
  175. if t == nil {
  176. s.errorf("no type: %s = %s", v.Name(), v)
  177. } else if t == tRangeIter {
  178. // not a proper type; ignore.
  179. } else if b, ok := t.Underlying().(*types.Basic); ok && b.Info()&types.IsUntyped != 0 {
  180. s.errorf("instruction has 'untyped' result: %s = %s : %s", v.Name(), v, t)
  181. }
  182. s.checkReferrerList(v)
  183. }
  184. // Untyped constants are legal as instruction Operands(),
  185. // for example:
  186. // _ = "foo"[0]
  187. // or:
  188. // if wordsize==64 {...}
  189. // All other non-Instruction Values can be found via their
  190. // enclosing Function or Package.
  191. }
  192. func (s *sanity) checkFinalInstr(instr Instruction) {
  193. switch instr := instr.(type) {
  194. case *If:
  195. if nsuccs := len(s.block.Succs); nsuccs != 2 {
  196. s.errorf("If-terminated block has %d successors; expected 2", nsuccs)
  197. return
  198. }
  199. if s.block.Succs[0] == s.block.Succs[1] {
  200. s.errorf("If-instruction has same True, False target blocks: %s", s.block.Succs[0])
  201. return
  202. }
  203. case *Jump:
  204. if nsuccs := len(s.block.Succs); nsuccs != 1 {
  205. s.errorf("Jump-terminated block has %d successors; expected 1", nsuccs)
  206. return
  207. }
  208. case *Return:
  209. if nsuccs := len(s.block.Succs); nsuccs != 0 {
  210. s.errorf("Return-terminated block has %d successors; expected none", nsuccs)
  211. return
  212. }
  213. if na, nf := len(instr.Results), s.fn.Signature.Results().Len(); nf != na {
  214. s.errorf("%d-ary return in %d-ary function", na, nf)
  215. }
  216. case *Panic:
  217. if nsuccs := len(s.block.Succs); nsuccs != 0 {
  218. s.errorf("Panic-terminated block has %d successors; expected none", nsuccs)
  219. return
  220. }
  221. default:
  222. s.errorf("non-control flow instruction at end of block")
  223. }
  224. }
  225. func (s *sanity) checkBlock(b *BasicBlock, index int) {
  226. s.block = b
  227. if b.Index != index {
  228. s.errorf("block has incorrect Index %d", b.Index)
  229. }
  230. if b.parent != s.fn {
  231. s.errorf("block has incorrect parent %s", b.parent)
  232. }
  233. // Check all blocks are reachable.
  234. // (The entry block is always implicitly reachable,
  235. // as is the Recover block, if any.)
  236. if (index > 0 && b != b.parent.Recover) && len(b.Preds) == 0 {
  237. s.warnf("unreachable block")
  238. if b.Instrs == nil {
  239. // Since this block is about to be pruned,
  240. // tolerating transient problems in it
  241. // simplifies other optimizations.
  242. return
  243. }
  244. }
  245. // Check predecessor and successor relations are dual,
  246. // and that all blocks in CFG belong to same function.
  247. for _, a := range b.Preds {
  248. found := false
  249. for _, bb := range a.Succs {
  250. if bb == b {
  251. found = true
  252. break
  253. }
  254. }
  255. if !found {
  256. s.errorf("expected successor edge in predecessor %s; found only: %s", a, a.Succs)
  257. }
  258. if a.parent != s.fn {
  259. s.errorf("predecessor %s belongs to different function %s", a, a.parent)
  260. }
  261. }
  262. for _, c := range b.Succs {
  263. found := false
  264. for _, bb := range c.Preds {
  265. if bb == b {
  266. found = true
  267. break
  268. }
  269. }
  270. if !found {
  271. s.errorf("expected predecessor edge in successor %s; found only: %s", c, c.Preds)
  272. }
  273. if c.parent != s.fn {
  274. s.errorf("successor %s belongs to different function %s", c, c.parent)
  275. }
  276. }
  277. // Check each instruction is sane.
  278. n := len(b.Instrs)
  279. if n == 0 {
  280. s.errorf("basic block contains no instructions")
  281. }
  282. var rands [10]*Value // reuse storage
  283. for j, instr := range b.Instrs {
  284. if instr == nil {
  285. s.errorf("nil instruction at index %d", j)
  286. continue
  287. }
  288. if b2 := instr.Block(); b2 == nil {
  289. s.errorf("nil Block() for instruction at index %d", j)
  290. continue
  291. } else if b2 != b {
  292. s.errorf("wrong Block() (%s) for instruction at index %d ", b2, j)
  293. continue
  294. }
  295. if j < n-1 {
  296. s.checkInstr(j, instr)
  297. } else {
  298. s.checkFinalInstr(instr)
  299. }
  300. // Check Instruction.Operands.
  301. operands:
  302. for i, op := range instr.Operands(rands[:0]) {
  303. if op == nil {
  304. s.errorf("nil operand pointer %d of %s", i, instr)
  305. continue
  306. }
  307. val := *op
  308. if val == nil {
  309. continue // a nil operand is ok
  310. }
  311. // Check that "untyped" types only appear on constant operands.
  312. if _, ok := (*op).(*Const); !ok {
  313. if basic, ok := (*op).Type().(*types.Basic); ok {
  314. if basic.Info()&types.IsUntyped != 0 {
  315. s.errorf("operand #%d of %s is untyped: %s", i, instr, basic)
  316. }
  317. }
  318. }
  319. // Check that Operands that are also Instructions belong to same function.
  320. // TODO(adonovan): also check their block dominates block b.
  321. if val, ok := val.(Instruction); ok {
  322. if val.Block() == nil {
  323. s.errorf("operand %d of %s is an instruction (%s) that belongs to no block", i, instr, val)
  324. } else if val.Parent() != s.fn {
  325. s.errorf("operand %d of %s is an instruction (%s) from function %s", i, instr, val, val.Parent())
  326. }
  327. }
  328. // Check that each function-local operand of
  329. // instr refers back to instr. (NB: quadratic)
  330. switch val := val.(type) {
  331. case *Const, *Global, *Builtin:
  332. continue // not local
  333. case *Function:
  334. if val.parent == nil {
  335. continue // only anon functions are local
  336. }
  337. }
  338. // TODO(adonovan): check val.Parent() != nil <=> val.Referrers() is defined.
  339. if refs := val.Referrers(); refs != nil {
  340. for _, ref := range *refs {
  341. if ref == instr {
  342. continue operands
  343. }
  344. }
  345. s.errorf("operand %d of %s (%s) does not refer to us", i, instr, val)
  346. } else {
  347. s.errorf("operand %d of %s (%s) has no referrers", i, instr, val)
  348. }
  349. }
  350. }
  351. }
  352. func (s *sanity) checkReferrerList(v Value) {
  353. refs := v.Referrers()
  354. if refs == nil {
  355. s.errorf("%s has missing referrer list", v.Name())
  356. return
  357. }
  358. for i, ref := range *refs {
  359. if _, ok := s.instrs[ref]; !ok {
  360. s.errorf("%s.Referrers()[%d] = %s is not an instruction belonging to this function", v.Name(), i, ref)
  361. }
  362. }
  363. }
  364. func (s *sanity) checkFunction(fn *Function) bool {
  365. // TODO(adonovan): check Function invariants:
  366. // - check params match signature
  367. // - check transient fields are nil
  368. // - warn if any fn.Locals do not appear among block instructions.
  369. s.fn = fn
  370. if fn.Prog == nil {
  371. s.errorf("nil Prog")
  372. }
  373. _ = fn.String() // must not crash
  374. _ = fn.RelString(fn.pkg()) // must not crash
  375. // All functions have a package, except delegates (which are
  376. // shared across packages, or duplicated as weak symbols in a
  377. // separate-compilation model), and error.Error.
  378. if fn.Pkg == nil {
  379. if strings.HasPrefix(fn.Synthetic, "wrapper ") ||
  380. strings.HasPrefix(fn.Synthetic, "bound ") ||
  381. strings.HasPrefix(fn.Synthetic, "thunk ") ||
  382. strings.HasSuffix(fn.name, "Error") {
  383. // ok
  384. } else {
  385. s.errorf("nil Pkg")
  386. }
  387. }
  388. if src, syn := fn.Synthetic == "", fn.Syntax() != nil; src != syn {
  389. s.errorf("got fromSource=%t, hasSyntax=%t; want same values", src, syn)
  390. }
  391. for i, l := range fn.Locals {
  392. if l.Parent() != fn {
  393. s.errorf("Local %s at index %d has wrong parent", l.Name(), i)
  394. }
  395. if l.Heap {
  396. s.errorf("Local %s at index %d has Heap flag set", l.Name(), i)
  397. }
  398. }
  399. // Build the set of valid referrers.
  400. s.instrs = make(map[Instruction]struct{})
  401. for _, b := range fn.Blocks {
  402. for _, instr := range b.Instrs {
  403. s.instrs[instr] = struct{}{}
  404. }
  405. }
  406. for i, p := range fn.Params {
  407. if p.Parent() != fn {
  408. s.errorf("Param %s at index %d has wrong parent", p.Name(), i)
  409. }
  410. // Check common suffix of Signature and Params match type.
  411. if sig := fn.Signature; sig != nil {
  412. j := i - len(fn.Params) + sig.Params().Len() // index within sig.Params
  413. if j < 0 {
  414. continue
  415. }
  416. if !types.Identical(p.Type(), sig.Params().At(j).Type()) {
  417. s.errorf("Param %s at index %d has wrong type (%s, versus %s in Signature)", p.Name(), i, p.Type(), sig.Params().At(j).Type())
  418. }
  419. }
  420. s.checkReferrerList(p)
  421. }
  422. for i, fv := range fn.FreeVars {
  423. if fv.Parent() != fn {
  424. s.errorf("FreeVar %s at index %d has wrong parent", fv.Name(), i)
  425. }
  426. s.checkReferrerList(fv)
  427. }
  428. if fn.Blocks != nil && len(fn.Blocks) == 0 {
  429. // Function _had_ blocks (so it's not external) but
  430. // they were "optimized" away, even the entry block.
  431. s.errorf("Blocks slice is non-nil but empty")
  432. }
  433. for i, b := range fn.Blocks {
  434. if b == nil {
  435. s.warnf("nil *BasicBlock at f.Blocks[%d]", i)
  436. continue
  437. }
  438. s.checkBlock(b, i)
  439. }
  440. if fn.Recover != nil && fn.Blocks[fn.Recover.Index] != fn.Recover {
  441. s.errorf("Recover block is not in Blocks slice")
  442. }
  443. s.block = nil
  444. for i, anon := range fn.AnonFuncs {
  445. if anon.Parent() != fn {
  446. s.errorf("AnonFuncs[%d]=%s but %s.Parent()=%s", i, anon, anon, anon.Parent())
  447. }
  448. }
  449. s.fn = nil
  450. return !s.insane
  451. }
  452. // sanityCheckPackage checks invariants of packages upon creation.
  453. // It does not require that the package is built.
  454. // Unlike sanityCheck (for functions), it just panics at the first error.
  455. func sanityCheckPackage(pkg *Package) {
  456. if pkg.Pkg == nil {
  457. panic(fmt.Sprintf("Package %s has no Object", pkg))
  458. }
  459. _ = pkg.String() // must not crash
  460. for name, mem := range pkg.Members {
  461. if name != mem.Name() {
  462. panic(fmt.Sprintf("%s: %T.Name() = %s, want %s",
  463. pkg.Pkg.Path(), mem, mem.Name(), name))
  464. }
  465. obj := mem.Object()
  466. if obj == nil {
  467. // This check is sound because fields
  468. // {Global,Function}.object have type
  469. // types.Object. (If they were declared as
  470. // *types.{Var,Func}, we'd have a non-empty
  471. // interface containing a nil pointer.)
  472. continue // not all members have typechecker objects
  473. }
  474. if obj.Name() != name {
  475. if obj.Name() == "init" && strings.HasPrefix(mem.Name(), "init#") {
  476. // Ok. The name of a declared init function varies between
  477. // its types.Func ("init") and its ssa.Function ("init#%d").
  478. } else {
  479. panic(fmt.Sprintf("%s: %T.Object().Name() = %s, want %s",
  480. pkg.Pkg.Path(), mem, obj.Name(), name))
  481. }
  482. }
  483. if obj.Pos() != mem.Pos() {
  484. panic(fmt.Sprintf("%s Pos=%d obj.Pos=%d", mem, mem.Pos(), obj.Pos()))
  485. }
  486. }
  487. }