github.com/FenixAra/go@v0.0.0-20170127160404-96ea0918e670/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 NoFramePointer bool // Must not use a frame pointer for this function 321 } 322 323 type Op uint8 324 325 // Node ops. 326 const ( 327 OXXX = Op(iota) 328 329 // names 330 ONAME // var, const or func name 331 ONONAME // unnamed arg or return value: f(int, string) (int, error) { etc } 332 OTYPE // type name 333 OPACK // import 334 OLITERAL // literal 335 336 // expressions 337 OADD // Left + Right 338 OSUB // Left - Right 339 OOR // Left | Right 340 OXOR // Left ^ Right 341 OADDSTR // +{List} (string addition, list elements are strings) 342 OADDR // &Left 343 OANDAND // Left && Right 344 OAPPEND // append(List) 345 OARRAYBYTESTR // Type(Left) (Type is string, Left is a []byte) 346 OARRAYBYTESTRTMP // Type(Left) (Type is string, Left is a []byte, ephemeral) 347 OARRAYRUNESTR // Type(Left) (Type is string, Left is a []rune) 348 OSTRARRAYBYTE // Type(Left) (Type is []byte, Left is a string) 349 OSTRARRAYBYTETMP // Type(Left) (Type is []byte, Left is a string, ephemeral) 350 OSTRARRAYRUNE // Type(Left) (Type is []rune, Left is a string) 351 OAS // Left = Right or (if Colas=true) Left := Right 352 OAS2 // List = Rlist (x, y, z = a, b, c) 353 OAS2FUNC // List = Rlist (x, y = f()) 354 OAS2RECV // List = Rlist (x, ok = <-c) 355 OAS2MAPR // List = Rlist (x, ok = m["foo"]) 356 OAS2DOTTYPE // List = Rlist (x, ok = I.(int)) 357 OASOP // Left Etype= Right (x += y) 358 OASWB // Left = Right (with write barrier) 359 OCALL // Left(List) (function call, method call or type conversion) 360 OCALLFUNC // Left(List) (function call f(args)) 361 OCALLMETH // Left(List) (direct method call x.Method(args)) 362 OCALLINTER // Left(List) (interface method call x.Method(args)) 363 OCALLPART // Left.Right (method expression x.Method, not called) 364 OCAP // cap(Left) 365 OCLOSE // close(Left) 366 OCLOSURE // func Type { Body } (func literal) 367 OCMPIFACE // Left Etype Right (interface comparison, x == y or x != y) 368 OCMPSTR // Left Etype Right (string comparison, x == y, x < y, etc) 369 OCOMPLIT // Right{List} (composite literal, not yet lowered to specific form) 370 OMAPLIT // Type{List} (composite literal, Type is map) 371 OSTRUCTLIT // Type{List} (composite literal, Type is struct) 372 OARRAYLIT // Type{List} (composite literal, Type is array) 373 OSLICELIT // Type{List} (composite literal, Type is slice) 374 OPTRLIT // &Left (left is composite literal) 375 OCONV // Type(Left) (type conversion) 376 OCONVIFACE // Type(Left) (type conversion, to interface) 377 OCONVNOP // Type(Left) (type conversion, no effect) 378 OCOPY // copy(Left, Right) 379 ODCL // var Left (declares Left of type Left.Type) 380 381 // Used during parsing but don't last. 382 ODCLFUNC // func f() or func (r) f() 383 ODCLFIELD // struct field, interface field, or func/method argument/return value. 384 ODCLCONST // const pi = 3.14 385 ODCLTYPE // type Int int 386 387 ODELETE // delete(Left, Right) 388 ODOT // Left.Sym (Left is of struct type) 389 ODOTPTR // Left.Sym (Left is of pointer to struct type) 390 ODOTMETH // Left.Sym (Left is non-interface, Right is method name) 391 ODOTINTER // Left.Sym (Left is interface, Right is method name) 392 OXDOT // Left.Sym (before rewrite to one of the preceding) 393 ODOTTYPE // Left.Right or Left.Type (.Right during parsing, .Type once resolved) 394 ODOTTYPE2 // Left.Right or Left.Type (.Right during parsing, .Type once resolved; on rhs of OAS2DOTTYPE) 395 OEQ // Left == Right 396 ONE // Left != Right 397 OLT // Left < Right 398 OLE // Left <= Right 399 OGE // Left >= Right 400 OGT // Left > Right 401 OIND // *Left 402 OINDEX // Left[Right] (index of array or slice) 403 OINDEXMAP // Left[Right] (index of map) 404 OKEY // Left:Right (key:value in struct/array/map literal) 405 OSTRUCTKEY // Sym:Left (key:value in struct literal, after type checking) 406 OLEN // len(Left) 407 OMAKE // make(List) (before type checking converts to one of the following) 408 OMAKECHAN // make(Type, Left) (type is chan) 409 OMAKEMAP // make(Type, Left) (type is map) 410 OMAKESLICE // make(Type, Left, Right) (type is slice) 411 OMUL // Left * Right 412 ODIV // Left / Right 413 OMOD // Left % Right 414 OLSH // Left << Right 415 ORSH // Left >> Right 416 OAND // Left & Right 417 OANDNOT // Left &^ Right 418 ONEW // new(Left) 419 ONOT // !Left 420 OCOM // ^Left 421 OPLUS // +Left 422 OMINUS // -Left 423 OOROR // Left || Right 424 OPANIC // panic(Left) 425 OPRINT // print(List) 426 OPRINTN // println(List) 427 OPAREN // (Left) 428 OSEND // Left <- Right 429 OSLICE // Left[List[0] : List[1]] (Left is untypechecked or slice) 430 OSLICEARR // Left[List[0] : List[1]] (Left is array) 431 OSLICESTR // Left[List[0] : List[1]] (Left is string) 432 OSLICE3 // Left[List[0] : List[1] : List[2]] (Left is untypedchecked or slice) 433 OSLICE3ARR // Left[List[0] : List[1] : List[2]] (Left is array) 434 ORECOVER // recover() 435 ORECV // <-Left 436 ORUNESTR // Type(Left) (Type is string, Left is rune) 437 OSELRECV // Left = <-Right.Left: (appears as .Left of OCASE; Right.Op == ORECV) 438 OSELRECV2 // List = <-Right.Left: (apperas as .Left of OCASE; count(List) == 2, Right.Op == ORECV) 439 OIOTA // iota 440 OREAL // real(Left) 441 OIMAG // imag(Left) 442 OCOMPLEX // complex(Left, Right) 443 OALIGNOF // unsafe.Alignof(Left) 444 OOFFSETOF // unsafe.Offsetof(Left) 445 OSIZEOF // unsafe.Sizeof(Left) 446 447 // statements 448 OBLOCK // { List } (block of code) 449 OBREAK // break 450 OCASE // case Left or List[0]..List[1]: Nbody (select case after processing; Left==nil and List==nil means default) 451 OXCASE // case List: Nbody (select case before processing; List==nil means default) 452 OCONTINUE // continue 453 ODEFER // defer Left (Left must be call) 454 OEMPTY // no-op (empty statement) 455 OFALL // fallthrough (after processing) 456 OXFALL // fallthrough (before processing) 457 OFOR // for Ninit; Left; Right { Nbody } 458 OGOTO // goto Left 459 OIF // if Ninit; Left { Nbody } else { Rlist } 460 OLABEL // Left: 461 OPROC // go Left (Left must be call) 462 ORANGE // for List = range Right { Nbody } 463 ORETURN // return List 464 OSELECT // select { List } (List is list of OXCASE or OCASE) 465 OSWITCH // switch Ninit; Left { List } (List is a list of OXCASE or OCASE) 466 OTYPESW // List = Left.(type) (appears as .Left of OSWITCH) 467 468 // types 469 OTCHAN // chan int 470 OTMAP // map[string]int 471 OTSTRUCT // struct{} 472 OTINTER // interface{} 473 OTFUNC // func() 474 OTARRAY // []int, [8]int, [N]int or [...]int 475 476 // misc 477 ODDD // func f(args ...int) or f(l...) or var a = [...]int{0, 1, 2}. 478 ODDDARG // func f(args ...int), introduced by escape analysis. 479 OINLCALL // intermediary representation of an inlined call. 480 OEFACE // itable and data words of an empty-interface value. 481 OITAB // itable word of an interface value. 482 OIDATA // data word of an interface value in Left 483 OSPTR // base pointer of a slice or string. 484 OCLOSUREVAR // variable reference at beginning of closure function 485 OCFUNC // reference to c function pointer (not go func value) 486 OCHECKNIL // emit code to ensure pointer/interface not nil 487 OVARKILL // variable is dead 488 OVARLIVE // variable is alive 489 OINDREGSP // offset plus indirect of REGSP, such as 8(SP). 490 491 // arch-specific opcodes 492 OCMP // compare: ACMP. 493 ODEC // decrement: ADEC. 494 OINC // increment: AINC. 495 OEXTEND // extend: ACWD/ACDQ/ACQO. 496 OHMUL // high mul: AMUL/AIMUL for unsigned/signed (OMUL uses AIMUL for both). 497 OLROT // left rotate: AROL. 498 ORROTC // right rotate-carry: ARCR. 499 ORETJMP // return to other function 500 OPS // compare parity set (for x86 NaN check) 501 OPC // compare parity clear (for x86 NaN check) 502 OSQRT // sqrt(float64), on systems that have hw support 503 OGETG // runtime.getg() (read g pointer) 504 505 OEND 506 ) 507 508 // Nodes is a pointer to a slice of *Node. 509 // For fields that are not used in most nodes, this is used instead of 510 // a slice to save space. 511 type Nodes struct{ slice *[]*Node } 512 513 // Slice returns the entries in Nodes as a slice. 514 // Changes to the slice entries (as in s[i] = n) will be reflected in 515 // the Nodes. 516 func (n Nodes) Slice() []*Node { 517 if n.slice == nil { 518 return nil 519 } 520 return *n.slice 521 } 522 523 // Len returns the number of entries in Nodes. 524 func (n Nodes) Len() int { 525 if n.slice == nil { 526 return 0 527 } 528 return len(*n.slice) 529 } 530 531 // Index returns the i'th element of Nodes. 532 // It panics if n does not have at least i+1 elements. 533 func (n Nodes) Index(i int) *Node { 534 return (*n.slice)[i] 535 } 536 537 // First returns the first element of Nodes (same as n.Index(0)). 538 // It panics if n has no elements. 539 func (n Nodes) First() *Node { 540 return (*n.slice)[0] 541 } 542 543 // Second returns the second element of Nodes (same as n.Index(1)). 544 // It panics if n has fewer than two elements. 545 func (n Nodes) Second() *Node { 546 return (*n.slice)[1] 547 } 548 549 // Set sets n to a slice. 550 // This takes ownership of the slice. 551 func (n *Nodes) Set(s []*Node) { 552 if len(s) == 0 { 553 n.slice = nil 554 } else { 555 // Copy s and take address of t rather than s to avoid 556 // allocation in the case where len(s) == 0 (which is 557 // over 3x more common, dynamically, for make.bash). 558 t := s 559 n.slice = &t 560 } 561 } 562 563 // Set1 sets n to a slice containing a single node. 564 func (n *Nodes) Set1(node *Node) { 565 n.slice = &[]*Node{node} 566 } 567 568 // Set2 sets n to a slice containing two nodes. 569 func (n *Nodes) Set2(n1, n2 *Node) { 570 n.slice = &[]*Node{n1, n2} 571 } 572 573 // MoveNodes sets n to the contents of n2, then clears n2. 574 func (n *Nodes) MoveNodes(n2 *Nodes) { 575 n.slice = n2.slice 576 n2.slice = nil 577 } 578 579 // SetIndex sets the i'th element of Nodes to node. 580 // It panics if n does not have at least i+1 elements. 581 func (n Nodes) SetIndex(i int, node *Node) { 582 (*n.slice)[i] = node 583 } 584 585 // Addr returns the address of the i'th element of Nodes. 586 // It panics if n does not have at least i+1 elements. 587 func (n Nodes) Addr(i int) **Node { 588 return &(*n.slice)[i] 589 } 590 591 // Append appends entries to Nodes. 592 // If a slice is passed in, this will take ownership of it. 593 func (n *Nodes) Append(a ...*Node) { 594 if len(a) == 0 { 595 return 596 } 597 if n.slice == nil { 598 n.slice = &a 599 } else { 600 *n.slice = append(*n.slice, a...) 601 } 602 } 603 604 // Prepend prepends entries to Nodes. 605 // If a slice is passed in, this will take ownership of it. 606 func (n *Nodes) Prepend(a ...*Node) { 607 if len(a) == 0 { 608 return 609 } 610 if n.slice == nil { 611 n.slice = &a 612 } else { 613 *n.slice = append(a, *n.slice...) 614 } 615 } 616 617 // AppendNodes appends the contents of *n2 to n, then clears n2. 618 func (n *Nodes) AppendNodes(n2 *Nodes) { 619 switch { 620 case n2.slice == nil: 621 case n.slice == nil: 622 n.slice = n2.slice 623 default: 624 *n.slice = append(*n.slice, *n2.slice...) 625 } 626 n2.slice = nil 627 }