10b57cec5SDimitry Andric //===---- MachineOutliner.cpp - Outline instructions -----------*- C++ -*-===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric ///
90b57cec5SDimitry Andric /// \file
100b57cec5SDimitry Andric /// Replaces repeated sequences of instructions with function calls.
110b57cec5SDimitry Andric ///
120b57cec5SDimitry Andric /// This works by placing every instruction from every basic block in a
130b57cec5SDimitry Andric /// suffix tree, and repeatedly querying that tree for repeated sequences of
140b57cec5SDimitry Andric /// instructions. If a sequence of instructions appears often, then it ought
150b57cec5SDimitry Andric /// to be beneficial to pull out into a function.
160b57cec5SDimitry Andric ///
170b57cec5SDimitry Andric /// The MachineOutliner communicates with a given target using hooks defined in
180b57cec5SDimitry Andric /// TargetInstrInfo.h. The target supplies the outliner with information on how
190b57cec5SDimitry Andric /// a specific sequence of instructions should be outlined. This information
200b57cec5SDimitry Andric /// is used to deduce the number of instructions necessary to
210b57cec5SDimitry Andric ///
220b57cec5SDimitry Andric /// * Create an outlined function
230b57cec5SDimitry Andric /// * Call that outlined function
240b57cec5SDimitry Andric ///
250b57cec5SDimitry Andric /// Targets must implement
260b57cec5SDimitry Andric /// * getOutliningCandidateInfo
270b57cec5SDimitry Andric /// * buildOutlinedFrame
280b57cec5SDimitry Andric /// * insertOutlinedCall
290b57cec5SDimitry Andric /// * isFunctionSafeToOutlineFrom
300b57cec5SDimitry Andric ///
310b57cec5SDimitry Andric /// in order to make use of the MachineOutliner.
320b57cec5SDimitry Andric ///
330b57cec5SDimitry Andric /// This was originally presented at the 2016 LLVM Developers' Meeting in the
340b57cec5SDimitry Andric /// talk "Reducing Code Size Using Outlining". For a high-level overview of
350b57cec5SDimitry Andric /// how this pass works, the talk is available on YouTube at
360b57cec5SDimitry Andric ///
370b57cec5SDimitry Andric /// https://www.youtube.com/watch?v=yorld-WSOeU
380b57cec5SDimitry Andric ///
390b57cec5SDimitry Andric /// The slides for the talk are available at
400b57cec5SDimitry Andric ///
410b57cec5SDimitry Andric /// http://www.llvm.org/devmtg/2016-11/Slides/Paquette-Outliner.pdf
420b57cec5SDimitry Andric ///
430b57cec5SDimitry Andric /// The talk provides an overview of how the outliner finds candidates and
440b57cec5SDimitry Andric /// ultimately outlines them. It describes how the main data structure for this
450b57cec5SDimitry Andric /// pass, the suffix tree, is queried and purged for candidates. It also gives
460b57cec5SDimitry Andric /// a simplified suffix tree construction algorithm for suffix trees based off
470b57cec5SDimitry Andric /// of the algorithm actually used here, Ukkonen's algorithm.
480b57cec5SDimitry Andric ///
490b57cec5SDimitry Andric /// For the original RFC for this pass, please see
500b57cec5SDimitry Andric ///
510b57cec5SDimitry Andric /// http://lists.llvm.org/pipermail/llvm-dev/2016-August/104170.html
520b57cec5SDimitry Andric ///
530b57cec5SDimitry Andric /// For more information on the suffix tree data structure, please see
540b57cec5SDimitry Andric /// https://www.cs.helsinki.fi/u/ukkonen/SuffixT1withFigs.pdf
550b57cec5SDimitry Andric ///
560b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
570b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOutliner.h"
580b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
595ffd83dbSDimitry Andric #include "llvm/ADT/SmallSet.h"
600b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
610b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
620b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
630b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
640b57cec5SDimitry Andric #include "llvm/CodeGen/Passes.h"
650b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
660b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
670b57cec5SDimitry Andric #include "llvm/IR/DIBuilder.h"
680b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
690b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
70480093f4SDimitry Andric #include "llvm/InitializePasses.h"
710b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
720b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
735ffd83dbSDimitry Andric #include "llvm/Support/SuffixTree.h"
740b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
750b57cec5SDimitry Andric #include <functional>
760b57cec5SDimitry Andric #include <tuple>
770b57cec5SDimitry Andric #include <vector>
780b57cec5SDimitry Andric
790b57cec5SDimitry Andric #define DEBUG_TYPE "machine-outliner"
800b57cec5SDimitry Andric
810b57cec5SDimitry Andric using namespace llvm;
820b57cec5SDimitry Andric using namespace ore;
830b57cec5SDimitry Andric using namespace outliner;
840b57cec5SDimitry Andric
850b57cec5SDimitry Andric STATISTIC(NumOutlined, "Number of candidates outlined");
860b57cec5SDimitry Andric STATISTIC(FunctionsCreated, "Number of functions created");
870b57cec5SDimitry Andric
880b57cec5SDimitry Andric // Set to true if the user wants the outliner to run on linkonceodr linkage
890b57cec5SDimitry Andric // functions. This is false by default because the linker can dedupe linkonceodr
900b57cec5SDimitry Andric // functions. Since the outliner is confined to a single module (modulo LTO),
910b57cec5SDimitry Andric // this is off by default. It should, however, be the default behaviour in
920b57cec5SDimitry Andric // LTO.
930b57cec5SDimitry Andric static cl::opt<bool> EnableLinkOnceODROutlining(
94480093f4SDimitry Andric "enable-linkonceodr-outlining", cl::Hidden,
950b57cec5SDimitry Andric cl::desc("Enable the machine outliner on linkonceodr functions"),
960b57cec5SDimitry Andric cl::init(false));
970b57cec5SDimitry Andric
985ffd83dbSDimitry Andric /// Number of times to re-run the outliner. This is not the total number of runs
995ffd83dbSDimitry Andric /// as the outliner will run at least one time. The default value is set to 0,
1005ffd83dbSDimitry Andric /// meaning the outliner will run one time and rerun zero times after that.
1015ffd83dbSDimitry Andric static cl::opt<unsigned> OutlinerReruns(
1025ffd83dbSDimitry Andric "machine-outliner-reruns", cl::init(0), cl::Hidden,
1035ffd83dbSDimitry Andric cl::desc(
1045ffd83dbSDimitry Andric "Number of times to rerun the outliner after the initial outline"));
1055ffd83dbSDimitry Andric
1060b57cec5SDimitry Andric namespace {
1070b57cec5SDimitry Andric
1080b57cec5SDimitry Andric /// Maps \p MachineInstrs to unsigned integers and stores the mappings.
1090b57cec5SDimitry Andric struct InstructionMapper {
1100b57cec5SDimitry Andric
1110b57cec5SDimitry Andric /// The next available integer to assign to a \p MachineInstr that
1120b57cec5SDimitry Andric /// cannot be outlined.
1130b57cec5SDimitry Andric ///
1140b57cec5SDimitry Andric /// Set to -3 for compatability with \p DenseMapInfo<unsigned>.
1150b57cec5SDimitry Andric unsigned IllegalInstrNumber = -3;
1160b57cec5SDimitry Andric
1170b57cec5SDimitry Andric /// The next available integer to assign to a \p MachineInstr that can
1180b57cec5SDimitry Andric /// be outlined.
1190b57cec5SDimitry Andric unsigned LegalInstrNumber = 0;
1200b57cec5SDimitry Andric
1210b57cec5SDimitry Andric /// Correspondence from \p MachineInstrs to unsigned integers.
1220b57cec5SDimitry Andric DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>
1230b57cec5SDimitry Andric InstructionIntegerMap;
1240b57cec5SDimitry Andric
1250b57cec5SDimitry Andric /// Correspondence between \p MachineBasicBlocks and target-defined flags.
1260b57cec5SDimitry Andric DenseMap<MachineBasicBlock *, unsigned> MBBFlagsMap;
1270b57cec5SDimitry Andric
1280b57cec5SDimitry Andric /// The vector of unsigned integers that the module is mapped to.
1290b57cec5SDimitry Andric std::vector<unsigned> UnsignedVec;
1300b57cec5SDimitry Andric
1310b57cec5SDimitry Andric /// Stores the location of the instruction associated with the integer
1320b57cec5SDimitry Andric /// at index i in \p UnsignedVec for each index i.
1330b57cec5SDimitry Andric std::vector<MachineBasicBlock::iterator> InstrList;
1340b57cec5SDimitry Andric
1350b57cec5SDimitry Andric // Set if we added an illegal number in the previous step.
1360b57cec5SDimitry Andric // Since each illegal number is unique, we only need one of them between
1370b57cec5SDimitry Andric // each range of legal numbers. This lets us make sure we don't add more
1380b57cec5SDimitry Andric // than one illegal number per range.
1390b57cec5SDimitry Andric bool AddedIllegalLastTime = false;
1400b57cec5SDimitry Andric
1410b57cec5SDimitry Andric /// Maps \p *It to a legal integer.
1420b57cec5SDimitry Andric ///
1430b57cec5SDimitry Andric /// Updates \p CanOutlineWithPrevInstr, \p HaveLegalRange, \p InstrListForMBB,
1440b57cec5SDimitry Andric /// \p UnsignedVecForMBB, \p InstructionIntegerMap, and \p LegalInstrNumber.
1450b57cec5SDimitry Andric ///
1460b57cec5SDimitry Andric /// \returns The integer that \p *It was mapped to.
mapToLegalUnsigned__anon306d754f0111::InstructionMapper1470b57cec5SDimitry Andric unsigned mapToLegalUnsigned(
1480b57cec5SDimitry Andric MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
1490b57cec5SDimitry Andric bool &HaveLegalRange, unsigned &NumLegalInBlock,
1500b57cec5SDimitry Andric std::vector<unsigned> &UnsignedVecForMBB,
1510b57cec5SDimitry Andric std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
1520b57cec5SDimitry Andric // We added something legal, so we should unset the AddedLegalLastTime
1530b57cec5SDimitry Andric // flag.
1540b57cec5SDimitry Andric AddedIllegalLastTime = false;
1550b57cec5SDimitry Andric
1560b57cec5SDimitry Andric // If we have at least two adjacent legal instructions (which may have
1570b57cec5SDimitry Andric // invisible instructions in between), remember that.
1580b57cec5SDimitry Andric if (CanOutlineWithPrevInstr)
1590b57cec5SDimitry Andric HaveLegalRange = true;
1600b57cec5SDimitry Andric CanOutlineWithPrevInstr = true;
1610b57cec5SDimitry Andric
1620b57cec5SDimitry Andric // Keep track of the number of legal instructions we insert.
1630b57cec5SDimitry Andric NumLegalInBlock++;
1640b57cec5SDimitry Andric
1650b57cec5SDimitry Andric // Get the integer for this instruction or give it the current
1660b57cec5SDimitry Andric // LegalInstrNumber.
1670b57cec5SDimitry Andric InstrListForMBB.push_back(It);
1680b57cec5SDimitry Andric MachineInstr &MI = *It;
1690b57cec5SDimitry Andric bool WasInserted;
1700b57cec5SDimitry Andric DenseMap<MachineInstr *, unsigned, MachineInstrExpressionTrait>::iterator
1710b57cec5SDimitry Andric ResultIt;
1720b57cec5SDimitry Andric std::tie(ResultIt, WasInserted) =
1730b57cec5SDimitry Andric InstructionIntegerMap.insert(std::make_pair(&MI, LegalInstrNumber));
1740b57cec5SDimitry Andric unsigned MINumber = ResultIt->second;
1750b57cec5SDimitry Andric
1760b57cec5SDimitry Andric // There was an insertion.
1770b57cec5SDimitry Andric if (WasInserted)
1780b57cec5SDimitry Andric LegalInstrNumber++;
1790b57cec5SDimitry Andric
1800b57cec5SDimitry Andric UnsignedVecForMBB.push_back(MINumber);
1810b57cec5SDimitry Andric
1820b57cec5SDimitry Andric // Make sure we don't overflow or use any integers reserved by the DenseMap.
1830b57cec5SDimitry Andric if (LegalInstrNumber >= IllegalInstrNumber)
1840b57cec5SDimitry Andric report_fatal_error("Instruction mapping overflow!");
1850b57cec5SDimitry Andric
1860b57cec5SDimitry Andric assert(LegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
1870b57cec5SDimitry Andric "Tried to assign DenseMap tombstone or empty key to instruction.");
1880b57cec5SDimitry Andric assert(LegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
1890b57cec5SDimitry Andric "Tried to assign DenseMap tombstone or empty key to instruction.");
1900b57cec5SDimitry Andric
1910b57cec5SDimitry Andric return MINumber;
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric
1940b57cec5SDimitry Andric /// Maps \p *It to an illegal integer.
1950b57cec5SDimitry Andric ///
1960b57cec5SDimitry Andric /// Updates \p InstrListForMBB, \p UnsignedVecForMBB, and \p
1970b57cec5SDimitry Andric /// IllegalInstrNumber.
1980b57cec5SDimitry Andric ///
1990b57cec5SDimitry Andric /// \returns The integer that \p *It was mapped to.
mapToIllegalUnsigned__anon306d754f0111::InstructionMapper200480093f4SDimitry Andric unsigned mapToIllegalUnsigned(
201480093f4SDimitry Andric MachineBasicBlock::iterator &It, bool &CanOutlineWithPrevInstr,
202480093f4SDimitry Andric std::vector<unsigned> &UnsignedVecForMBB,
2030b57cec5SDimitry Andric std::vector<MachineBasicBlock::iterator> &InstrListForMBB) {
2040b57cec5SDimitry Andric // Can't outline an illegal instruction. Set the flag.
2050b57cec5SDimitry Andric CanOutlineWithPrevInstr = false;
2060b57cec5SDimitry Andric
2070b57cec5SDimitry Andric // Only add one illegal number per range of legal numbers.
2080b57cec5SDimitry Andric if (AddedIllegalLastTime)
2090b57cec5SDimitry Andric return IllegalInstrNumber;
2100b57cec5SDimitry Andric
2110b57cec5SDimitry Andric // Remember that we added an illegal number last time.
2120b57cec5SDimitry Andric AddedIllegalLastTime = true;
2130b57cec5SDimitry Andric unsigned MINumber = IllegalInstrNumber;
2140b57cec5SDimitry Andric
2150b57cec5SDimitry Andric InstrListForMBB.push_back(It);
2160b57cec5SDimitry Andric UnsignedVecForMBB.push_back(IllegalInstrNumber);
2170b57cec5SDimitry Andric IllegalInstrNumber--;
2180b57cec5SDimitry Andric
2190b57cec5SDimitry Andric assert(LegalInstrNumber < IllegalInstrNumber &&
2200b57cec5SDimitry Andric "Instruction mapping overflow!");
2210b57cec5SDimitry Andric
2220b57cec5SDimitry Andric assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getEmptyKey() &&
2230b57cec5SDimitry Andric "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
2240b57cec5SDimitry Andric
2250b57cec5SDimitry Andric assert(IllegalInstrNumber != DenseMapInfo<unsigned>::getTombstoneKey() &&
2260b57cec5SDimitry Andric "IllegalInstrNumber cannot be DenseMap tombstone or empty key!");
2270b57cec5SDimitry Andric
2280b57cec5SDimitry Andric return MINumber;
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric
2310b57cec5SDimitry Andric /// Transforms a \p MachineBasicBlock into a \p vector of \p unsigneds
2320b57cec5SDimitry Andric /// and appends it to \p UnsignedVec and \p InstrList.
2330b57cec5SDimitry Andric ///
2340b57cec5SDimitry Andric /// Two instructions are assigned the same integer if they are identical.
2350b57cec5SDimitry Andric /// If an instruction is deemed unsafe to outline, then it will be assigned an
2360b57cec5SDimitry Andric /// unique integer. The resulting mapping is placed into a suffix tree and
2370b57cec5SDimitry Andric /// queried for candidates.
2380b57cec5SDimitry Andric ///
2390b57cec5SDimitry Andric /// \param MBB The \p MachineBasicBlock to be translated into integers.
2400b57cec5SDimitry Andric /// \param TII \p TargetInstrInfo for the function.
convertToUnsignedVec__anon306d754f0111::InstructionMapper2410b57cec5SDimitry Andric void convertToUnsignedVec(MachineBasicBlock &MBB,
2420b57cec5SDimitry Andric const TargetInstrInfo &TII) {
2430b57cec5SDimitry Andric unsigned Flags = 0;
2440b57cec5SDimitry Andric
2450b57cec5SDimitry Andric // Don't even map in this case.
2460b57cec5SDimitry Andric if (!TII.isMBBSafeToOutlineFrom(MBB, Flags))
2470b57cec5SDimitry Andric return;
2480b57cec5SDimitry Andric
2490b57cec5SDimitry Andric // Store info for the MBB for later outlining.
2500b57cec5SDimitry Andric MBBFlagsMap[&MBB] = Flags;
2510b57cec5SDimitry Andric
2520b57cec5SDimitry Andric MachineBasicBlock::iterator It = MBB.begin();
2530b57cec5SDimitry Andric
2540b57cec5SDimitry Andric // The number of instructions in this block that will be considered for
2550b57cec5SDimitry Andric // outlining.
2560b57cec5SDimitry Andric unsigned NumLegalInBlock = 0;
2570b57cec5SDimitry Andric
2580b57cec5SDimitry Andric // True if we have at least two legal instructions which aren't separated
2590b57cec5SDimitry Andric // by an illegal instruction.
2600b57cec5SDimitry Andric bool HaveLegalRange = false;
2610b57cec5SDimitry Andric
2620b57cec5SDimitry Andric // True if we can perform outlining given the last mapped (non-invisible)
2630b57cec5SDimitry Andric // instruction. This lets us know if we have a legal range.
2640b57cec5SDimitry Andric bool CanOutlineWithPrevInstr = false;
2650b57cec5SDimitry Andric
2660b57cec5SDimitry Andric // FIXME: Should this all just be handled in the target, rather than using
2670b57cec5SDimitry Andric // repeated calls to getOutliningType?
2680b57cec5SDimitry Andric std::vector<unsigned> UnsignedVecForMBB;
2690b57cec5SDimitry Andric std::vector<MachineBasicBlock::iterator> InstrListForMBB;
2700b57cec5SDimitry Andric
271480093f4SDimitry Andric for (MachineBasicBlock::iterator Et = MBB.end(); It != Et; ++It) {
2720b57cec5SDimitry Andric // Keep track of where this instruction is in the module.
2730b57cec5SDimitry Andric switch (TII.getOutliningType(It, Flags)) {
2740b57cec5SDimitry Andric case InstrType::Illegal:
275480093f4SDimitry Andric mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
276480093f4SDimitry Andric InstrListForMBB);
2770b57cec5SDimitry Andric break;
2780b57cec5SDimitry Andric
2790b57cec5SDimitry Andric case InstrType::Legal:
2800b57cec5SDimitry Andric mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
2810b57cec5SDimitry Andric NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
2820b57cec5SDimitry Andric break;
2830b57cec5SDimitry Andric
2840b57cec5SDimitry Andric case InstrType::LegalTerminator:
2850b57cec5SDimitry Andric mapToLegalUnsigned(It, CanOutlineWithPrevInstr, HaveLegalRange,
2860b57cec5SDimitry Andric NumLegalInBlock, UnsignedVecForMBB, InstrListForMBB);
2870b57cec5SDimitry Andric // The instruction also acts as a terminator, so we have to record that
2880b57cec5SDimitry Andric // in the string.
2890b57cec5SDimitry Andric mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
2900b57cec5SDimitry Andric InstrListForMBB);
2910b57cec5SDimitry Andric break;
2920b57cec5SDimitry Andric
2930b57cec5SDimitry Andric case InstrType::Invisible:
2940b57cec5SDimitry Andric // Normally this is set by mapTo(Blah)Unsigned, but we just want to
2950b57cec5SDimitry Andric // skip this instruction. So, unset the flag here.
2960b57cec5SDimitry Andric AddedIllegalLastTime = false;
2970b57cec5SDimitry Andric break;
2980b57cec5SDimitry Andric }
2990b57cec5SDimitry Andric }
3000b57cec5SDimitry Andric
3010b57cec5SDimitry Andric // Are there enough legal instructions in the block for outlining to be
3020b57cec5SDimitry Andric // possible?
3030b57cec5SDimitry Andric if (HaveLegalRange) {
3040b57cec5SDimitry Andric // After we're done every insertion, uniquely terminate this part of the
3050b57cec5SDimitry Andric // "string". This makes sure we won't match across basic block or function
3060b57cec5SDimitry Andric // boundaries since the "end" is encoded uniquely and thus appears in no
3070b57cec5SDimitry Andric // repeated substring.
3080b57cec5SDimitry Andric mapToIllegalUnsigned(It, CanOutlineWithPrevInstr, UnsignedVecForMBB,
3090b57cec5SDimitry Andric InstrListForMBB);
310af732203SDimitry Andric llvm::append_range(InstrList, InstrListForMBB);
311af732203SDimitry Andric llvm::append_range(UnsignedVec, UnsignedVecForMBB);
3120b57cec5SDimitry Andric }
3130b57cec5SDimitry Andric }
3140b57cec5SDimitry Andric
InstructionMapper__anon306d754f0111::InstructionMapper3150b57cec5SDimitry Andric InstructionMapper() {
3160b57cec5SDimitry Andric // Make sure that the implementation of DenseMapInfo<unsigned> hasn't
3170b57cec5SDimitry Andric // changed.
3180b57cec5SDimitry Andric assert(DenseMapInfo<unsigned>::getEmptyKey() == (unsigned)-1 &&
3190b57cec5SDimitry Andric "DenseMapInfo<unsigned>'s empty key isn't -1!");
3200b57cec5SDimitry Andric assert(DenseMapInfo<unsigned>::getTombstoneKey() == (unsigned)-2 &&
3210b57cec5SDimitry Andric "DenseMapInfo<unsigned>'s tombstone key isn't -2!");
3220b57cec5SDimitry Andric }
3230b57cec5SDimitry Andric };
3240b57cec5SDimitry Andric
3250b57cec5SDimitry Andric /// An interprocedural pass which finds repeated sequences of
3260b57cec5SDimitry Andric /// instructions and replaces them with calls to functions.
3270b57cec5SDimitry Andric ///
3280b57cec5SDimitry Andric /// Each instruction is mapped to an unsigned integer and placed in a string.
3290b57cec5SDimitry Andric /// The resulting mapping is then placed in a \p SuffixTree. The \p SuffixTree
3300b57cec5SDimitry Andric /// is then repeatedly queried for repeated sequences of instructions. Each
3310b57cec5SDimitry Andric /// non-overlapping repeated sequence is then placed in its own
3320b57cec5SDimitry Andric /// \p MachineFunction and each instance is then replaced with a call to that
3330b57cec5SDimitry Andric /// function.
3340b57cec5SDimitry Andric struct MachineOutliner : public ModulePass {
3350b57cec5SDimitry Andric
3360b57cec5SDimitry Andric static char ID;
3370b57cec5SDimitry Andric
3380b57cec5SDimitry Andric /// Set to true if the outliner should consider functions with
3390b57cec5SDimitry Andric /// linkonceodr linkage.
3400b57cec5SDimitry Andric bool OutlineFromLinkOnceODRs = false;
3410b57cec5SDimitry Andric
3425ffd83dbSDimitry Andric /// The current repeat number of machine outlining.
3435ffd83dbSDimitry Andric unsigned OutlineRepeatedNum = 0;
3445ffd83dbSDimitry Andric
3450b57cec5SDimitry Andric /// Set to true if the outliner should run on all functions in the module
3460b57cec5SDimitry Andric /// considered safe for outlining.
3470b57cec5SDimitry Andric /// Set to true by default for compatibility with llc's -run-pass option.
3480b57cec5SDimitry Andric /// Set when the pass is constructed in TargetPassConfig.
3490b57cec5SDimitry Andric bool RunOnAllFunctions = true;
3500b57cec5SDimitry Andric
getPassName__anon306d754f0111::MachineOutliner3510b57cec5SDimitry Andric StringRef getPassName() const override { return "Machine Outliner"; }
3520b57cec5SDimitry Andric
getAnalysisUsage__anon306d754f0111::MachineOutliner3530b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
3548bcb0991SDimitry Andric AU.addRequired<MachineModuleInfoWrapperPass>();
3558bcb0991SDimitry Andric AU.addPreserved<MachineModuleInfoWrapperPass>();
3560b57cec5SDimitry Andric AU.setPreservesAll();
3570b57cec5SDimitry Andric ModulePass::getAnalysisUsage(AU);
3580b57cec5SDimitry Andric }
3590b57cec5SDimitry Andric
MachineOutliner__anon306d754f0111::MachineOutliner3600b57cec5SDimitry Andric MachineOutliner() : ModulePass(ID) {
3610b57cec5SDimitry Andric initializeMachineOutlinerPass(*PassRegistry::getPassRegistry());
3620b57cec5SDimitry Andric }
3630b57cec5SDimitry Andric
3640b57cec5SDimitry Andric /// Remark output explaining that not outlining a set of candidates would be
3650b57cec5SDimitry Andric /// better than outlining that set.
3660b57cec5SDimitry Andric void emitNotOutliningCheaperRemark(
3670b57cec5SDimitry Andric unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
3680b57cec5SDimitry Andric OutlinedFunction &OF);
3690b57cec5SDimitry Andric
3700b57cec5SDimitry Andric /// Remark output explaining that a function was outlined.
3710b57cec5SDimitry Andric void emitOutlinedFunctionRemark(OutlinedFunction &OF);
3720b57cec5SDimitry Andric
3730b57cec5SDimitry Andric /// Find all repeated substrings that satisfy the outlining cost model by
3740b57cec5SDimitry Andric /// constructing a suffix tree.
3750b57cec5SDimitry Andric ///
3760b57cec5SDimitry Andric /// If a substring appears at least twice, then it must be represented by
3770b57cec5SDimitry Andric /// an internal node which appears in at least two suffixes. Each suffix
3780b57cec5SDimitry Andric /// is represented by a leaf node. To do this, we visit each internal node
3790b57cec5SDimitry Andric /// in the tree, using the leaf children of each internal node. If an
3800b57cec5SDimitry Andric /// internal node represents a beneficial substring, then we use each of
3810b57cec5SDimitry Andric /// its leaf children to find the locations of its substring.
3820b57cec5SDimitry Andric ///
3830b57cec5SDimitry Andric /// \param Mapper Contains outlining mapping information.
3840b57cec5SDimitry Andric /// \param[out] FunctionList Filled with a list of \p OutlinedFunctions
3850b57cec5SDimitry Andric /// each type of candidate.
3860b57cec5SDimitry Andric void findCandidates(InstructionMapper &Mapper,
3870b57cec5SDimitry Andric std::vector<OutlinedFunction> &FunctionList);
3880b57cec5SDimitry Andric
3890b57cec5SDimitry Andric /// Replace the sequences of instructions represented by \p OutlinedFunctions
3900b57cec5SDimitry Andric /// with calls to functions.
3910b57cec5SDimitry Andric ///
3920b57cec5SDimitry Andric /// \param M The module we are outlining from.
3930b57cec5SDimitry Andric /// \param FunctionList A list of functions to be inserted into the module.
3940b57cec5SDimitry Andric /// \param Mapper Contains the instruction mappings for the module.
3950b57cec5SDimitry Andric bool outline(Module &M, std::vector<OutlinedFunction> &FunctionList,
396480093f4SDimitry Andric InstructionMapper &Mapper, unsigned &OutlinedFunctionNum);
3970b57cec5SDimitry Andric
3980b57cec5SDimitry Andric /// Creates a function for \p OF and inserts it into the module.
3990b57cec5SDimitry Andric MachineFunction *createOutlinedFunction(Module &M, OutlinedFunction &OF,
4000b57cec5SDimitry Andric InstructionMapper &Mapper,
4010b57cec5SDimitry Andric unsigned Name);
4020b57cec5SDimitry Andric
4035ffd83dbSDimitry Andric /// Calls 'doOutline()' 1 + OutlinerReruns times.
404480093f4SDimitry Andric bool runOnModule(Module &M) override;
405480093f4SDimitry Andric
4060b57cec5SDimitry Andric /// Construct a suffix tree on the instructions in \p M and outline repeated
4070b57cec5SDimitry Andric /// strings from that tree.
408480093f4SDimitry Andric bool doOutline(Module &M, unsigned &OutlinedFunctionNum);
4090b57cec5SDimitry Andric
4100b57cec5SDimitry Andric /// Return a DISubprogram for OF if one exists, and null otherwise. Helper
4110b57cec5SDimitry Andric /// function for remark emission.
getSubprogramOrNull__anon306d754f0111::MachineOutliner4120b57cec5SDimitry Andric DISubprogram *getSubprogramOrNull(const OutlinedFunction &OF) {
4130b57cec5SDimitry Andric for (const Candidate &C : OF.Candidates)
414480093f4SDimitry Andric if (MachineFunction *MF = C.getMF())
415480093f4SDimitry Andric if (DISubprogram *SP = MF->getFunction().getSubprogram())
4160b57cec5SDimitry Andric return SP;
4170b57cec5SDimitry Andric return nullptr;
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric
4200b57cec5SDimitry Andric /// Populate and \p InstructionMapper with instruction-to-integer mappings.
4210b57cec5SDimitry Andric /// These are used to construct a suffix tree.
4220b57cec5SDimitry Andric void populateMapper(InstructionMapper &Mapper, Module &M,
4230b57cec5SDimitry Andric MachineModuleInfo &MMI);
4240b57cec5SDimitry Andric
4250b57cec5SDimitry Andric /// Initialize information necessary to output a size remark.
4260b57cec5SDimitry Andric /// FIXME: This should be handled by the pass manager, not the outliner.
4270b57cec5SDimitry Andric /// FIXME: This is nearly identical to the initSizeRemarkInfo in the legacy
4280b57cec5SDimitry Andric /// pass manager.
429480093f4SDimitry Andric void initSizeRemarkInfo(const Module &M, const MachineModuleInfo &MMI,
4300b57cec5SDimitry Andric StringMap<unsigned> &FunctionToInstrCount);
4310b57cec5SDimitry Andric
4320b57cec5SDimitry Andric /// Emit the remark.
4330b57cec5SDimitry Andric // FIXME: This should be handled by the pass manager, not the outliner.
434480093f4SDimitry Andric void
435480093f4SDimitry Andric emitInstrCountChangedRemark(const Module &M, const MachineModuleInfo &MMI,
4360b57cec5SDimitry Andric const StringMap<unsigned> &FunctionToInstrCount);
4370b57cec5SDimitry Andric };
4380b57cec5SDimitry Andric } // Anonymous namespace.
4390b57cec5SDimitry Andric
4400b57cec5SDimitry Andric char MachineOutliner::ID = 0;
4410b57cec5SDimitry Andric
4420b57cec5SDimitry Andric namespace llvm {
createMachineOutlinerPass(bool RunOnAllFunctions)4430b57cec5SDimitry Andric ModulePass *createMachineOutlinerPass(bool RunOnAllFunctions) {
4440b57cec5SDimitry Andric MachineOutliner *OL = new MachineOutliner();
4450b57cec5SDimitry Andric OL->RunOnAllFunctions = RunOnAllFunctions;
4460b57cec5SDimitry Andric return OL;
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric
4490b57cec5SDimitry Andric } // namespace llvm
4500b57cec5SDimitry Andric
4510b57cec5SDimitry Andric INITIALIZE_PASS(MachineOutliner, DEBUG_TYPE, "Machine Function Outliner", false,
4520b57cec5SDimitry Andric false)
4530b57cec5SDimitry Andric
emitNotOutliningCheaperRemark(unsigned StringLen,std::vector<Candidate> & CandidatesForRepeatedSeq,OutlinedFunction & OF)4540b57cec5SDimitry Andric void MachineOutliner::emitNotOutliningCheaperRemark(
4550b57cec5SDimitry Andric unsigned StringLen, std::vector<Candidate> &CandidatesForRepeatedSeq,
4560b57cec5SDimitry Andric OutlinedFunction &OF) {
4570b57cec5SDimitry Andric // FIXME: Right now, we arbitrarily choose some Candidate from the
4580b57cec5SDimitry Andric // OutlinedFunction. This isn't necessarily fixed, nor does it have to be.
4590b57cec5SDimitry Andric // We should probably sort these by function name or something to make sure
4600b57cec5SDimitry Andric // the remarks are stable.
4610b57cec5SDimitry Andric Candidate &C = CandidatesForRepeatedSeq.front();
4620b57cec5SDimitry Andric MachineOptimizationRemarkEmitter MORE(*(C.getMF()), nullptr);
4630b57cec5SDimitry Andric MORE.emit([&]() {
4640b57cec5SDimitry Andric MachineOptimizationRemarkMissed R(DEBUG_TYPE, "NotOutliningCheaper",
4650b57cec5SDimitry Andric C.front()->getDebugLoc(), C.getMBB());
4660b57cec5SDimitry Andric R << "Did not outline " << NV("Length", StringLen) << " instructions"
4670b57cec5SDimitry Andric << " from " << NV("NumOccurrences", CandidatesForRepeatedSeq.size())
4680b57cec5SDimitry Andric << " locations."
4690b57cec5SDimitry Andric << " Bytes from outlining all occurrences ("
4700b57cec5SDimitry Andric << NV("OutliningCost", OF.getOutliningCost()) << ")"
4710b57cec5SDimitry Andric << " >= Unoutlined instruction bytes ("
4720b57cec5SDimitry Andric << NV("NotOutliningCost", OF.getNotOutlinedCost()) << ")"
4730b57cec5SDimitry Andric << " (Also found at: ";
4740b57cec5SDimitry Andric
4750b57cec5SDimitry Andric // Tell the user the other places the candidate was found.
4760b57cec5SDimitry Andric for (unsigned i = 1, e = CandidatesForRepeatedSeq.size(); i < e; i++) {
4770b57cec5SDimitry Andric R << NV((Twine("OtherStartLoc") + Twine(i)).str(),
4780b57cec5SDimitry Andric CandidatesForRepeatedSeq[i].front()->getDebugLoc());
4790b57cec5SDimitry Andric if (i != e - 1)
4800b57cec5SDimitry Andric R << ", ";
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric
4830b57cec5SDimitry Andric R << ")";
4840b57cec5SDimitry Andric return R;
4850b57cec5SDimitry Andric });
4860b57cec5SDimitry Andric }
4870b57cec5SDimitry Andric
emitOutlinedFunctionRemark(OutlinedFunction & OF)4880b57cec5SDimitry Andric void MachineOutliner::emitOutlinedFunctionRemark(OutlinedFunction &OF) {
4890b57cec5SDimitry Andric MachineBasicBlock *MBB = &*OF.MF->begin();
4900b57cec5SDimitry Andric MachineOptimizationRemarkEmitter MORE(*OF.MF, nullptr);
4910b57cec5SDimitry Andric MachineOptimizationRemark R(DEBUG_TYPE, "OutlinedFunction",
4920b57cec5SDimitry Andric MBB->findDebugLoc(MBB->begin()), MBB);
4930b57cec5SDimitry Andric R << "Saved " << NV("OutliningBenefit", OF.getBenefit()) << " bytes by "
4940b57cec5SDimitry Andric << "outlining " << NV("Length", OF.getNumInstrs()) << " instructions "
4950b57cec5SDimitry Andric << "from " << NV("NumOccurrences", OF.getOccurrenceCount())
4960b57cec5SDimitry Andric << " locations. "
4970b57cec5SDimitry Andric << "(Found at: ";
4980b57cec5SDimitry Andric
4990b57cec5SDimitry Andric // Tell the user the other places the candidate was found.
5000b57cec5SDimitry Andric for (size_t i = 0, e = OF.Candidates.size(); i < e; i++) {
5010b57cec5SDimitry Andric
5020b57cec5SDimitry Andric R << NV((Twine("StartLoc") + Twine(i)).str(),
5030b57cec5SDimitry Andric OF.Candidates[i].front()->getDebugLoc());
5040b57cec5SDimitry Andric if (i != e - 1)
5050b57cec5SDimitry Andric R << ", ";
5060b57cec5SDimitry Andric }
5070b57cec5SDimitry Andric
5080b57cec5SDimitry Andric R << ")";
5090b57cec5SDimitry Andric
5100b57cec5SDimitry Andric MORE.emit(R);
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric
findCandidates(InstructionMapper & Mapper,std::vector<OutlinedFunction> & FunctionList)513480093f4SDimitry Andric void MachineOutliner::findCandidates(
514480093f4SDimitry Andric InstructionMapper &Mapper, std::vector<OutlinedFunction> &FunctionList) {
5150b57cec5SDimitry Andric FunctionList.clear();
5160b57cec5SDimitry Andric SuffixTree ST(Mapper.UnsignedVec);
5170b57cec5SDimitry Andric
518480093f4SDimitry Andric // First, find all of the repeated substrings in the tree of minimum length
5190b57cec5SDimitry Andric // 2.
5200b57cec5SDimitry Andric std::vector<Candidate> CandidatesForRepeatedSeq;
521*5f7ddb14SDimitry Andric for (const SuffixTree::RepeatedSubstring &RS : ST) {
5220b57cec5SDimitry Andric CandidatesForRepeatedSeq.clear();
5230b57cec5SDimitry Andric unsigned StringLen = RS.Length;
5240b57cec5SDimitry Andric for (const unsigned &StartIdx : RS.StartIndices) {
5250b57cec5SDimitry Andric unsigned EndIdx = StartIdx + StringLen - 1;
5260b57cec5SDimitry Andric // Trick: Discard some candidates that would be incompatible with the
5270b57cec5SDimitry Andric // ones we've already found for this sequence. This will save us some
5280b57cec5SDimitry Andric // work in candidate selection.
5290b57cec5SDimitry Andric //
5300b57cec5SDimitry Andric // If two candidates overlap, then we can't outline them both. This
5310b57cec5SDimitry Andric // happens when we have candidates that look like, say
5320b57cec5SDimitry Andric //
5330b57cec5SDimitry Andric // AA (where each "A" is an instruction).
5340b57cec5SDimitry Andric //
5350b57cec5SDimitry Andric // We might have some portion of the module that looks like this:
5360b57cec5SDimitry Andric // AAAAAA (6 A's)
5370b57cec5SDimitry Andric //
5380b57cec5SDimitry Andric // In this case, there are 5 different copies of "AA" in this range, but
5390b57cec5SDimitry Andric // at most 3 can be outlined. If only outlining 3 of these is going to
5400b57cec5SDimitry Andric // be unbeneficial, then we ought to not bother.
5410b57cec5SDimitry Andric //
5420b57cec5SDimitry Andric // Note that two things DON'T overlap when they look like this:
5430b57cec5SDimitry Andric // start1...end1 .... start2...end2
5440b57cec5SDimitry Andric // That is, one must either
5450b57cec5SDimitry Andric // * End before the other starts
5460b57cec5SDimitry Andric // * Start after the other ends
547af732203SDimitry Andric if (llvm::all_of(CandidatesForRepeatedSeq, [&StartIdx,
548af732203SDimitry Andric &EndIdx](const Candidate &C) {
5490b57cec5SDimitry Andric return (EndIdx < C.getStartIdx() || StartIdx > C.getEndIdx());
5500b57cec5SDimitry Andric })) {
5510b57cec5SDimitry Andric // It doesn't overlap with anything, so we can outline it.
5520b57cec5SDimitry Andric // Each sequence is over [StartIt, EndIt].
5530b57cec5SDimitry Andric // Save the candidate and its location.
5540b57cec5SDimitry Andric
5550b57cec5SDimitry Andric MachineBasicBlock::iterator StartIt = Mapper.InstrList[StartIdx];
5560b57cec5SDimitry Andric MachineBasicBlock::iterator EndIt = Mapper.InstrList[EndIdx];
5570b57cec5SDimitry Andric MachineBasicBlock *MBB = StartIt->getParent();
5580b57cec5SDimitry Andric
5590b57cec5SDimitry Andric CandidatesForRepeatedSeq.emplace_back(StartIdx, StringLen, StartIt,
5600b57cec5SDimitry Andric EndIt, MBB, FunctionList.size(),
5610b57cec5SDimitry Andric Mapper.MBBFlagsMap[MBB]);
5620b57cec5SDimitry Andric }
5630b57cec5SDimitry Andric }
5640b57cec5SDimitry Andric
5650b57cec5SDimitry Andric // We've found something we might want to outline.
5660b57cec5SDimitry Andric // Create an OutlinedFunction to store it and check if it'd be beneficial
5670b57cec5SDimitry Andric // to outline.
5680b57cec5SDimitry Andric if (CandidatesForRepeatedSeq.size() < 2)
5690b57cec5SDimitry Andric continue;
5700b57cec5SDimitry Andric
5710b57cec5SDimitry Andric // Arbitrarily choose a TII from the first candidate.
5720b57cec5SDimitry Andric // FIXME: Should getOutliningCandidateInfo move to TargetMachine?
5730b57cec5SDimitry Andric const TargetInstrInfo *TII =
5740b57cec5SDimitry Andric CandidatesForRepeatedSeq[0].getMF()->getSubtarget().getInstrInfo();
5750b57cec5SDimitry Andric
5760b57cec5SDimitry Andric OutlinedFunction OF =
5770b57cec5SDimitry Andric TII->getOutliningCandidateInfo(CandidatesForRepeatedSeq);
5780b57cec5SDimitry Andric
5790b57cec5SDimitry Andric // If we deleted too many candidates, then there's nothing worth outlining.
5800b57cec5SDimitry Andric // FIXME: This should take target-specified instruction sizes into account.
5810b57cec5SDimitry Andric if (OF.Candidates.size() < 2)
5820b57cec5SDimitry Andric continue;
5830b57cec5SDimitry Andric
5840b57cec5SDimitry Andric // Is it better to outline this candidate than not?
5850b57cec5SDimitry Andric if (OF.getBenefit() < 1) {
5860b57cec5SDimitry Andric emitNotOutliningCheaperRemark(StringLen, CandidatesForRepeatedSeq, OF);
5870b57cec5SDimitry Andric continue;
5880b57cec5SDimitry Andric }
5890b57cec5SDimitry Andric
5900b57cec5SDimitry Andric FunctionList.push_back(OF);
5910b57cec5SDimitry Andric }
5920b57cec5SDimitry Andric }
5930b57cec5SDimitry Andric
createOutlinedFunction(Module & M,OutlinedFunction & OF,InstructionMapper & Mapper,unsigned Name)594480093f4SDimitry Andric MachineFunction *MachineOutliner::createOutlinedFunction(
595480093f4SDimitry Andric Module &M, OutlinedFunction &OF, InstructionMapper &Mapper, unsigned Name) {
5960b57cec5SDimitry Andric
5970b57cec5SDimitry Andric // Create the function name. This should be unique.
5980b57cec5SDimitry Andric // FIXME: We should have a better naming scheme. This should be stable,
5990b57cec5SDimitry Andric // regardless of changes to the outliner's cost model/traversal order.
6005ffd83dbSDimitry Andric std::string FunctionName = "OUTLINED_FUNCTION_";
6015ffd83dbSDimitry Andric if (OutlineRepeatedNum > 0)
6025ffd83dbSDimitry Andric FunctionName += std::to_string(OutlineRepeatedNum + 1) + "_";
6035ffd83dbSDimitry Andric FunctionName += std::to_string(Name);
6040b57cec5SDimitry Andric
6050b57cec5SDimitry Andric // Create the function using an IR-level function.
6060b57cec5SDimitry Andric LLVMContext &C = M.getContext();
6070b57cec5SDimitry Andric Function *F = Function::Create(FunctionType::get(Type::getVoidTy(C), false),
6080b57cec5SDimitry Andric Function::ExternalLinkage, FunctionName, M);
6090b57cec5SDimitry Andric
6100b57cec5SDimitry Andric // NOTE: If this is linkonceodr, then we can take advantage of linker deduping
6110b57cec5SDimitry Andric // which gives us better results when we outline from linkonceodr functions.
6120b57cec5SDimitry Andric F->setLinkage(GlobalValue::InternalLinkage);
6130b57cec5SDimitry Andric F->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
6140b57cec5SDimitry Andric
6150b57cec5SDimitry Andric // Set optsize/minsize, so we don't insert padding between outlined
6160b57cec5SDimitry Andric // functions.
6170b57cec5SDimitry Andric F->addFnAttr(Attribute::OptimizeForSize);
6180b57cec5SDimitry Andric F->addFnAttr(Attribute::MinSize);
6190b57cec5SDimitry Andric
6200b57cec5SDimitry Andric // Include target features from an arbitrary candidate for the outlined
6210b57cec5SDimitry Andric // function. This makes sure the outlined function knows what kinds of
6220b57cec5SDimitry Andric // instructions are going into it. This is fine, since all parent functions
6230b57cec5SDimitry Andric // must necessarily support the instructions that are in the outlined region.
6240b57cec5SDimitry Andric Candidate &FirstCand = OF.Candidates.front();
6250b57cec5SDimitry Andric const Function &ParentFn = FirstCand.getMF()->getFunction();
6260b57cec5SDimitry Andric if (ParentFn.hasFnAttribute("target-features"))
6270b57cec5SDimitry Andric F->addFnAttr(ParentFn.getFnAttribute("target-features"));
6280b57cec5SDimitry Andric
6295ffd83dbSDimitry Andric // Set nounwind, so we don't generate eh_frame.
6305ffd83dbSDimitry Andric if (llvm::all_of(OF.Candidates, [](const outliner::Candidate &C) {
6315ffd83dbSDimitry Andric return C.getMF()->getFunction().hasFnAttribute(Attribute::NoUnwind);
6325ffd83dbSDimitry Andric }))
6335ffd83dbSDimitry Andric F->addFnAttr(Attribute::NoUnwind);
6345ffd83dbSDimitry Andric
6350b57cec5SDimitry Andric BasicBlock *EntryBB = BasicBlock::Create(C, "entry", F);
6360b57cec5SDimitry Andric IRBuilder<> Builder(EntryBB);
6370b57cec5SDimitry Andric Builder.CreateRetVoid();
6380b57cec5SDimitry Andric
6398bcb0991SDimitry Andric MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
6400b57cec5SDimitry Andric MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
6410b57cec5SDimitry Andric MachineBasicBlock &MBB = *MF.CreateMachineBasicBlock();
6420b57cec5SDimitry Andric const TargetSubtargetInfo &STI = MF.getSubtarget();
6430b57cec5SDimitry Andric const TargetInstrInfo &TII = *STI.getInstrInfo();
6440b57cec5SDimitry Andric
6450b57cec5SDimitry Andric // Insert the new function into the module.
6460b57cec5SDimitry Andric MF.insert(MF.begin(), &MBB);
6470b57cec5SDimitry Andric
6485ffd83dbSDimitry Andric MachineFunction *OriginalMF = FirstCand.front()->getMF();
6495ffd83dbSDimitry Andric const std::vector<MCCFIInstruction> &Instrs =
6505ffd83dbSDimitry Andric OriginalMF->getFrameInstructions();
6510b57cec5SDimitry Andric for (auto I = FirstCand.front(), E = std::next(FirstCand.back()); I != E;
6520b57cec5SDimitry Andric ++I) {
653af732203SDimitry Andric if (I->isDebugInstr())
654af732203SDimitry Andric continue;
6550b57cec5SDimitry Andric MachineInstr *NewMI = MF.CloneMachineInstr(&*I);
6565ffd83dbSDimitry Andric if (I->isCFIInstruction()) {
6575ffd83dbSDimitry Andric unsigned CFIIndex = NewMI->getOperand(0).getCFIIndex();
6585ffd83dbSDimitry Andric MCCFIInstruction CFI = Instrs[CFIIndex];
6595ffd83dbSDimitry Andric (void)MF.addFrameInst(CFI);
6605ffd83dbSDimitry Andric }
6610b57cec5SDimitry Andric NewMI->dropMemRefs(MF);
6620b57cec5SDimitry Andric
6630b57cec5SDimitry Andric // Don't keep debug information for outlined instructions.
6640b57cec5SDimitry Andric NewMI->setDebugLoc(DebugLoc());
6650b57cec5SDimitry Andric MBB.insert(MBB.end(), NewMI);
6660b57cec5SDimitry Andric }
6670b57cec5SDimitry Andric
6685ffd83dbSDimitry Andric // Set normal properties for a late MachineFunction.
6695ffd83dbSDimitry Andric MF.getProperties().reset(MachineFunctionProperties::Property::IsSSA);
6705ffd83dbSDimitry Andric MF.getProperties().set(MachineFunctionProperties::Property::NoPHIs);
6715ffd83dbSDimitry Andric MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs);
6725ffd83dbSDimitry Andric MF.getProperties().set(MachineFunctionProperties::Property::TracksLiveness);
6730b57cec5SDimitry Andric MF.getRegInfo().freezeReservedRegs(MF);
6740b57cec5SDimitry Andric
6755ffd83dbSDimitry Andric // Compute live-in set for outlined fn
6765ffd83dbSDimitry Andric const MachineRegisterInfo &MRI = MF.getRegInfo();
6775ffd83dbSDimitry Andric const TargetRegisterInfo &TRI = *MRI.getTargetRegisterInfo();
6785ffd83dbSDimitry Andric LivePhysRegs LiveIns(TRI);
6795ffd83dbSDimitry Andric for (auto &Cand : OF.Candidates) {
6805ffd83dbSDimitry Andric // Figure out live-ins at the first instruction.
6815ffd83dbSDimitry Andric MachineBasicBlock &OutlineBB = *Cand.front()->getParent();
6825ffd83dbSDimitry Andric LivePhysRegs CandLiveIns(TRI);
6835ffd83dbSDimitry Andric CandLiveIns.addLiveOuts(OutlineBB);
6845ffd83dbSDimitry Andric for (const MachineInstr &MI :
6855ffd83dbSDimitry Andric reverse(make_range(Cand.front(), OutlineBB.end())))
6865ffd83dbSDimitry Andric CandLiveIns.stepBackward(MI);
6875ffd83dbSDimitry Andric
6885ffd83dbSDimitry Andric // The live-in set for the outlined function is the union of the live-ins
6895ffd83dbSDimitry Andric // from all the outlining points.
690af732203SDimitry Andric for (MCPhysReg Reg : CandLiveIns)
6915ffd83dbSDimitry Andric LiveIns.addReg(Reg);
6925ffd83dbSDimitry Andric }
6935ffd83dbSDimitry Andric addLiveIns(MBB, LiveIns);
6945ffd83dbSDimitry Andric
6955ffd83dbSDimitry Andric TII.buildOutlinedFrame(MBB, MF, OF);
6965ffd83dbSDimitry Andric
6970b57cec5SDimitry Andric // If there's a DISubprogram associated with this outlined function, then
6980b57cec5SDimitry Andric // emit debug info for the outlined function.
6990b57cec5SDimitry Andric if (DISubprogram *SP = getSubprogramOrNull(OF)) {
7000b57cec5SDimitry Andric // We have a DISubprogram. Get its DICompileUnit.
7010b57cec5SDimitry Andric DICompileUnit *CU = SP->getUnit();
7020b57cec5SDimitry Andric DIBuilder DB(M, true, CU);
7030b57cec5SDimitry Andric DIFile *Unit = SP->getFile();
7040b57cec5SDimitry Andric Mangler Mg;
7050b57cec5SDimitry Andric // Get the mangled name of the function for the linkage name.
7060b57cec5SDimitry Andric std::string Dummy;
7070b57cec5SDimitry Andric llvm::raw_string_ostream MangledNameStream(Dummy);
7080b57cec5SDimitry Andric Mg.getNameWithPrefix(MangledNameStream, F, false);
7090b57cec5SDimitry Andric
7100b57cec5SDimitry Andric DISubprogram *OutlinedSP = DB.createFunction(
7110b57cec5SDimitry Andric Unit /* Context */, F->getName(), StringRef(MangledNameStream.str()),
7120b57cec5SDimitry Andric Unit /* File */,
7130b57cec5SDimitry Andric 0 /* Line 0 is reserved for compiler-generated code. */,
7140b57cec5SDimitry Andric DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
7150b57cec5SDimitry Andric 0, /* Line 0 is reserved for compiler-generated code. */
7160b57cec5SDimitry Andric DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
7170b57cec5SDimitry Andric /* Outlined code is optimized code by definition. */
7180b57cec5SDimitry Andric DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
7190b57cec5SDimitry Andric
7200b57cec5SDimitry Andric // Don't add any new variables to the subprogram.
7210b57cec5SDimitry Andric DB.finalizeSubprogram(OutlinedSP);
7220b57cec5SDimitry Andric
7230b57cec5SDimitry Andric // Attach subprogram to the function.
7240b57cec5SDimitry Andric F->setSubprogram(OutlinedSP);
7250b57cec5SDimitry Andric // We're done with the DIBuilder.
7260b57cec5SDimitry Andric DB.finalize();
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric
7290b57cec5SDimitry Andric return &MF;
7300b57cec5SDimitry Andric }
7310b57cec5SDimitry Andric
outline(Module & M,std::vector<OutlinedFunction> & FunctionList,InstructionMapper & Mapper,unsigned & OutlinedFunctionNum)7320b57cec5SDimitry Andric bool MachineOutliner::outline(Module &M,
7330b57cec5SDimitry Andric std::vector<OutlinedFunction> &FunctionList,
734480093f4SDimitry Andric InstructionMapper &Mapper,
735480093f4SDimitry Andric unsigned &OutlinedFunctionNum) {
7360b57cec5SDimitry Andric
7370b57cec5SDimitry Andric bool OutlinedSomething = false;
7380b57cec5SDimitry Andric
7390b57cec5SDimitry Andric // Sort by benefit. The most beneficial functions should be outlined first.
7400b57cec5SDimitry Andric llvm::stable_sort(FunctionList, [](const OutlinedFunction &LHS,
7410b57cec5SDimitry Andric const OutlinedFunction &RHS) {
7420b57cec5SDimitry Andric return LHS.getBenefit() > RHS.getBenefit();
7430b57cec5SDimitry Andric });
7440b57cec5SDimitry Andric
7450b57cec5SDimitry Andric // Walk over each function, outlining them as we go along. Functions are
7460b57cec5SDimitry Andric // outlined greedily, based off the sort above.
7470b57cec5SDimitry Andric for (OutlinedFunction &OF : FunctionList) {
7480b57cec5SDimitry Andric // If we outlined something that overlapped with a candidate in a previous
7490b57cec5SDimitry Andric // step, then we can't outline from it.
7500b57cec5SDimitry Andric erase_if(OF.Candidates, [&Mapper](Candidate &C) {
7510b57cec5SDimitry Andric return std::any_of(
7520b57cec5SDimitry Andric Mapper.UnsignedVec.begin() + C.getStartIdx(),
7530b57cec5SDimitry Andric Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
7540b57cec5SDimitry Andric [](unsigned I) { return (I == static_cast<unsigned>(-1)); });
7550b57cec5SDimitry Andric });
7560b57cec5SDimitry Andric
7570b57cec5SDimitry Andric // If we made it unbeneficial to outline this function, skip it.
7580b57cec5SDimitry Andric if (OF.getBenefit() < 1)
7590b57cec5SDimitry Andric continue;
7600b57cec5SDimitry Andric
7610b57cec5SDimitry Andric // It's beneficial. Create the function and outline its sequence's
7620b57cec5SDimitry Andric // occurrences.
7630b57cec5SDimitry Andric OF.MF = createOutlinedFunction(M, OF, Mapper, OutlinedFunctionNum);
7640b57cec5SDimitry Andric emitOutlinedFunctionRemark(OF);
7650b57cec5SDimitry Andric FunctionsCreated++;
7660b57cec5SDimitry Andric OutlinedFunctionNum++; // Created a function, move to the next name.
7670b57cec5SDimitry Andric MachineFunction *MF = OF.MF;
7680b57cec5SDimitry Andric const TargetSubtargetInfo &STI = MF->getSubtarget();
7690b57cec5SDimitry Andric const TargetInstrInfo &TII = *STI.getInstrInfo();
7700b57cec5SDimitry Andric
7710b57cec5SDimitry Andric // Replace occurrences of the sequence with calls to the new function.
7720b57cec5SDimitry Andric for (Candidate &C : OF.Candidates) {
7730b57cec5SDimitry Andric MachineBasicBlock &MBB = *C.getMBB();
7740b57cec5SDimitry Andric MachineBasicBlock::iterator StartIt = C.front();
7750b57cec5SDimitry Andric MachineBasicBlock::iterator EndIt = C.back();
7760b57cec5SDimitry Andric
7770b57cec5SDimitry Andric // Insert the call.
7780b57cec5SDimitry Andric auto CallInst = TII.insertOutlinedCall(M, MBB, StartIt, *MF, C);
7790b57cec5SDimitry Andric
7800b57cec5SDimitry Andric // If the caller tracks liveness, then we need to make sure that
7810b57cec5SDimitry Andric // anything we outline doesn't break liveness assumptions. The outlined
7820b57cec5SDimitry Andric // functions themselves currently don't track liveness, but we should
7830b57cec5SDimitry Andric // make sure that the ranges we yank things out of aren't wrong.
7840b57cec5SDimitry Andric if (MBB.getParent()->getProperties().hasProperty(
7850b57cec5SDimitry Andric MachineFunctionProperties::Property::TracksLiveness)) {
7865ffd83dbSDimitry Andric // The following code is to add implicit def operands to the call
7870b57cec5SDimitry Andric // instruction. It also updates call site information for moved
7880b57cec5SDimitry Andric // code.
7895ffd83dbSDimitry Andric SmallSet<Register, 2> UseRegs, DefRegs;
7900b57cec5SDimitry Andric // Copy over the defs in the outlined range.
7910b57cec5SDimitry Andric // First inst in outlined range <-- Anything that's defined in this
7920b57cec5SDimitry Andric // ... .. range has to be added as an
7930b57cec5SDimitry Andric // implicit Last inst in outlined range <-- def to the call
7940b57cec5SDimitry Andric // instruction. Also remove call site information for outlined block
7955ffd83dbSDimitry Andric // of code. The exposed uses need to be copied in the outlined range.
7965ffd83dbSDimitry Andric for (MachineBasicBlock::reverse_iterator
7975ffd83dbSDimitry Andric Iter = EndIt.getReverse(),
7985ffd83dbSDimitry Andric Last = std::next(CallInst.getReverse());
7995ffd83dbSDimitry Andric Iter != Last; Iter++) {
8005ffd83dbSDimitry Andric MachineInstr *MI = &*Iter;
8015ffd83dbSDimitry Andric for (MachineOperand &MOP : MI->operands()) {
8025ffd83dbSDimitry Andric // Skip over anything that isn't a register.
8035ffd83dbSDimitry Andric if (!MOP.isReg())
8045ffd83dbSDimitry Andric continue;
8055ffd83dbSDimitry Andric
8065ffd83dbSDimitry Andric if (MOP.isDef()) {
8075ffd83dbSDimitry Andric // Introduce DefRegs set to skip the redundant register.
8085ffd83dbSDimitry Andric DefRegs.insert(MOP.getReg());
809*5f7ddb14SDimitry Andric if (!MOP.isDead() && UseRegs.count(MOP.getReg()))
8105ffd83dbSDimitry Andric // Since the regiester is modeled as defined,
8115ffd83dbSDimitry Andric // it is not necessary to be put in use register set.
8125ffd83dbSDimitry Andric UseRegs.erase(MOP.getReg());
8135ffd83dbSDimitry Andric } else if (!MOP.isUndef()) {
8145ffd83dbSDimitry Andric // Any register which is not undefined should
8155ffd83dbSDimitry Andric // be put in the use register set.
8165ffd83dbSDimitry Andric UseRegs.insert(MOP.getReg());
8175ffd83dbSDimitry Andric }
8185ffd83dbSDimitry Andric }
8195ffd83dbSDimitry Andric if (MI->isCandidateForCallSiteEntry())
8205ffd83dbSDimitry Andric MI->getMF()->eraseCallSiteInfo(MI);
8215ffd83dbSDimitry Andric }
8225ffd83dbSDimitry Andric
8235ffd83dbSDimitry Andric for (const Register &I : DefRegs)
8245ffd83dbSDimitry Andric // If it's a def, add it to the call instruction.
8255ffd83dbSDimitry Andric CallInst->addOperand(
8265ffd83dbSDimitry Andric MachineOperand::CreateReg(I, true, /* isDef = true */
8275ffd83dbSDimitry Andric true /* isImp = true */));
8285ffd83dbSDimitry Andric
8295ffd83dbSDimitry Andric for (const Register &I : UseRegs)
8305ffd83dbSDimitry Andric // If it's a exposed use, add it to the call instruction.
8315ffd83dbSDimitry Andric CallInst->addOperand(
8325ffd83dbSDimitry Andric MachineOperand::CreateReg(I, false, /* isDef = false */
8335ffd83dbSDimitry Andric true /* isImp = true */));
8340b57cec5SDimitry Andric }
8350b57cec5SDimitry Andric
8360b57cec5SDimitry Andric // Erase from the point after where the call was inserted up to, and
8370b57cec5SDimitry Andric // including, the final instruction in the sequence.
8380b57cec5SDimitry Andric // Erase needs one past the end, so we need std::next there too.
8390b57cec5SDimitry Andric MBB.erase(std::next(StartIt), std::next(EndIt));
8400b57cec5SDimitry Andric
8410b57cec5SDimitry Andric // Keep track of what we removed by marking them all as -1.
8420b57cec5SDimitry Andric std::for_each(Mapper.UnsignedVec.begin() + C.getStartIdx(),
8430b57cec5SDimitry Andric Mapper.UnsignedVec.begin() + C.getEndIdx() + 1,
8440b57cec5SDimitry Andric [](unsigned &I) { I = static_cast<unsigned>(-1); });
8450b57cec5SDimitry Andric OutlinedSomething = true;
8460b57cec5SDimitry Andric
8470b57cec5SDimitry Andric // Statistics.
8480b57cec5SDimitry Andric NumOutlined++;
8490b57cec5SDimitry Andric }
8500b57cec5SDimitry Andric }
8510b57cec5SDimitry Andric
8520b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "OutlinedSomething = " << OutlinedSomething << "\n";);
8530b57cec5SDimitry Andric return OutlinedSomething;
8540b57cec5SDimitry Andric }
8550b57cec5SDimitry Andric
populateMapper(InstructionMapper & Mapper,Module & M,MachineModuleInfo & MMI)8560b57cec5SDimitry Andric void MachineOutliner::populateMapper(InstructionMapper &Mapper, Module &M,
8570b57cec5SDimitry Andric MachineModuleInfo &MMI) {
8580b57cec5SDimitry Andric // Build instruction mappings for each function in the module. Start by
8590b57cec5SDimitry Andric // iterating over each Function in M.
8600b57cec5SDimitry Andric for (Function &F : M) {
8610b57cec5SDimitry Andric
8620b57cec5SDimitry Andric // If there's nothing in F, then there's no reason to try and outline from
8630b57cec5SDimitry Andric // it.
8640b57cec5SDimitry Andric if (F.empty())
8650b57cec5SDimitry Andric continue;
8660b57cec5SDimitry Andric
8670b57cec5SDimitry Andric // There's something in F. Check if it has a MachineFunction associated with
8680b57cec5SDimitry Andric // it.
8690b57cec5SDimitry Andric MachineFunction *MF = MMI.getMachineFunction(F);
8700b57cec5SDimitry Andric
8710b57cec5SDimitry Andric // If it doesn't, then there's nothing to outline from. Move to the next
8720b57cec5SDimitry Andric // Function.
8730b57cec5SDimitry Andric if (!MF)
8740b57cec5SDimitry Andric continue;
8750b57cec5SDimitry Andric
8760b57cec5SDimitry Andric const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
8770b57cec5SDimitry Andric
8780b57cec5SDimitry Andric if (!RunOnAllFunctions && !TII->shouldOutlineFromFunctionByDefault(*MF))
8790b57cec5SDimitry Andric continue;
8800b57cec5SDimitry Andric
8810b57cec5SDimitry Andric // We have a MachineFunction. Ask the target if it's suitable for outlining.
8820b57cec5SDimitry Andric // If it isn't, then move on to the next Function in the module.
8830b57cec5SDimitry Andric if (!TII->isFunctionSafeToOutlineFrom(*MF, OutlineFromLinkOnceODRs))
8840b57cec5SDimitry Andric continue;
8850b57cec5SDimitry Andric
8860b57cec5SDimitry Andric // We have a function suitable for outlining. Iterate over every
8870b57cec5SDimitry Andric // MachineBasicBlock in MF and try to map its instructions to a list of
8880b57cec5SDimitry Andric // unsigned integers.
8890b57cec5SDimitry Andric for (MachineBasicBlock &MBB : *MF) {
8900b57cec5SDimitry Andric // If there isn't anything in MBB, then there's no point in outlining from
8910b57cec5SDimitry Andric // it.
8920b57cec5SDimitry Andric // If there are fewer than 2 instructions in the MBB, then it can't ever
8930b57cec5SDimitry Andric // contain something worth outlining.
8940b57cec5SDimitry Andric // FIXME: This should be based off of the maximum size in B of an outlined
8950b57cec5SDimitry Andric // call versus the size in B of the MBB.
8960b57cec5SDimitry Andric if (MBB.empty() || MBB.size() < 2)
8970b57cec5SDimitry Andric continue;
8980b57cec5SDimitry Andric
8990b57cec5SDimitry Andric // Check if MBB could be the target of an indirect branch. If it is, then
9000b57cec5SDimitry Andric // we don't want to outline from it.
9010b57cec5SDimitry Andric if (MBB.hasAddressTaken())
9020b57cec5SDimitry Andric continue;
9030b57cec5SDimitry Andric
9040b57cec5SDimitry Andric // MBB is suitable for outlining. Map it to a list of unsigneds.
9050b57cec5SDimitry Andric Mapper.convertToUnsignedVec(MBB, *TII);
9060b57cec5SDimitry Andric }
9070b57cec5SDimitry Andric }
9080b57cec5SDimitry Andric }
9090b57cec5SDimitry Andric
initSizeRemarkInfo(const Module & M,const MachineModuleInfo & MMI,StringMap<unsigned> & FunctionToInstrCount)9100b57cec5SDimitry Andric void MachineOutliner::initSizeRemarkInfo(
9110b57cec5SDimitry Andric const Module &M, const MachineModuleInfo &MMI,
9120b57cec5SDimitry Andric StringMap<unsigned> &FunctionToInstrCount) {
9130b57cec5SDimitry Andric // Collect instruction counts for every function. We'll use this to emit
9140b57cec5SDimitry Andric // per-function size remarks later.
9150b57cec5SDimitry Andric for (const Function &F : M) {
9160b57cec5SDimitry Andric MachineFunction *MF = MMI.getMachineFunction(F);
9170b57cec5SDimitry Andric
9180b57cec5SDimitry Andric // We only care about MI counts here. If there's no MachineFunction at this
9190b57cec5SDimitry Andric // point, then there won't be after the outliner runs, so let's move on.
9200b57cec5SDimitry Andric if (!MF)
9210b57cec5SDimitry Andric continue;
9220b57cec5SDimitry Andric FunctionToInstrCount[F.getName().str()] = MF->getInstructionCount();
9230b57cec5SDimitry Andric }
9240b57cec5SDimitry Andric }
9250b57cec5SDimitry Andric
emitInstrCountChangedRemark(const Module & M,const MachineModuleInfo & MMI,const StringMap<unsigned> & FunctionToInstrCount)9260b57cec5SDimitry Andric void MachineOutliner::emitInstrCountChangedRemark(
9270b57cec5SDimitry Andric const Module &M, const MachineModuleInfo &MMI,
9280b57cec5SDimitry Andric const StringMap<unsigned> &FunctionToInstrCount) {
9290b57cec5SDimitry Andric // Iterate over each function in the module and emit remarks.
9300b57cec5SDimitry Andric // Note that we won't miss anything by doing this, because the outliner never
9310b57cec5SDimitry Andric // deletes functions.
9320b57cec5SDimitry Andric for (const Function &F : M) {
9330b57cec5SDimitry Andric MachineFunction *MF = MMI.getMachineFunction(F);
9340b57cec5SDimitry Andric
9350b57cec5SDimitry Andric // The outliner never deletes functions. If we don't have a MF here, then we
9360b57cec5SDimitry Andric // didn't have one prior to outlining either.
9370b57cec5SDimitry Andric if (!MF)
9380b57cec5SDimitry Andric continue;
9390b57cec5SDimitry Andric
9405ffd83dbSDimitry Andric std::string Fname = std::string(F.getName());
9410b57cec5SDimitry Andric unsigned FnCountAfter = MF->getInstructionCount();
9420b57cec5SDimitry Andric unsigned FnCountBefore = 0;
9430b57cec5SDimitry Andric
9440b57cec5SDimitry Andric // Check if the function was recorded before.
9450b57cec5SDimitry Andric auto It = FunctionToInstrCount.find(Fname);
9460b57cec5SDimitry Andric
9470b57cec5SDimitry Andric // Did we have a previously-recorded size? If yes, then set FnCountBefore
9480b57cec5SDimitry Andric // to that.
9490b57cec5SDimitry Andric if (It != FunctionToInstrCount.end())
9500b57cec5SDimitry Andric FnCountBefore = It->second;
9510b57cec5SDimitry Andric
9520b57cec5SDimitry Andric // Compute the delta and emit a remark if there was a change.
9530b57cec5SDimitry Andric int64_t FnDelta = static_cast<int64_t>(FnCountAfter) -
9540b57cec5SDimitry Andric static_cast<int64_t>(FnCountBefore);
9550b57cec5SDimitry Andric if (FnDelta == 0)
9560b57cec5SDimitry Andric continue;
9570b57cec5SDimitry Andric
9580b57cec5SDimitry Andric MachineOptimizationRemarkEmitter MORE(*MF, nullptr);
9590b57cec5SDimitry Andric MORE.emit([&]() {
9600b57cec5SDimitry Andric MachineOptimizationRemarkAnalysis R("size-info", "FunctionMISizeChange",
961480093f4SDimitry Andric DiagnosticLocation(), &MF->front());
9620b57cec5SDimitry Andric R << DiagnosticInfoOptimizationBase::Argument("Pass", "Machine Outliner")
9630b57cec5SDimitry Andric << ": Function: "
9640b57cec5SDimitry Andric << DiagnosticInfoOptimizationBase::Argument("Function", F.getName())
9650b57cec5SDimitry Andric << ": MI instruction count changed from "
9660b57cec5SDimitry Andric << DiagnosticInfoOptimizationBase::Argument("MIInstrsBefore",
9670b57cec5SDimitry Andric FnCountBefore)
9680b57cec5SDimitry Andric << " to "
9690b57cec5SDimitry Andric << DiagnosticInfoOptimizationBase::Argument("MIInstrsAfter",
9700b57cec5SDimitry Andric FnCountAfter)
9710b57cec5SDimitry Andric << "; Delta: "
9720b57cec5SDimitry Andric << DiagnosticInfoOptimizationBase::Argument("Delta", FnDelta);
9730b57cec5SDimitry Andric return R;
9740b57cec5SDimitry Andric });
9750b57cec5SDimitry Andric }
9760b57cec5SDimitry Andric }
9770b57cec5SDimitry Andric
runOnModule(Module & M)9780b57cec5SDimitry Andric bool MachineOutliner::runOnModule(Module &M) {
9790b57cec5SDimitry Andric // Check if there's anything in the module. If it's empty, then there's
9800b57cec5SDimitry Andric // nothing to outline.
9810b57cec5SDimitry Andric if (M.empty())
9820b57cec5SDimitry Andric return false;
9830b57cec5SDimitry Andric
984480093f4SDimitry Andric // Number to append to the current outlined function.
985480093f4SDimitry Andric unsigned OutlinedFunctionNum = 0;
986480093f4SDimitry Andric
9875ffd83dbSDimitry Andric OutlineRepeatedNum = 0;
988480093f4SDimitry Andric if (!doOutline(M, OutlinedFunctionNum))
989480093f4SDimitry Andric return false;
9905ffd83dbSDimitry Andric
9915ffd83dbSDimitry Andric for (unsigned I = 0; I < OutlinerReruns; ++I) {
9925ffd83dbSDimitry Andric OutlinedFunctionNum = 0;
9935ffd83dbSDimitry Andric OutlineRepeatedNum++;
9945ffd83dbSDimitry Andric if (!doOutline(M, OutlinedFunctionNum)) {
9955ffd83dbSDimitry Andric LLVM_DEBUG({
9965ffd83dbSDimitry Andric dbgs() << "Did not outline on iteration " << I + 2 << " out of "
9975ffd83dbSDimitry Andric << OutlinerReruns + 1 << "\n";
9985ffd83dbSDimitry Andric });
9995ffd83dbSDimitry Andric break;
10005ffd83dbSDimitry Andric }
10015ffd83dbSDimitry Andric }
10025ffd83dbSDimitry Andric
1003480093f4SDimitry Andric return true;
1004480093f4SDimitry Andric }
1005480093f4SDimitry Andric
doOutline(Module & M,unsigned & OutlinedFunctionNum)1006480093f4SDimitry Andric bool MachineOutliner::doOutline(Module &M, unsigned &OutlinedFunctionNum) {
10078bcb0991SDimitry Andric MachineModuleInfo &MMI = getAnalysis<MachineModuleInfoWrapperPass>().getMMI();
10080b57cec5SDimitry Andric
10090b57cec5SDimitry Andric // If the user passed -enable-machine-outliner=always or
10100b57cec5SDimitry Andric // -enable-machine-outliner, the pass will run on all functions in the module.
10110b57cec5SDimitry Andric // Otherwise, if the target supports default outlining, it will run on all
10120b57cec5SDimitry Andric // functions deemed by the target to be worth outlining from by default. Tell
10130b57cec5SDimitry Andric // the user how the outliner is running.
1014480093f4SDimitry Andric LLVM_DEBUG({
10150b57cec5SDimitry Andric dbgs() << "Machine Outliner: Running on ";
10160b57cec5SDimitry Andric if (RunOnAllFunctions)
10170b57cec5SDimitry Andric dbgs() << "all functions";
10180b57cec5SDimitry Andric else
10190b57cec5SDimitry Andric dbgs() << "target-default functions";
1020480093f4SDimitry Andric dbgs() << "\n";
1021480093f4SDimitry Andric });
10220b57cec5SDimitry Andric
10230b57cec5SDimitry Andric // If the user specifies that they want to outline from linkonceodrs, set
10240b57cec5SDimitry Andric // it here.
10250b57cec5SDimitry Andric OutlineFromLinkOnceODRs = EnableLinkOnceODROutlining;
10260b57cec5SDimitry Andric InstructionMapper Mapper;
10270b57cec5SDimitry Andric
10280b57cec5SDimitry Andric // Prepare instruction mappings for the suffix tree.
10290b57cec5SDimitry Andric populateMapper(Mapper, M, MMI);
10300b57cec5SDimitry Andric std::vector<OutlinedFunction> FunctionList;
10310b57cec5SDimitry Andric
10320b57cec5SDimitry Andric // Find all of the outlining candidates.
10330b57cec5SDimitry Andric findCandidates(Mapper, FunctionList);
10340b57cec5SDimitry Andric
10350b57cec5SDimitry Andric // If we've requested size remarks, then collect the MI counts of every
10360b57cec5SDimitry Andric // function before outlining, and the MI counts after outlining.
10370b57cec5SDimitry Andric // FIXME: This shouldn't be in the outliner at all; it should ultimately be
10380b57cec5SDimitry Andric // the pass manager's responsibility.
10390b57cec5SDimitry Andric // This could pretty easily be placed in outline instead, but because we
10400b57cec5SDimitry Andric // really ultimately *don't* want this here, it's done like this for now
10410b57cec5SDimitry Andric // instead.
10420b57cec5SDimitry Andric
10430b57cec5SDimitry Andric // Check if we want size remarks.
10440b57cec5SDimitry Andric bool ShouldEmitSizeRemarks = M.shouldEmitInstrCountChangedRemark();
10450b57cec5SDimitry Andric StringMap<unsigned> FunctionToInstrCount;
10460b57cec5SDimitry Andric if (ShouldEmitSizeRemarks)
10470b57cec5SDimitry Andric initSizeRemarkInfo(M, MMI, FunctionToInstrCount);
10480b57cec5SDimitry Andric
10490b57cec5SDimitry Andric // Outline each of the candidates and return true if something was outlined.
1050480093f4SDimitry Andric bool OutlinedSomething =
1051480093f4SDimitry Andric outline(M, FunctionList, Mapper, OutlinedFunctionNum);
10520b57cec5SDimitry Andric
10530b57cec5SDimitry Andric // If we outlined something, we definitely changed the MI count of the
10540b57cec5SDimitry Andric // module. If we've asked for size remarks, then output them.
10550b57cec5SDimitry Andric // FIXME: This should be in the pass manager.
10560b57cec5SDimitry Andric if (ShouldEmitSizeRemarks && OutlinedSomething)
10570b57cec5SDimitry Andric emitInstrCountChangedRemark(M, MMI, FunctionToInstrCount);
10580b57cec5SDimitry Andric
10595ffd83dbSDimitry Andric LLVM_DEBUG({
10605ffd83dbSDimitry Andric if (!OutlinedSomething)
10615ffd83dbSDimitry Andric dbgs() << "Stopped outlining at iteration " << OutlineRepeatedNum
10625ffd83dbSDimitry Andric << " because no changes were found.\n";
10635ffd83dbSDimitry Andric });
10645ffd83dbSDimitry Andric
10650b57cec5SDimitry Andric return OutlinedSomething;
10660b57cec5SDimitry Andric }
1067