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