Source file src/cmd/compile/internal/dwarfgen/dwarf.go

     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 dwarfgen
     6  
     7  import (
     8  	"bytes"
     9  	"flag"
    10  	"fmt"
    11  	"internal/buildcfg"
    12  	"slices"
    13  	"sort"
    14  	"strings"
    15  
    16  	"cmd/compile/internal/base"
    17  	"cmd/compile/internal/ir"
    18  	"cmd/compile/internal/reflectdata"
    19  	"cmd/compile/internal/ssa"
    20  	"cmd/compile/internal/ssa/ssadebug"
    21  	"cmd/compile/internal/ssagen"
    22  	"cmd/compile/internal/typecheck"
    23  	"cmd/compile/internal/types"
    24  	"cmd/internal/dwarf"
    25  	"cmd/internal/obj"
    26  	"cmd/internal/objabi"
    27  	"cmd/internal/src"
    28  )
    29  
    30  func Info(ctxt *obj.Link, fnsym *obj.LSym, infosym *obj.LSym, curfn obj.Func) (scopes []dwarf.Scope, inlcalls dwarf.InlCalls) {
    31  	fn := curfn.(*ir.Func)
    32  
    33  	if fn.Nname != nil {
    34  		expect := fn.Linksym()
    35  		if fnsym.ABI() == obj.ABI0 {
    36  			expect = fn.LinksymABI(obj.ABI0)
    37  		}
    38  		if fnsym != expect {
    39  			base.Fatalf("unexpected fnsym: %v != %v", fnsym, expect)
    40  		}
    41  	}
    42  
    43  	// Back when there were two different *Funcs for a function, this code
    44  	// was not consistent about whether a particular *Node being processed
    45  	// was an ODCLFUNC or ONAME node. Partly this is because inlined function
    46  	// bodies have no ODCLFUNC node, which was it's own inconsistency.
    47  	// In any event, the handling of the two different nodes for DWARF purposes
    48  	// was subtly different, likely in unintended ways. CL 272253 merged the
    49  	// two nodes' Func fields, so that code sees the same *Func whether it is
    50  	// holding the ODCLFUNC or the ONAME. This resulted in changes in the
    51  	// DWARF output. To preserve the existing DWARF output and leave an
    52  	// intentional change for a future CL, this code does the following when
    53  	// fn.Op == ONAME:
    54  	//
    55  	// 1. Disallow use of createComplexVars in createDwarfVars.
    56  	//    It was not possible to reach that code for an ONAME before,
    57  	//    because the DebugInfo was set only on the ODCLFUNC Func.
    58  	//    Calling into it in the ONAME case causes an index out of bounds panic.
    59  	//
    60  	// 2. Do not populate apdecls. fn.Func.Dcl was in the ODCLFUNC Func,
    61  	//    not the ONAME Func. Populating apdecls for the ONAME case results
    62  	//    in selected being populated after createSimpleVars is called in
    63  	//    createDwarfVars, and then that causes the loop to skip all the entries
    64  	//    in dcl, meaning that the RecordAutoType calls don't happen.
    65  	//
    66  	// These two adjustments keep toolstash -cmp working for now.
    67  	// Deciding the right answer is, as they say, future work.
    68  	//
    69  	// We can tell the difference between the old ODCLFUNC and ONAME
    70  	// cases by looking at the infosym.Name. If it's empty, DebugInfo is
    71  	// being called from (*obj.Link).populateDWARF, which used to use
    72  	// the ODCLFUNC. If it's non-empty (the name will end in $abstract),
    73  	// DebugInfo is being called from (*obj.Link).DwarfAbstractFunc,
    74  	// which used to use the ONAME form.
    75  	isODCLFUNC := infosym.Name == ""
    76  
    77  	var apdecls []*ir.Name
    78  	// Populate decls for fn.
    79  	if isODCLFUNC {
    80  		for _, n := range fn.Dcl {
    81  			if n.Op() != ir.ONAME { // might be OTYPE or OLITERAL
    82  				continue
    83  			}
    84  			switch n.Class {
    85  			case ir.PAUTO:
    86  				if !n.Used() {
    87  					// Text == nil -> generating abstract function
    88  					if fnsym.Func().Text != nil {
    89  						base.Fatalf("debuginfo unused node (AllocFrame should truncate fn.Func.Dcl)")
    90  					}
    91  					continue
    92  				}
    93  			case ir.PPARAM, ir.PPARAMOUT:
    94  			default:
    95  				continue
    96  			}
    97  			if !shouldEmitDwarfVar(n) {
    98  				continue
    99  			}
   100  			apdecls = append(apdecls, n)
   101  			if n.Type().Kind() == types.TSSA {
   102  				// Can happen for TypeInt128 types. This only happens for
   103  				// spill locations, so not a huge deal.
   104  				continue
   105  			}
   106  			fnsym.Func().RecordAutoType(reflectdata.TypeLinksym(n.Type()))
   107  		}
   108  	}
   109  
   110  	var closureVars map[*ir.Name]int64
   111  	if fn.Needctxt() {
   112  		closureVars = make(map[*ir.Name]int64)
   113  		csiter := typecheck.NewClosureStructIter(fn.ClosureVars)
   114  		for {
   115  			n, _, offset := csiter.Next()
   116  			if n == nil {
   117  				break
   118  			}
   119  			closureVars[n] = offset
   120  			if n.Heapaddr != nil {
   121  				closureVars[n.Heapaddr] = offset
   122  			}
   123  		}
   124  	}
   125  
   126  	decls, dwarfVars := createDwarfVars(fnsym, isODCLFUNC, fn, apdecls, closureVars)
   127  
   128  	// For each type referenced by the functions auto vars but not
   129  	// already referenced by a dwarf var, attach an R_USETYPE relocation to
   130  	// the function symbol to insure that the type included in DWARF
   131  	// processing during linking.
   132  	// Do the same with R_USEIFACE relocations from the function symbol for the
   133  	// same reason.
   134  	// All these R_USETYPE relocations are only looked at if the function
   135  	// survives deadcode elimination in the linker.
   136  	typesyms := []*obj.LSym{}
   137  	for t := range fnsym.Func().Autot {
   138  		typesyms = append(typesyms, t)
   139  	}
   140  	for i := range fnsym.R {
   141  		if fnsym.R[i].Type == objabi.R_USEIFACE && !strings.HasPrefix(fnsym.R[i].Sym.Name, "go:itab.") {
   142  			// Types referenced through itab will be referenced from somewhere else
   143  			typesyms = append(typesyms, fnsym.R[i].Sym)
   144  		}
   145  	}
   146  	slices.SortFunc(typesyms, func(a, b *obj.LSym) int {
   147  		return strings.Compare(a.Name, b.Name)
   148  	})
   149  	var lastsym *obj.LSym
   150  	for _, sym := range typesyms {
   151  		if sym == lastsym {
   152  			continue
   153  		}
   154  		lastsym = sym
   155  		infosym.AddRel(ctxt, obj.Reloc{Type: objabi.R_USETYPE, Sym: sym})
   156  	}
   157  	fnsym.Func().Autot = nil
   158  
   159  	var varScopes []ir.ScopeID
   160  	for _, decl := range decls {
   161  		pos := declPos(decl)
   162  		varScopes = append(varScopes, findScope(fn.Marks, pos))
   163  	}
   164  
   165  	scopes = assembleScopes(fnsym, fn, dwarfVars, varScopes)
   166  	if base.Flag.GenDwarfInl > 0 {
   167  		inlcalls = assembleInlines(fnsym, dwarfVars)
   168  	}
   169  	return scopes, inlcalls
   170  }
   171  
   172  func declPos(decl *ir.Name) src.XPos {
   173  	return decl.Canonical().Pos()
   174  }
   175  
   176  // createDwarfVars process fn, returning a list of DWARF variables and the
   177  // Nodes they represent.
   178  func createDwarfVars(fnsym *obj.LSym, complexOK bool, fn *ir.Func, apDecls []*ir.Name, closureVars map[*ir.Name]int64) ([]*ir.Name, []*dwarf.Var) {
   179  	// Collect a raw list of DWARF vars.
   180  	var vars []*dwarf.Var
   181  	var decls []*ir.Name
   182  
   183  	// Build a VarID lookup map for SSA debug info if available.
   184  	var debug *ssadebug.FuncDebug
   185  	var varIDMap map[*ir.Name]ssa.VarID
   186  	if fn.DebugInfo != nil {
   187  		debug = fn.DebugInfo.(*ssadebug.FuncDebug)
   188  		varIDMap = make(map[*ir.Name]ssa.VarID, len(debug.Vars))
   189  		for i, n := range debug.Vars {
   190  			varIDMap[n] = ssa.VarID(i)
   191  		}
   192  	}
   193  	canUseComplex := complexOK && debug != nil
   194  
   195  	// markVarSeen marks a variable and all its associated slot names as seen.
   196  	// This is needed because decomposed variables may have slots whose ir.Name
   197  	// differs from the variable itself (e.g., PAUTO vs PPARAMOUT for the same
   198  	// logical variable). Without this, the dcl loop could create duplicate
   199  	// conservative entries for names that are already covered by a complex var.
   200  	seen := make(map[*ir.Name]bool)
   201  	markVarSeen := func(n *ir.Name, varID ssa.VarID) {
   202  		seen[n] = true
   203  		if debug != nil && int(varID) < len(debug.VarSlots) {
   204  			for _, slot := range debug.VarSlots[varID] {
   205  				seen[debug.Slots[slot].N] = true
   206  			}
   207  		}
   208  	}
   209  
   210  	// Unified loop: for each variable in apDecls, try createComplexVar
   211  	// (SSA debug info) first, then fall back to createSimpleVar.
   212  	for _, n := range apDecls {
   213  		if !shouldEmitDwarfVar(n) {
   214  			continue
   215  		}
   216  		if canUseComplex {
   217  			if vid, ok := varIDMap[n]; ok {
   218  				if dvar := createComplexVar(fnsym, fn, vid, closureVars); dvar != nil {
   219  					decls = append(decls, n)
   220  					vars = append(vars, dvar)
   221  					markVarSeen(n, vid)
   222  					continue
   223  				}
   224  			}
   225  		}
   226  		seen[n] = true
   227  		decls = append(decls, n)
   228  		vars = append(vars, createSimpleVar(fnsym, n, closureVars))
   229  	}
   230  
   231  	// Add SSA-tracked vars not in apDecls.
   232  	if canUseComplex {
   233  		for i, n := range debug.Vars {
   234  			if seen[n] {
   235  				continue
   236  			}
   237  			if !shouldEmitDwarfVar(n) {
   238  				continue
   239  			}
   240  			if dvar := createComplexVar(fnsym, fn, ssa.VarID(i), closureVars); dvar != nil {
   241  				decls = append(decls, n)
   242  				vars = append(vars, dvar)
   243  				markVarSeen(n, ssa.VarID(i))
   244  			}
   245  		}
   246  	}
   247  
   248  	// Recover declarations eliminated by the stackframe pass. Inlined
   249  	// declarations still belong to their concrete inline instance even when
   250  	// optimization has removed all of their named values.
   251  	if debug != nil {
   252  		for _, n := range debug.OptDcl {
   253  			if seen[n] || !shouldEmitDwarfVar(n) {
   254  				continue
   255  			}
   256  			// There is no allocated stack slot for these declarations. Do not
   257  			// use createSimpleVar, which would invent a location for them.
   258  			if n.InlLocal() || n.InlFormal() {
   259  				decls = append(decls, n)
   260  				vars = append(vars, createConservativeVar(fnsym, fn, n, closureVars))
   261  				seen[n] = true
   262  				continue
   263  			}
   264  			if n.Class != ir.PAUTO {
   265  				continue
   266  			}
   267  			types.CalcSize(n.Type())
   268  			if n.Type().Size() == 0 {
   269  				decls = append(decls, n)
   270  				vars = append(vars, createSimpleVar(fnsym, n, closureVars))
   271  				vars[len(vars)-1].StackOffset = 0
   272  				fnsym.Func().RecordAutoType(reflectdata.TypeLinksym(n.Type()))
   273  				seen[n] = true
   274  			}
   275  		}
   276  	}
   277  
   278  	// For inlined functions or functions with register output params,
   279  	// collect additional declarations that may not be in apDecls.
   280  	dcl := apDecls
   281  	if fnsym.WasInlined() {
   282  		dcl = preInliningDcls(fnsym)
   283  	} else if debug != nil {
   284  		// The backend's stackframe pass prunes away entries from the
   285  		// fn's Dcl list, including PARAMOUT nodes that correspond to
   286  		// output params passed in registers. Add back in these
   287  		// entries here so that we can process them properly during
   288  		// DWARF-gen. See issue 48573 for more details.
   289  		for _, n := range debug.RegOutputParams {
   290  			if !ssa.IsVarWantedForDebug(n) {
   291  				continue
   292  			}
   293  			if n.Class != ir.PPARAMOUT || !n.IsOutputParamInRegisters() {
   294  				base.Fatalf("invalid ir.Name on debugInfo.RegOutputParams list")
   295  			}
   296  			dcl = append(dcl, n)
   297  		}
   298  	}
   299  
   300  	// Process remaining variables not yet handled. For each variable,
   301  	// try createComplexVar first, then fall back to createSimpleVar
   302  	// for non-SSA-able params, or createConservativeVar for the rest.
   303  	for _, n := range dcl {
   304  		if seen[n] {
   305  			continue
   306  		}
   307  		if !shouldEmitDwarfVar(n) {
   308  			continue
   309  		}
   310  		seen[n] = true
   311  		if canUseComplex {
   312  			if vid, ok := varIDMap[n]; ok {
   313  				if dvar := createComplexVar(fnsym, fn, vid, closureVars); dvar != nil {
   314  					decls = append(decls, n)
   315  					vars = append(vars, dvar)
   316  					continue
   317  				}
   318  			}
   319  		}
   320  		if n.Class == ir.PPARAM && !ssa.CanSSA(n.Type()) {
   321  			decls = append(decls, n)
   322  			vars = append(vars, createSimpleVar(fnsym, n, closureVars))
   323  			continue
   324  		}
   325  		decls = append(decls, n)
   326  		vars = append(vars, createConservativeVar(fnsym, fn, n, closureVars))
   327  	}
   328  
   329  	// Sort decls and vars.
   330  	sortDeclsAndVars(fn, decls, vars)
   331  
   332  	return decls, vars
   333  }
   334  
   335  // createConservativeVar creates a DWARF variable with a conservative location
   336  // description. This is used for variables that were optimized away or otherwise
   337  // don't have precise location info. The intent is to communicate that "yes,
   338  // there is a variable named X in this function, but no, I don't have enough
   339  // information to reliably report its contents."
   340  // For heap-escaped variables, a location list is created that describes
   341  // dereferencing the pointer at the stack offset.
   342  func createConservativeVar(fnsym *obj.LSym, fn *ir.Func, n *ir.Name, closureVars map[*ir.Name]int64) *dwarf.Var {
   343  	typename := dwarf.InfoPrefix + types.TypeSymName(n.Type())
   344  	tag := dwarf.DW_TAG_variable
   345  	isReturnValue := (n.Class == ir.PPARAMOUT)
   346  	if n.Class == ir.PPARAM || n.Class == ir.PPARAMOUT {
   347  		tag = dwarf.DW_TAG_formal_parameter
   348  	}
   349  	inlIndex := 0
   350  	if base.Flag.GenDwarfInl > 1 {
   351  		if n.InlFormal() || n.InlLocal() {
   352  			inlIndex = posInlIndex(n.Pos()) + 1
   353  			if n.InlFormal() {
   354  				tag = dwarf.DW_TAG_formal_parameter
   355  			}
   356  		}
   357  	}
   358  	declpos := base.Ctxt.InnermostPos(n.Pos())
   359  	dvar := &dwarf.Var{
   360  		Name:          n.Sym().Name,
   361  		IsReturnValue: isReturnValue,
   362  		Tag:           tag,
   363  		WithLoclist:   true,
   364  		StackOffset:   int32(n.FrameOffset()),
   365  		Type:          base.Ctxt.Lookup(typename),
   366  		DeclFile:      declpos.RelFilename(),
   367  		DeclLine:      declpos.RelLine(),
   368  		DeclCol:       declpos.RelCol(),
   369  		InlIndex:      int32(inlIndex),
   370  		ChildIndex:    -1,
   371  		DictIndex:     n.DictIndex,
   372  		ClosureOffset: closureOffset(n, closureVars),
   373  	}
   374  	if base.Ctxt.Flag_locationlists && n.Esc() == ir.EscHeap && n.Heapaddr != nil {
   375  		// The variable was promoted to the heap and has a known heap
   376  		// address, so describe its location by dereferencing the pointer
   377  		// stored at its stack offset. A heap-escaped variable may have no
   378  		// Heapaddr if it was declared in unreachable code: escape analysis
   379  		// marks it as heap-allocated, but SSA generation skips the dead
   380  		// declaration and never allocates the address. In that case fall
   381  		// through and emit a conservative variable with no location list.
   382  		debug := fn.DebugInfo.(*ssadebug.FuncDebug)
   383  		list := createHeapDerefLocationList(n, debug.EntryID)
   384  		dvar.PutLocationList = func(listSym, startPC dwarf.Sym) {
   385  			debug.PutLocationList(list, base.Ctxt, listSym.(*obj.LSym), startPC.(*obj.LSym))
   386  		}
   387  	}
   388  	// Record go type to ensure that it gets emitted by the linker.
   389  	fnsym.Func().RecordAutoType(reflectdata.TypeLinksym(n.Type()))
   390  	return dvar
   391  }
   392  
   393  // sortDeclsAndVars sorts the decl and dwarf var lists according to
   394  // parameter declaration order, so as to insure that when a subprogram
   395  // DIE is emitted, its parameter children appear in declaration order.
   396  // Prior to the advent of the register ABI, sorting by frame offset
   397  // would achieve this; with the register we now need to go back to the
   398  // original function signature.
   399  func sortDeclsAndVars(fn *ir.Func, decls []*ir.Name, vars []*dwarf.Var) {
   400  	paramOrder := make(map[*ir.Name]int)
   401  	idx := 1
   402  	for _, f := range fn.Type().RecvParamsResults() {
   403  		if n, ok := f.Nname.(*ir.Name); ok {
   404  			paramOrder[n] = idx
   405  			idx++
   406  		}
   407  	}
   408  	sort.Stable(varsAndDecls{decls, vars, paramOrder})
   409  }
   410  
   411  type varsAndDecls struct {
   412  	decls      []*ir.Name
   413  	vars       []*dwarf.Var
   414  	paramOrder map[*ir.Name]int
   415  }
   416  
   417  func (v varsAndDecls) Len() int {
   418  	return len(v.decls)
   419  }
   420  
   421  func (v varsAndDecls) Less(i, j int) bool {
   422  	nameLT := func(ni, nj *ir.Name) bool {
   423  		oi, foundi := v.paramOrder[ni]
   424  		oj, foundj := v.paramOrder[nj]
   425  		if foundi {
   426  			if foundj {
   427  				return oi < oj
   428  			} else {
   429  				return true
   430  			}
   431  		}
   432  		return false
   433  	}
   434  	return nameLT(v.decls[i], v.decls[j])
   435  }
   436  
   437  func (v varsAndDecls) Swap(i, j int) {
   438  	v.vars[i], v.vars[j] = v.vars[j], v.vars[i]
   439  	v.decls[i], v.decls[j] = v.decls[j], v.decls[i]
   440  }
   441  
   442  // Given a function that was inlined at some point during the
   443  // compilation, return a sorted list of nodes corresponding to the
   444  // autos/locals in that function prior to inlining. If this is a
   445  // function that is not local to the package being compiled, then the
   446  // names of the variables may have been "versioned" to avoid conflicts
   447  // with local vars; disregard this versioning when sorting.
   448  func preInliningDcls(fnsym *obj.LSym) []*ir.Name {
   449  	fn := base.Ctxt.DwFixups.GetPrecursorFunc(fnsym).(*ir.Func)
   450  	var rdcl []*ir.Name
   451  	for _, n := range fn.Inl.Dcl {
   452  		if n.Sym().Name[0] == '.' || !shouldEmitDwarfVarSafe(n) {
   453  			continue
   454  		}
   455  		rdcl = append(rdcl, n)
   456  	}
   457  	return rdcl
   458  }
   459  
   460  func createSimpleVar(fnsym *obj.LSym, n *ir.Name, closureVars map[*ir.Name]int64) *dwarf.Var {
   461  	var tag int
   462  	var offs int64
   463  
   464  	localAutoOffset := func() int64 {
   465  		offs = n.FrameOffset()
   466  		if base.Ctxt.Arch.FixedFrameSize == 0 {
   467  			offs -= int64(base.Ctxt.Arch.RegSize)
   468  		}
   469  		if buildcfg.FramePointerEnabled {
   470  			offs -= int64(types.PtrSize)
   471  		}
   472  		return offs
   473  	}
   474  
   475  	switch n.Class {
   476  	case ir.PAUTO:
   477  		offs = localAutoOffset()
   478  		tag = dwarf.DW_TAG_variable
   479  	case ir.PPARAM, ir.PPARAMOUT:
   480  		tag = dwarf.DW_TAG_formal_parameter
   481  		if n.IsOutputParamInRegisters() {
   482  			offs = localAutoOffset()
   483  		} else {
   484  			offs = n.FrameOffset() + base.Ctxt.Arch.FixedFrameSize
   485  		}
   486  
   487  	default:
   488  		base.Fatalf("createSimpleVar unexpected class %v for node %v", n.Class, n)
   489  	}
   490  
   491  	typename := dwarf.InfoPrefix + types.TypeSymName(n.Type())
   492  	delete(fnsym.Func().Autot, reflectdata.TypeLinksym(n.Type()))
   493  	inlIndex := 0
   494  	if base.Flag.GenDwarfInl > 1 {
   495  		if n.InlFormal() || n.InlLocal() {
   496  			inlIndex = posInlIndex(n.Pos()) + 1
   497  			if n.InlFormal() {
   498  				tag = dwarf.DW_TAG_formal_parameter
   499  			}
   500  		}
   501  	}
   502  	declpos := base.Ctxt.InnermostPos(declPos(n))
   503  	return &dwarf.Var{
   504  		Name:          n.Sym().Name,
   505  		IsReturnValue: n.Class == ir.PPARAMOUT,
   506  		IsInlFormal:   n.InlFormal(),
   507  		Tag:           tag,
   508  		StackOffset:   int32(offs),
   509  		Type:          base.Ctxt.Lookup(typename),
   510  		DeclFile:      declpos.RelFilename(),
   511  		DeclLine:      declpos.RelLine(),
   512  		DeclCol:       declpos.RelCol(),
   513  		InlIndex:      int32(inlIndex),
   514  		ChildIndex:    -1,
   515  		DictIndex:     n.DictIndex,
   516  		ClosureOffset: closureOffset(n, closureVars),
   517  	}
   518  }
   519  
   520  // createComplexVar builds a single DWARF variable entry and location list.
   521  func createComplexVar(fnsym *obj.LSym, fn *ir.Func, varID ssa.VarID, closureVars map[*ir.Name]int64) *dwarf.Var {
   522  	debug := fn.DebugInfo.(*ssadebug.FuncDebug)
   523  	n := debug.Vars[varID]
   524  
   525  	var tag int
   526  	switch n.Class {
   527  	case ir.PAUTO:
   528  		tag = dwarf.DW_TAG_variable
   529  	case ir.PPARAM, ir.PPARAMOUT:
   530  		tag = dwarf.DW_TAG_formal_parameter
   531  	default:
   532  		return nil
   533  	}
   534  
   535  	gotype := reflectdata.TypeLinksym(n.Type())
   536  	delete(fnsym.Func().Autot, gotype)
   537  	typename := dwarf.InfoPrefix + gotype.Name[len("type:"):]
   538  	inlIndex := 0
   539  	if base.Flag.GenDwarfInl > 1 {
   540  		if n.InlFormal() || n.InlLocal() {
   541  			inlIndex = posInlIndex(n.Pos()) + 1
   542  			if n.InlFormal() {
   543  				tag = dwarf.DW_TAG_formal_parameter
   544  			}
   545  		}
   546  	}
   547  	declpos := base.Ctxt.InnermostPos(n.Pos())
   548  	dvar := &dwarf.Var{
   549  		Name:          n.Sym().Name,
   550  		IsReturnValue: n.Class == ir.PPARAMOUT,
   551  		IsInlFormal:   n.InlFormal(),
   552  		Tag:           tag,
   553  		WithLoclist:   true,
   554  		Type:          base.Ctxt.Lookup(typename),
   555  		// The stack offset is used as a sorting key, so for decomposed
   556  		// variables just give it the first one. It's not used otherwise.
   557  		// This won't work well if the first slot hasn't been assigned a stack
   558  		// location, but it's not obvious how to do better.
   559  		StackOffset:   ssagen.StackOffset(debug.Slots[debug.VarSlots[varID][0]]),
   560  		DeclFile:      declpos.RelFilename(),
   561  		DeclLine:      declpos.RelLine(),
   562  		DeclCol:       declpos.RelCol(),
   563  		InlIndex:      int32(inlIndex),
   564  		ChildIndex:    -1,
   565  		DictIndex:     n.DictIndex,
   566  		ClosureOffset: closureOffset(n, closureVars),
   567  	}
   568  	list := debug.LocationLists[varID]
   569  	if len(list) != 0 {
   570  		dvar.PutLocationList = func(listSym, startPC dwarf.Sym) {
   571  			debug.PutLocationList(list, base.Ctxt, listSym.(*obj.LSym), startPC.(*obj.LSym))
   572  		}
   573  	}
   574  	return dvar
   575  }
   576  
   577  // createHeapDerefLocationList creates a location list for a heap-escaped variable
   578  // that describes "dereference pointer at stack offset"
   579  func createHeapDerefLocationList(n *ir.Name, entryID ssa.ID) []ssa.LocListEntry {
   580  	// Get the stack offset where the heap pointer is stored
   581  	heapPtrOffset := n.Heapaddr.FrameOffset()
   582  	if base.Ctxt.Arch.FixedFrameSize == 0 {
   583  		heapPtrOffset -= int64(base.Ctxt.Arch.RegSize)
   584  	}
   585  	if buildcfg.FramePointerEnabled {
   586  		heapPtrOffset -= int64(types.PtrSize)
   587  	}
   588  
   589  	// Create a location expression: DW_OP_fbreg <offset> DW_OP_deref
   590  	var expr []byte
   591  	expr = append(expr, dwarf.DW_OP_fbreg)
   592  	expr = dwarf.AppendSleb128(expr, heapPtrOffset)
   593  	expr = append(expr, dwarf.DW_OP_deref)
   594  
   595  	return []ssa.LocListEntry{{
   596  		StartBlock: entryID,
   597  		StartValue: ssa.BlockStart.ID,
   598  		EndBlock:   entryID,
   599  		EndValue:   ssa.FuncEnd.ID,
   600  		Expr:       expr,
   601  	}}
   602  }
   603  
   604  // RecordFlags records the specified command-line flags to be placed
   605  // in the DWARF info.
   606  func RecordFlags(flags ...string) {
   607  	if base.Ctxt.Pkgpath == "" {
   608  		base.Fatalf("missing pkgpath")
   609  	}
   610  
   611  	type BoolFlag interface {
   612  		IsBoolFlag() bool
   613  	}
   614  	type CountFlag interface {
   615  		IsCountFlag() bool
   616  	}
   617  	var cmd bytes.Buffer
   618  	for _, name := range flags {
   619  		f := flag.Lookup(name)
   620  		if f == nil {
   621  			continue
   622  		}
   623  		getter := f.Value.(flag.Getter)
   624  		if getter.String() == f.DefValue {
   625  			// Flag has default value, so omit it.
   626  			continue
   627  		}
   628  		if bf, ok := f.Value.(BoolFlag); ok && bf.IsBoolFlag() {
   629  			val, ok := getter.Get().(bool)
   630  			if ok && val {
   631  				fmt.Fprintf(&cmd, " -%s", f.Name)
   632  				continue
   633  			}
   634  		}
   635  		if cf, ok := f.Value.(CountFlag); ok && cf.IsCountFlag() {
   636  			val, ok := getter.Get().(int)
   637  			if ok && val == 1 {
   638  				fmt.Fprintf(&cmd, " -%s", f.Name)
   639  				continue
   640  			}
   641  		}
   642  		fmt.Fprintf(&cmd, " -%s=%v", f.Name, getter.Get())
   643  	}
   644  
   645  	// Adds flag to producer string signaling whether regabi is turned on or
   646  	// off.
   647  	// Once regabi is turned on across the board and the relative GOEXPERIMENT
   648  	// knobs no longer exist this code should be removed.
   649  	if buildcfg.Experiment.RegabiArgs {
   650  		cmd.Write([]byte(" regabi"))
   651  	}
   652  
   653  	if cmd.Len() == 0 {
   654  		return
   655  	}
   656  	s := base.Ctxt.Lookup(dwarf.CUInfoPrefix + "producer." + base.Ctxt.Pkgpath)
   657  	s.Type = objabi.SDWARFCUINFO
   658  	// Sometimes (for example when building tests) we can link
   659  	// together two package main archives. So allow dups.
   660  	s.Set(obj.AttrDuplicateOK, true)
   661  	base.Ctxt.Data = append(base.Ctxt.Data, s)
   662  	s.P = cmd.Bytes()[1:]
   663  }
   664  
   665  // RecordPackageName records the name of the package being
   666  // compiled, so that the linker can save it in the compile unit's DIE.
   667  func RecordPackageName() {
   668  	s := base.Ctxt.Lookup(dwarf.CUInfoPrefix + "packagename." + base.Ctxt.Pkgpath)
   669  	s.Type = objabi.SDWARFCUINFO
   670  	// Sometimes (for example when building tests) we can link
   671  	// together two package main archives. So allow dups.
   672  	s.Set(obj.AttrDuplicateOK, true)
   673  	base.Ctxt.Data = append(base.Ctxt.Data, s)
   674  	s.P = []byte(types.LocalPkg.Name)
   675  }
   676  
   677  // shouldEmitDwarfVar reports whether n should have a DWARF variable entry.
   678  // This consolidates filtering that was previously spread across IR (AutoTemp),
   679  // SSA (IsVarWantedForDebug), and dwarfgen (symbol name checks).
   680  func shouldEmitDwarfVar(n *ir.Name) bool {
   681  	if ir.IsAutoTmp(n) {
   682  		return false
   683  	}
   684  	return shouldEmitDwarfVarSafe(n)
   685  }
   686  
   687  // shouldEmitDwarfVarSafe is like shouldEmitDwarfVar but omits the ir.IsAutoTmp
   688  // check, making it safe to call during parallel compilation on shared ir.Name
   689  // nodes (e.g., in preInliningDcls). ir.IsAutoTmp reads the mutable flags bitset,
   690  // which can race with other goroutines writing different flags during compilation.
   691  // Auto temps have names starting with "." so callers must filter those separately.
   692  func shouldEmitDwarfVarSafe(n *ir.Name) bool {
   693  	if !ssa.IsVarWantedForDebug(n) {
   694  		return false
   695  	}
   696  	if n.Sym().Name == "_" {
   697  		return false
   698  	}
   699  	if n.Type().IsUntyped() {
   700  		return false
   701  	}
   702  	return true
   703  }
   704  
   705  func closureOffset(n *ir.Name, closureVars map[*ir.Name]int64) int64 {
   706  	return closureVars[n]
   707  }
   708  

View as plain text