Path: blob/main/contrib/llvm-project/llvm/lib/CodeGen/DFAPacketizer.cpp
35232 views
//=- llvm/CodeGen/DFAPacketizer.cpp - DFA Packetizer for VLIW -*- C++ -*-=====//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// This class implements a deterministic finite automaton (DFA) based8// packetizing mechanism for VLIW architectures. It provides APIs to9// determine whether there exists a legal mapping of instructions to10// functional unit assignments in a packet. The DFA is auto-generated from11// the target's Schedule.td file.12//13// A DFA consists of 3 major elements: states, inputs, and transitions. For14// the packetizing mechanism, the input is the set of instruction classes for15// a target. The state models all possible combinations of functional unit16// consumption for a given set of instructions in a packet. A transition17// models the addition of an instruction to a packet. In the DFA constructed18// by this class, if an instruction can be added to a packet, then a valid19// transition exists from the corresponding state. Invalid transitions20// indicate that the instruction cannot be added to the current packet.21//22//===----------------------------------------------------------------------===//2324#include "llvm/CodeGen/DFAPacketizer.h"25#include "llvm/ADT/StringExtras.h"26#include "llvm/Analysis/AliasAnalysis.h"27#include "llvm/CodeGen/MachineFunction.h"28#include "llvm/CodeGen/MachineInstr.h"29#include "llvm/CodeGen/MachineInstrBundle.h"30#include "llvm/CodeGen/ScheduleDAG.h"31#include "llvm/CodeGen/TargetInstrInfo.h"32#include "llvm/CodeGen/TargetSubtargetInfo.h"33#include "llvm/MC/MCInstrDesc.h"34#include "llvm/Support/CommandLine.h"35#include "llvm/Support/Debug.h"36#include "llvm/Support/raw_ostream.h"37#include <algorithm>38#include <cassert>39#include <iterator>40#include <memory>41#include <vector>4243using namespace llvm;4445#define DEBUG_TYPE "packets"4647static cl::opt<unsigned> InstrLimit("dfa-instr-limit", cl::Hidden,48cl::init(0), cl::desc("If present, stops packetizing after N instructions"));4950static unsigned InstrCount = 0;5152// Check if the resources occupied by a MCInstrDesc are available in the53// current state.54bool DFAPacketizer::canReserveResources(const MCInstrDesc *MID) {55unsigned Action = ItinActions[MID->getSchedClass()];56if (MID->getSchedClass() == 0 || Action == 0)57return false;58return A.canAdd(Action);59}6061// Reserve the resources occupied by a MCInstrDesc and change the current62// state to reflect that change.63void DFAPacketizer::reserveResources(const MCInstrDesc *MID) {64unsigned Action = ItinActions[MID->getSchedClass()];65if (MID->getSchedClass() == 0 || Action == 0)66return;67A.add(Action);68}6970// Check if the resources occupied by a machine instruction are available71// in the current state.72bool DFAPacketizer::canReserveResources(MachineInstr &MI) {73const MCInstrDesc &MID = MI.getDesc();74return canReserveResources(&MID);75}7677// Reserve the resources occupied by a machine instruction and change the78// current state to reflect that change.79void DFAPacketizer::reserveResources(MachineInstr &MI) {80const MCInstrDesc &MID = MI.getDesc();81reserveResources(&MID);82}8384unsigned DFAPacketizer::getUsedResources(unsigned InstIdx) {85ArrayRef<NfaPath> NfaPaths = A.getNfaPaths();86assert(!NfaPaths.empty() && "Invalid bundle!");87const NfaPath &RS = NfaPaths.front();8889// RS stores the cumulative resources used up to and including the I'th90// instruction. The 0th instruction is the base case.91if (InstIdx == 0)92return RS[0];93// Return the difference between the cumulative resources used by InstIdx and94// its predecessor.95return RS[InstIdx] ^ RS[InstIdx - 1];96}9798DefaultVLIWScheduler::DefaultVLIWScheduler(MachineFunction &MF,99MachineLoopInfo &MLI,100AAResults *AA)101: ScheduleDAGInstrs(MF, &MLI), AA(AA) {102CanHandleTerminators = true;103}104105/// Apply each ScheduleDAGMutation step in order.106void DefaultVLIWScheduler::postProcessDAG() {107for (auto &M : Mutations)108M->apply(this);109}110111void DefaultVLIWScheduler::schedule() {112// Build the scheduling graph.113buildSchedGraph(AA);114postProcessDAG();115}116117VLIWPacketizerList::VLIWPacketizerList(MachineFunction &mf,118MachineLoopInfo &mli, AAResults *aa)119: MF(mf), TII(mf.getSubtarget().getInstrInfo()), AA(aa) {120ResourceTracker = TII->CreateTargetScheduleState(MF.getSubtarget());121ResourceTracker->setTrackResources(true);122VLIWScheduler = new DefaultVLIWScheduler(MF, mli, AA);123}124125VLIWPacketizerList::~VLIWPacketizerList() {126delete VLIWScheduler;127delete ResourceTracker;128}129130// End the current packet, bundle packet instructions and reset DFA state.131void VLIWPacketizerList::endPacket(MachineBasicBlock *MBB,132MachineBasicBlock::iterator MI) {133LLVM_DEBUG({134if (!CurrentPacketMIs.empty()) {135dbgs() << "Finalizing packet:\n";136unsigned Idx = 0;137for (MachineInstr *MI : CurrentPacketMIs) {138unsigned R = ResourceTracker->getUsedResources(Idx++);139dbgs() << " * [res:0x" << utohexstr(R) << "] " << *MI;140}141}142});143if (CurrentPacketMIs.size() > 1) {144MachineInstr &MIFirst = *CurrentPacketMIs.front();145finalizeBundle(*MBB, MIFirst.getIterator(), MI.getInstrIterator());146}147CurrentPacketMIs.clear();148ResourceTracker->clearResources();149LLVM_DEBUG(dbgs() << "End packet\n");150}151152// Bundle machine instructions into packets.153void VLIWPacketizerList::PacketizeMIs(MachineBasicBlock *MBB,154MachineBasicBlock::iterator BeginItr,155MachineBasicBlock::iterator EndItr) {156assert(VLIWScheduler && "VLIW Scheduler is not initialized!");157VLIWScheduler->startBlock(MBB);158VLIWScheduler->enterRegion(MBB, BeginItr, EndItr,159std::distance(BeginItr, EndItr));160VLIWScheduler->schedule();161162LLVM_DEBUG({163dbgs() << "Scheduling DAG of the packetize region\n";164VLIWScheduler->dump();165});166167// Generate MI -> SU map.168MIToSUnit.clear();169for (SUnit &SU : VLIWScheduler->SUnits)170MIToSUnit[SU.getInstr()] = &SU;171172bool LimitPresent = InstrLimit.getPosition();173174// The main packetizer loop.175for (; BeginItr != EndItr; ++BeginItr) {176if (LimitPresent) {177if (InstrCount >= InstrLimit) {178EndItr = BeginItr;179break;180}181InstrCount++;182}183MachineInstr &MI = *BeginItr;184initPacketizerState();185186// End the current packet if needed.187if (isSoloInstruction(MI)) {188endPacket(MBB, MI);189continue;190}191192// Ignore pseudo instructions.193if (ignorePseudoInstruction(MI, MBB))194continue;195196SUnit *SUI = MIToSUnit[&MI];197assert(SUI && "Missing SUnit Info!");198199// Ask DFA if machine resource is available for MI.200LLVM_DEBUG(dbgs() << "Checking resources for adding MI to packet " << MI);201202bool ResourceAvail = ResourceTracker->canReserveResources(MI);203LLVM_DEBUG({204if (ResourceAvail)205dbgs() << " Resources are available for adding MI to packet\n";206else207dbgs() << " Resources NOT available\n";208});209if (ResourceAvail && shouldAddToPacket(MI)) {210// Dependency check for MI with instructions in CurrentPacketMIs.211for (auto *MJ : CurrentPacketMIs) {212SUnit *SUJ = MIToSUnit[MJ];213assert(SUJ && "Missing SUnit Info!");214215LLVM_DEBUG(dbgs() << " Checking against MJ " << *MJ);216// Is it legal to packetize SUI and SUJ together.217if (!isLegalToPacketizeTogether(SUI, SUJ)) {218LLVM_DEBUG(dbgs() << " Not legal to add MI, try to prune\n");219// Allow packetization if dependency can be pruned.220if (!isLegalToPruneDependencies(SUI, SUJ)) {221// End the packet if dependency cannot be pruned.222LLVM_DEBUG(dbgs()223<< " Could not prune dependencies for adding MI\n");224endPacket(MBB, MI);225break;226}227LLVM_DEBUG(dbgs() << " Pruned dependence for adding MI\n");228}229}230} else {231LLVM_DEBUG(if (ResourceAvail) dbgs()232<< "Resources are available, but instruction should not be "233"added to packet\n "234<< MI);235// End the packet if resource is not available, or if the instruction236// should not be added to the current packet.237endPacket(MBB, MI);238}239240// Add MI to the current packet.241LLVM_DEBUG(dbgs() << "* Adding MI to packet " << MI << '\n');242BeginItr = addToPacket(MI);243} // For all instructions in the packetization range.244245// End any packet left behind.246endPacket(MBB, EndItr);247VLIWScheduler->exitRegion();248VLIWScheduler->finishBlock();249}250251bool VLIWPacketizerList::alias(const MachineMemOperand &Op1,252const MachineMemOperand &Op2,253bool UseTBAA) const {254if (!Op1.getValue() || !Op2.getValue() || !Op1.getSize().hasValue() ||255!Op2.getSize().hasValue())256return true;257258int64_t MinOffset = std::min(Op1.getOffset(), Op2.getOffset());259int64_t Overlapa = Op1.getSize().getValue() + Op1.getOffset() - MinOffset;260int64_t Overlapb = Op2.getSize().getValue() + Op2.getOffset() - MinOffset;261262AliasResult AAResult =263AA->alias(MemoryLocation(Op1.getValue(), Overlapa,264UseTBAA ? Op1.getAAInfo() : AAMDNodes()),265MemoryLocation(Op2.getValue(), Overlapb,266UseTBAA ? Op2.getAAInfo() : AAMDNodes()));267268return AAResult != AliasResult::NoAlias;269}270271bool VLIWPacketizerList::alias(const MachineInstr &MI1,272const MachineInstr &MI2,273bool UseTBAA) const {274if (MI1.memoperands_empty() || MI2.memoperands_empty())275return true;276277for (const MachineMemOperand *Op1 : MI1.memoperands())278for (const MachineMemOperand *Op2 : MI2.memoperands())279if (alias(*Op1, *Op2, UseTBAA))280return true;281return false;282}283284// Add a DAG mutation object to the ordered list.285void VLIWPacketizerList::addMutation(286std::unique_ptr<ScheduleDAGMutation> Mutation) {287VLIWScheduler->addMutation(std::move(Mutation));288}289290291