emit.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. // Helpers for emitting SSA instructions.
  6. import (
  7. "fmt"
  8. "go/ast"
  9. "go/token"
  10. "go/types"
  11. )
  12. // emitNew emits to f a new (heap Alloc) instruction allocating an
  13. // object of type typ. pos is the optional source location.
  14. //
  15. func emitNew(f *Function, typ types.Type, pos token.Pos) *Alloc {
  16. v := &Alloc{Heap: true}
  17. v.setType(types.NewPointer(typ))
  18. v.setPos(pos)
  19. f.emit(v)
  20. return v
  21. }
  22. // emitLoad emits to f an instruction to load the address addr into a
  23. // new temporary, and returns the value so defined.
  24. //
  25. func emitLoad(f *Function, addr Value) *UnOp {
  26. v := &UnOp{Op: token.MUL, X: addr}
  27. v.setType(deref(addr.Type()))
  28. f.emit(v)
  29. return v
  30. }
  31. // emitDebugRef emits to f a DebugRef pseudo-instruction associating
  32. // expression e with value v.
  33. //
  34. func emitDebugRef(f *Function, e ast.Expr, v Value, isAddr bool) {
  35. if !f.debugInfo() {
  36. return // debugging not enabled
  37. }
  38. if v == nil || e == nil {
  39. panic("nil")
  40. }
  41. var obj types.Object
  42. e = unparen(e)
  43. if id, ok := e.(*ast.Ident); ok {
  44. if isBlankIdent(id) {
  45. return
  46. }
  47. obj = f.Pkg.objectOf(id)
  48. switch obj.(type) {
  49. case *types.Nil, *types.Const, *types.Builtin:
  50. return
  51. }
  52. }
  53. f.emit(&DebugRef{
  54. X: v,
  55. Expr: e,
  56. IsAddr: isAddr,
  57. object: obj,
  58. })
  59. }
  60. // emitArith emits to f code to compute the binary operation op(x, y)
  61. // where op is an eager shift, logical or arithmetic operation.
  62. // (Use emitCompare() for comparisons and Builder.logicalBinop() for
  63. // non-eager operations.)
  64. //
  65. func emitArith(f *Function, op token.Token, x, y Value, t types.Type, pos token.Pos) Value {
  66. switch op {
  67. case token.SHL, token.SHR:
  68. x = emitConv(f, x, t)
  69. // y may be signed or an 'untyped' constant.
  70. // TODO(adonovan): whence signed values?
  71. if b, ok := y.Type().Underlying().(*types.Basic); ok && b.Info()&types.IsUnsigned == 0 {
  72. y = emitConv(f, y, types.Typ[types.Uint64])
  73. }
  74. case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT:
  75. x = emitConv(f, x, t)
  76. y = emitConv(f, y, t)
  77. default:
  78. panic("illegal op in emitArith: " + op.String())
  79. }
  80. v := &BinOp{
  81. Op: op,
  82. X: x,
  83. Y: y,
  84. }
  85. v.setPos(pos)
  86. v.setType(t)
  87. return f.emit(v)
  88. }
  89. // emitCompare emits to f code compute the boolean result of
  90. // comparison comparison 'x op y'.
  91. //
  92. func emitCompare(f *Function, op token.Token, x, y Value, pos token.Pos) Value {
  93. xt := x.Type().Underlying()
  94. yt := y.Type().Underlying()
  95. // Special case to optimise a tagless SwitchStmt so that
  96. // these are equivalent
  97. // switch { case e: ...}
  98. // switch true { case e: ... }
  99. // if e==true { ... }
  100. // even in the case when e's type is an interface.
  101. // TODO(adonovan): opt: generalise to x==true, false!=y, etc.
  102. if x == vTrue && op == token.EQL {
  103. if yt, ok := yt.(*types.Basic); ok && yt.Info()&types.IsBoolean != 0 {
  104. return y
  105. }
  106. }
  107. if types.Identical(xt, yt) {
  108. // no conversion necessary
  109. } else if _, ok := xt.(*types.Interface); ok {
  110. y = emitConv(f, y, x.Type())
  111. } else if _, ok := yt.(*types.Interface); ok {
  112. x = emitConv(f, x, y.Type())
  113. } else if _, ok := x.(*Const); ok {
  114. x = emitConv(f, x, y.Type())
  115. } else if _, ok := y.(*Const); ok {
  116. y = emitConv(f, y, x.Type())
  117. //lint:ignore SA9003 no-op
  118. } else {
  119. // other cases, e.g. channels. No-op.
  120. }
  121. v := &BinOp{
  122. Op: op,
  123. X: x,
  124. Y: y,
  125. }
  126. v.setPos(pos)
  127. v.setType(tBool)
  128. return f.emit(v)
  129. }
  130. // isValuePreserving returns true if a conversion from ut_src to
  131. // ut_dst is value-preserving, i.e. just a change of type.
  132. // Precondition: neither argument is a named type.
  133. //
  134. func isValuePreserving(ut_src, ut_dst types.Type) bool {
  135. // Identical underlying types?
  136. if structTypesIdentical(ut_dst, ut_src) {
  137. return true
  138. }
  139. switch ut_dst.(type) {
  140. case *types.Chan:
  141. // Conversion between channel types?
  142. _, ok := ut_src.(*types.Chan)
  143. return ok
  144. case *types.Pointer:
  145. // Conversion between pointers with identical base types?
  146. _, ok := ut_src.(*types.Pointer)
  147. return ok
  148. }
  149. return false
  150. }
  151. // emitConv emits to f code to convert Value val to exactly type typ,
  152. // and returns the converted value. Implicit conversions are required
  153. // by language assignability rules in assignments, parameter passing,
  154. // etc. Conversions cannot fail dynamically.
  155. //
  156. func emitConv(f *Function, val Value, typ types.Type) Value {
  157. t_src := val.Type()
  158. // Identical types? Conversion is a no-op.
  159. if types.Identical(t_src, typ) {
  160. return val
  161. }
  162. ut_dst := typ.Underlying()
  163. ut_src := t_src.Underlying()
  164. // Just a change of type, but not value or representation?
  165. if isValuePreserving(ut_src, ut_dst) {
  166. c := &ChangeType{X: val}
  167. c.setType(typ)
  168. return f.emit(c)
  169. }
  170. // Conversion to, or construction of a value of, an interface type?
  171. if _, ok := ut_dst.(*types.Interface); ok {
  172. // Assignment from one interface type to another?
  173. if _, ok := ut_src.(*types.Interface); ok {
  174. c := &ChangeInterface{X: val}
  175. c.setType(typ)
  176. return f.emit(c)
  177. }
  178. // Untyped nil constant? Return interface-typed nil constant.
  179. if ut_src == tUntypedNil {
  180. return nilConst(typ)
  181. }
  182. // Convert (non-nil) "untyped" literals to their default type.
  183. if t, ok := ut_src.(*types.Basic); ok && t.Info()&types.IsUntyped != 0 {
  184. val = emitConv(f, val, DefaultType(ut_src))
  185. }
  186. f.Pkg.Prog.needMethodsOf(val.Type())
  187. mi := &MakeInterface{X: val}
  188. mi.setType(typ)
  189. return f.emit(mi)
  190. }
  191. // Conversion of a compile-time constant value?
  192. if c, ok := val.(*Const); ok {
  193. if _, ok := ut_dst.(*types.Basic); ok || c.IsNil() {
  194. // Conversion of a compile-time constant to
  195. // another constant type results in a new
  196. // constant of the destination type and
  197. // (initially) the same abstract value.
  198. // We don't truncate the value yet.
  199. return NewConst(c.Value, typ)
  200. }
  201. // We're converting from constant to non-constant type,
  202. // e.g. string -> []byte/[]rune.
  203. }
  204. // A representation-changing conversion?
  205. // At least one of {ut_src,ut_dst} must be *Basic.
  206. // (The other may be []byte or []rune.)
  207. _, ok1 := ut_src.(*types.Basic)
  208. _, ok2 := ut_dst.(*types.Basic)
  209. if ok1 || ok2 {
  210. c := &Convert{X: val}
  211. c.setType(typ)
  212. return f.emit(c)
  213. }
  214. panic(fmt.Sprintf("in %s: cannot convert %s (%s) to %s", f, val, val.Type(), typ))
  215. }
  216. // emitStore emits to f an instruction to store value val at location
  217. // addr, applying implicit conversions as required by assignability rules.
  218. //
  219. func emitStore(f *Function, addr, val Value, pos token.Pos) *Store {
  220. s := &Store{
  221. Addr: addr,
  222. Val: emitConv(f, val, deref(addr.Type())),
  223. pos: pos,
  224. }
  225. f.emit(s)
  226. return s
  227. }
  228. // emitJump emits to f a jump to target, and updates the control-flow graph.
  229. // Postcondition: f.currentBlock is nil.
  230. //
  231. func emitJump(f *Function, target *BasicBlock) {
  232. b := f.currentBlock
  233. b.emit(new(Jump))
  234. addEdge(b, target)
  235. f.currentBlock = nil
  236. }
  237. // emitIf emits to f a conditional jump to tblock or fblock based on
  238. // cond, and updates the control-flow graph.
  239. // Postcondition: f.currentBlock is nil.
  240. //
  241. func emitIf(f *Function, cond Value, tblock, fblock *BasicBlock) {
  242. b := f.currentBlock
  243. b.emit(&If{Cond: cond})
  244. addEdge(b, tblock)
  245. addEdge(b, fblock)
  246. f.currentBlock = nil
  247. }
  248. // emitExtract emits to f an instruction to extract the index'th
  249. // component of tuple. It returns the extracted value.
  250. //
  251. func emitExtract(f *Function, tuple Value, index int) Value {
  252. e := &Extract{Tuple: tuple, Index: index}
  253. e.setType(tuple.Type().(*types.Tuple).At(index).Type())
  254. return f.emit(e)
  255. }
  256. // emitTypeAssert emits to f a type assertion value := x.(t) and
  257. // returns the value. x.Type() must be an interface.
  258. //
  259. func emitTypeAssert(f *Function, x Value, t types.Type, pos token.Pos) Value {
  260. a := &TypeAssert{X: x, AssertedType: t}
  261. a.setPos(pos)
  262. a.setType(t)
  263. return f.emit(a)
  264. }
  265. // emitTypeTest emits to f a type test value,ok := x.(t) and returns
  266. // a (value, ok) tuple. x.Type() must be an interface.
  267. //
  268. func emitTypeTest(f *Function, x Value, t types.Type, pos token.Pos) Value {
  269. a := &TypeAssert{
  270. X: x,
  271. AssertedType: t,
  272. CommaOk: true,
  273. }
  274. a.setPos(pos)
  275. a.setType(types.NewTuple(
  276. newVar("value", t),
  277. varOk,
  278. ))
  279. return f.emit(a)
  280. }
  281. // emitTailCall emits to f a function call in tail position. The
  282. // caller is responsible for all fields of 'call' except its type.
  283. // Intended for wrapper methods.
  284. // Precondition: f does/will not use deferred procedure calls.
  285. // Postcondition: f.currentBlock is nil.
  286. //
  287. func emitTailCall(f *Function, call *Call) {
  288. tresults := f.Signature.Results()
  289. nr := tresults.Len()
  290. if nr == 1 {
  291. call.typ = tresults.At(0).Type()
  292. } else {
  293. call.typ = tresults
  294. }
  295. tuple := f.emit(call)
  296. var ret Return
  297. switch nr {
  298. case 0:
  299. // no-op
  300. case 1:
  301. ret.Results = []Value{tuple}
  302. default:
  303. for i := 0; i < nr; i++ {
  304. v := emitExtract(f, tuple, i)
  305. // TODO(adonovan): in principle, this is required:
  306. // v = emitConv(f, o.Type, f.Signature.Results[i].Type)
  307. // but in practice emitTailCall is only used when
  308. // the types exactly match.
  309. ret.Results = append(ret.Results, v)
  310. }
  311. }
  312. f.emit(&ret)
  313. f.currentBlock = nil
  314. }
  315. // emitImplicitSelections emits to f code to apply the sequence of
  316. // implicit field selections specified by indices to base value v, and
  317. // returns the selected value.
  318. //
  319. // If v is the address of a struct, the result will be the address of
  320. // a field; if it is the value of a struct, the result will be the
  321. // value of a field.
  322. //
  323. func emitImplicitSelections(f *Function, v Value, indices []int) Value {
  324. for _, index := range indices {
  325. fld := deref(v.Type()).Underlying().(*types.Struct).Field(index)
  326. if isPointer(v.Type()) {
  327. instr := &FieldAddr{
  328. X: v,
  329. Field: index,
  330. }
  331. instr.setType(types.NewPointer(fld.Type()))
  332. v = f.emit(instr)
  333. // Load the field's value iff indirectly embedded.
  334. if isPointer(fld.Type()) {
  335. v = emitLoad(f, v)
  336. }
  337. } else {
  338. instr := &Field{
  339. X: v,
  340. Field: index,
  341. }
  342. instr.setType(fld.Type())
  343. v = f.emit(instr)
  344. }
  345. }
  346. return v
  347. }
  348. // emitFieldSelection emits to f code to select the index'th field of v.
  349. //
  350. // If wantAddr, the input must be a pointer-to-struct and the result
  351. // will be the field's address; otherwise the result will be the
  352. // field's value.
  353. // Ident id is used for position and debug info.
  354. //
  355. func emitFieldSelection(f *Function, v Value, index int, wantAddr bool, id *ast.Ident) Value {
  356. fld := deref(v.Type()).Underlying().(*types.Struct).Field(index)
  357. if isPointer(v.Type()) {
  358. instr := &FieldAddr{
  359. X: v,
  360. Field: index,
  361. }
  362. instr.setPos(id.Pos())
  363. instr.setType(types.NewPointer(fld.Type()))
  364. v = f.emit(instr)
  365. // Load the field's value iff we don't want its address.
  366. if !wantAddr {
  367. v = emitLoad(f, v)
  368. }
  369. } else {
  370. instr := &Field{
  371. X: v,
  372. Field: index,
  373. }
  374. instr.setPos(id.Pos())
  375. instr.setType(fld.Type())
  376. v = f.emit(instr)
  377. }
  378. emitDebugRef(f, id, v, wantAddr)
  379. return v
  380. }
  381. // zeroValue emits to f code to produce a zero value of type t,
  382. // and returns it.
  383. //
  384. func zeroValue(f *Function, t types.Type) Value {
  385. switch t.Underlying().(type) {
  386. case *types.Struct, *types.Array:
  387. return emitLoad(f, f.addLocal(t, token.NoPos))
  388. default:
  389. return zeroConst(t)
  390. }
  391. }
  392. // createRecoverBlock emits to f a block of code to return after a
  393. // recovered panic, and sets f.Recover to it.
  394. //
  395. // If f's result parameters are named, the code loads and returns
  396. // their current values, otherwise it returns the zero values of their
  397. // type.
  398. //
  399. // Idempotent.
  400. //
  401. func createRecoverBlock(f *Function) {
  402. if f.Recover != nil {
  403. return // already created
  404. }
  405. saved := f.currentBlock
  406. f.Recover = f.newBasicBlock("recover")
  407. f.currentBlock = f.Recover
  408. var results []Value
  409. if f.namedResults != nil {
  410. // Reload NRPs to form value tuple.
  411. for _, r := range f.namedResults {
  412. results = append(results, emitLoad(f, r))
  413. }
  414. } else {
  415. R := f.Signature.Results()
  416. for i, n := 0, R.Len(); i < n; i++ {
  417. T := R.At(i).Type()
  418. // Return zero value of each result type.
  419. results = append(results, zeroValue(f, T))
  420. }
  421. }
  422. f.emit(&Return{Results: results})
  423. f.currentBlock = saved
  424. }