Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/compile/internal/gc/pgen.go

Documentation: cmd/compile/internal/gc

     1  // Copyright 2011 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 gc
     6  
     7  import (
     8  	"cmd/compile/internal/ssa"
     9  	"cmd/compile/internal/types"
    10  	"cmd/internal/dwarf"
    11  	"cmd/internal/obj"
    12  	"cmd/internal/objabi"
    13  	"cmd/internal/src"
    14  	"cmd/internal/sys"
    15  	"internal/race"
    16  	"math/rand"
    17  	"sort"
    18  	"sync"
    19  	"time"
    20  )
    21  
    22  // "Portable" code generation.
    23  
    24  var (
    25  	nBackendWorkers int     // number of concurrent backend workers, set by a compiler flag
    26  	compilequeue    []*Node // functions waiting to be compiled
    27  )
    28  
    29  func emitptrargsmap(fn *Node) {
    30  	if fn.funcname() == "_" || fn.Func.Nname.Sym.Linkname != "" {
    31  		return
    32  	}
    33  	lsym := Ctxt.Lookup(fn.Func.lsym.Name + ".args_stackmap")
    34  
    35  	nptr := int(fn.Type.ArgWidth() / int64(Widthptr))
    36  	bv := bvalloc(int32(nptr) * 2)
    37  	nbitmap := 1
    38  	if fn.Type.NumResults() > 0 {
    39  		nbitmap = 2
    40  	}
    41  	off := duint32(lsym, 0, uint32(nbitmap))
    42  	off = duint32(lsym, off, uint32(bv.n))
    43  
    44  	if fn.IsMethod() {
    45  		onebitwalktype1(fn.Type.Recvs(), 0, bv)
    46  	}
    47  	if fn.Type.NumParams() > 0 {
    48  		onebitwalktype1(fn.Type.Params(), 0, bv)
    49  	}
    50  	off = dbvec(lsym, off, bv)
    51  
    52  	if fn.Type.NumResults() > 0 {
    53  		onebitwalktype1(fn.Type.Results(), 0, bv)
    54  		off = dbvec(lsym, off, bv)
    55  	}
    56  
    57  	ggloblsym(lsym, int32(off), obj.RODATA|obj.LOCAL)
    58  }
    59  
    60  // cmpstackvarlt reports whether the stack variable a sorts before b.
    61  //
    62  // Sort the list of stack variables. Autos after anything else,
    63  // within autos, unused after used, within used, things with
    64  // pointers first, zeroed things first, and then decreasing size.
    65  // Because autos are laid out in decreasing addresses
    66  // on the stack, pointers first, zeroed things first and decreasing size
    67  // really means, in memory, things with pointers needing zeroing at
    68  // the top of the stack and increasing in size.
    69  // Non-autos sort on offset.
    70  func cmpstackvarlt(a, b *Node) bool {
    71  	if (a.Class() == PAUTO) != (b.Class() == PAUTO) {
    72  		return b.Class() == PAUTO
    73  	}
    74  
    75  	if a.Class() != PAUTO {
    76  		return a.Xoffset < b.Xoffset
    77  	}
    78  
    79  	if a.Name.Used() != b.Name.Used() {
    80  		return a.Name.Used()
    81  	}
    82  
    83  	ap := types.Haspointers(a.Type)
    84  	bp := types.Haspointers(b.Type)
    85  	if ap != bp {
    86  		return ap
    87  	}
    88  
    89  	ap = a.Name.Needzero()
    90  	bp = b.Name.Needzero()
    91  	if ap != bp {
    92  		return ap
    93  	}
    94  
    95  	if a.Type.Width != b.Type.Width {
    96  		return a.Type.Width > b.Type.Width
    97  	}
    98  
    99  	return a.Sym.Name < b.Sym.Name
   100  }
   101  
   102  // byStackvar implements sort.Interface for []*Node using cmpstackvarlt.
   103  type byStackVar []*Node
   104  
   105  func (s byStackVar) Len() int           { return len(s) }
   106  func (s byStackVar) Less(i, j int) bool { return cmpstackvarlt(s[i], s[j]) }
   107  func (s byStackVar) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
   108  
   109  func (s *ssafn) AllocFrame(f *ssa.Func) {
   110  	s.stksize = 0
   111  	s.stkptrsize = 0
   112  	fn := s.curfn.Func
   113  
   114  	// Mark the PAUTO's unused.
   115  	for _, ln := range fn.Dcl {
   116  		if ln.Class() == PAUTO {
   117  			ln.Name.SetUsed(false)
   118  		}
   119  	}
   120  
   121  	for _, l := range f.RegAlloc {
   122  		if ls, ok := l.(ssa.LocalSlot); ok {
   123  			ls.N.(*Node).Name.SetUsed(true)
   124  		}
   125  	}
   126  
   127  	scratchUsed := false
   128  	for _, b := range f.Blocks {
   129  		for _, v := range b.Values {
   130  			if n, ok := v.Aux.(*Node); ok {
   131  				switch n.Class() {
   132  				case PPARAM, PPARAMOUT:
   133  					// Don't modify nodfp; it is a global.
   134  					if n != nodfp {
   135  						n.Name.SetUsed(true)
   136  					}
   137  				case PAUTO:
   138  					n.Name.SetUsed(true)
   139  				}
   140  			}
   141  			if !scratchUsed {
   142  				scratchUsed = v.Op.UsesScratch()
   143  			}
   144  
   145  		}
   146  	}
   147  
   148  	if f.Config.NeedsFpScratch && scratchUsed {
   149  		s.scratchFpMem = tempAt(src.NoXPos, s.curfn, types.Types[TUINT64])
   150  	}
   151  
   152  	sort.Sort(byStackVar(fn.Dcl))
   153  
   154  	// Reassign stack offsets of the locals that are used.
   155  	lastHasPtr := false
   156  	for i, n := range fn.Dcl {
   157  		if n.Op != ONAME || n.Class() != PAUTO {
   158  			continue
   159  		}
   160  		if !n.Name.Used() {
   161  			fn.Dcl = fn.Dcl[:i]
   162  			break
   163  		}
   164  
   165  		dowidth(n.Type)
   166  		w := n.Type.Width
   167  		if w >= thearch.MAXWIDTH || w < 0 {
   168  			Fatalf("bad width")
   169  		}
   170  		if w == 0 && lastHasPtr {
   171  			// Pad between a pointer-containing object and a zero-sized object.
   172  			// This prevents a pointer to the zero-sized object from being interpreted
   173  			// as a pointer to the pointer-containing object (and causing it
   174  			// to be scanned when it shouldn't be). See issue 24993.
   175  			w = 1
   176  		}
   177  		s.stksize += w
   178  		s.stksize = Rnd(s.stksize, int64(n.Type.Align))
   179  		if types.Haspointers(n.Type) {
   180  			s.stkptrsize = s.stksize
   181  			lastHasPtr = true
   182  		} else {
   183  			lastHasPtr = false
   184  		}
   185  		if thearch.LinkArch.InFamily(sys.MIPS, sys.MIPS64, sys.ARM, sys.ARM64, sys.PPC64, sys.S390X) {
   186  			s.stksize = Rnd(s.stksize, int64(Widthptr))
   187  		}
   188  		n.Xoffset = -s.stksize
   189  	}
   190  
   191  	s.stksize = Rnd(s.stksize, int64(Widthreg))
   192  	s.stkptrsize = Rnd(s.stkptrsize, int64(Widthreg))
   193  }
   194  
   195  func funccompile(fn *Node) {
   196  	if Curfn != nil {
   197  		Fatalf("funccompile %v inside %v", fn.Func.Nname.Sym, Curfn.Func.Nname.Sym)
   198  	}
   199  
   200  	if fn.Type == nil {
   201  		if nerrors == 0 {
   202  			Fatalf("funccompile missing type")
   203  		}
   204  		return
   205  	}
   206  
   207  	// assign parameter offsets
   208  	dowidth(fn.Type)
   209  
   210  	if fn.Nbody.Len() == 0 {
   211  		// Initialize ABI wrappers if necessary.
   212  		fn.Func.initLSym(false)
   213  		emitptrargsmap(fn)
   214  		return
   215  	}
   216  
   217  	dclcontext = PAUTO
   218  	Curfn = fn
   219  
   220  	compile(fn)
   221  
   222  	Curfn = nil
   223  	dclcontext = PEXTERN
   224  }
   225  
   226  func compile(fn *Node) {
   227  	saveerrors()
   228  
   229  	order(fn)
   230  	if nerrors != 0 {
   231  		return
   232  	}
   233  
   234  	walk(fn)
   235  	if nerrors != 0 {
   236  		return
   237  	}
   238  	if instrumenting {
   239  		instrument(fn)
   240  	}
   241  
   242  	// From this point, there should be no uses of Curfn. Enforce that.
   243  	Curfn = nil
   244  
   245  	if fn.funcname() == "_" {
   246  		// We don't need to generate code for this function, just report errors in its body.
   247  		// At this point we've generated any errors needed.
   248  		// (Beyond here we generate only non-spec errors, like "stack frame too large".)
   249  		// See issue 29870.
   250  		return
   251  	}
   252  
   253  	// Set up the function's LSym early to avoid data races with the assemblers.
   254  	fn.Func.initLSym(true)
   255  
   256  	// Make sure type syms are declared for all types that might
   257  	// be types of stack objects. We need to do this here
   258  	// because symbols must be allocated before the parallel
   259  	// phase of the compiler.
   260  	for _, n := range fn.Func.Dcl {
   261  		switch n.Class() {
   262  		case PPARAM, PPARAMOUT, PAUTO:
   263  			if livenessShouldTrack(n) && n.Name.Addrtaken() {
   264  				dtypesym(n.Type)
   265  				// Also make sure we allocate a linker symbol
   266  				// for the stack object data, for the same reason.
   267  				if fn.Func.lsym.Func.StackObjects == nil {
   268  					fn.Func.lsym.Func.StackObjects = Ctxt.Lookup(fn.Func.lsym.Name + ".stkobj")
   269  				}
   270  			}
   271  		}
   272  	}
   273  
   274  	if compilenow(fn) {
   275  		compileSSA(fn, 0)
   276  	} else {
   277  		compilequeue = append(compilequeue, fn)
   278  	}
   279  }
   280  
   281  // compilenow reports whether to compile immediately.
   282  // If functions are not compiled immediately,
   283  // they are enqueued in compilequeue,
   284  // which is drained by compileFunctions.
   285  func compilenow(fn *Node) bool {
   286  	// Issue 38068: if this function is a method AND an inline
   287  	// candidate AND was not inlined (yet), put it onto the compile
   288  	// queue instead of compiling it immediately. This is in case we
   289  	// wind up inlining it into a method wrapper that is generated by
   290  	// compiling a function later on in the xtop list.
   291  	if fn.IsMethod() && isInlinableButNotInlined(fn) {
   292  		return false
   293  	}
   294  	return nBackendWorkers == 1 && Debug_compilelater == 0
   295  }
   296  
   297  // isInlinableButNotInlined returns true if 'fn' was marked as an
   298  // inline candidate but then never inlined (presumably because we
   299  // found no call sites).
   300  func isInlinableButNotInlined(fn *Node) bool {
   301  	if fn.Func.Nname.Func.Inl == nil {
   302  		return false
   303  	}
   304  	if fn.Sym == nil {
   305  		return true
   306  	}
   307  	return !fn.Sym.Linksym().WasInlined()
   308  }
   309  
   310  const maxStackSize = 1 << 30
   311  
   312  // compileSSA builds an SSA backend function,
   313  // uses it to generate a plist,
   314  // and flushes that plist to machine code.
   315  // worker indicates which of the backend workers is doing the processing.
   316  func compileSSA(fn *Node, worker int) {
   317  	f := buildssa(fn, worker)
   318  	// Note: check arg size to fix issue 25507.
   319  	if f.Frontend().(*ssafn).stksize >= maxStackSize || fn.Type.ArgWidth() >= maxStackSize {
   320  		largeStackFramesMu.Lock()
   321  		largeStackFrames = append(largeStackFrames, largeStack{locals: f.Frontend().(*ssafn).stksize, args: fn.Type.ArgWidth(), pos: fn.Pos})
   322  		largeStackFramesMu.Unlock()
   323  		return
   324  	}
   325  	pp := newProgs(fn, worker)
   326  	defer pp.Free()
   327  	genssa(f, pp)
   328  	// Check frame size again.
   329  	// The check above included only the space needed for local variables.
   330  	// After genssa, the space needed includes local variables and the callee arg region.
   331  	// We must do this check prior to calling pp.Flush.
   332  	// If there are any oversized stack frames,
   333  	// the assembler may emit inscrutable complaints about invalid instructions.
   334  	if pp.Text.To.Offset >= maxStackSize {
   335  		largeStackFramesMu.Lock()
   336  		locals := f.Frontend().(*ssafn).stksize
   337  		largeStackFrames = append(largeStackFrames, largeStack{locals: locals, args: fn.Type.ArgWidth(), callee: pp.Text.To.Offset - locals, pos: fn.Pos})
   338  		largeStackFramesMu.Unlock()
   339  		return
   340  	}
   341  
   342  	pp.Flush() // assemble, fill in boilerplate, etc.
   343  	// fieldtrack must be called after pp.Flush. See issue 20014.
   344  	fieldtrack(pp.Text.From.Sym, fn.Func.FieldTrack)
   345  }
   346  
   347  func init() {
   348  	if race.Enabled {
   349  		rand.Seed(time.Now().UnixNano())
   350  	}
   351  }
   352  
   353  // compileFunctions compiles all functions in compilequeue.
   354  // It fans out nBackendWorkers to do the work
   355  // and waits for them to complete.
   356  func compileFunctions() {
   357  	if len(compilequeue) != 0 {
   358  		sizeCalculationDisabled = true // not safe to calculate sizes concurrently
   359  		if race.Enabled {
   360  			// Randomize compilation order to try to shake out races.
   361  			tmp := make([]*Node, len(compilequeue))
   362  			perm := rand.Perm(len(compilequeue))
   363  			for i, v := range perm {
   364  				tmp[v] = compilequeue[i]
   365  			}
   366  			copy(compilequeue, tmp)
   367  		} else {
   368  			// Compile the longest functions first,
   369  			// since they're most likely to be the slowest.
   370  			// This helps avoid stragglers.
   371  			sort.Slice(compilequeue, func(i, j int) bool {
   372  				return compilequeue[i].Nbody.Len() > compilequeue[j].Nbody.Len()
   373  			})
   374  		}
   375  		var wg sync.WaitGroup
   376  		Ctxt.InParallel = true
   377  		c := make(chan *Node, nBackendWorkers)
   378  		for i := 0; i < nBackendWorkers; i++ {
   379  			wg.Add(1)
   380  			go func(worker int) {
   381  				for fn := range c {
   382  					compileSSA(fn, worker)
   383  				}
   384  				wg.Done()
   385  			}(i)
   386  		}
   387  		for _, fn := range compilequeue {
   388  			c <- fn
   389  		}
   390  		close(c)
   391  		compilequeue = nil
   392  		wg.Wait()
   393  		Ctxt.InParallel = false
   394  		sizeCalculationDisabled = false
   395  	}
   396  }
   397  
   398  func debuginfo(fnsym *obj.LSym, infosym *obj.LSym, curfn interface{}) ([]dwarf.Scope, dwarf.InlCalls) {
   399  	fn := curfn.(*Node)
   400  	if fn.Func.Nname != nil {
   401  		if expect := fn.Func.Nname.Sym.Linksym(); fnsym != expect {
   402  			Fatalf("unexpected fnsym: %v != %v", fnsym, expect)
   403  		}
   404  	}
   405  
   406  	var apdecls []*Node
   407  	// Populate decls for fn.
   408  	for _, n := range fn.Func.Dcl {
   409  		if n.Op != ONAME { // might be OTYPE or OLITERAL
   410  			continue
   411  		}
   412  		switch n.Class() {
   413  		case PAUTO:
   414  			if !n.Name.Used() {
   415  				// Text == nil -> generating abstract function
   416  				if fnsym.Func.Text != nil {
   417  					Fatalf("debuginfo unused node (AllocFrame should truncate fn.Func.Dcl)")
   418  				}
   419  				continue
   420  			}
   421  		case PPARAM, PPARAMOUT:
   422  		default:
   423  			continue
   424  		}
   425  		apdecls = append(apdecls, n)
   426  		fnsym.Func.RecordAutoType(ngotype(n).Linksym())
   427  	}
   428  
   429  	decls, dwarfVars := createDwarfVars(fnsym, fn.Func, apdecls)
   430  
   431  	// For each type referenced by the functions auto vars, attach a
   432  	// dummy relocation to the function symbol to insure that the type
   433  	// included in DWARF processing during linking.
   434  	typesyms := []*obj.LSym{}
   435  	for t, _ := range fnsym.Func.Autot {
   436  		typesyms = append(typesyms, t)
   437  	}
   438  	sort.Sort(obj.BySymName(typesyms))
   439  	for _, sym := range typesyms {
   440  		r := obj.Addrel(infosym)
   441  		r.Sym = sym
   442  		r.Type = objabi.R_USETYPE
   443  	}
   444  	fnsym.Func.Autot = nil
   445  
   446  	var varScopes []ScopeID
   447  	for _, decl := range decls {
   448  		pos := declPos(decl)
   449  		varScopes = append(varScopes, findScope(fn.Func.Marks, pos))
   450  	}
   451  
   452  	scopes := assembleScopes(fnsym, fn, dwarfVars, varScopes)
   453  	var inlcalls dwarf.InlCalls
   454  	if genDwarfInline > 0 {
   455  		inlcalls = assembleInlines(fnsym, dwarfVars)
   456  	}
   457  	return scopes, inlcalls
   458  }
   459  
   460  func declPos(decl *Node) src.XPos {
   461  	if decl.Name.Defn != nil && (decl.Name.Captured() || decl.Name.Byval()) {
   462  		// It's not clear which position is correct for captured variables here:
   463  		// * decl.Pos is the wrong position for captured variables, in the inner
   464  		//   function, but it is the right position in the outer function.
   465  		// * decl.Name.Defn is nil for captured variables that were arguments
   466  		//   on the outer function, however the decl.Pos for those seems to be
   467  		//   correct.
   468  		// * decl.Name.Defn is the "wrong" thing for variables declared in the
   469  		//   header of a type switch, it's their position in the header, rather
   470  		//   than the position of the case statement. In principle this is the
   471  		//   right thing, but here we prefer the latter because it makes each
   472  		//   instance of the header variable local to the lexical block of its
   473  		//   case statement.
   474  		// This code is probably wrong for type switch variables that are also
   475  		// captured.
   476  		return decl.Name.Defn.Pos
   477  	}
   478  	return decl.Pos
   479  }
   480  
   481  // createSimpleVars creates a DWARF entry for every variable declared in the
   482  // function, claiming that they are permanently on the stack.
   483  func createSimpleVars(apDecls []*Node) ([]*Node, []*dwarf.Var, map[*Node]bool) {
   484  	var vars []*dwarf.Var
   485  	var decls []*Node
   486  	selected := make(map[*Node]bool)
   487  	for _, n := range apDecls {
   488  		if n.IsAutoTmp() {
   489  			continue
   490  		}
   491  
   492  		decls = append(decls, n)
   493  		vars = append(vars, createSimpleVar(n))
   494  		selected[n] = true
   495  	}
   496  	return decls, vars, selected
   497  }
   498  
   499  func createSimpleVar(n *Node) *dwarf.Var {
   500  	var abbrev int
   501  	offs := n.Xoffset
   502  
   503  	switch n.Class() {
   504  	case PAUTO:
   505  		abbrev = dwarf.DW_ABRV_AUTO
   506  		if Ctxt.FixedFrameSize() == 0 {
   507  			offs -= int64(Widthptr)
   508  		}
   509  		if objabi.Framepointer_enabled(objabi.GOOS, objabi.GOARCH) || objabi.GOARCH == "arm64" {
   510  			// There is a word space for FP on ARM64 even if the frame pointer is disabled
   511  			offs -= int64(Widthptr)
   512  		}
   513  
   514  	case PPARAM, PPARAMOUT:
   515  		abbrev = dwarf.DW_ABRV_PARAM
   516  		offs += Ctxt.FixedFrameSize()
   517  	default:
   518  		Fatalf("createSimpleVar unexpected class %v for node %v", n.Class(), n)
   519  	}
   520  
   521  	typename := dwarf.InfoPrefix + typesymname(n.Type)
   522  	inlIndex := 0
   523  	if genDwarfInline > 1 {
   524  		if n.Name.InlFormal() || n.Name.InlLocal() {
   525  			inlIndex = posInlIndex(n.Pos) + 1
   526  			if n.Name.InlFormal() {
   527  				abbrev = dwarf.DW_ABRV_PARAM
   528  			}
   529  		}
   530  	}
   531  	declpos := Ctxt.InnermostPos(declPos(n))
   532  	return &dwarf.Var{
   533  		Name:          n.Sym.Name,
   534  		IsReturnValue: n.Class() == PPARAMOUT,
   535  		IsInlFormal:   n.Name.InlFormal(),
   536  		Abbrev:        abbrev,
   537  		StackOffset:   int32(offs),
   538  		Type:          Ctxt.Lookup(typename),
   539  		DeclFile:      declpos.RelFilename(),
   540  		DeclLine:      declpos.RelLine(),
   541  		DeclCol:       declpos.Col(),
   542  		InlIndex:      int32(inlIndex),
   543  		ChildIndex:    -1,
   544  	}
   545  }
   546  
   547  // createComplexVars creates recomposed DWARF vars with location lists,
   548  // suitable for describing optimized code.
   549  func createComplexVars(fn *Func) ([]*Node, []*dwarf.Var, map[*Node]bool) {
   550  	debugInfo := fn.DebugInfo
   551  
   552  	// Produce a DWARF variable entry for each user variable.
   553  	var decls []*Node
   554  	var vars []*dwarf.Var
   555  	ssaVars := make(map[*Node]bool)
   556  
   557  	for varID, dvar := range debugInfo.Vars {
   558  		n := dvar.(*Node)
   559  		ssaVars[n] = true
   560  		for _, slot := range debugInfo.VarSlots[varID] {
   561  			ssaVars[debugInfo.Slots[slot].N.(*Node)] = true
   562  		}
   563  
   564  		if dvar := createComplexVar(fn, ssa.VarID(varID)); dvar != nil {
   565  			decls = append(decls, n)
   566  			vars = append(vars, dvar)
   567  		}
   568  	}
   569  
   570  	return decls, vars, ssaVars
   571  }
   572  
   573  // createDwarfVars process fn, returning a list of DWARF variables and the
   574  // Nodes they represent.
   575  func createDwarfVars(fnsym *obj.LSym, fn *Func, apDecls []*Node) ([]*Node, []*dwarf.Var) {
   576  	// Collect a raw list of DWARF vars.
   577  	var vars []*dwarf.Var
   578  	var decls []*Node
   579  	var selected map[*Node]bool
   580  	if Ctxt.Flag_locationlists && Ctxt.Flag_optimize && fn.DebugInfo != nil {
   581  		decls, vars, selected = createComplexVars(fn)
   582  	} else {
   583  		decls, vars, selected = createSimpleVars(apDecls)
   584  	}
   585  
   586  	dcl := apDecls
   587  	if fnsym.WasInlined() {
   588  		dcl = preInliningDcls(fnsym)
   589  	}
   590  
   591  	// If optimization is enabled, the list above will typically be
   592  	// missing some of the original pre-optimization variables in the
   593  	// function (they may have been promoted to registers, folded into
   594  	// constants, dead-coded away, etc).  Input arguments not eligible
   595  	// for SSA optimization are also missing.  Here we add back in entries
   596  	// for selected missing vars. Note that the recipe below creates a
   597  	// conservative location. The idea here is that we want to
   598  	// communicate to the user that "yes, there is a variable named X
   599  	// in this function, but no, I don't have enough information to
   600  	// reliably report its contents."
   601  	// For non-SSA-able arguments, however, the correct information
   602  	// is known -- they have a single home on the stack.
   603  	for _, n := range dcl {
   604  		if _, found := selected[n]; found {
   605  			continue
   606  		}
   607  		c := n.Sym.Name[0]
   608  		if c == '.' || n.Type.IsUntyped() {
   609  			continue
   610  		}
   611  		if n.Class() == PPARAM && !canSSAType(n.Type) {
   612  			// SSA-able args get location lists, and may move in and
   613  			// out of registers, so those are handled elsewhere.
   614  			// Autos and named output params seem to get handled
   615  			// with VARDEF, which creates location lists.
   616  			// Args not of SSA-able type are treated here; they
   617  			// are homed on the stack in a single place for the
   618  			// entire call.
   619  			vars = append(vars, createSimpleVar(n))
   620  			decls = append(decls, n)
   621  			continue
   622  		}
   623  		typename := dwarf.InfoPrefix + typesymname(n.Type)
   624  		decls = append(decls, n)
   625  		abbrev := dwarf.DW_ABRV_AUTO_LOCLIST
   626  		isReturnValue := (n.Class() == PPARAMOUT)
   627  		if n.Class() == PPARAM || n.Class() == PPARAMOUT {
   628  			abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   629  		} else if n.Class() == PAUTOHEAP {
   630  			// If dcl in question has been promoted to heap, do a bit
   631  			// of extra work to recover original class (auto or param);
   632  			// see issue 30908. This insures that we get the proper
   633  			// signature in the abstract function DIE, but leaves a
   634  			// misleading location for the param (we want pointer-to-heap
   635  			// and not stack).
   636  			// TODO(thanm): generate a better location expression
   637  			stackcopy := n.Name.Param.Stackcopy
   638  			if stackcopy != nil && (stackcopy.Class() == PPARAM || stackcopy.Class() == PPARAMOUT) {
   639  				abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   640  				isReturnValue = (stackcopy.Class() == PPARAMOUT)
   641  			}
   642  		}
   643  		inlIndex := 0
   644  		if genDwarfInline > 1 {
   645  			if n.Name.InlFormal() || n.Name.InlLocal() {
   646  				inlIndex = posInlIndex(n.Pos) + 1
   647  				if n.Name.InlFormal() {
   648  					abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   649  				}
   650  			}
   651  		}
   652  		declpos := Ctxt.InnermostPos(n.Pos)
   653  		vars = append(vars, &dwarf.Var{
   654  			Name:          n.Sym.Name,
   655  			IsReturnValue: isReturnValue,
   656  			Abbrev:        abbrev,
   657  			StackOffset:   int32(n.Xoffset),
   658  			Type:          Ctxt.Lookup(typename),
   659  			DeclFile:      declpos.RelFilename(),
   660  			DeclLine:      declpos.RelLine(),
   661  			DeclCol:       declpos.Col(),
   662  			InlIndex:      int32(inlIndex),
   663  			ChildIndex:    -1,
   664  		})
   665  		// Record go type of to insure that it gets emitted by the linker.
   666  		fnsym.Func.RecordAutoType(ngotype(n).Linksym())
   667  	}
   668  
   669  	return decls, vars
   670  }
   671  
   672  // Given a function that was inlined at some point during the
   673  // compilation, return a sorted list of nodes corresponding to the
   674  // autos/locals in that function prior to inlining. If this is a
   675  // function that is not local to the package being compiled, then the
   676  // names of the variables may have been "versioned" to avoid conflicts
   677  // with local vars; disregard this versioning when sorting.
   678  func preInliningDcls(fnsym *obj.LSym) []*Node {
   679  	fn := Ctxt.DwFixups.GetPrecursorFunc(fnsym).(*Node)
   680  	var rdcl []*Node
   681  	for _, n := range fn.Func.Inl.Dcl {
   682  		c := n.Sym.Name[0]
   683  		// Avoid reporting "_" parameters, since if there are more than
   684  		// one, it can result in a collision later on, as in #23179.
   685  		if unversion(n.Sym.Name) == "_" || c == '.' || n.Type.IsUntyped() {
   686  			continue
   687  		}
   688  		rdcl = append(rdcl, n)
   689  	}
   690  	return rdcl
   691  }
   692  
   693  // stackOffset returns the stack location of a LocalSlot relative to the
   694  // stack pointer, suitable for use in a DWARF location entry. This has nothing
   695  // to do with its offset in the user variable.
   696  func stackOffset(slot ssa.LocalSlot) int32 {
   697  	n := slot.N.(*Node)
   698  	var base int64
   699  	switch n.Class() {
   700  	case PAUTO:
   701  		if Ctxt.FixedFrameSize() == 0 {
   702  			base -= int64(Widthptr)
   703  		}
   704  		if objabi.Framepointer_enabled(objabi.GOOS, objabi.GOARCH) || objabi.GOARCH == "arm64" {
   705  			// There is a word space for FP on ARM64 even if the frame pointer is disabled
   706  			base -= int64(Widthptr)
   707  		}
   708  	case PPARAM, PPARAMOUT:
   709  		base += Ctxt.FixedFrameSize()
   710  	}
   711  	return int32(base + n.Xoffset + slot.Off)
   712  }
   713  
   714  // createComplexVar builds a single DWARF variable entry and location list.
   715  func createComplexVar(fn *Func, varID ssa.VarID) *dwarf.Var {
   716  	debug := fn.DebugInfo
   717  	n := debug.Vars[varID].(*Node)
   718  
   719  	var abbrev int
   720  	switch n.Class() {
   721  	case PAUTO:
   722  		abbrev = dwarf.DW_ABRV_AUTO_LOCLIST
   723  	case PPARAM, PPARAMOUT:
   724  		abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   725  	default:
   726  		return nil
   727  	}
   728  
   729  	gotype := ngotype(n).Linksym()
   730  	typename := dwarf.InfoPrefix + gotype.Name[len("type."):]
   731  	inlIndex := 0
   732  	if genDwarfInline > 1 {
   733  		if n.Name.InlFormal() || n.Name.InlLocal() {
   734  			inlIndex = posInlIndex(n.Pos) + 1
   735  			if n.Name.InlFormal() {
   736  				abbrev = dwarf.DW_ABRV_PARAM_LOCLIST
   737  			}
   738  		}
   739  	}
   740  	declpos := Ctxt.InnermostPos(n.Pos)
   741  	dvar := &dwarf.Var{
   742  		Name:          n.Sym.Name,
   743  		IsReturnValue: n.Class() == PPARAMOUT,
   744  		IsInlFormal:   n.Name.InlFormal(),
   745  		Abbrev:        abbrev,
   746  		Type:          Ctxt.Lookup(typename),
   747  		// The stack offset is used as a sorting key, so for decomposed
   748  		// variables just give it the first one. It's not used otherwise.
   749  		// This won't work well if the first slot hasn't been assigned a stack
   750  		// location, but it's not obvious how to do better.
   751  		StackOffset: stackOffset(debug.Slots[debug.VarSlots[varID][0]]),
   752  		DeclFile:    declpos.RelFilename(),
   753  		DeclLine:    declpos.RelLine(),
   754  		DeclCol:     declpos.Col(),
   755  		InlIndex:    int32(inlIndex),
   756  		ChildIndex:  -1,
   757  	}
   758  	list := debug.LocationLists[varID]
   759  	if len(list) != 0 {
   760  		dvar.PutLocationList = func(listSym, startPC dwarf.Sym) {
   761  			debug.PutLocationList(list, Ctxt, listSym.(*obj.LSym), startPC.(*obj.LSym))
   762  		}
   763  	}
   764  	return dvar
   765  }
   766  
   767  // fieldtrack adds R_USEFIELD relocations to fnsym to record any
   768  // struct fields that it used.
   769  func fieldtrack(fnsym *obj.LSym, tracked map[*types.Sym]struct{}) {
   770  	if fnsym == nil {
   771  		return
   772  	}
   773  	if objabi.Fieldtrack_enabled == 0 || len(tracked) == 0 {
   774  		return
   775  	}
   776  
   777  	trackSyms := make([]*types.Sym, 0, len(tracked))
   778  	for sym := range tracked {
   779  		trackSyms = append(trackSyms, sym)
   780  	}
   781  	sort.Sort(symByName(trackSyms))
   782  	for _, sym := range trackSyms {
   783  		r := obj.Addrel(fnsym)
   784  		r.Sym = sym.Linksym()
   785  		r.Type = objabi.R_USEFIELD
   786  	}
   787  }
   788  
   789  type symByName []*types.Sym
   790  
   791  func (a symByName) Len() int           { return len(a) }
   792  func (a symByName) Less(i, j int) bool { return a[i].Name < a[j].Name }
   793  func (a symByName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
   794  

View as plain text