Path: blob/main/contrib/llvm-project/llvm/lib/Target/WebAssembly/WebAssemblyFrameLowering.cpp
35266 views
//===-- WebAssemblyFrameLowering.cpp - WebAssembly Frame Lowering ----------==//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7///8/// \file9/// This file contains the WebAssembly implementation of10/// TargetFrameLowering class.11///12/// On WebAssembly, there aren't a lot of things to do here. There are no13/// callee-saved registers to save, and no spill slots.14///15/// The stack grows downward.16///17//===----------------------------------------------------------------------===//1819#include "WebAssemblyFrameLowering.h"20#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"21#include "Utils/WebAssemblyTypeUtilities.h"22#include "WebAssembly.h"23#include "WebAssemblyInstrInfo.h"24#include "WebAssemblyMachineFunctionInfo.h"25#include "WebAssemblySubtarget.h"26#include "WebAssemblyTargetMachine.h"27#include "llvm/CodeGen/Analysis.h"28#include "llvm/CodeGen/MachineFrameInfo.h"29#include "llvm/CodeGen/MachineFunction.h"30#include "llvm/CodeGen/MachineInstrBuilder.h"31#include "llvm/CodeGen/MachineModuleInfoImpls.h"32#include "llvm/CodeGen/MachineRegisterInfo.h"33#include "llvm/IR/Instructions.h"34#include "llvm/MC/MCAsmInfo.h"35#include "llvm/Support/Debug.h"36using namespace llvm;3738#define DEBUG_TYPE "wasm-frame-info"3940// TODO: wasm6441// TODO: Emit TargetOpcode::CFI_INSTRUCTION instructions4243// In an ideal world, when objects are added to the MachineFrameInfo by44// FunctionLoweringInfo::set, we could somehow hook into target-specific code to45// ensure they are assigned the right stack ID. However there isn't a hook that46// runs between then and DAG building time, though, so instead we hoist stack47// objects lazily when they are first used, and comprehensively after the DAG is48// built via the PreprocessISelDAG hook, called by the49// SelectionDAGISel::runOnMachineFunction. We have to do it in two places50// because we want to do it while building the selection DAG for uses of alloca,51// but not all alloca instructions are used so we have to follow up afterwards.52std::optional<unsigned>53WebAssemblyFrameLowering::getLocalForStackObject(MachineFunction &MF,54int FrameIndex) {55MachineFrameInfo &MFI = MF.getFrameInfo();5657// If already hoisted to a local, done.58if (MFI.getStackID(FrameIndex) == TargetStackID::WasmLocal)59return static_cast<unsigned>(MFI.getObjectOffset(FrameIndex));6061// If not allocated in the object address space, this object will be in62// linear memory.63const AllocaInst *AI = MFI.getObjectAllocation(FrameIndex);64if (!AI || !WebAssembly::isWasmVarAddressSpace(AI->getAddressSpace()))65return std::nullopt;6667// Otherwise, allocate this object in the named value stack, outside of linear68// memory.69SmallVector<EVT, 4> ValueVTs;70const WebAssemblyTargetLowering &TLI =71*MF.getSubtarget<WebAssemblySubtarget>().getTargetLowering();72WebAssemblyFunctionInfo *FuncInfo = MF.getInfo<WebAssemblyFunctionInfo>();73ComputeValueVTs(TLI, MF.getDataLayout(), AI->getAllocatedType(), ValueVTs);74MFI.setStackID(FrameIndex, TargetStackID::WasmLocal);75// Abuse SP offset to record the index of the first local in the object.76unsigned Local = FuncInfo->getParams().size() + FuncInfo->getLocals().size();77MFI.setObjectOffset(FrameIndex, Local);78// Allocate WebAssembly locals for each non-aggregate component of the79// allocation.80for (EVT ValueVT : ValueVTs)81FuncInfo->addLocal(ValueVT.getSimpleVT());82// Abuse object size to record number of WebAssembly locals allocated to83// this object.84MFI.setObjectSize(FrameIndex, ValueVTs.size());85return static_cast<unsigned>(Local);86}8788/// We need a base pointer in the case of having items on the stack that89/// require stricter alignment than the stack pointer itself. Because we need90/// to shift the stack pointer by some unknown amount to force the alignment,91/// we need to record the value of the stack pointer on entry to the function.92bool WebAssemblyFrameLowering::hasBP(const MachineFunction &MF) const {93const auto *RegInfo =94MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();95return RegInfo->hasStackRealignment(MF);96}9798/// Return true if the specified function should have a dedicated frame pointer99/// register.100bool WebAssemblyFrameLowering::hasFP(const MachineFunction &MF) const {101const MachineFrameInfo &MFI = MF.getFrameInfo();102103// When we have var-sized objects, we move the stack pointer by an unknown104// amount, and need to emit a frame pointer to restore the stack to where we105// were on function entry.106// If we already need a base pointer, we use that to fix up the stack pointer.107// If there are no fixed-size objects, we would have no use of a frame108// pointer, and thus should not emit one.109bool HasFixedSizedObjects = MFI.getStackSize() > 0;110bool NeedsFixedReference = !hasBP(MF) || HasFixedSizedObjects;111112return MFI.isFrameAddressTaken() ||113(MFI.hasVarSizedObjects() && NeedsFixedReference) ||114MFI.hasStackMap() || MFI.hasPatchPoint();115}116117/// Under normal circumstances, when a frame pointer is not required, we reserve118/// argument space for call sites in the function immediately on entry to the119/// current function. This eliminates the need for add/sub sp brackets around120/// call sites. Returns true if the call frame is included as part of the stack121/// frame.122bool WebAssemblyFrameLowering::hasReservedCallFrame(123const MachineFunction &MF) const {124return !MF.getFrameInfo().hasVarSizedObjects();125}126127// Returns true if this function needs a local user-space stack pointer for its128// local frame (not for exception handling).129bool WebAssemblyFrameLowering::needsSPForLocalFrame(130const MachineFunction &MF) const {131auto &MFI = MF.getFrameInfo();132auto &MRI = MF.getRegInfo();133// llvm.stacksave can explicitly read SP register and it can appear without134// dynamic alloca.135bool HasExplicitSPUse =136any_of(MRI.use_operands(getSPReg(MF)),137[](MachineOperand &MO) { return !MO.isImplicit(); });138139return MFI.getStackSize() || MFI.adjustsStack() || hasFP(MF) ||140HasExplicitSPUse;141}142143// In function with EH pads, we need to make a copy of the value of144// __stack_pointer global in SP32/64 register, in order to use it when145// restoring __stack_pointer after an exception is caught.146bool WebAssemblyFrameLowering::needsPrologForEH(147const MachineFunction &MF) const {148auto EHType = MF.getTarget().getMCAsmInfo()->getExceptionHandlingType();149return EHType == ExceptionHandling::Wasm &&150MF.getFunction().hasPersonalityFn() && MF.getFrameInfo().hasCalls();151}152153/// Returns true if this function needs a local user-space stack pointer.154/// Unlike a machine stack pointer, the wasm user stack pointer is a global155/// variable, so it is loaded into a register in the prolog.156bool WebAssemblyFrameLowering::needsSP(const MachineFunction &MF) const {157return needsSPForLocalFrame(MF) || needsPrologForEH(MF);158}159160/// Returns true if the local user-space stack pointer needs to be written back161/// to __stack_pointer global by this function (this is not meaningful if162/// needsSP is false). If false, the stack red zone can be used and only a local163/// SP is needed.164bool WebAssemblyFrameLowering::needsSPWriteback(165const MachineFunction &MF) const {166auto &MFI = MF.getFrameInfo();167assert(needsSP(MF));168// When we don't need a local stack pointer for its local frame but only to169// support EH, we don't need to write SP back in the epilog, because we don't170// bump down the stack pointer in the prolog. We need to write SP back in the171// epilog only if172// 1. We need SP not only for EH support but also because we actually use173// stack or we have a frame address taken.174// 2. We cannot use the red zone.175bool CanUseRedZone = MFI.getStackSize() <= RedZoneSize && !MFI.hasCalls() &&176!MF.getFunction().hasFnAttribute(Attribute::NoRedZone);177return needsSPForLocalFrame(MF) && !CanUseRedZone;178}179180unsigned WebAssemblyFrameLowering::getSPReg(const MachineFunction &MF) {181return MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()182? WebAssembly::SP64183: WebAssembly::SP32;184}185186unsigned WebAssemblyFrameLowering::getFPReg(const MachineFunction &MF) {187return MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()188? WebAssembly::FP64189: WebAssembly::FP32;190}191192unsigned193WebAssemblyFrameLowering::getOpcConst(const MachineFunction &MF) {194return MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()195? WebAssembly::CONST_I64196: WebAssembly::CONST_I32;197}198199unsigned WebAssemblyFrameLowering::getOpcAdd(const MachineFunction &MF) {200return MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()201? WebAssembly::ADD_I64202: WebAssembly::ADD_I32;203}204205unsigned WebAssemblyFrameLowering::getOpcSub(const MachineFunction &MF) {206return MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()207? WebAssembly::SUB_I64208: WebAssembly::SUB_I32;209}210211unsigned WebAssemblyFrameLowering::getOpcAnd(const MachineFunction &MF) {212return MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()213? WebAssembly::AND_I64214: WebAssembly::AND_I32;215}216217unsigned218WebAssemblyFrameLowering::getOpcGlobGet(const MachineFunction &MF) {219return MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()220? WebAssembly::GLOBAL_GET_I64221: WebAssembly::GLOBAL_GET_I32;222}223224unsigned225WebAssemblyFrameLowering::getOpcGlobSet(const MachineFunction &MF) {226return MF.getSubtarget<WebAssemblySubtarget>().hasAddr64()227? WebAssembly::GLOBAL_SET_I64228: WebAssembly::GLOBAL_SET_I32;229}230231void WebAssemblyFrameLowering::writeSPToGlobal(232unsigned SrcReg, MachineFunction &MF, MachineBasicBlock &MBB,233MachineBasicBlock::iterator &InsertStore, const DebugLoc &DL) const {234const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();235236const char *ES = "__stack_pointer";237auto *SPSymbol = MF.createExternalSymbolName(ES);238239BuildMI(MBB, InsertStore, DL, TII->get(getOpcGlobSet(MF)))240.addExternalSymbol(SPSymbol)241.addReg(SrcReg);242}243244MachineBasicBlock::iterator245WebAssemblyFrameLowering::eliminateCallFramePseudoInstr(246MachineFunction &MF, MachineBasicBlock &MBB,247MachineBasicBlock::iterator I) const {248assert(!I->getOperand(0).getImm() && (hasFP(MF) || hasBP(MF)) &&249"Call frame pseudos should only be used for dynamic stack adjustment");250auto &ST = MF.getSubtarget<WebAssemblySubtarget>();251const auto *TII = ST.getInstrInfo();252if (I->getOpcode() == TII->getCallFrameDestroyOpcode() &&253needsSPWriteback(MF)) {254DebugLoc DL = I->getDebugLoc();255writeSPToGlobal(getSPReg(MF), MF, MBB, I, DL);256}257return MBB.erase(I);258}259260void WebAssemblyFrameLowering::emitPrologue(MachineFunction &MF,261MachineBasicBlock &MBB) const {262// TODO: Do ".setMIFlag(MachineInstr::FrameSetup)" on emitted instructions263auto &MFI = MF.getFrameInfo();264assert(MFI.getCalleeSavedInfo().empty() &&265"WebAssembly should not have callee-saved registers");266267if (!needsSP(MF))268return;269uint64_t StackSize = MFI.getStackSize();270271auto &ST = MF.getSubtarget<WebAssemblySubtarget>();272const auto *TII = ST.getInstrInfo();273auto &MRI = MF.getRegInfo();274275auto InsertPt = MBB.begin();276while (InsertPt != MBB.end() &&277WebAssembly::isArgument(InsertPt->getOpcode()))278++InsertPt;279DebugLoc DL;280281const TargetRegisterClass *PtrRC =282MRI.getTargetRegisterInfo()->getPointerRegClass(MF);283unsigned SPReg = getSPReg(MF);284if (StackSize)285SPReg = MRI.createVirtualRegister(PtrRC);286287const char *ES = "__stack_pointer";288auto *SPSymbol = MF.createExternalSymbolName(ES);289BuildMI(MBB, InsertPt, DL, TII->get(getOpcGlobGet(MF)), SPReg)290.addExternalSymbol(SPSymbol);291292bool HasBP = hasBP(MF);293if (HasBP) {294auto FI = MF.getInfo<WebAssemblyFunctionInfo>();295Register BasePtr = MRI.createVirtualRegister(PtrRC);296FI->setBasePointerVreg(BasePtr);297BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY), BasePtr)298.addReg(SPReg);299}300if (StackSize) {301// Subtract the frame size302Register OffsetReg = MRI.createVirtualRegister(PtrRC);303BuildMI(MBB, InsertPt, DL, TII->get(getOpcConst(MF)), OffsetReg)304.addImm(StackSize);305BuildMI(MBB, InsertPt, DL, TII->get(getOpcSub(MF)), getSPReg(MF))306.addReg(SPReg)307.addReg(OffsetReg);308}309if (HasBP) {310Register BitmaskReg = MRI.createVirtualRegister(PtrRC);311Align Alignment = MFI.getMaxAlign();312BuildMI(MBB, InsertPt, DL, TII->get(getOpcConst(MF)), BitmaskReg)313.addImm((int64_t) ~(Alignment.value() - 1));314BuildMI(MBB, InsertPt, DL, TII->get(getOpcAnd(MF)), getSPReg(MF))315.addReg(getSPReg(MF))316.addReg(BitmaskReg);317}318if (hasFP(MF)) {319// Unlike most conventional targets (where FP points to the saved FP),320// FP points to the bottom of the fixed-size locals, so we can use positive321// offsets in load/store instructions.322BuildMI(MBB, InsertPt, DL, TII->get(WebAssembly::COPY), getFPReg(MF))323.addReg(getSPReg(MF));324}325if (StackSize && needsSPWriteback(MF)) {326writeSPToGlobal(getSPReg(MF), MF, MBB, InsertPt, DL);327}328}329330void WebAssemblyFrameLowering::emitEpilogue(MachineFunction &MF,331MachineBasicBlock &MBB) const {332uint64_t StackSize = MF.getFrameInfo().getStackSize();333if (!needsSP(MF) || !needsSPWriteback(MF))334return;335auto &ST = MF.getSubtarget<WebAssemblySubtarget>();336const auto *TII = ST.getInstrInfo();337auto &MRI = MF.getRegInfo();338auto InsertPt = MBB.getFirstTerminator();339DebugLoc DL;340341if (InsertPt != MBB.end())342DL = InsertPt->getDebugLoc();343344// Restore the stack pointer. If we had fixed-size locals, add the offset345// subtracted in the prolog.346unsigned SPReg = 0;347unsigned SPFPReg = hasFP(MF) ? getFPReg(MF) : getSPReg(MF);348if (hasBP(MF)) {349auto FI = MF.getInfo<WebAssemblyFunctionInfo>();350SPReg = FI->getBasePointerVreg();351} else if (StackSize) {352const TargetRegisterClass *PtrRC =353MRI.getTargetRegisterInfo()->getPointerRegClass(MF);354Register OffsetReg = MRI.createVirtualRegister(PtrRC);355BuildMI(MBB, InsertPt, DL, TII->get(getOpcConst(MF)), OffsetReg)356.addImm(StackSize);357// In the epilog we don't need to write the result back to the SP32/64358// physreg because it won't be used again. We can use a stackified register359// instead.360SPReg = MRI.createVirtualRegister(PtrRC);361BuildMI(MBB, InsertPt, DL, TII->get(getOpcAdd(MF)), SPReg)362.addReg(SPFPReg)363.addReg(OffsetReg);364} else {365SPReg = SPFPReg;366}367368writeSPToGlobal(SPReg, MF, MBB, InsertPt, DL);369}370371bool WebAssemblyFrameLowering::isSupportedStackID(372TargetStackID::Value ID) const {373// Use the Object stack for WebAssembly locals which can only be accessed374// by name, not via an address in linear memory.375if (ID == TargetStackID::WasmLocal)376return true;377378return TargetFrameLowering::isSupportedStackID(ID);379}380381TargetFrameLowering::DwarfFrameBase382WebAssemblyFrameLowering::getDwarfFrameBase(const MachineFunction &MF) const {383DwarfFrameBase Loc;384Loc.Kind = DwarfFrameBase::WasmFrameBase;385const WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();386if (needsSP(MF) && MFI.isFrameBaseVirtual()) {387unsigned LocalNum = MFI.getFrameBaseLocal();388Loc.Location.WasmLoc = {WebAssembly::TI_LOCAL, LocalNum};389} else {390// TODO: This should work on a breakpoint at a function with no frame,391// but probably won't work for traversing up the stack.392Loc.Location.WasmLoc = {WebAssembly::TI_GLOBAL_RELOC, 0};393}394return Loc;395}396397398