github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/cmd/compile/internal/ssa/func.go (about) 1 // Copyright 2015 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 package ssa 6 7 import ( 8 "cmd/internal/src" 9 "crypto/sha1" 10 "fmt" 11 "io" 12 "math" 13 "os" 14 "strings" 15 ) 16 17 type writeSyncer interface { 18 io.Writer 19 Sync() error 20 } 21 22 // A Func represents a Go func declaration (or function literal) and its body. 23 // This package compiles each Func independently. 24 // Funcs are single-use; a new Func must be created for every compiled function. 25 type Func struct { 26 Config *Config // architecture information 27 Cache *Cache // re-usable cache 28 fe Frontend // frontend state associated with this Func, callbacks into compiler frontend 29 pass *pass // current pass information (name, options, etc.) 30 Name string // e.g. bytes·Compare 31 Type Type // type signature of the function. 32 Blocks []*Block // unordered set of all basic blocks (note: not indexable by ID) 33 Entry *Block // the entry basic block 34 bid idAlloc // block ID allocator 35 vid idAlloc // value ID allocator 36 37 // Given an environment variable used for debug hash match, 38 // what file (if any) receives the yes/no logging? 39 logfiles map[string]writeSyncer 40 HTMLWriter *HTMLWriter // html writer, for debugging 41 DebugTest bool // default true unless $GOSSAHASH != ""; as a debugging aid, make new code conditional on this and use GOSSAHASH to binary search for failing cases 42 43 scheduled bool // Values in Blocks are in final order 44 NoSplit bool // true if function is marked as nosplit. Used by schedule check pass. 45 46 WBPos src.XPos // line number of first write barrier 47 48 // when register allocation is done, maps value ids to locations 49 RegAlloc []Location 50 51 // map from LocalSlot to set of Values that we want to store in that slot. 52 NamedValues map[LocalSlot][]*Value 53 // Names is a copy of NamedValues.Keys. We keep a separate list 54 // of keys to make iteration order deterministic. 55 Names []LocalSlot 56 57 freeValues *Value // free Values linked by argstorage[0]. All other fields except ID are 0/nil. 58 freeBlocks *Block // free Blocks linked by succstorage[0].b. All other fields except ID are 0/nil. 59 60 cachedPostorder []*Block // cached postorder traversal 61 cachedIdom []*Block // cached immediate dominators 62 cachedSdom SparseTree // cached dominator tree 63 cachedLoopnest *loopnest // cached loop nest information 64 65 auxmap auxmap // map from aux values to opaque ids used by CSE 66 67 constants map[int64][]*Value // constants cache, keyed by constant value; users must check value's Op and Type 68 } 69 70 // NewFunc returns a new, empty function object. 71 // Caller must set f.Config and f.Cache before using f. 72 func NewFunc(fe Frontend) *Func { 73 return &Func{fe: fe, NamedValues: make(map[LocalSlot][]*Value)} 74 } 75 76 // NumBlocks returns an integer larger than the id of any Block in the Func. 77 func (f *Func) NumBlocks() int { 78 return f.bid.num() 79 } 80 81 // NumValues returns an integer larger than the id of any Value in the Func. 82 func (f *Func) NumValues() int { 83 return f.vid.num() 84 } 85 86 // newSparseSet returns a sparse set that can store at least up to n integers. 87 func (f *Func) newSparseSet(n int) *sparseSet { 88 for i, scr := range f.Cache.scrSparse { 89 if scr != nil && scr.cap() >= n { 90 f.Cache.scrSparse[i] = nil 91 scr.clear() 92 return scr 93 } 94 } 95 return newSparseSet(n) 96 } 97 98 // retSparseSet returns a sparse set to the config's cache of sparse sets to be reused by f.newSparseSet. 99 func (f *Func) retSparseSet(ss *sparseSet) { 100 for i, scr := range f.Cache.scrSparse { 101 if scr == nil { 102 f.Cache.scrSparse[i] = ss 103 return 104 } 105 } 106 f.Cache.scrSparse = append(f.Cache.scrSparse, ss) 107 } 108 109 // newValue allocates a new Value with the given fields and places it at the end of b.Values. 110 func (f *Func) newValue(op Op, t Type, b *Block, pos src.XPos) *Value { 111 var v *Value 112 if f.freeValues != nil { 113 v = f.freeValues 114 f.freeValues = v.argstorage[0] 115 v.argstorage[0] = nil 116 } else { 117 ID := f.vid.get() 118 if int(ID) < len(f.Cache.values) { 119 v = &f.Cache.values[ID] 120 v.ID = ID 121 } else { 122 v = &Value{ID: ID} 123 } 124 } 125 v.Op = op 126 v.Type = t 127 v.Block = b 128 v.Pos = pos 129 b.Values = append(b.Values, v) 130 return v 131 } 132 133 // newValueNoBlock allocates a new Value with the given fields. 134 // The returned value is not placed in any block. Once the caller 135 // decides on a block b, it must set b.Block and append 136 // the returned value to b.Values. 137 func (f *Func) newValueNoBlock(op Op, t Type, pos src.XPos) *Value { 138 var v *Value 139 if f.freeValues != nil { 140 v = f.freeValues 141 f.freeValues = v.argstorage[0] 142 v.argstorage[0] = nil 143 } else { 144 ID := f.vid.get() 145 if int(ID) < len(f.Cache.values) { 146 v = &f.Cache.values[ID] 147 v.ID = ID 148 } else { 149 v = &Value{ID: ID} 150 } 151 } 152 v.Op = op 153 v.Type = t 154 v.Block = nil // caller must fix this. 155 v.Pos = pos 156 return v 157 } 158 159 // logPassStat writes a string key and int value as a warning in a 160 // tab-separated format easily handled by spreadsheets or awk. 161 // file names, lines, and function names are included to provide enough (?) 162 // context to allow item-by-item comparisons across runs. 163 // For example: 164 // awk 'BEGIN {FS="\t"} $3~/TIME/{sum+=$4} END{print "t(ns)=",sum}' t.log 165 func (f *Func) LogStat(key string, args ...interface{}) { 166 value := "" 167 for _, a := range args { 168 value += fmt.Sprintf("\t%v", a) 169 } 170 n := "missing_pass" 171 if f.pass != nil { 172 n = strings.Replace(f.pass.name, " ", "_", -1) 173 } 174 f.Warnl(f.Entry.Pos, "\t%s\t%s%s\t%s", n, key, value, f.Name) 175 } 176 177 // freeValue frees a value. It must no longer be referenced. 178 func (f *Func) freeValue(v *Value) { 179 if v.Block == nil { 180 f.Fatalf("trying to free an already freed value") 181 } 182 if v.Uses != 0 { 183 f.Fatalf("value %s still has %d uses", v, v.Uses) 184 } 185 // Clear everything but ID (which we reuse). 186 id := v.ID 187 188 // Values with zero arguments and OpOffPtr values might be cached, so remove them there. 189 nArgs := opcodeTable[v.Op].argLen 190 if nArgs == 0 || v.Op == OpOffPtr { 191 vv := f.constants[v.AuxInt] 192 for i, cv := range vv { 193 if v == cv { 194 vv[i] = vv[len(vv)-1] 195 vv[len(vv)-1] = nil 196 f.constants[v.AuxInt] = vv[0 : len(vv)-1] 197 break 198 } 199 } 200 } 201 *v = Value{} 202 v.ID = id 203 v.argstorage[0] = f.freeValues 204 f.freeValues = v 205 } 206 207 // newBlock allocates a new Block of the given kind and places it at the end of f.Blocks. 208 func (f *Func) NewBlock(kind BlockKind) *Block { 209 var b *Block 210 if f.freeBlocks != nil { 211 b = f.freeBlocks 212 f.freeBlocks = b.succstorage[0].b 213 b.succstorage[0].b = nil 214 } else { 215 ID := f.bid.get() 216 if int(ID) < len(f.Cache.blocks) { 217 b = &f.Cache.blocks[ID] 218 b.ID = ID 219 } else { 220 b = &Block{ID: ID} 221 } 222 } 223 b.Kind = kind 224 b.Func = f 225 b.Preds = b.predstorage[:0] 226 b.Succs = b.succstorage[:0] 227 b.Values = b.valstorage[:0] 228 f.Blocks = append(f.Blocks, b) 229 f.invalidateCFG() 230 return b 231 } 232 233 func (f *Func) freeBlock(b *Block) { 234 if b.Func == nil { 235 f.Fatalf("trying to free an already freed block") 236 } 237 // Clear everything but ID (which we reuse). 238 id := b.ID 239 *b = Block{} 240 b.ID = id 241 b.succstorage[0].b = f.freeBlocks 242 f.freeBlocks = b 243 } 244 245 // NewValue0 returns a new value in the block with no arguments and zero aux values. 246 func (b *Block) NewValue0(pos src.XPos, op Op, t Type) *Value { 247 v := b.Func.newValue(op, t, b, pos) 248 v.AuxInt = 0 249 v.Args = v.argstorage[:0] 250 return v 251 } 252 253 // NewValue returns a new value in the block with no arguments and an auxint value. 254 func (b *Block) NewValue0I(pos src.XPos, op Op, t Type, auxint int64) *Value { 255 v := b.Func.newValue(op, t, b, pos) 256 v.AuxInt = auxint 257 v.Args = v.argstorage[:0] 258 return v 259 } 260 261 // NewValue returns a new value in the block with no arguments and an aux value. 262 func (b *Block) NewValue0A(pos src.XPos, op Op, t Type, aux interface{}) *Value { 263 if _, ok := aux.(int64); ok { 264 // Disallow int64 aux values. They should be in the auxint field instead. 265 // Maybe we want to allow this at some point, but for now we disallow it 266 // to prevent errors like using NewValue1A instead of NewValue1I. 267 b.Fatalf("aux field has int64 type op=%s type=%s aux=%v", op, t, aux) 268 } 269 v := b.Func.newValue(op, t, b, pos) 270 v.AuxInt = 0 271 v.Aux = aux 272 v.Args = v.argstorage[:0] 273 return v 274 } 275 276 // NewValue returns a new value in the block with no arguments and both an auxint and aux values. 277 func (b *Block) NewValue0IA(pos src.XPos, op Op, t Type, auxint int64, aux interface{}) *Value { 278 v := b.Func.newValue(op, t, b, pos) 279 v.AuxInt = auxint 280 v.Aux = aux 281 v.Args = v.argstorage[:0] 282 return v 283 } 284 285 // NewValue1 returns a new value in the block with one argument and zero aux values. 286 func (b *Block) NewValue1(pos src.XPos, op Op, t Type, arg *Value) *Value { 287 v := b.Func.newValue(op, t, b, pos) 288 v.AuxInt = 0 289 v.Args = v.argstorage[:1] 290 v.argstorage[0] = arg 291 arg.Uses++ 292 return v 293 } 294 295 // NewValue1I returns a new value in the block with one argument and an auxint value. 296 func (b *Block) NewValue1I(pos src.XPos, op Op, t Type, auxint int64, arg *Value) *Value { 297 v := b.Func.newValue(op, t, b, pos) 298 v.AuxInt = auxint 299 v.Args = v.argstorage[:1] 300 v.argstorage[0] = arg 301 arg.Uses++ 302 return v 303 } 304 305 // NewValue1A returns a new value in the block with one argument and an aux value. 306 func (b *Block) NewValue1A(pos src.XPos, op Op, t Type, aux interface{}, arg *Value) *Value { 307 v := b.Func.newValue(op, t, b, pos) 308 v.AuxInt = 0 309 v.Aux = aux 310 v.Args = v.argstorage[:1] 311 v.argstorage[0] = arg 312 arg.Uses++ 313 return v 314 } 315 316 // NewValue1IA returns a new value in the block with one argument and both an auxint and aux values. 317 func (b *Block) NewValue1IA(pos src.XPos, op Op, t Type, auxint int64, aux interface{}, arg *Value) *Value { 318 v := b.Func.newValue(op, t, b, pos) 319 v.AuxInt = auxint 320 v.Aux = aux 321 v.Args = v.argstorage[:1] 322 v.argstorage[0] = arg 323 arg.Uses++ 324 return v 325 } 326 327 // NewValue2 returns a new value in the block with two arguments and zero aux values. 328 func (b *Block) NewValue2(pos src.XPos, op Op, t Type, arg0, arg1 *Value) *Value { 329 v := b.Func.newValue(op, t, b, pos) 330 v.AuxInt = 0 331 v.Args = v.argstorage[:2] 332 v.argstorage[0] = arg0 333 v.argstorage[1] = arg1 334 arg0.Uses++ 335 arg1.Uses++ 336 return v 337 } 338 339 // NewValue2I returns a new value in the block with two arguments and an auxint value. 340 func (b *Block) NewValue2I(pos src.XPos, op Op, t Type, auxint int64, arg0, arg1 *Value) *Value { 341 v := b.Func.newValue(op, t, b, pos) 342 v.AuxInt = auxint 343 v.Args = v.argstorage[:2] 344 v.argstorage[0] = arg0 345 v.argstorage[1] = arg1 346 arg0.Uses++ 347 arg1.Uses++ 348 return v 349 } 350 351 // NewValue3 returns a new value in the block with three arguments and zero aux values. 352 func (b *Block) NewValue3(pos src.XPos, op Op, t Type, arg0, arg1, arg2 *Value) *Value { 353 v := b.Func.newValue(op, t, b, pos) 354 v.AuxInt = 0 355 v.Args = v.argstorage[:3] 356 v.argstorage[0] = arg0 357 v.argstorage[1] = arg1 358 v.argstorage[2] = arg2 359 arg0.Uses++ 360 arg1.Uses++ 361 arg2.Uses++ 362 return v 363 } 364 365 // NewValue3I returns a new value in the block with three arguments and an auxint value. 366 func (b *Block) NewValue3I(pos src.XPos, op Op, t Type, auxint int64, arg0, arg1, arg2 *Value) *Value { 367 v := b.Func.newValue(op, t, b, pos) 368 v.AuxInt = auxint 369 v.Args = v.argstorage[:3] 370 v.argstorage[0] = arg0 371 v.argstorage[1] = arg1 372 v.argstorage[2] = arg2 373 arg0.Uses++ 374 arg1.Uses++ 375 arg2.Uses++ 376 return v 377 } 378 379 // NewValue3A returns a new value in the block with three argument and an aux value. 380 func (b *Block) NewValue3A(pos src.XPos, op Op, t Type, aux interface{}, arg0, arg1, arg2 *Value) *Value { 381 v := b.Func.newValue(op, t, b, pos) 382 v.AuxInt = 0 383 v.Aux = aux 384 v.Args = v.argstorage[:3] 385 v.argstorage[0] = arg0 386 v.argstorage[1] = arg1 387 v.argstorage[2] = arg2 388 arg0.Uses++ 389 arg1.Uses++ 390 arg2.Uses++ 391 return v 392 } 393 394 // NewValue4 returns a new value in the block with four arguments and zero aux values. 395 func (b *Block) NewValue4(pos src.XPos, op Op, t Type, arg0, arg1, arg2, arg3 *Value) *Value { 396 v := b.Func.newValue(op, t, b, pos) 397 v.AuxInt = 0 398 v.Args = []*Value{arg0, arg1, arg2, arg3} 399 arg0.Uses++ 400 arg1.Uses++ 401 arg2.Uses++ 402 arg3.Uses++ 403 return v 404 } 405 406 // constVal returns a constant value for c. 407 func (f *Func) constVal(pos src.XPos, op Op, t Type, c int64, setAuxInt bool) *Value { 408 if f.constants == nil { 409 f.constants = make(map[int64][]*Value) 410 } 411 vv := f.constants[c] 412 for _, v := range vv { 413 if v.Op == op && v.Type.Compare(t) == CMPeq { 414 if setAuxInt && v.AuxInt != c { 415 panic(fmt.Sprintf("cached const %s should have AuxInt of %d", v.LongString(), c)) 416 } 417 return v 418 } 419 } 420 var v *Value 421 if setAuxInt { 422 v = f.Entry.NewValue0I(pos, op, t, c) 423 } else { 424 v = f.Entry.NewValue0(pos, op, t) 425 } 426 f.constants[c] = append(vv, v) 427 return v 428 } 429 430 // These magic auxint values let us easily cache non-numeric constants 431 // using the same constants map while making collisions unlikely. 432 // These values are unlikely to occur in regular code and 433 // are easy to grep for in case of bugs. 434 const ( 435 constSliceMagic = 1122334455 436 constInterfaceMagic = 2233445566 437 constNilMagic = 3344556677 438 constEmptyStringMagic = 4455667788 439 ) 440 441 // ConstInt returns an int constant representing its argument. 442 func (f *Func) ConstBool(pos src.XPos, t Type, c bool) *Value { 443 i := int64(0) 444 if c { 445 i = 1 446 } 447 return f.constVal(pos, OpConstBool, t, i, true) 448 } 449 func (f *Func) ConstInt8(pos src.XPos, t Type, c int8) *Value { 450 return f.constVal(pos, OpConst8, t, int64(c), true) 451 } 452 func (f *Func) ConstInt16(pos src.XPos, t Type, c int16) *Value { 453 return f.constVal(pos, OpConst16, t, int64(c), true) 454 } 455 func (f *Func) ConstInt32(pos src.XPos, t Type, c int32) *Value { 456 return f.constVal(pos, OpConst32, t, int64(c), true) 457 } 458 func (f *Func) ConstInt64(pos src.XPos, t Type, c int64) *Value { 459 return f.constVal(pos, OpConst64, t, c, true) 460 } 461 func (f *Func) ConstFloat32(pos src.XPos, t Type, c float64) *Value { 462 return f.constVal(pos, OpConst32F, t, int64(math.Float64bits(float64(float32(c)))), true) 463 } 464 func (f *Func) ConstFloat64(pos src.XPos, t Type, c float64) *Value { 465 return f.constVal(pos, OpConst64F, t, int64(math.Float64bits(c)), true) 466 } 467 468 func (f *Func) ConstSlice(pos src.XPos, t Type) *Value { 469 return f.constVal(pos, OpConstSlice, t, constSliceMagic, false) 470 } 471 func (f *Func) ConstInterface(pos src.XPos, t Type) *Value { 472 return f.constVal(pos, OpConstInterface, t, constInterfaceMagic, false) 473 } 474 func (f *Func) ConstNil(pos src.XPos, t Type) *Value { 475 return f.constVal(pos, OpConstNil, t, constNilMagic, false) 476 } 477 func (f *Func) ConstEmptyString(pos src.XPos, t Type) *Value { 478 v := f.constVal(pos, OpConstString, t, constEmptyStringMagic, false) 479 v.Aux = "" 480 return v 481 } 482 func (f *Func) ConstOffPtrSP(pos src.XPos, t Type, c int64, sp *Value) *Value { 483 v := f.constVal(pos, OpOffPtr, t, c, true) 484 if len(v.Args) == 0 { 485 v.AddArg(sp) 486 } 487 return v 488 489 } 490 491 func (f *Func) Frontend() Frontend { return f.fe } 492 func (f *Func) Warnl(pos src.XPos, msg string, args ...interface{}) { f.fe.Warnl(pos, msg, args...) } 493 func (f *Func) Logf(msg string, args ...interface{}) { f.fe.Logf(msg, args...) } 494 func (f *Func) Log() bool { return f.fe.Log() } 495 func (f *Func) Fatalf(msg string, args ...interface{}) { f.fe.Fatalf(f.Entry.Pos, msg, args...) } 496 497 // postorder returns the reachable blocks in f in a postorder traversal. 498 func (f *Func) postorder() []*Block { 499 if f.cachedPostorder == nil { 500 f.cachedPostorder = postorder(f) 501 } 502 return f.cachedPostorder 503 } 504 505 func (f *Func) Postorder() []*Block { 506 return f.postorder() 507 } 508 509 // Idom returns a map from block ID to the immediate dominator of that block. 510 // f.Entry.ID maps to nil. Unreachable blocks map to nil as well. 511 func (f *Func) Idom() []*Block { 512 if f.cachedIdom == nil { 513 f.cachedIdom = dominators(f) 514 } 515 return f.cachedIdom 516 } 517 518 // sdom returns a sparse tree representing the dominator relationships 519 // among the blocks of f. 520 func (f *Func) sdom() SparseTree { 521 if f.cachedSdom == nil { 522 f.cachedSdom = newSparseTree(f, f.Idom()) 523 } 524 return f.cachedSdom 525 } 526 527 // loopnest returns the loop nest information for f. 528 func (f *Func) loopnest() *loopnest { 529 if f.cachedLoopnest == nil { 530 f.cachedLoopnest = loopnestfor(f) 531 } 532 return f.cachedLoopnest 533 } 534 535 // invalidateCFG tells f that its CFG has changed. 536 func (f *Func) invalidateCFG() { 537 f.cachedPostorder = nil 538 f.cachedIdom = nil 539 f.cachedSdom = nil 540 f.cachedLoopnest = nil 541 } 542 543 // DebugHashMatch returns true if environment variable evname 544 // 1) is empty (this is a special more-quickly implemented case of 3) 545 // 2) is "y" or "Y" 546 // 3) is a suffix of the sha1 hash of name 547 // 4) is a suffix of the environment variable 548 // fmt.Sprintf("%s%d", evname, n) 549 // provided that all such variables are nonempty for 0 <= i <= n 550 // Otherwise it returns false. 551 // When true is returned the message 552 // "%s triggered %s\n", evname, name 553 // is printed on the file named in environment variable 554 // GSHS_LOGFILE 555 // or standard out if that is empty or there is an error 556 // opening the file. 557 func (f *Func) DebugHashMatch(evname, name string) bool { 558 evhash := os.Getenv(evname) 559 switch evhash { 560 case "": 561 return true // default behavior with no EV is "on" 562 case "y", "Y": 563 f.logDebugHashMatch(evname, name) 564 return true 565 case "n", "N": 566 return false 567 } 568 // Check the hash of the name against a partial input hash. 569 // We use this feature to do a binary search to 570 // find a function that is incorrectly compiled. 571 hstr := "" 572 for _, b := range sha1.Sum([]byte(name)) { 573 hstr += fmt.Sprintf("%08b", b) 574 } 575 576 if strings.HasSuffix(hstr, evhash) { 577 f.logDebugHashMatch(evname, name) 578 return true 579 } 580 581 // Iteratively try additional hashes to allow tests for multi-point 582 // failure. 583 for i := 0; true; i++ { 584 ev := fmt.Sprintf("%s%d", evname, i) 585 evv := os.Getenv(ev) 586 if evv == "" { 587 break 588 } 589 if strings.HasSuffix(hstr, evv) { 590 f.logDebugHashMatch(ev, name) 591 return true 592 } 593 } 594 return false 595 } 596 597 func (f *Func) logDebugHashMatch(evname, name string) { 598 if f.logfiles == nil { 599 f.logfiles = make(map[string]writeSyncer) 600 } 601 file := f.logfiles[evname] 602 if file == nil { 603 file = os.Stdout 604 if tmpfile := os.Getenv("GSHS_LOGFILE"); tmpfile != "" { 605 var err error 606 file, err = os.Create(tmpfile) 607 if err != nil { 608 f.Fatalf("could not open hash-testing logfile %s", tmpfile) 609 } 610 } 611 f.logfiles[evname] = file 612 } 613 fmt.Fprintf(file, "%s triggered %s\n", evname, name) 614 file.Sync() 615 } 616 617 func DebugNameMatch(evname, name string) bool { 618 return os.Getenv(evname) == name 619 }