github.com/panjjo/go@v0.0.0-20161104043856-d62b31386338/src/cmd/compile/internal/gc/syntax.go (about) 1 // Copyright 2009 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 5 // “Abstract” syntax representation. 6 7 package gc 8 9 // A Node is a single node in the syntax tree. 10 // Actually the syntax tree is a syntax DAG, because there is only one 11 // node with Op=ONAME for a given instance of a variable x. 12 // The same is true for Op=OTYPE and Op=OLITERAL. 13 type Node struct { 14 // Tree structure. 15 // Generic recursive walks should follow these fields. 16 Left *Node 17 Right *Node 18 Ninit Nodes 19 Nbody Nodes 20 List Nodes 21 Rlist Nodes 22 23 // most nodes 24 Type *Type 25 Orig *Node // original form, for printing, and tracking copies of ONAMEs 26 27 // func 28 Func *Func 29 30 // ONAME 31 Name *Name 32 33 Sym *Sym // various 34 E interface{} // Opt or Val, see methods below 35 36 // Various. Usually an offset into a struct. For example: 37 // - ONAME nodes that refer to local variables use it to identify their stack frame position. 38 // - ODOT, ODOTPTR, and OINDREGSP use it to indicate offset relative to their base address. 39 // - OSTRUCTKEY uses it to store the named field's offset. 40 // - OXCASE and OXFALL use it to validate the use of fallthrough. 41 // - ONONAME uses it to store the current value of iota, see Node.Iota 42 // Possibly still more uses. If you find any, document them. 43 Xoffset int64 44 45 Lineno int32 46 47 Esc uint16 // EscXXX 48 49 Op Op 50 Ullman uint8 // sethi/ullman number 51 Addable bool // addressable 52 Etype EType // op for OASOP, etype for OTYPE, exclam for export, 6g saved reg, ChanDir for OTCHAN, for OINDEXMAP 1=LHS,0=RHS 53 Bounded bool // bounds check unnecessary 54 NonNil bool // guaranteed to be non-nil 55 Class Class // PPARAM, PAUTO, PEXTERN, etc 56 Embedded uint8 // ODCLFIELD embedded type 57 Colas bool // OAS resulting from := 58 Diag bool // already printed error about this 59 Noescape bool // func arguments do not escape; TODO(rsc): move Noescape to Func struct (see CL 7360) 60 Walkdef uint8 // tracks state during typecheckdef; 2 == loop detected 61 Typecheck uint8 // tracks state during typechecking; 2 == loop detected 62 Local bool 63 IsStatic bool // whether this Node will be converted to purely static data 64 Initorder uint8 65 Used bool // for variable/label declared and not used error 66 Isddd bool // is the argument variadic 67 Implicit bool 68 Addrtaken bool // address taken, even if not moved to heap 69 Assigned bool // is the variable ever assigned to 70 Likely int8 // likeliness of if statement 71 hasVal int8 // +1 for Val, -1 for Opt, 0 for not yet set 72 flags uint8 // TODO: store more bool fields in this flag field 73 } 74 75 // IsAutoTmp indicates if n was created by the compiler as a temporary, 76 // based on the setting of the .AutoTemp flag in n's Name. 77 func (n *Node) IsAutoTmp() bool { 78 if n == nil || n.Op != ONAME { 79 return false 80 } 81 return n.Name.AutoTemp 82 } 83 84 const ( 85 hasBreak = 1 << iota 86 isClosureVar 87 isOutputParamHeapAddr 88 noInline // used internally by inliner to indicate that a function call should not be inlined; set for OCALLFUNC and OCALLMETH only 89 ) 90 91 func (n *Node) HasBreak() bool { 92 return n.flags&hasBreak != 0 93 } 94 func (n *Node) SetHasBreak(b bool) { 95 if b { 96 n.flags |= hasBreak 97 } else { 98 n.flags &^= hasBreak 99 } 100 } 101 func (n *Node) isClosureVar() bool { 102 return n.flags&isClosureVar != 0 103 } 104 func (n *Node) setIsClosureVar(b bool) { 105 if b { 106 n.flags |= isClosureVar 107 } else { 108 n.flags &^= isClosureVar 109 } 110 } 111 func (n *Node) noInline() bool { 112 return n.flags&noInline != 0 113 } 114 func (n *Node) setNoInline(b bool) { 115 if b { 116 n.flags |= noInline 117 } else { 118 n.flags &^= noInline 119 } 120 } 121 122 func (n *Node) IsOutputParamHeapAddr() bool { 123 return n.flags&isOutputParamHeapAddr != 0 124 } 125 func (n *Node) setIsOutputParamHeapAddr(b bool) { 126 if b { 127 n.flags |= isOutputParamHeapAddr 128 } else { 129 n.flags &^= isOutputParamHeapAddr 130 } 131 } 132 133 // Val returns the Val for the node. 134 func (n *Node) Val() Val { 135 if n.hasVal != +1 { 136 return Val{} 137 } 138 return Val{n.E} 139 } 140 141 // SetVal sets the Val for the node, which must not have been used with SetOpt. 142 func (n *Node) SetVal(v Val) { 143 if n.hasVal == -1 { 144 Debug['h'] = 1 145 Dump("have Opt", n) 146 Fatalf("have Opt") 147 } 148 n.hasVal = +1 149 n.E = v.U 150 } 151 152 // Opt returns the optimizer data for the node. 153 func (n *Node) Opt() interface{} { 154 if n.hasVal != -1 { 155 return nil 156 } 157 return n.E 158 } 159 160 // SetOpt sets the optimizer data for the node, which must not have been used with SetVal. 161 // SetOpt(nil) is ignored for Vals to simplify call sites that are clearing Opts. 162 func (n *Node) SetOpt(x interface{}) { 163 if x == nil && n.hasVal >= 0 { 164 return 165 } 166 if n.hasVal == +1 { 167 Debug['h'] = 1 168 Dump("have Val", n) 169 Fatalf("have Val") 170 } 171 n.hasVal = -1 172 n.E = x 173 } 174 175 func (n *Node) Iota() int64 { 176 return n.Xoffset 177 } 178 179 func (n *Node) SetIota(x int64) { 180 n.Xoffset = x 181 } 182 183 // Name holds Node fields used only by named nodes (ONAME, OPACK, OLABEL, some OLITERAL). 184 type Name struct { 185 Pack *Node // real package for import . names 186 Pkg *Pkg // pkg for OPACK nodes 187 Heapaddr *Node // temp holding heap address of param (could move to Param?) 188 Defn *Node // initializing assignment 189 Curfn *Node // function for local variables 190 Param *Param // additional fields for ONAME 191 Decldepth int32 // declaration loop depth, increased for every loop or label 192 Vargen int32 // unique name for ONAME within a function. Function outputs are numbered starting at one. 193 Funcdepth int32 194 Readonly bool 195 Captured bool // is the variable captured by a closure 196 Byval bool // is the variable captured by value or by reference 197 Needzero bool // if it contains pointers, needs to be zeroed on function entry 198 Keepalive bool // mark value live across unknown assembly call 199 AutoTemp bool // is the variable a temporary (implies no dwarf info. reset if escapes to heap) 200 } 201 202 type Param struct { 203 Ntype *Node 204 205 // ONAME PAUTOHEAP 206 Stackcopy *Node // the PPARAM/PPARAMOUT on-stack slot (moved func params only) 207 208 // ONAME PPARAM 209 Field *Field // TFIELD in arg struct 210 211 // ONAME closure linkage 212 // Consider: 213 // 214 // func f() { 215 // x := 1 // x1 216 // func() { 217 // use(x) // x2 218 // func() { 219 // use(x) // x3 220 // --- parser is here --- 221 // }() 222 // }() 223 // } 224 // 225 // There is an original declaration of x and then a chain of mentions of x 226 // leading into the current function. Each time x is mentioned in a new closure, 227 // we create a variable representing x for use in that specific closure, 228 // since the way you get to x is different in each closure. 229 // 230 // Let's number the specific variables as shown in the code: 231 // x1 is the original x, x2 is when mentioned in the closure, 232 // and x3 is when mentioned in the closure in the closure. 233 // 234 // We keep these linked (assume N > 1): 235 // 236 // - x1.Defn = original declaration statement for x (like most variables) 237 // - x1.Innermost = current innermost closure x (in this case x3), or nil for none 238 // - x1.isClosureVar() = false 239 // 240 // - xN.Defn = x1, N > 1 241 // - xN.isClosureVar() = true, N > 1 242 // - x2.Outer = nil 243 // - xN.Outer = x(N-1), N > 2 244 // 245 // 246 // When we look up x in the symbol table, we always get x1. 247 // Then we can use x1.Innermost (if not nil) to get the x 248 // for the innermost known closure function, 249 // but the first reference in a closure will find either no x1.Innermost 250 // or an x1.Innermost with .Funcdepth < Funcdepth. 251 // In that case, a new xN must be created, linked in with: 252 // 253 // xN.Defn = x1 254 // xN.Outer = x1.Innermost 255 // x1.Innermost = xN 256 // 257 // When we finish the function, we'll process its closure variables 258 // and find xN and pop it off the list using: 259 // 260 // x1 := xN.Defn 261 // x1.Innermost = xN.Outer 262 // 263 // We leave xN.Innermost set so that we can still get to the original 264 // variable quickly. Not shown here, but once we're 265 // done parsing a function and no longer need xN.Outer for the 266 // lexical x reference links as described above, closurebody 267 // recomputes xN.Outer as the semantic x reference link tree, 268 // even filling in x in intermediate closures that might not 269 // have mentioned it along the way to inner closures that did. 270 // See closurebody for details. 271 // 272 // During the eventual compilation, then, for closure variables we have: 273 // 274 // xN.Defn = original variable 275 // xN.Outer = variable captured in next outward scope 276 // to make closure where xN appears 277 // 278 // Because of the sharding of pieces of the node, x.Defn means x.Name.Defn 279 // and x.Innermost/Outer means x.Name.Param.Innermost/Outer. 280 Innermost *Node 281 Outer *Node 282 283 // OTYPE pragmas 284 // 285 // TODO: Should Func pragmas also be stored on the Name? 286 Pragma Pragma 287 } 288 289 // Func holds Node fields used only with function-like nodes. 290 type Func struct { 291 Shortname *Node 292 Enter Nodes // for example, allocate and initialize memory for escaping parameters 293 Exit Nodes 294 Cvars Nodes // closure params 295 Dcl []*Node // autodcl for this func/closure 296 Inldcl Nodes // copy of dcl for use in inlining 297 Closgen int 298 Outerfunc *Node // outer function (for closure) 299 FieldTrack map[*Sym]struct{} 300 Ntype *Node // signature 301 Top int // top context (Ecall, Eproc, etc) 302 Closure *Node // OCLOSURE <-> ODCLFUNC 303 Nname *Node 304 305 Inl Nodes // copy of the body for use in inlining 306 InlCost int32 307 Depth int32 308 309 Label int32 // largest auto-generated label in this function 310 311 Endlineno int32 312 WBLineno int32 // line number of first write barrier 313 314 Pragma Pragma // go:xxx function annotations 315 Dupok bool // duplicate definitions ok 316 Wrapper bool // is method wrapper 317 Needctxt bool // function uses context register (has closure variables) 318 ReflectMethod bool // function calls reflect.Type.Method or MethodByName 319 IsHiddenClosure bool 320 } 321 322 type Op uint8 323 324 // Node ops. 325 const ( 326 OXXX = Op(iota) 327 328 // names 329 ONAME // var, const or func name 330 ONONAME // unnamed arg or return value: f(int, string) (int, error) { etc } 331 OTYPE // type name 332 OPACK // import 333 OLITERAL // literal 334 335 // expressions 336 OADD // Left + Right 337 OSUB // Left - Right 338 OOR // Left | Right 339 OXOR // Left ^ Right 340 OADDSTR // +{List} (string addition, list elements are strings) 341 OADDR // &Left 342 OANDAND // Left && Right 343 OAPPEND // append(List) 344 OARRAYBYTESTR // Type(Left) (Type is string, Left is a []byte) 345 OARRAYBYTESTRTMP // Type(Left) (Type is string, Left is a []byte, ephemeral) 346 OARRAYRUNESTR // Type(Left) (Type is string, Left is a []rune) 347 OSTRARRAYBYTE // Type(Left) (Type is []byte, Left is a string) 348 OSTRARRAYBYTETMP // Type(Left) (Type is []byte, Left is a string, ephemeral) 349 OSTRARRAYRUNE // Type(Left) (Type is []rune, Left is a string) 350 OAS // Left = Right or (if Colas=true) Left := Right 351 OAS2 // List = Rlist (x, y, z = a, b, c) 352 OAS2FUNC // List = Rlist (x, y = f()) 353 OAS2RECV // List = Rlist (x, ok = <-c) 354 OAS2MAPR // List = Rlist (x, ok = m["foo"]) 355 OAS2DOTTYPE // List = Rlist (x, ok = I.(int)) 356 OASOP // Left Etype= Right (x += y) 357 OASWB // Left = Right (with write barrier) 358 OCALL // Left(List) (function call, method call or type conversion) 359 OCALLFUNC // Left(List) (function call f(args)) 360 OCALLMETH // Left(List) (direct method call x.Method(args)) 361 OCALLINTER // Left(List) (interface method call x.Method(args)) 362 OCALLPART // Left.Right (method expression x.Method, not called) 363 OCAP // cap(Left) 364 OCLOSE // close(Left) 365 OCLOSURE // func Type { Body } (func literal) 366 OCMPIFACE // Left Etype Right (interface comparison, x == y or x != y) 367 OCMPSTR // Left Etype Right (string comparison, x == y, x < y, etc) 368 OCOMPLIT // Right{List} (composite literal, not yet lowered to specific form) 369 OMAPLIT // Type{List} (composite literal, Type is map) 370 OSTRUCTLIT // Type{List} (composite literal, Type is struct) 371 OARRAYLIT // Type{List} (composite literal, Type is array) 372 OSLICELIT // Type{List} (composite literal, Type is slice) 373 OPTRLIT // &Left (left is composite literal) 374 OCONV // Type(Left) (type conversion) 375 OCONVIFACE // Type(Left) (type conversion, to interface) 376 OCONVNOP // Type(Left) (type conversion, no effect) 377 OCOPY // copy(Left, Right) 378 ODCL // var Left (declares Left of type Left.Type) 379 380 // Used during parsing but don't last. 381 ODCLFUNC // func f() or func (r) f() 382 ODCLFIELD // struct field, interface field, or func/method argument/return value. 383 ODCLCONST // const pi = 3.14 384 ODCLTYPE // type Int int 385 386 ODELETE // delete(Left, Right) 387 ODOT // Left.Sym (Left is of struct type) 388 ODOTPTR // Left.Sym (Left is of pointer to struct type) 389 ODOTMETH // Left.Sym (Left is non-interface, Right is method name) 390 ODOTINTER // Left.Sym (Left is interface, Right is method name) 391 OXDOT // Left.Sym (before rewrite to one of the preceding) 392 ODOTTYPE // Left.Right or Left.Type (.Right during parsing, .Type once resolved) 393 ODOTTYPE2 // Left.Right or Left.Type (.Right during parsing, .Type once resolved; on rhs of OAS2DOTTYPE) 394 OEQ // Left == Right 395 ONE // Left != Right 396 OLT // Left < Right 397 OLE // Left <= Right 398 OGE // Left >= Right 399 OGT // Left > Right 400 OIND // *Left 401 OINDEX // Left[Right] (index of array or slice) 402 OINDEXMAP // Left[Right] (index of map) 403 OKEY // Left:Right (key:value in struct/array/map literal) 404 OSTRUCTKEY // Sym:Left (key:value in struct literal, after type checking) 405 OLEN // len(Left) 406 OMAKE // make(List) (before type checking converts to one of the following) 407 OMAKECHAN // make(Type, Left) (type is chan) 408 OMAKEMAP // make(Type, Left) (type is map) 409 OMAKESLICE // make(Type, Left, Right) (type is slice) 410 OMUL // Left * Right 411 ODIV // Left / Right 412 OMOD // Left % Right 413 OLSH // Left << Right 414 ORSH // Left >> Right 415 OAND // Left & Right 416 OANDNOT // Left &^ Right 417 ONEW // new(Left) 418 ONOT // !Left 419 OCOM // ^Left 420 OPLUS // +Left 421 OMINUS // -Left 422 OOROR // Left || Right 423 OPANIC // panic(Left) 424 OPRINT // print(List) 425 OPRINTN // println(List) 426 OPAREN // (Left) 427 OSEND // Left <- Right 428 OSLICE // Left[List[0] : List[1]] (Left is untypechecked or slice) 429 OSLICEARR // Left[List[0] : List[1]] (Left is array) 430 OSLICESTR // Left[List[0] : List[1]] (Left is string) 431 OSLICE3 // Left[List[0] : List[1] : List[2]] (Left is untypedchecked or slice) 432 OSLICE3ARR // Left[List[0] : List[1] : List[2]] (Left is array) 433 ORECOVER // recover() 434 ORECV // <-Left 435 ORUNESTR // Type(Left) (Type is string, Left is rune) 436 OSELRECV // Left = <-Right.Left: (appears as .Left of OCASE; Right.Op == ORECV) 437 OSELRECV2 // List = <-Right.Left: (apperas as .Left of OCASE; count(List) == 2, Right.Op == ORECV) 438 OIOTA // iota 439 OREAL // real(Left) 440 OIMAG // imag(Left) 441 OCOMPLEX // complex(Left, Right) 442 OALIGNOF // unsafe.Alignof(Left) 443 OOFFSETOF // unsafe.Offsetof(Left) 444 OSIZEOF // unsafe.Sizeof(Left) 445 446 // statements 447 OBLOCK // { List } (block of code) 448 OBREAK // break 449 OCASE // case Left or List[0]..List[1]: Nbody (select case after processing; Left==nil and List==nil means default) 450 OXCASE // case List: Nbody (select case before processing; List==nil means default) 451 OCONTINUE // continue 452 ODEFER // defer Left (Left must be call) 453 OEMPTY // no-op (empty statement) 454 OFALL // fallthrough (after processing) 455 OXFALL // fallthrough (before processing) 456 OFOR // for Ninit; Left; Right { Nbody } 457 OGOTO // goto Left 458 OIF // if Ninit; Left { Nbody } else { Rlist } 459 OLABEL // Left: 460 OPROC // go Left (Left must be call) 461 ORANGE // for List = range Right { Nbody } 462 ORETURN // return List 463 OSELECT // select { List } (List is list of OXCASE or OCASE) 464 OSWITCH // switch Ninit; Left { List } (List is a list of OXCASE or OCASE) 465 OTYPESW // List = Left.(type) (appears as .Left of OSWITCH) 466 467 // types 468 OTCHAN // chan int 469 OTMAP // map[string]int 470 OTSTRUCT // struct{} 471 OTINTER // interface{} 472 OTFUNC // func() 473 OTARRAY // []int, [8]int, [N]int or [...]int 474 475 // misc 476 ODDD // func f(args ...int) or f(l...) or var a = [...]int{0, 1, 2}. 477 ODDDARG // func f(args ...int), introduced by escape analysis. 478 OINLCALL // intermediary representation of an inlined call. 479 OEFACE // itable and data words of an empty-interface value. 480 OITAB // itable word of an interface value. 481 OIDATA // data word of an interface value in Left 482 OSPTR // base pointer of a slice or string. 483 OCLOSUREVAR // variable reference at beginning of closure function 484 OCFUNC // reference to c function pointer (not go func value) 485 OCHECKNIL // emit code to ensure pointer/interface not nil 486 OVARKILL // variable is dead 487 OVARLIVE // variable is alive 488 OINDREGSP // offset plus indirect of REGSP, such as 8(SP). 489 490 // arch-specific opcodes 491 OCMP // compare: ACMP. 492 ODEC // decrement: ADEC. 493 OINC // increment: AINC. 494 OEXTEND // extend: ACWD/ACDQ/ACQO. 495 OHMUL // high mul: AMUL/AIMUL for unsigned/signed (OMUL uses AIMUL for both). 496 OLROT // left rotate: AROL. 497 ORROTC // right rotate-carry: ARCR. 498 ORETJMP // return to other function 499 OPS // compare parity set (for x86 NaN check) 500 OPC // compare parity clear (for x86 NaN check) 501 OSQRT // sqrt(float64), on systems that have hw support 502 OGETG // runtime.getg() (read g pointer) 503 504 OEND 505 ) 506 507 // Nodes is a pointer to a slice of *Node. 508 // For fields that are not used in most nodes, this is used instead of 509 // a slice to save space. 510 type Nodes struct{ slice *[]*Node } 511 512 // Slice returns the entries in Nodes as a slice. 513 // Changes to the slice entries (as in s[i] = n) will be reflected in 514 // the Nodes. 515 func (n Nodes) Slice() []*Node { 516 if n.slice == nil { 517 return nil 518 } 519 return *n.slice 520 } 521 522 // Len returns the number of entries in Nodes. 523 func (n Nodes) Len() int { 524 if n.slice == nil { 525 return 0 526 } 527 return len(*n.slice) 528 } 529 530 // Index returns the i'th element of Nodes. 531 // It panics if n does not have at least i+1 elements. 532 func (n Nodes) Index(i int) *Node { 533 return (*n.slice)[i] 534 } 535 536 // First returns the first element of Nodes (same as n.Index(0)). 537 // It panics if n has no elements. 538 func (n Nodes) First() *Node { 539 return (*n.slice)[0] 540 } 541 542 // Second returns the second element of Nodes (same as n.Index(1)). 543 // It panics if n has fewer than two elements. 544 func (n Nodes) Second() *Node { 545 return (*n.slice)[1] 546 } 547 548 // Set sets n to a slice. 549 // This takes ownership of the slice. 550 func (n *Nodes) Set(s []*Node) { 551 if len(s) == 0 { 552 n.slice = nil 553 } else { 554 // Copy s and take address of t rather than s to avoid 555 // allocation in the case where len(s) == 0 (which is 556 // over 3x more common, dynamically, for make.bash). 557 t := s 558 n.slice = &t 559 } 560 } 561 562 // Set1 sets n to a slice containing a single node. 563 func (n *Nodes) Set1(node *Node) { 564 n.slice = &[]*Node{node} 565 } 566 567 // Set2 sets n to a slice containing two nodes. 568 func (n *Nodes) Set2(n1, n2 *Node) { 569 n.slice = &[]*Node{n1, n2} 570 } 571 572 // MoveNodes sets n to the contents of n2, then clears n2. 573 func (n *Nodes) MoveNodes(n2 *Nodes) { 574 n.slice = n2.slice 575 n2.slice = nil 576 } 577 578 // SetIndex sets the i'th element of Nodes to node. 579 // It panics if n does not have at least i+1 elements. 580 func (n Nodes) SetIndex(i int, node *Node) { 581 (*n.slice)[i] = node 582 } 583 584 // Addr returns the address of the i'th element of Nodes. 585 // It panics if n does not have at least i+1 elements. 586 func (n Nodes) Addr(i int) **Node { 587 return &(*n.slice)[i] 588 } 589 590 // Append appends entries to Nodes. 591 // If a slice is passed in, this will take ownership of it. 592 func (n *Nodes) Append(a ...*Node) { 593 if len(a) == 0 { 594 return 595 } 596 if n.slice == nil { 597 n.slice = &a 598 } else { 599 *n.slice = append(*n.slice, a...) 600 } 601 } 602 603 // Prepend prepends entries to Nodes. 604 // If a slice is passed in, this will take ownership of it. 605 func (n *Nodes) Prepend(a ...*Node) { 606 if len(a) == 0 { 607 return 608 } 609 if n.slice == nil { 610 n.slice = &a 611 } else { 612 *n.slice = append(a, *n.slice...) 613 } 614 } 615 616 // AppendNodes appends the contents of *n2 to n, then clears n2. 617 func (n *Nodes) AppendNodes(n2 *Nodes) { 618 switch { 619 case n2.slice == nil: 620 case n.slice == nil: 621 n.slice = n2.slice 622 default: 623 *n.slice = append(*n.slice, *n2.slice...) 624 } 625 n2.slice = nil 626 }