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