1e8d8bef9SDimitry Andric //===- IROutliner.cpp -- Outline Similar Regions ----------------*- C++ -*-===// 2e8d8bef9SDimitry Andric // 3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6e8d8bef9SDimitry Andric // 7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 8e8d8bef9SDimitry Andric /// 9e8d8bef9SDimitry Andric /// \file 10e8d8bef9SDimitry Andric // Implementation for the IROutliner which is used by the IROutliner Pass. 11e8d8bef9SDimitry Andric // 12e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===// 13e8d8bef9SDimitry Andric 14e8d8bef9SDimitry Andric #include "llvm/Transforms/IPO/IROutliner.h" 15e8d8bef9SDimitry Andric #include "llvm/Analysis/IRSimilarityIdentifier.h" 16e8d8bef9SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h" 17e8d8bef9SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h" 18e8d8bef9SDimitry Andric #include "llvm/IR/Attributes.h" 19fe6060f1SDimitry Andric #include "llvm/IR/DIBuilder.h" 20*81ad6265SDimitry Andric #include "llvm/IR/DebugInfo.h" 21*81ad6265SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h" 22349cc55cSDimitry Andric #include "llvm/IR/Dominators.h" 23fe6060f1SDimitry Andric #include "llvm/IR/Mangler.h" 24e8d8bef9SDimitry Andric #include "llvm/IR/PassManager.h" 25e8d8bef9SDimitry Andric #include "llvm/InitializePasses.h" 26e8d8bef9SDimitry Andric #include "llvm/Pass.h" 27e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h" 28e8d8bef9SDimitry Andric #include "llvm/Transforms/IPO.h" 29e8d8bef9SDimitry Andric #include <vector> 30e8d8bef9SDimitry Andric 31e8d8bef9SDimitry Andric #define DEBUG_TYPE "iroutliner" 32e8d8bef9SDimitry Andric 33e8d8bef9SDimitry Andric using namespace llvm; 34e8d8bef9SDimitry Andric using namespace IRSimilarity; 35e8d8bef9SDimitry Andric 36349cc55cSDimitry Andric // A command flag to be used for debugging to exclude branches from similarity 37349cc55cSDimitry Andric // matching and outlining. 3804eeddc0SDimitry Andric namespace llvm { 39349cc55cSDimitry Andric extern cl::opt<bool> DisableBranches; 40349cc55cSDimitry Andric 4104eeddc0SDimitry Andric // A command flag to be used for debugging to indirect calls from similarity 4204eeddc0SDimitry Andric // matching and outlining. 4304eeddc0SDimitry Andric extern cl::opt<bool> DisableIndirectCalls; 441fd87a68SDimitry Andric 451fd87a68SDimitry Andric // A command flag to be used for debugging to exclude intrinsics from similarity 461fd87a68SDimitry Andric // matching and outlining. 471fd87a68SDimitry Andric extern cl::opt<bool> DisableIntrinsics; 481fd87a68SDimitry Andric 4904eeddc0SDimitry Andric } // namespace llvm 5004eeddc0SDimitry Andric 51e8d8bef9SDimitry Andric // Set to true if the user wants the ir outliner to run on linkonceodr linkage 52e8d8bef9SDimitry Andric // functions. This is false by default because the linker can dedupe linkonceodr 53e8d8bef9SDimitry Andric // functions. Since the outliner is confined to a single module (modulo LTO), 54e8d8bef9SDimitry Andric // this is off by default. It should, however, be the default behavior in 55e8d8bef9SDimitry Andric // LTO. 56e8d8bef9SDimitry Andric static cl::opt<bool> EnableLinkOnceODRIROutlining( 57e8d8bef9SDimitry Andric "enable-linkonceodr-ir-outlining", cl::Hidden, 58e8d8bef9SDimitry Andric cl::desc("Enable the IR outliner on linkonceodr functions"), 59e8d8bef9SDimitry Andric cl::init(false)); 60e8d8bef9SDimitry Andric 61e8d8bef9SDimitry Andric // This is a debug option to test small pieces of code to ensure that outlining 62e8d8bef9SDimitry Andric // works correctly. 63e8d8bef9SDimitry Andric static cl::opt<bool> NoCostModel( 64e8d8bef9SDimitry Andric "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden, 65e8d8bef9SDimitry Andric cl::desc("Debug option to outline greedily, without restriction that " 66e8d8bef9SDimitry Andric "calculated benefit outweighs cost")); 67e8d8bef9SDimitry Andric 68e8d8bef9SDimitry Andric /// The OutlinableGroup holds all the overarching information for outlining 69e8d8bef9SDimitry Andric /// a set of regions that are structurally similar to one another, such as the 70e8d8bef9SDimitry Andric /// types of the overall function, the output blocks, the sets of stores needed 71e8d8bef9SDimitry Andric /// and a list of the different regions. This information is used in the 72e8d8bef9SDimitry Andric /// deduplication of extracted regions with the same structure. 73e8d8bef9SDimitry Andric struct OutlinableGroup { 74e8d8bef9SDimitry Andric /// The sections that could be outlined 75e8d8bef9SDimitry Andric std::vector<OutlinableRegion *> Regions; 76e8d8bef9SDimitry Andric 77e8d8bef9SDimitry Andric /// The argument types for the function created as the overall function to 78e8d8bef9SDimitry Andric /// replace the extracted function for each region. 79e8d8bef9SDimitry Andric std::vector<Type *> ArgumentTypes; 80e8d8bef9SDimitry Andric /// The FunctionType for the overall function. 81e8d8bef9SDimitry Andric FunctionType *OutlinedFunctionType = nullptr; 82e8d8bef9SDimitry Andric /// The Function for the collective overall function. 83e8d8bef9SDimitry Andric Function *OutlinedFunction = nullptr; 84e8d8bef9SDimitry Andric 85e8d8bef9SDimitry Andric /// Flag for whether we should not consider this group of OutlinableRegions 86e8d8bef9SDimitry Andric /// for extraction. 87e8d8bef9SDimitry Andric bool IgnoreGroup = false; 88e8d8bef9SDimitry Andric 89349cc55cSDimitry Andric /// The return blocks for the overall function. 90349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> EndBBs; 91349cc55cSDimitry Andric 92349cc55cSDimitry Andric /// The PHIBlocks with their corresponding return block based on the return 93349cc55cSDimitry Andric /// value as the key. 94349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> PHIBlocks; 95e8d8bef9SDimitry Andric 96e8d8bef9SDimitry Andric /// A set containing the different GVN store sets needed. Each array contains 97e8d8bef9SDimitry Andric /// a sorted list of the different values that need to be stored into output 98e8d8bef9SDimitry Andric /// registers. 99e8d8bef9SDimitry Andric DenseSet<ArrayRef<unsigned>> OutputGVNCombinations; 100e8d8bef9SDimitry Andric 101e8d8bef9SDimitry Andric /// Flag for whether the \ref ArgumentTypes have been defined after the 102e8d8bef9SDimitry Andric /// extraction of the first region. 103e8d8bef9SDimitry Andric bool InputTypesSet = false; 104e8d8bef9SDimitry Andric 105e8d8bef9SDimitry Andric /// The number of input values in \ref ArgumentTypes. Anything after this 106e8d8bef9SDimitry Andric /// index in ArgumentTypes is an output argument. 107e8d8bef9SDimitry Andric unsigned NumAggregateInputs = 0; 108e8d8bef9SDimitry Andric 109349cc55cSDimitry Andric /// The mapping of the canonical numbering of the values in outlined sections 110349cc55cSDimitry Andric /// to specific arguments. 111349cc55cSDimitry Andric DenseMap<unsigned, unsigned> CanonicalNumberToAggArg; 112349cc55cSDimitry Andric 113349cc55cSDimitry Andric /// The number of branches in the region target a basic block that is outside 114349cc55cSDimitry Andric /// of the region. 115349cc55cSDimitry Andric unsigned BranchesToOutside = 0; 116349cc55cSDimitry Andric 11704eeddc0SDimitry Andric /// Tracker counting backwards from the highest unsigned value possible to 11804eeddc0SDimitry Andric /// avoid conflicting with the GVNs of assigned values. We start at -3 since 11904eeddc0SDimitry Andric /// -2 and -1 are assigned by the DenseMap. 12004eeddc0SDimitry Andric unsigned PHINodeGVNTracker = -3; 12104eeddc0SDimitry Andric 12204eeddc0SDimitry Andric DenseMap<unsigned, 12304eeddc0SDimitry Andric std::pair<std::pair<unsigned, unsigned>, SmallVector<unsigned, 2>>> 12404eeddc0SDimitry Andric PHINodeGVNToGVNs; 12504eeddc0SDimitry Andric DenseMap<hash_code, unsigned> GVNsToPHINodeGVN; 12604eeddc0SDimitry Andric 127e8d8bef9SDimitry Andric /// The number of instructions that will be outlined by extracting \ref 128e8d8bef9SDimitry Andric /// Regions. 129e8d8bef9SDimitry Andric InstructionCost Benefit = 0; 130e8d8bef9SDimitry Andric /// The number of added instructions needed for the outlining of the \ref 131e8d8bef9SDimitry Andric /// Regions. 132e8d8bef9SDimitry Andric InstructionCost Cost = 0; 133e8d8bef9SDimitry Andric 134e8d8bef9SDimitry Andric /// The argument that needs to be marked with the swifterr attribute. If not 135e8d8bef9SDimitry Andric /// needed, there is no value. 136e8d8bef9SDimitry Andric Optional<unsigned> SwiftErrorArgument; 137e8d8bef9SDimitry Andric 138e8d8bef9SDimitry Andric /// For the \ref Regions, we look at every Value. If it is a constant, 139e8d8bef9SDimitry Andric /// we check whether it is the same in Region. 140e8d8bef9SDimitry Andric /// 141e8d8bef9SDimitry Andric /// \param [in,out] NotSame contains the global value numbers where the 142e8d8bef9SDimitry Andric /// constant is not always the same, and must be passed in as an argument. 143e8d8bef9SDimitry Andric void findSameConstants(DenseSet<unsigned> &NotSame); 144e8d8bef9SDimitry Andric 145e8d8bef9SDimitry Andric /// For the regions, look at each set of GVN stores needed and account for 146e8d8bef9SDimitry Andric /// each combination. Add an argument to the argument types if there is 147e8d8bef9SDimitry Andric /// more than one combination. 148e8d8bef9SDimitry Andric /// 149e8d8bef9SDimitry Andric /// \param [in] M - The module we are outlining from. 150e8d8bef9SDimitry Andric void collectGVNStoreSets(Module &M); 151e8d8bef9SDimitry Andric }; 152e8d8bef9SDimitry Andric 153e8d8bef9SDimitry Andric /// Move the contents of \p SourceBB to before the last instruction of \p 154e8d8bef9SDimitry Andric /// TargetBB. 155e8d8bef9SDimitry Andric /// \param SourceBB - the BasicBlock to pull Instructions from. 156e8d8bef9SDimitry Andric /// \param TargetBB - the BasicBlock to put Instruction into. 157e8d8bef9SDimitry Andric static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) { 158349cc55cSDimitry Andric for (Instruction &I : llvm::make_early_inc_range(SourceBB)) 159349cc55cSDimitry Andric I.moveBefore(TargetBB, TargetBB.end()); 160e8d8bef9SDimitry Andric } 161349cc55cSDimitry Andric 162349cc55cSDimitry Andric /// A function to sort the keys of \p Map, which must be a mapping of constant 163349cc55cSDimitry Andric /// values to basic blocks and return it in \p SortedKeys 164349cc55cSDimitry Andric /// 165349cc55cSDimitry Andric /// \param SortedKeys - The vector the keys will be return in and sorted. 166349cc55cSDimitry Andric /// \param Map - The DenseMap containing keys to sort. 167349cc55cSDimitry Andric static void getSortedConstantKeys(std::vector<Value *> &SortedKeys, 168349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> &Map) { 169349cc55cSDimitry Andric for (auto &VtoBB : Map) 170349cc55cSDimitry Andric SortedKeys.push_back(VtoBB.first); 171349cc55cSDimitry Andric 172349cc55cSDimitry Andric stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) { 173349cc55cSDimitry Andric const ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS); 174349cc55cSDimitry Andric const ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS); 175349cc55cSDimitry Andric assert(RHSC && "Not a constant integer in return value?"); 176349cc55cSDimitry Andric assert(LHSC && "Not a constant integer in return value?"); 177349cc55cSDimitry Andric 178349cc55cSDimitry Andric return LHSC->getLimitedValue() < RHSC->getLimitedValue(); 179349cc55cSDimitry Andric }); 180349cc55cSDimitry Andric } 181349cc55cSDimitry Andric 182349cc55cSDimitry Andric Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other, 183349cc55cSDimitry Andric Value *V) { 184349cc55cSDimitry Andric Optional<unsigned> GVN = Candidate->getGVN(V); 185*81ad6265SDimitry Andric assert(GVN && "No GVN for incoming value"); 186349cc55cSDimitry Andric Optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN); 187349cc55cSDimitry Andric Optional<unsigned> FirstGVN = Other.Candidate->fromCanonicalNum(*CanonNum); 188349cc55cSDimitry Andric Optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN); 189*81ad6265SDimitry Andric return FoundValueOpt.value_or(nullptr); 190*81ad6265SDimitry Andric } 191*81ad6265SDimitry Andric 192*81ad6265SDimitry Andric BasicBlock * 193*81ad6265SDimitry Andric OutlinableRegion::findCorrespondingBlockIn(const OutlinableRegion &Other, 194*81ad6265SDimitry Andric BasicBlock *BB) { 195*81ad6265SDimitry Andric Instruction *FirstNonPHI = BB->getFirstNonPHI(); 196*81ad6265SDimitry Andric assert(FirstNonPHI && "block is empty?"); 197*81ad6265SDimitry Andric Value *CorrespondingVal = findCorrespondingValueIn(Other, FirstNonPHI); 198*81ad6265SDimitry Andric if (!CorrespondingVal) 199*81ad6265SDimitry Andric return nullptr; 200*81ad6265SDimitry Andric BasicBlock *CorrespondingBlock = 201*81ad6265SDimitry Andric cast<Instruction>(CorrespondingVal)->getParent(); 202*81ad6265SDimitry Andric return CorrespondingBlock; 203e8d8bef9SDimitry Andric } 204e8d8bef9SDimitry Andric 20504eeddc0SDimitry Andric /// Rewrite the BranchInsts in the incoming blocks to \p PHIBlock that are found 20604eeddc0SDimitry Andric /// in \p Included to branch to BasicBlock \p Replace if they currently branch 20704eeddc0SDimitry Andric /// to the BasicBlock \p Find. This is used to fix up the incoming basic blocks 20804eeddc0SDimitry Andric /// when PHINodes are included in outlined regions. 20904eeddc0SDimitry Andric /// 21004eeddc0SDimitry Andric /// \param PHIBlock - The BasicBlock containing the PHINodes that need to be 21104eeddc0SDimitry Andric /// checked. 21204eeddc0SDimitry Andric /// \param Find - The successor block to be replaced. 21304eeddc0SDimitry Andric /// \param Replace - The new succesor block to branch to. 21404eeddc0SDimitry Andric /// \param Included - The set of blocks about to be outlined. 21504eeddc0SDimitry Andric static void replaceTargetsFromPHINode(BasicBlock *PHIBlock, BasicBlock *Find, 21604eeddc0SDimitry Andric BasicBlock *Replace, 21704eeddc0SDimitry Andric DenseSet<BasicBlock *> &Included) { 21804eeddc0SDimitry Andric for (PHINode &PN : PHIBlock->phis()) { 21904eeddc0SDimitry Andric for (unsigned Idx = 0, PNEnd = PN.getNumIncomingValues(); Idx != PNEnd; 22004eeddc0SDimitry Andric ++Idx) { 22104eeddc0SDimitry Andric // Check if the incoming block is included in the set of blocks being 22204eeddc0SDimitry Andric // outlined. 22304eeddc0SDimitry Andric BasicBlock *Incoming = PN.getIncomingBlock(Idx); 22404eeddc0SDimitry Andric if (!Included.contains(Incoming)) 22504eeddc0SDimitry Andric continue; 22604eeddc0SDimitry Andric 22704eeddc0SDimitry Andric BranchInst *BI = dyn_cast<BranchInst>(Incoming->getTerminator()); 22804eeddc0SDimitry Andric assert(BI && "Not a branch instruction?"); 22904eeddc0SDimitry Andric // Look over the branching instructions into this block to see if we 23004eeddc0SDimitry Andric // used to branch to Find in this outlined block. 23104eeddc0SDimitry Andric for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ != End; 23204eeddc0SDimitry Andric Succ++) { 23304eeddc0SDimitry Andric // If we have found the block to replace, we do so here. 23404eeddc0SDimitry Andric if (BI->getSuccessor(Succ) != Find) 23504eeddc0SDimitry Andric continue; 23604eeddc0SDimitry Andric BI->setSuccessor(Succ, Replace); 23704eeddc0SDimitry Andric } 23804eeddc0SDimitry Andric } 23904eeddc0SDimitry Andric } 24004eeddc0SDimitry Andric } 24104eeddc0SDimitry Andric 24204eeddc0SDimitry Andric 243e8d8bef9SDimitry Andric void OutlinableRegion::splitCandidate() { 244e8d8bef9SDimitry Andric assert(!CandidateSplit && "Candidate already split!"); 245e8d8bef9SDimitry Andric 246349cc55cSDimitry Andric Instruction *BackInst = Candidate->backInstruction(); 247349cc55cSDimitry Andric 248349cc55cSDimitry Andric Instruction *EndInst = nullptr; 249349cc55cSDimitry Andric // Check whether the last instruction is a terminator, if it is, we do 250349cc55cSDimitry Andric // not split on the following instruction. We leave the block as it is. We 251349cc55cSDimitry Andric // also check that this is not the last instruction in the Module, otherwise 252349cc55cSDimitry Andric // the check for whether the current following instruction matches the 253349cc55cSDimitry Andric // previously recorded instruction will be incorrect. 254349cc55cSDimitry Andric if (!BackInst->isTerminator() || 255349cc55cSDimitry Andric BackInst->getParent() != &BackInst->getFunction()->back()) { 256349cc55cSDimitry Andric EndInst = Candidate->end()->Inst; 257349cc55cSDimitry Andric assert(EndInst && "Expected an end instruction?"); 258349cc55cSDimitry Andric } 259349cc55cSDimitry Andric 260349cc55cSDimitry Andric // We check if the current instruction following the last instruction in the 261349cc55cSDimitry Andric // region is the same as the recorded instruction following the last 262349cc55cSDimitry Andric // instruction. If they do not match, there could be problems in rewriting 263349cc55cSDimitry Andric // the program after outlining, so we ignore it. 264349cc55cSDimitry Andric if (!BackInst->isTerminator() && 265349cc55cSDimitry Andric EndInst != BackInst->getNextNonDebugInstruction()) 266349cc55cSDimitry Andric return; 267349cc55cSDimitry Andric 268e8d8bef9SDimitry Andric Instruction *StartInst = (*Candidate->begin()).Inst; 269349cc55cSDimitry Andric assert(StartInst && "Expected a start instruction?"); 270e8d8bef9SDimitry Andric StartBB = StartInst->getParent(); 271e8d8bef9SDimitry Andric PrevBB = StartBB; 272e8d8bef9SDimitry Andric 27304eeddc0SDimitry Andric DenseSet<BasicBlock *> BBSet; 27404eeddc0SDimitry Andric Candidate->getBasicBlocks(BBSet); 27504eeddc0SDimitry Andric 27604eeddc0SDimitry Andric // We iterate over the instructions in the region, if we find a PHINode, we 27704eeddc0SDimitry Andric // check if there are predecessors outside of the region, if there are, 27804eeddc0SDimitry Andric // we ignore this region since we are unable to handle the severing of the 27904eeddc0SDimitry Andric // phi node right now. 280*81ad6265SDimitry Andric 281*81ad6265SDimitry Andric // TODO: Handle extraneous inputs for PHINodes through variable number of 282*81ad6265SDimitry Andric // inputs, similar to how outputs are handled. 28304eeddc0SDimitry Andric BasicBlock::iterator It = StartInst->getIterator(); 284*81ad6265SDimitry Andric EndBB = BackInst->getParent(); 285*81ad6265SDimitry Andric BasicBlock *IBlock; 286*81ad6265SDimitry Andric BasicBlock *PHIPredBlock = nullptr; 287*81ad6265SDimitry Andric bool EndBBTermAndBackInstDifferent = EndBB->getTerminator() != BackInst; 28804eeddc0SDimitry Andric while (PHINode *PN = dyn_cast<PHINode>(&*It)) { 28904eeddc0SDimitry Andric unsigned NumPredsOutsideRegion = 0; 290*81ad6265SDimitry Andric for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 291*81ad6265SDimitry Andric if (!BBSet.contains(PN->getIncomingBlock(i))) { 292*81ad6265SDimitry Andric PHIPredBlock = PN->getIncomingBlock(i); 29304eeddc0SDimitry Andric ++NumPredsOutsideRegion; 294*81ad6265SDimitry Andric continue; 295*81ad6265SDimitry Andric } 296*81ad6265SDimitry Andric 297*81ad6265SDimitry Andric // We must consider the case there the incoming block to the PHINode is 298*81ad6265SDimitry Andric // the same as the final block of the OutlinableRegion. If this is the 299*81ad6265SDimitry Andric // case, the branch from this block must also be outlined to be valid. 300*81ad6265SDimitry Andric IBlock = PN->getIncomingBlock(i); 301*81ad6265SDimitry Andric if (IBlock == EndBB && EndBBTermAndBackInstDifferent) { 302*81ad6265SDimitry Andric PHIPredBlock = PN->getIncomingBlock(i); 303*81ad6265SDimitry Andric ++NumPredsOutsideRegion; 304*81ad6265SDimitry Andric } 305*81ad6265SDimitry Andric } 30604eeddc0SDimitry Andric 30704eeddc0SDimitry Andric if (NumPredsOutsideRegion > 1) 30804eeddc0SDimitry Andric return; 30904eeddc0SDimitry Andric 31004eeddc0SDimitry Andric It++; 31104eeddc0SDimitry Andric } 31204eeddc0SDimitry Andric 31304eeddc0SDimitry Andric // If the region starts with a PHINode, but is not the initial instruction of 31404eeddc0SDimitry Andric // the BasicBlock, we ignore this region for now. 31504eeddc0SDimitry Andric if (isa<PHINode>(StartInst) && StartInst != &*StartBB->begin()) 31604eeddc0SDimitry Andric return; 31704eeddc0SDimitry Andric 31804eeddc0SDimitry Andric // If the region ends with a PHINode, but does not contain all of the phi node 31904eeddc0SDimitry Andric // instructions of the region, we ignore it for now. 320*81ad6265SDimitry Andric if (isa<PHINode>(BackInst) && 321*81ad6265SDimitry Andric BackInst != &*std::prev(EndBB->getFirstInsertionPt())) 32204eeddc0SDimitry Andric return; 32304eeddc0SDimitry Andric 324e8d8bef9SDimitry Andric // The basic block gets split like so: 325e8d8bef9SDimitry Andric // block: block: 326e8d8bef9SDimitry Andric // inst1 inst1 327e8d8bef9SDimitry Andric // inst2 inst2 328e8d8bef9SDimitry Andric // region1 br block_to_outline 329e8d8bef9SDimitry Andric // region2 block_to_outline: 330e8d8bef9SDimitry Andric // region3 -> region1 331e8d8bef9SDimitry Andric // region4 region2 332e8d8bef9SDimitry Andric // inst3 region3 333e8d8bef9SDimitry Andric // inst4 region4 334e8d8bef9SDimitry Andric // br block_after_outline 335e8d8bef9SDimitry Andric // block_after_outline: 336e8d8bef9SDimitry Andric // inst3 337e8d8bef9SDimitry Andric // inst4 338e8d8bef9SDimitry Andric 339e8d8bef9SDimitry Andric std::string OriginalName = PrevBB->getName().str(); 340e8d8bef9SDimitry Andric 341e8d8bef9SDimitry Andric StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline"); 342349cc55cSDimitry Andric PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB); 343*81ad6265SDimitry Andric // If there was a PHINode with an incoming block outside the region, 344*81ad6265SDimitry Andric // make sure is correctly updated in the newly split block. 345*81ad6265SDimitry Andric if (PHIPredBlock) 346*81ad6265SDimitry Andric PrevBB->replaceSuccessorsPhiUsesWith(PHIPredBlock, PrevBB); 347e8d8bef9SDimitry Andric 348e8d8bef9SDimitry Andric CandidateSplit = true; 349349cc55cSDimitry Andric if (!BackInst->isTerminator()) { 350349cc55cSDimitry Andric EndBB = EndInst->getParent(); 351349cc55cSDimitry Andric FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline"); 352349cc55cSDimitry Andric EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB); 353349cc55cSDimitry Andric FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB); 35404eeddc0SDimitry Andric } else { 355349cc55cSDimitry Andric EndBB = BackInst->getParent(); 356349cc55cSDimitry Andric EndsInBranch = true; 357349cc55cSDimitry Andric FollowBB = nullptr; 358e8d8bef9SDimitry Andric } 359e8d8bef9SDimitry Andric 36004eeddc0SDimitry Andric // Refind the basic block set. 36104eeddc0SDimitry Andric BBSet.clear(); 36204eeddc0SDimitry Andric Candidate->getBasicBlocks(BBSet); 36304eeddc0SDimitry Andric // For the phi nodes in the new starting basic block of the region, we 36404eeddc0SDimitry Andric // reassign the targets of the basic blocks branching instructions. 36504eeddc0SDimitry Andric replaceTargetsFromPHINode(StartBB, PrevBB, StartBB, BBSet); 36604eeddc0SDimitry Andric if (FollowBB) 36704eeddc0SDimitry Andric replaceTargetsFromPHINode(FollowBB, EndBB, FollowBB, BBSet); 36804eeddc0SDimitry Andric } 36904eeddc0SDimitry Andric 370e8d8bef9SDimitry Andric void OutlinableRegion::reattachCandidate() { 371e8d8bef9SDimitry Andric assert(CandidateSplit && "Candidate is not split!"); 372e8d8bef9SDimitry Andric 373e8d8bef9SDimitry Andric // The basic block gets reattached like so: 374e8d8bef9SDimitry Andric // block: block: 375e8d8bef9SDimitry Andric // inst1 inst1 376e8d8bef9SDimitry Andric // inst2 inst2 377e8d8bef9SDimitry Andric // br block_to_outline region1 378e8d8bef9SDimitry Andric // block_to_outline: -> region2 379e8d8bef9SDimitry Andric // region1 region3 380e8d8bef9SDimitry Andric // region2 region4 381e8d8bef9SDimitry Andric // region3 inst3 382e8d8bef9SDimitry Andric // region4 inst4 383e8d8bef9SDimitry Andric // br block_after_outline 384e8d8bef9SDimitry Andric // block_after_outline: 385e8d8bef9SDimitry Andric // inst3 386e8d8bef9SDimitry Andric // inst4 387e8d8bef9SDimitry Andric assert(StartBB != nullptr && "StartBB for Candidate is not defined!"); 388e8d8bef9SDimitry Andric 389e8d8bef9SDimitry Andric assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!"); 390*81ad6265SDimitry Andric // Make sure PHINode references to the block we are merging into are 391*81ad6265SDimitry Andric // updated to be incoming blocks from the predecessor to the current block. 392*81ad6265SDimitry Andric 393*81ad6265SDimitry Andric // NOTE: If this is updated such that the outlined block can have more than 394*81ad6265SDimitry Andric // one incoming block to a PHINode, this logic will have to updated 395*81ad6265SDimitry Andric // to handle multiple precessors instead. 396*81ad6265SDimitry Andric 397*81ad6265SDimitry Andric // We only need to update this if the outlined section contains a PHINode, if 398*81ad6265SDimitry Andric // it does not, then the incoming block was never changed in the first place. 399*81ad6265SDimitry Andric // On the other hand, if PrevBB has no predecessors, it means that all 400*81ad6265SDimitry Andric // incoming blocks to the first block are contained in the region, and there 401*81ad6265SDimitry Andric // will be nothing to update. 402*81ad6265SDimitry Andric Instruction *StartInst = (*Candidate->begin()).Inst; 403*81ad6265SDimitry Andric if (isa<PHINode>(StartInst) && !PrevBB->hasNPredecessors(0)) { 404*81ad6265SDimitry Andric assert(!PrevBB->hasNPredecessorsOrMore(2) && 405*81ad6265SDimitry Andric "PrevBB has more than one predecessor. Should be 0 or 1."); 406*81ad6265SDimitry Andric BasicBlock *BeforePrevBB = PrevBB->getSinglePredecessor(); 407*81ad6265SDimitry Andric PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, BeforePrevBB); 408*81ad6265SDimitry Andric } 409e8d8bef9SDimitry Andric PrevBB->getTerminator()->eraseFromParent(); 410e8d8bef9SDimitry Andric 41104eeddc0SDimitry Andric // If we reattaching after outlining, we iterate over the phi nodes to 41204eeddc0SDimitry Andric // the initial block, and reassign the branch instructions of the incoming 41304eeddc0SDimitry Andric // blocks to the block we are remerging into. 41404eeddc0SDimitry Andric if (!ExtractedFunction) { 41504eeddc0SDimitry Andric DenseSet<BasicBlock *> BBSet; 41604eeddc0SDimitry Andric Candidate->getBasicBlocks(BBSet); 41704eeddc0SDimitry Andric 41804eeddc0SDimitry Andric replaceTargetsFromPHINode(StartBB, StartBB, PrevBB, BBSet); 41904eeddc0SDimitry Andric if (!EndsInBranch) 42004eeddc0SDimitry Andric replaceTargetsFromPHINode(FollowBB, FollowBB, EndBB, BBSet); 42104eeddc0SDimitry Andric } 42204eeddc0SDimitry Andric 423e8d8bef9SDimitry Andric moveBBContents(*StartBB, *PrevBB); 424e8d8bef9SDimitry Andric 425e8d8bef9SDimitry Andric BasicBlock *PlacementBB = PrevBB; 426e8d8bef9SDimitry Andric if (StartBB != EndBB) 427e8d8bef9SDimitry Andric PlacementBB = EndBB; 428349cc55cSDimitry Andric if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) { 429349cc55cSDimitry Andric assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!"); 430349cc55cSDimitry Andric assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!"); 431349cc55cSDimitry Andric PlacementBB->getTerminator()->eraseFromParent(); 432e8d8bef9SDimitry Andric moveBBContents(*FollowBB, *PlacementBB); 433349cc55cSDimitry Andric PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB); 434349cc55cSDimitry Andric FollowBB->eraseFromParent(); 435349cc55cSDimitry Andric } 436e8d8bef9SDimitry Andric 437e8d8bef9SDimitry Andric PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB); 438e8d8bef9SDimitry Andric StartBB->eraseFromParent(); 439e8d8bef9SDimitry Andric 440e8d8bef9SDimitry Andric // Make sure to save changes back to the StartBB. 441e8d8bef9SDimitry Andric StartBB = PrevBB; 442e8d8bef9SDimitry Andric EndBB = nullptr; 443e8d8bef9SDimitry Andric PrevBB = nullptr; 444e8d8bef9SDimitry Andric FollowBB = nullptr; 445e8d8bef9SDimitry Andric 446e8d8bef9SDimitry Andric CandidateSplit = false; 447e8d8bef9SDimitry Andric } 448e8d8bef9SDimitry Andric 449e8d8bef9SDimitry Andric /// Find whether \p V matches the Constants previously found for the \p GVN. 450e8d8bef9SDimitry Andric /// 451e8d8bef9SDimitry Andric /// \param V - The value to check for consistency. 452e8d8bef9SDimitry Andric /// \param GVN - The global value number assigned to \p V. 453e8d8bef9SDimitry Andric /// \param GVNToConstant - The mapping of global value number to Constants. 454e8d8bef9SDimitry Andric /// \returns true if the Value matches the Constant mapped to by V and false if 455e8d8bef9SDimitry Andric /// it \p V is a Constant but does not match. 456e8d8bef9SDimitry Andric /// \returns None if \p V is not a Constant. 457e8d8bef9SDimitry Andric static Optional<bool> 458e8d8bef9SDimitry Andric constantMatches(Value *V, unsigned GVN, 459e8d8bef9SDimitry Andric DenseMap<unsigned, Constant *> &GVNToConstant) { 460e8d8bef9SDimitry Andric // See if we have a constants 461e8d8bef9SDimitry Andric Constant *CST = dyn_cast<Constant>(V); 462e8d8bef9SDimitry Andric if (!CST) 463e8d8bef9SDimitry Andric return None; 464e8d8bef9SDimitry Andric 465e8d8bef9SDimitry Andric // Holds a mapping from a global value number to a Constant. 466e8d8bef9SDimitry Andric DenseMap<unsigned, Constant *>::iterator GVNToConstantIt; 467e8d8bef9SDimitry Andric bool Inserted; 468e8d8bef9SDimitry Andric 469e8d8bef9SDimitry Andric 470e8d8bef9SDimitry Andric // If we have a constant, try to make a new entry in the GVNToConstant. 471e8d8bef9SDimitry Andric std::tie(GVNToConstantIt, Inserted) = 472e8d8bef9SDimitry Andric GVNToConstant.insert(std::make_pair(GVN, CST)); 473e8d8bef9SDimitry Andric // If it was found and is not equal, it is not the same. We do not 474e8d8bef9SDimitry Andric // handle this case yet, and exit early. 475e8d8bef9SDimitry Andric if (Inserted || (GVNToConstantIt->second == CST)) 476e8d8bef9SDimitry Andric return true; 477e8d8bef9SDimitry Andric 478e8d8bef9SDimitry Andric return false; 479e8d8bef9SDimitry Andric } 480e8d8bef9SDimitry Andric 481e8d8bef9SDimitry Andric InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) { 482e8d8bef9SDimitry Andric InstructionCost Benefit = 0; 483e8d8bef9SDimitry Andric 484e8d8bef9SDimitry Andric // Estimate the benefit of outlining a specific sections of the program. We 485e8d8bef9SDimitry Andric // delegate mostly this task to the TargetTransformInfo so that if the target 486e8d8bef9SDimitry Andric // has specific changes, we can have a more accurate estimate. 487e8d8bef9SDimitry Andric 488e8d8bef9SDimitry Andric // However, getInstructionCost delegates the code size calculation for 489e8d8bef9SDimitry Andric // arithmetic instructions to getArithmeticInstrCost in 490e8d8bef9SDimitry Andric // include/Analysis/TargetTransformImpl.h, where it always estimates that the 491e8d8bef9SDimitry Andric // code size for a division and remainder instruction to be equal to 4, and 492e8d8bef9SDimitry Andric // everything else to 1. This is not an accurate representation of the 493e8d8bef9SDimitry Andric // division instruction for targets that have a native division instruction. 494e8d8bef9SDimitry Andric // To be overly conservative, we only add 1 to the number of instructions for 495e8d8bef9SDimitry Andric // each division instruction. 496349cc55cSDimitry Andric for (IRInstructionData &ID : *Candidate) { 497349cc55cSDimitry Andric Instruction *I = ID.Inst; 498349cc55cSDimitry Andric switch (I->getOpcode()) { 499e8d8bef9SDimitry Andric case Instruction::FDiv: 500e8d8bef9SDimitry Andric case Instruction::FRem: 501e8d8bef9SDimitry Andric case Instruction::SDiv: 502e8d8bef9SDimitry Andric case Instruction::SRem: 503e8d8bef9SDimitry Andric case Instruction::UDiv: 504e8d8bef9SDimitry Andric case Instruction::URem: 505e8d8bef9SDimitry Andric Benefit += 1; 506e8d8bef9SDimitry Andric break; 507e8d8bef9SDimitry Andric default: 508349cc55cSDimitry Andric Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize); 509e8d8bef9SDimitry Andric break; 510e8d8bef9SDimitry Andric } 511e8d8bef9SDimitry Andric } 512e8d8bef9SDimitry Andric 513e8d8bef9SDimitry Andric return Benefit; 514e8d8bef9SDimitry Andric } 515e8d8bef9SDimitry Andric 51604eeddc0SDimitry Andric /// Check the \p OutputMappings structure for value \p Input, if it exists 51704eeddc0SDimitry Andric /// it has been used as an output for outlining, and has been renamed, and we 51804eeddc0SDimitry Andric /// return the new value, otherwise, we return the same value. 51904eeddc0SDimitry Andric /// 52004eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of values to their renamed value 52104eeddc0SDimitry Andric /// after being used as an output for an outlined region. 52204eeddc0SDimitry Andric /// \param Input [in] - The value to find the remapped value of, if it exists. 52304eeddc0SDimitry Andric /// \return The remapped value if it has been renamed, and the same value if has 52404eeddc0SDimitry Andric /// not. 52504eeddc0SDimitry Andric static Value *findOutputMapping(const DenseMap<Value *, Value *> OutputMappings, 52604eeddc0SDimitry Andric Value *Input) { 52704eeddc0SDimitry Andric DenseMap<Value *, Value *>::const_iterator OutputMapping = 52804eeddc0SDimitry Andric OutputMappings.find(Input); 52904eeddc0SDimitry Andric if (OutputMapping != OutputMappings.end()) 53004eeddc0SDimitry Andric return OutputMapping->second; 53104eeddc0SDimitry Andric return Input; 53204eeddc0SDimitry Andric } 53304eeddc0SDimitry Andric 534e8d8bef9SDimitry Andric /// Find whether \p Region matches the global value numbering to Constant 535e8d8bef9SDimitry Andric /// mapping found so far. 536e8d8bef9SDimitry Andric /// 537e8d8bef9SDimitry Andric /// \param Region - The OutlinableRegion we are checking for constants 538e8d8bef9SDimitry Andric /// \param GVNToConstant - The mapping of global value number to Constants. 539e8d8bef9SDimitry Andric /// \param NotSame - The set of global value numbers that do not have the same 540e8d8bef9SDimitry Andric /// constant in each region. 541e8d8bef9SDimitry Andric /// \returns true if all Constants are the same in every use of a Constant in \p 542e8d8bef9SDimitry Andric /// Region and false if not 543e8d8bef9SDimitry Andric static bool 544e8d8bef9SDimitry Andric collectRegionsConstants(OutlinableRegion &Region, 545e8d8bef9SDimitry Andric DenseMap<unsigned, Constant *> &GVNToConstant, 546e8d8bef9SDimitry Andric DenseSet<unsigned> &NotSame) { 547e8d8bef9SDimitry Andric bool ConstantsTheSame = true; 548e8d8bef9SDimitry Andric 549e8d8bef9SDimitry Andric IRSimilarityCandidate &C = *Region.Candidate; 550e8d8bef9SDimitry Andric for (IRInstructionData &ID : C) { 551e8d8bef9SDimitry Andric 552e8d8bef9SDimitry Andric // Iterate over the operands in an instruction. If the global value number, 553e8d8bef9SDimitry Andric // assigned by the IRSimilarityCandidate, has been seen before, we check if 554e8d8bef9SDimitry Andric // the the number has been found to be not the same value in each instance. 555e8d8bef9SDimitry Andric for (Value *V : ID.OperVals) { 556e8d8bef9SDimitry Andric Optional<unsigned> GVNOpt = C.getGVN(V); 557*81ad6265SDimitry Andric assert(GVNOpt && "Expected a GVN for operand?"); 558e8d8bef9SDimitry Andric unsigned GVN = GVNOpt.getValue(); 559e8d8bef9SDimitry Andric 560e8d8bef9SDimitry Andric // Check if this global value has been found to not be the same already. 561e8d8bef9SDimitry Andric if (NotSame.contains(GVN)) { 562e8d8bef9SDimitry Andric if (isa<Constant>(V)) 563e8d8bef9SDimitry Andric ConstantsTheSame = false; 564e8d8bef9SDimitry Andric continue; 565e8d8bef9SDimitry Andric } 566e8d8bef9SDimitry Andric 567e8d8bef9SDimitry Andric // If it has been the same so far, we check the value for if the 568e8d8bef9SDimitry Andric // associated Constant value match the previous instances of the same 569e8d8bef9SDimitry Andric // global value number. If the global value does not map to a Constant, 570e8d8bef9SDimitry Andric // it is considered to not be the same value. 571e8d8bef9SDimitry Andric Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant); 572*81ad6265SDimitry Andric if (ConstantMatches) { 573e8d8bef9SDimitry Andric if (ConstantMatches.getValue()) 574e8d8bef9SDimitry Andric continue; 575e8d8bef9SDimitry Andric else 576e8d8bef9SDimitry Andric ConstantsTheSame = false; 577e8d8bef9SDimitry Andric } 578e8d8bef9SDimitry Andric 579e8d8bef9SDimitry Andric // While this value is a register, it might not have been previously, 580e8d8bef9SDimitry Andric // make sure we don't already have a constant mapped to this global value 581e8d8bef9SDimitry Andric // number. 582e8d8bef9SDimitry Andric if (GVNToConstant.find(GVN) != GVNToConstant.end()) 583e8d8bef9SDimitry Andric ConstantsTheSame = false; 584e8d8bef9SDimitry Andric 585e8d8bef9SDimitry Andric NotSame.insert(GVN); 586e8d8bef9SDimitry Andric } 587e8d8bef9SDimitry Andric } 588e8d8bef9SDimitry Andric 589e8d8bef9SDimitry Andric return ConstantsTheSame; 590e8d8bef9SDimitry Andric } 591e8d8bef9SDimitry Andric 592e8d8bef9SDimitry Andric void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) { 593e8d8bef9SDimitry Andric DenseMap<unsigned, Constant *> GVNToConstant; 594e8d8bef9SDimitry Andric 595e8d8bef9SDimitry Andric for (OutlinableRegion *Region : Regions) 596e8d8bef9SDimitry Andric collectRegionsConstants(*Region, GVNToConstant, NotSame); 597e8d8bef9SDimitry Andric } 598e8d8bef9SDimitry Andric 599e8d8bef9SDimitry Andric void OutlinableGroup::collectGVNStoreSets(Module &M) { 600e8d8bef9SDimitry Andric for (OutlinableRegion *OS : Regions) 601e8d8bef9SDimitry Andric OutputGVNCombinations.insert(OS->GVNStores); 602e8d8bef9SDimitry Andric 603e8d8bef9SDimitry Andric // We are adding an extracted argument to decide between which output path 604e8d8bef9SDimitry Andric // to use in the basic block. It is used in a switch statement and only 605e8d8bef9SDimitry Andric // needs to be an integer. 606e8d8bef9SDimitry Andric if (OutputGVNCombinations.size() > 1) 607e8d8bef9SDimitry Andric ArgumentTypes.push_back(Type::getInt32Ty(M.getContext())); 608e8d8bef9SDimitry Andric } 609e8d8bef9SDimitry Andric 610fe6060f1SDimitry Andric /// Get the subprogram if it exists for one of the outlined regions. 611fe6060f1SDimitry Andric /// 612fe6060f1SDimitry Andric /// \param [in] Group - The set of regions to find a subprogram for. 613fe6060f1SDimitry Andric /// \returns the subprogram if it exists, or nullptr. 614fe6060f1SDimitry Andric static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) { 615fe6060f1SDimitry Andric for (OutlinableRegion *OS : Group.Regions) 616fe6060f1SDimitry Andric if (Function *F = OS->Call->getFunction()) 617fe6060f1SDimitry Andric if (DISubprogram *SP = F->getSubprogram()) 618fe6060f1SDimitry Andric return SP; 619fe6060f1SDimitry Andric 620fe6060f1SDimitry Andric return nullptr; 621fe6060f1SDimitry Andric } 622fe6060f1SDimitry Andric 623e8d8bef9SDimitry Andric Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group, 624e8d8bef9SDimitry Andric unsigned FunctionNameSuffix) { 625e8d8bef9SDimitry Andric assert(!Group.OutlinedFunction && "Function is already defined!"); 626e8d8bef9SDimitry Andric 627349cc55cSDimitry Andric Type *RetTy = Type::getVoidTy(M.getContext()); 628349cc55cSDimitry Andric // All extracted functions _should_ have the same return type at this point 629349cc55cSDimitry Andric // since the similarity identifier ensures that all branches outside of the 630349cc55cSDimitry Andric // region occur in the same place. 631349cc55cSDimitry Andric 632349cc55cSDimitry Andric // NOTE: Should we ever move to the model that uses a switch at every point 633349cc55cSDimitry Andric // needed, meaning that we could branch within the region or out, it is 634349cc55cSDimitry Andric // possible that we will need to switch to using the most general case all of 635349cc55cSDimitry Andric // the time. 636349cc55cSDimitry Andric for (OutlinableRegion *R : Group.Regions) { 637349cc55cSDimitry Andric Type *ExtractedFuncType = R->ExtractedFunction->getReturnType(); 638349cc55cSDimitry Andric if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) || 639349cc55cSDimitry Andric (RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16))) 640349cc55cSDimitry Andric RetTy = ExtractedFuncType; 641349cc55cSDimitry Andric } 642349cc55cSDimitry Andric 643e8d8bef9SDimitry Andric Group.OutlinedFunctionType = FunctionType::get( 644349cc55cSDimitry Andric RetTy, Group.ArgumentTypes, false); 645e8d8bef9SDimitry Andric 646e8d8bef9SDimitry Andric // These functions will only be called from within the same module, so 647e8d8bef9SDimitry Andric // we can set an internal linkage. 648e8d8bef9SDimitry Andric Group.OutlinedFunction = Function::Create( 649e8d8bef9SDimitry Andric Group.OutlinedFunctionType, GlobalValue::InternalLinkage, 650e8d8bef9SDimitry Andric "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M); 651e8d8bef9SDimitry Andric 652e8d8bef9SDimitry Andric // Transfer the swifterr attribute to the correct function parameter. 653*81ad6265SDimitry Andric if (Group.SwiftErrorArgument) 654e8d8bef9SDimitry Andric Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.getValue(), 655e8d8bef9SDimitry Andric Attribute::SwiftError); 656e8d8bef9SDimitry Andric 657e8d8bef9SDimitry Andric Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize); 658e8d8bef9SDimitry Andric Group.OutlinedFunction->addFnAttr(Attribute::MinSize); 659e8d8bef9SDimitry Andric 660fe6060f1SDimitry Andric // If there's a DISubprogram associated with this outlined function, then 661fe6060f1SDimitry Andric // emit debug info for the outlined function. 662fe6060f1SDimitry Andric if (DISubprogram *SP = getSubprogramOrNull(Group)) { 663fe6060f1SDimitry Andric Function *F = Group.OutlinedFunction; 664fe6060f1SDimitry Andric // We have a DISubprogram. Get its DICompileUnit. 665fe6060f1SDimitry Andric DICompileUnit *CU = SP->getUnit(); 666fe6060f1SDimitry Andric DIBuilder DB(M, true, CU); 667fe6060f1SDimitry Andric DIFile *Unit = SP->getFile(); 668fe6060f1SDimitry Andric Mangler Mg; 669fe6060f1SDimitry Andric // Get the mangled name of the function for the linkage name. 670fe6060f1SDimitry Andric std::string Dummy; 671fe6060f1SDimitry Andric llvm::raw_string_ostream MangledNameStream(Dummy); 672fe6060f1SDimitry Andric Mg.getNameWithPrefix(MangledNameStream, F, false); 673fe6060f1SDimitry Andric 674fe6060f1SDimitry Andric DISubprogram *OutlinedSP = DB.createFunction( 675fe6060f1SDimitry Andric Unit /* Context */, F->getName(), MangledNameStream.str(), 676fe6060f1SDimitry Andric Unit /* File */, 677fe6060f1SDimitry Andric 0 /* Line 0 is reserved for compiler-generated code. */, 678fe6060f1SDimitry Andric DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */ 679fe6060f1SDimitry Andric 0, /* Line 0 is reserved for compiler-generated code. */ 680fe6060f1SDimitry Andric DINode::DIFlags::FlagArtificial /* Compiler-generated code. */, 681fe6060f1SDimitry Andric /* Outlined code is optimized code by definition. */ 682fe6060f1SDimitry Andric DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized); 683fe6060f1SDimitry Andric 684fe6060f1SDimitry Andric // Don't add any new variables to the subprogram. 685fe6060f1SDimitry Andric DB.finalizeSubprogram(OutlinedSP); 686fe6060f1SDimitry Andric 687fe6060f1SDimitry Andric // Attach subprogram to the function. 688fe6060f1SDimitry Andric F->setSubprogram(OutlinedSP); 689fe6060f1SDimitry Andric // We're done with the DIBuilder. 690fe6060f1SDimitry Andric DB.finalize(); 691fe6060f1SDimitry Andric } 692fe6060f1SDimitry Andric 693e8d8bef9SDimitry Andric return Group.OutlinedFunction; 694e8d8bef9SDimitry Andric } 695e8d8bef9SDimitry Andric 696e8d8bef9SDimitry Andric /// Move each BasicBlock in \p Old to \p New. 697e8d8bef9SDimitry Andric /// 698fe6060f1SDimitry Andric /// \param [in] Old - The function to move the basic blocks from. 699e8d8bef9SDimitry Andric /// \param [in] New - The function to move the basic blocks to. 700349cc55cSDimitry Andric /// \param [out] NewEnds - The return blocks of the new overall function. 701349cc55cSDimitry Andric static void moveFunctionData(Function &Old, Function &New, 702349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> &NewEnds) { 703349cc55cSDimitry Andric for (BasicBlock &CurrBB : llvm::make_early_inc_range(Old)) { 704349cc55cSDimitry Andric CurrBB.removeFromParent(); 705349cc55cSDimitry Andric CurrBB.insertInto(&New); 706349cc55cSDimitry Andric Instruction *I = CurrBB.getTerminator(); 707fe6060f1SDimitry Andric 708349cc55cSDimitry Andric // For each block we find a return instruction is, it is a potential exit 709349cc55cSDimitry Andric // path for the function. We keep track of each block based on the return 710349cc55cSDimitry Andric // value here. 711349cc55cSDimitry Andric if (ReturnInst *RI = dyn_cast<ReturnInst>(I)) 712349cc55cSDimitry Andric NewEnds.insert(std::make_pair(RI->getReturnValue(), &CurrBB)); 713349cc55cSDimitry Andric 714349cc55cSDimitry Andric std::vector<Instruction *> DebugInsts; 715349cc55cSDimitry Andric 716349cc55cSDimitry Andric for (Instruction &Val : CurrBB) { 717fe6060f1SDimitry Andric // We must handle the scoping of called functions differently than 718fe6060f1SDimitry Andric // other outlined instructions. 719fe6060f1SDimitry Andric if (!isa<CallInst>(&Val)) { 720fe6060f1SDimitry Andric // Remove the debug information for outlined functions. 721fe6060f1SDimitry Andric Val.setDebugLoc(DebugLoc()); 722*81ad6265SDimitry Andric 723*81ad6265SDimitry Andric // Loop info metadata may contain line locations. Update them to have no 724*81ad6265SDimitry Andric // value in the new subprogram since the outlined code could be from 725*81ad6265SDimitry Andric // several locations. 726*81ad6265SDimitry Andric auto updateLoopInfoLoc = [&New](Metadata *MD) -> Metadata * { 727*81ad6265SDimitry Andric if (DISubprogram *SP = New.getSubprogram()) 728*81ad6265SDimitry Andric if (auto *Loc = dyn_cast_or_null<DILocation>(MD)) 729*81ad6265SDimitry Andric return DILocation::get(New.getContext(), Loc->getLine(), 730*81ad6265SDimitry Andric Loc->getColumn(), SP, nullptr); 731*81ad6265SDimitry Andric return MD; 732*81ad6265SDimitry Andric }; 733*81ad6265SDimitry Andric updateLoopMetadataDebugLocations(Val, updateLoopInfoLoc); 734fe6060f1SDimitry Andric continue; 735fe6060f1SDimitry Andric } 736fe6060f1SDimitry Andric 737fe6060f1SDimitry Andric // From this point we are only handling call instructions. 738fe6060f1SDimitry Andric CallInst *CI = cast<CallInst>(&Val); 739fe6060f1SDimitry Andric 740fe6060f1SDimitry Andric // We add any debug statements here, to be removed after. Since the 741fe6060f1SDimitry Andric // instructions originate from many different locations in the program, 742fe6060f1SDimitry Andric // it will cause incorrect reporting from a debugger if we keep the 743fe6060f1SDimitry Andric // same debug instructions. 744fe6060f1SDimitry Andric if (isa<DbgInfoIntrinsic>(CI)) { 745fe6060f1SDimitry Andric DebugInsts.push_back(&Val); 746fe6060f1SDimitry Andric continue; 747fe6060f1SDimitry Andric } 748fe6060f1SDimitry Andric 749fe6060f1SDimitry Andric // Edit the scope of called functions inside of outlined functions. 750fe6060f1SDimitry Andric if (DISubprogram *SP = New.getSubprogram()) { 751fe6060f1SDimitry Andric DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP); 752fe6060f1SDimitry Andric Val.setDebugLoc(DI); 753fe6060f1SDimitry Andric } 754fe6060f1SDimitry Andric } 755fe6060f1SDimitry Andric 756fe6060f1SDimitry Andric for (Instruction *I : DebugInsts) 757fe6060f1SDimitry Andric I->eraseFromParent(); 758e8d8bef9SDimitry Andric } 759e8d8bef9SDimitry Andric } 760e8d8bef9SDimitry Andric 761e8d8bef9SDimitry Andric /// Find the the constants that will need to be lifted into arguments 762e8d8bef9SDimitry Andric /// as they are not the same in each instance of the region. 763e8d8bef9SDimitry Andric /// 764e8d8bef9SDimitry Andric /// \param [in] C - The IRSimilarityCandidate containing the region we are 765e8d8bef9SDimitry Andric /// analyzing. 766e8d8bef9SDimitry Andric /// \param [in] NotSame - The set of global value numbers that do not have a 767e8d8bef9SDimitry Andric /// single Constant across all OutlinableRegions similar to \p C. 768e8d8bef9SDimitry Andric /// \param [out] Inputs - The list containing the global value numbers of the 769e8d8bef9SDimitry Andric /// arguments needed for the region of code. 770e8d8bef9SDimitry Andric static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame, 771e8d8bef9SDimitry Andric std::vector<unsigned> &Inputs) { 772e8d8bef9SDimitry Andric DenseSet<unsigned> Seen; 773e8d8bef9SDimitry Andric // Iterate over the instructions, and find what constants will need to be 774e8d8bef9SDimitry Andric // extracted into arguments. 775e8d8bef9SDimitry Andric for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end(); 776e8d8bef9SDimitry Andric IDIt != EndIDIt; IDIt++) { 777e8d8bef9SDimitry Andric for (Value *V : (*IDIt).OperVals) { 778e8d8bef9SDimitry Andric // Since these are stored before any outlining, they will be in the 779e8d8bef9SDimitry Andric // global value numbering. 780*81ad6265SDimitry Andric unsigned GVN = *C.getGVN(V); 781e8d8bef9SDimitry Andric if (isa<Constant>(V)) 782e8d8bef9SDimitry Andric if (NotSame.contains(GVN) && !Seen.contains(GVN)) { 783e8d8bef9SDimitry Andric Inputs.push_back(GVN); 784e8d8bef9SDimitry Andric Seen.insert(GVN); 785e8d8bef9SDimitry Andric } 786e8d8bef9SDimitry Andric } 787e8d8bef9SDimitry Andric } 788e8d8bef9SDimitry Andric } 789e8d8bef9SDimitry Andric 790e8d8bef9SDimitry Andric /// Find the GVN for the inputs that have been found by the CodeExtractor. 791e8d8bef9SDimitry Andric /// 792e8d8bef9SDimitry Andric /// \param [in] C - The IRSimilarityCandidate containing the region we are 793e8d8bef9SDimitry Andric /// analyzing. 794e8d8bef9SDimitry Andric /// \param [in] CurrentInputs - The set of inputs found by the 795e8d8bef9SDimitry Andric /// CodeExtractor. 796e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced 797e8d8bef9SDimitry Andric /// by a new output value. 798fe6060f1SDimitry Andric /// \param [out] EndInputNumbers - The global value numbers for the extracted 799e8d8bef9SDimitry Andric /// arguments. 800e8d8bef9SDimitry Andric static void mapInputsToGVNs(IRSimilarityCandidate &C, 801e8d8bef9SDimitry Andric SetVector<Value *> &CurrentInputs, 802e8d8bef9SDimitry Andric const DenseMap<Value *, Value *> &OutputMappings, 803e8d8bef9SDimitry Andric std::vector<unsigned> &EndInputNumbers) { 804e8d8bef9SDimitry Andric // Get the Global Value Number for each input. We check if the Value has been 805e8d8bef9SDimitry Andric // replaced by a different value at output, and use the original value before 806e8d8bef9SDimitry Andric // replacement. 807e8d8bef9SDimitry Andric for (Value *Input : CurrentInputs) { 808e8d8bef9SDimitry Andric assert(Input && "Have a nullptr as an input"); 809e8d8bef9SDimitry Andric if (OutputMappings.find(Input) != OutputMappings.end()) 810e8d8bef9SDimitry Andric Input = OutputMappings.find(Input)->second; 811*81ad6265SDimitry Andric assert(C.getGVN(Input) && "Could not find a numbering for the given input"); 812e8d8bef9SDimitry Andric EndInputNumbers.push_back(C.getGVN(Input).getValue()); 813e8d8bef9SDimitry Andric } 814e8d8bef9SDimitry Andric } 815e8d8bef9SDimitry Andric 816e8d8bef9SDimitry Andric /// Find the original value for the \p ArgInput values if any one of them was 817e8d8bef9SDimitry Andric /// replaced during a previous extraction. 818e8d8bef9SDimitry Andric /// 819e8d8bef9SDimitry Andric /// \param [in] ArgInputs - The inputs to be extracted by the code extractor. 820e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced 821e8d8bef9SDimitry Andric /// by a new output value. 822e8d8bef9SDimitry Andric /// \param [out] RemappedArgInputs - The remapped values according to 823e8d8bef9SDimitry Andric /// \p OutputMappings that will be extracted. 824e8d8bef9SDimitry Andric static void 825e8d8bef9SDimitry Andric remapExtractedInputs(const ArrayRef<Value *> ArgInputs, 826e8d8bef9SDimitry Andric const DenseMap<Value *, Value *> &OutputMappings, 827e8d8bef9SDimitry Andric SetVector<Value *> &RemappedArgInputs) { 828e8d8bef9SDimitry Andric // Get the global value number for each input that will be extracted as an 829e8d8bef9SDimitry Andric // argument by the code extractor, remapping if needed for reloaded values. 830e8d8bef9SDimitry Andric for (Value *Input : ArgInputs) { 831e8d8bef9SDimitry Andric if (OutputMappings.find(Input) != OutputMappings.end()) 832e8d8bef9SDimitry Andric Input = OutputMappings.find(Input)->second; 833e8d8bef9SDimitry Andric RemappedArgInputs.insert(Input); 834e8d8bef9SDimitry Andric } 835e8d8bef9SDimitry Andric } 836e8d8bef9SDimitry Andric 837e8d8bef9SDimitry Andric /// Find the input GVNs and the output values for a region of Instructions. 838e8d8bef9SDimitry Andric /// Using the code extractor, we collect the inputs to the extracted function. 839e8d8bef9SDimitry Andric /// 840e8d8bef9SDimitry Andric /// The \p Region can be identified as needing to be ignored in this function. 841e8d8bef9SDimitry Andric /// It should be checked whether it should be ignored after a call to this 842e8d8bef9SDimitry Andric /// function. 843e8d8bef9SDimitry Andric /// 844e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed. 845e8d8bef9SDimitry Andric /// \param [out] InputGVNs - The global value numbers for the extracted 846e8d8bef9SDimitry Andric /// arguments. 847e8d8bef9SDimitry Andric /// \param [in] NotSame - The global value numbers in the region that do not 848e8d8bef9SDimitry Andric /// have the same constant value in the regions structurally similar to 849e8d8bef9SDimitry Andric /// \p Region. 850e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced 851e8d8bef9SDimitry Andric /// by a new output value after extraction. 852e8d8bef9SDimitry Andric /// \param [out] ArgInputs - The values of the inputs to the extracted function. 853e8d8bef9SDimitry Andric /// \param [out] Outputs - The set of values extracted by the CodeExtractor 854e8d8bef9SDimitry Andric /// as outputs. 855e8d8bef9SDimitry Andric static void getCodeExtractorArguments( 856e8d8bef9SDimitry Andric OutlinableRegion &Region, std::vector<unsigned> &InputGVNs, 857e8d8bef9SDimitry Andric DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings, 858e8d8bef9SDimitry Andric SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) { 859e8d8bef9SDimitry Andric IRSimilarityCandidate &C = *Region.Candidate; 860e8d8bef9SDimitry Andric 861e8d8bef9SDimitry Andric // OverallInputs are the inputs to the region found by the CodeExtractor, 862e8d8bef9SDimitry Andric // SinkCands and HoistCands are used by the CodeExtractor to find sunken 863e8d8bef9SDimitry Andric // allocas of values whose lifetimes are contained completely within the 864e8d8bef9SDimitry Andric // outlined region. PremappedInputs are the arguments found by the 865e8d8bef9SDimitry Andric // CodeExtractor, removing conditions such as sunken allocas, but that 866e8d8bef9SDimitry Andric // may need to be remapped due to the extracted output values replacing 867e8d8bef9SDimitry Andric // the original values. We use DummyOutputs for this first run of finding 868e8d8bef9SDimitry Andric // inputs and outputs since the outputs could change during findAllocas, 869e8d8bef9SDimitry Andric // the correct set of extracted outputs will be in the final Outputs ValueSet. 870e8d8bef9SDimitry Andric SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands, 871e8d8bef9SDimitry Andric DummyOutputs; 872e8d8bef9SDimitry Andric 873e8d8bef9SDimitry Andric // Use the code extractor to get the inputs and outputs, without sunken 874e8d8bef9SDimitry Andric // allocas or removing llvm.assumes. 875e8d8bef9SDimitry Andric CodeExtractor *CE = Region.CE; 876e8d8bef9SDimitry Andric CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands); 877e8d8bef9SDimitry Andric assert(Region.StartBB && "Region must have a start BasicBlock!"); 878e8d8bef9SDimitry Andric Function *OrigF = Region.StartBB->getParent(); 879e8d8bef9SDimitry Andric CodeExtractorAnalysisCache CEAC(*OrigF); 880e8d8bef9SDimitry Andric BasicBlock *Dummy = nullptr; 881e8d8bef9SDimitry Andric 882e8d8bef9SDimitry Andric // The region may be ineligible due to VarArgs in the parent function. In this 883e8d8bef9SDimitry Andric // case we ignore the region. 884e8d8bef9SDimitry Andric if (!CE->isEligible()) { 885e8d8bef9SDimitry Andric Region.IgnoreRegion = true; 886e8d8bef9SDimitry Andric return; 887e8d8bef9SDimitry Andric } 888e8d8bef9SDimitry Andric 889e8d8bef9SDimitry Andric // Find if any values are going to be sunk into the function when extracted 890e8d8bef9SDimitry Andric CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy); 891e8d8bef9SDimitry Andric CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands); 892e8d8bef9SDimitry Andric 893e8d8bef9SDimitry Andric // TODO: Support regions with sunken allocas: values whose lifetimes are 894e8d8bef9SDimitry Andric // contained completely within the outlined region. These are not guaranteed 895e8d8bef9SDimitry Andric // to be the same in every region, so we must elevate them all to arguments 896e8d8bef9SDimitry Andric // when they appear. If these values are not equal, it means there is some 897e8d8bef9SDimitry Andric // Input in OverallInputs that was removed for ArgInputs. 898e8d8bef9SDimitry Andric if (OverallInputs.size() != PremappedInputs.size()) { 899e8d8bef9SDimitry Andric Region.IgnoreRegion = true; 900e8d8bef9SDimitry Andric return; 901e8d8bef9SDimitry Andric } 902e8d8bef9SDimitry Andric 903e8d8bef9SDimitry Andric findConstants(C, NotSame, InputGVNs); 904e8d8bef9SDimitry Andric 905e8d8bef9SDimitry Andric mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs); 906e8d8bef9SDimitry Andric 907e8d8bef9SDimitry Andric remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings, 908e8d8bef9SDimitry Andric ArgInputs); 909e8d8bef9SDimitry Andric 910e8d8bef9SDimitry Andric // Sort the GVNs, since we now have constants included in the \ref InputGVNs 911e8d8bef9SDimitry Andric // we need to make sure they are in a deterministic order. 912e8d8bef9SDimitry Andric stable_sort(InputGVNs); 913e8d8bef9SDimitry Andric } 914e8d8bef9SDimitry Andric 915e8d8bef9SDimitry Andric /// Look over the inputs and map each input argument to an argument in the 916e8d8bef9SDimitry Andric /// overall function for the OutlinableRegions. This creates a way to replace 917e8d8bef9SDimitry Andric /// the arguments of the extracted function with the arguments of the new 918e8d8bef9SDimitry Andric /// overall function. 919e8d8bef9SDimitry Andric /// 920e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed. 921fe6060f1SDimitry Andric /// \param [in] InputGVNs - The global value numbering of the input values 922e8d8bef9SDimitry Andric /// collected. 923e8d8bef9SDimitry Andric /// \param [in] ArgInputs - The values of the arguments to the extracted 924e8d8bef9SDimitry Andric /// function. 925e8d8bef9SDimitry Andric static void 926e8d8bef9SDimitry Andric findExtractedInputToOverallInputMapping(OutlinableRegion &Region, 927e8d8bef9SDimitry Andric std::vector<unsigned> &InputGVNs, 928e8d8bef9SDimitry Andric SetVector<Value *> &ArgInputs) { 929e8d8bef9SDimitry Andric 930e8d8bef9SDimitry Andric IRSimilarityCandidate &C = *Region.Candidate; 931e8d8bef9SDimitry Andric OutlinableGroup &Group = *Region.Parent; 932e8d8bef9SDimitry Andric 933e8d8bef9SDimitry Andric // This counts the argument number in the overall function. 934e8d8bef9SDimitry Andric unsigned TypeIndex = 0; 935e8d8bef9SDimitry Andric 936e8d8bef9SDimitry Andric // This counts the argument number in the extracted function. 937e8d8bef9SDimitry Andric unsigned OriginalIndex = 0; 938e8d8bef9SDimitry Andric 939e8d8bef9SDimitry Andric // Find the mapping of the extracted arguments to the arguments for the 940e8d8bef9SDimitry Andric // overall function. Since there may be extra arguments in the overall 941e8d8bef9SDimitry Andric // function to account for the extracted constants, we have two different 942e8d8bef9SDimitry Andric // counters as we find extracted arguments, and as we come across overall 943e8d8bef9SDimitry Andric // arguments. 944349cc55cSDimitry Andric 945349cc55cSDimitry Andric // Additionally, in our first pass, for the first extracted function, 946349cc55cSDimitry Andric // we find argument locations for the canonical value numbering. This 947349cc55cSDimitry Andric // numbering overrides any discovered location for the extracted code. 948e8d8bef9SDimitry Andric for (unsigned InputVal : InputGVNs) { 949349cc55cSDimitry Andric Optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal); 950*81ad6265SDimitry Andric assert(CanonicalNumberOpt && "Canonical number not found?"); 951349cc55cSDimitry Andric unsigned CanonicalNumber = CanonicalNumberOpt.getValue(); 952349cc55cSDimitry Andric 953e8d8bef9SDimitry Andric Optional<Value *> InputOpt = C.fromGVN(InputVal); 954*81ad6265SDimitry Andric assert(InputOpt && "Global value number not found?"); 955e8d8bef9SDimitry Andric Value *Input = InputOpt.getValue(); 956e8d8bef9SDimitry Andric 957349cc55cSDimitry Andric DenseMap<unsigned, unsigned>::iterator AggArgIt = 958349cc55cSDimitry Andric Group.CanonicalNumberToAggArg.find(CanonicalNumber); 959349cc55cSDimitry Andric 960e8d8bef9SDimitry Andric if (!Group.InputTypesSet) { 961e8d8bef9SDimitry Andric Group.ArgumentTypes.push_back(Input->getType()); 962e8d8bef9SDimitry Andric // If the input value has a swifterr attribute, make sure to mark the 963e8d8bef9SDimitry Andric // argument in the overall function. 964e8d8bef9SDimitry Andric if (Input->isSwiftError()) { 965e8d8bef9SDimitry Andric assert( 966*81ad6265SDimitry Andric !Group.SwiftErrorArgument && 967e8d8bef9SDimitry Andric "Argument already marked with swifterr for this OutlinableGroup!"); 968e8d8bef9SDimitry Andric Group.SwiftErrorArgument = TypeIndex; 969e8d8bef9SDimitry Andric } 970e8d8bef9SDimitry Andric } 971e8d8bef9SDimitry Andric 972e8d8bef9SDimitry Andric // Check if we have a constant. If we do add it to the overall argument 973e8d8bef9SDimitry Andric // number to Constant map for the region, and continue to the next input. 974e8d8bef9SDimitry Andric if (Constant *CST = dyn_cast<Constant>(Input)) { 975349cc55cSDimitry Andric if (AggArgIt != Group.CanonicalNumberToAggArg.end()) 976349cc55cSDimitry Andric Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST)); 977349cc55cSDimitry Andric else { 978349cc55cSDimitry Andric Group.CanonicalNumberToAggArg.insert( 979349cc55cSDimitry Andric std::make_pair(CanonicalNumber, TypeIndex)); 980e8d8bef9SDimitry Andric Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST)); 981349cc55cSDimitry Andric } 982e8d8bef9SDimitry Andric TypeIndex++; 983e8d8bef9SDimitry Andric continue; 984e8d8bef9SDimitry Andric } 985e8d8bef9SDimitry Andric 986e8d8bef9SDimitry Andric // It is not a constant, we create the mapping from extracted argument list 987349cc55cSDimitry Andric // to the overall argument list, using the canonical location, if it exists. 988e8d8bef9SDimitry Andric assert(ArgInputs.count(Input) && "Input cannot be found!"); 989e8d8bef9SDimitry Andric 990349cc55cSDimitry Andric if (AggArgIt != Group.CanonicalNumberToAggArg.end()) { 991349cc55cSDimitry Andric if (OriginalIndex != AggArgIt->second) 992349cc55cSDimitry Andric Region.ChangedArgOrder = true; 993349cc55cSDimitry Andric Region.ExtractedArgToAgg.insert( 994349cc55cSDimitry Andric std::make_pair(OriginalIndex, AggArgIt->second)); 995349cc55cSDimitry Andric Region.AggArgToExtracted.insert( 996349cc55cSDimitry Andric std::make_pair(AggArgIt->second, OriginalIndex)); 997349cc55cSDimitry Andric } else { 998349cc55cSDimitry Andric Group.CanonicalNumberToAggArg.insert( 999349cc55cSDimitry Andric std::make_pair(CanonicalNumber, TypeIndex)); 1000e8d8bef9SDimitry Andric Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex)); 1001e8d8bef9SDimitry Andric Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex)); 1002349cc55cSDimitry Andric } 1003e8d8bef9SDimitry Andric OriginalIndex++; 1004e8d8bef9SDimitry Andric TypeIndex++; 1005e8d8bef9SDimitry Andric } 1006e8d8bef9SDimitry Andric 1007e8d8bef9SDimitry Andric // If the function type definitions for the OutlinableGroup holding the region 1008e8d8bef9SDimitry Andric // have not been set, set the length of the inputs here. We should have the 1009e8d8bef9SDimitry Andric // same inputs for all of the different regions contained in the 1010e8d8bef9SDimitry Andric // OutlinableGroup since they are all structurally similar to one another. 1011e8d8bef9SDimitry Andric if (!Group.InputTypesSet) { 1012e8d8bef9SDimitry Andric Group.NumAggregateInputs = TypeIndex; 1013e8d8bef9SDimitry Andric Group.InputTypesSet = true; 1014e8d8bef9SDimitry Andric } 1015e8d8bef9SDimitry Andric 1016e8d8bef9SDimitry Andric Region.NumExtractedInputs = OriginalIndex; 1017e8d8bef9SDimitry Andric } 1018e8d8bef9SDimitry Andric 101904eeddc0SDimitry Andric /// Check if the \p V has any uses outside of the region other than \p PN. 102004eeddc0SDimitry Andric /// 102104eeddc0SDimitry Andric /// \param V [in] - The value to check. 102204eeddc0SDimitry Andric /// \param PHILoc [in] - The location in the PHINode of \p V. 102304eeddc0SDimitry Andric /// \param PN [in] - The PHINode using \p V. 102404eeddc0SDimitry Andric /// \param Exits [in] - The potential blocks we exit to from the outlined 102504eeddc0SDimitry Andric /// region. 102604eeddc0SDimitry Andric /// \param BlocksInRegion [in] - The basic blocks contained in the region. 102704eeddc0SDimitry Andric /// \returns true if \p V has any use soutside its region other than \p PN. 102804eeddc0SDimitry Andric static bool outputHasNonPHI(Value *V, unsigned PHILoc, PHINode &PN, 102904eeddc0SDimitry Andric SmallPtrSet<BasicBlock *, 1> &Exits, 103004eeddc0SDimitry Andric DenseSet<BasicBlock *> &BlocksInRegion) { 103104eeddc0SDimitry Andric // We check to see if the value is used by the PHINode from some other 103204eeddc0SDimitry Andric // predecessor not included in the region. If it is, we make sure 103304eeddc0SDimitry Andric // to keep it as an output. 1034*81ad6265SDimitry Andric if (any_of(llvm::seq<unsigned>(0, PN.getNumIncomingValues()), 1035*81ad6265SDimitry Andric [PHILoc, &PN, V, &BlocksInRegion](unsigned Idx) { 103604eeddc0SDimitry Andric return (Idx != PHILoc && V == PN.getIncomingValue(Idx) && 103704eeddc0SDimitry Andric !BlocksInRegion.contains(PN.getIncomingBlock(Idx))); 103804eeddc0SDimitry Andric })) 103904eeddc0SDimitry Andric return true; 104004eeddc0SDimitry Andric 104104eeddc0SDimitry Andric // Check if the value is used by any other instructions outside the region. 104204eeddc0SDimitry Andric return any_of(V->users(), [&Exits, &BlocksInRegion](User *U) { 104304eeddc0SDimitry Andric Instruction *I = dyn_cast<Instruction>(U); 104404eeddc0SDimitry Andric if (!I) 104504eeddc0SDimitry Andric return false; 104604eeddc0SDimitry Andric 104704eeddc0SDimitry Andric // If the use of the item is inside the region, we skip it. Uses 104804eeddc0SDimitry Andric // inside the region give us useful information about how the item could be 104904eeddc0SDimitry Andric // used as an output. 105004eeddc0SDimitry Andric BasicBlock *Parent = I->getParent(); 105104eeddc0SDimitry Andric if (BlocksInRegion.contains(Parent)) 105204eeddc0SDimitry Andric return false; 105304eeddc0SDimitry Andric 105404eeddc0SDimitry Andric // If it's not a PHINode then we definitely know the use matters. This 105504eeddc0SDimitry Andric // output value will not completely combined with another item in a PHINode 105604eeddc0SDimitry Andric // as it is directly reference by another non-phi instruction 105704eeddc0SDimitry Andric if (!isa<PHINode>(I)) 105804eeddc0SDimitry Andric return true; 105904eeddc0SDimitry Andric 106004eeddc0SDimitry Andric // If we have a PHINode outside one of the exit locations, then it 106104eeddc0SDimitry Andric // can be considered an outside use as well. If there is a PHINode 106204eeddc0SDimitry Andric // contained in the Exit where this values use matters, it will be 106304eeddc0SDimitry Andric // caught when we analyze that PHINode. 106404eeddc0SDimitry Andric if (!Exits.contains(Parent)) 106504eeddc0SDimitry Andric return true; 106604eeddc0SDimitry Andric 106704eeddc0SDimitry Andric return false; 106804eeddc0SDimitry Andric }); 106904eeddc0SDimitry Andric } 107004eeddc0SDimitry Andric 107104eeddc0SDimitry Andric /// Test whether \p CurrentExitFromRegion contains any PhiNodes that should be 107204eeddc0SDimitry Andric /// considered outputs. A PHINodes is an output when more than one incoming 107304eeddc0SDimitry Andric /// value has been marked by the CodeExtractor as an output. 107404eeddc0SDimitry Andric /// 107504eeddc0SDimitry Andric /// \param CurrentExitFromRegion [in] - The block to analyze. 107604eeddc0SDimitry Andric /// \param PotentialExitsFromRegion [in] - The potential exit blocks from the 107704eeddc0SDimitry Andric /// region. 107804eeddc0SDimitry Andric /// \param RegionBlocks [in] - The basic blocks in the region. 107904eeddc0SDimitry Andric /// \param Outputs [in, out] - The existing outputs for the region, we may add 108004eeddc0SDimitry Andric /// PHINodes to this as we find that they replace output values. 108104eeddc0SDimitry Andric /// \param OutputsReplacedByPHINode [out] - A set containing outputs that are 108204eeddc0SDimitry Andric /// totally replaced by a PHINode. 108304eeddc0SDimitry Andric /// \param OutputsWithNonPhiUses [out] - A set containing outputs that are used 108404eeddc0SDimitry Andric /// in PHINodes, but have other uses, and should still be considered outputs. 108504eeddc0SDimitry Andric static void analyzeExitPHIsForOutputUses( 108604eeddc0SDimitry Andric BasicBlock *CurrentExitFromRegion, 108704eeddc0SDimitry Andric SmallPtrSet<BasicBlock *, 1> &PotentialExitsFromRegion, 108804eeddc0SDimitry Andric DenseSet<BasicBlock *> &RegionBlocks, SetVector<Value *> &Outputs, 108904eeddc0SDimitry Andric DenseSet<Value *> &OutputsReplacedByPHINode, 109004eeddc0SDimitry Andric DenseSet<Value *> &OutputsWithNonPhiUses) { 109104eeddc0SDimitry Andric for (PHINode &PN : CurrentExitFromRegion->phis()) { 109204eeddc0SDimitry Andric // Find all incoming values from the outlining region. 109304eeddc0SDimitry Andric SmallVector<unsigned, 2> IncomingVals; 109404eeddc0SDimitry Andric for (unsigned I = 0, E = PN.getNumIncomingValues(); I < E; ++I) 109504eeddc0SDimitry Andric if (RegionBlocks.contains(PN.getIncomingBlock(I))) 109604eeddc0SDimitry Andric IncomingVals.push_back(I); 109704eeddc0SDimitry Andric 109804eeddc0SDimitry Andric // Do not process PHI if there are no predecessors from region. 109904eeddc0SDimitry Andric unsigned NumIncomingVals = IncomingVals.size(); 110004eeddc0SDimitry Andric if (NumIncomingVals == 0) 110104eeddc0SDimitry Andric continue; 110204eeddc0SDimitry Andric 110304eeddc0SDimitry Andric // If there is one predecessor, we mark it as a value that needs to be kept 110404eeddc0SDimitry Andric // as an output. 110504eeddc0SDimitry Andric if (NumIncomingVals == 1) { 110604eeddc0SDimitry Andric Value *V = PN.getIncomingValue(*IncomingVals.begin()); 110704eeddc0SDimitry Andric OutputsWithNonPhiUses.insert(V); 110804eeddc0SDimitry Andric OutputsReplacedByPHINode.erase(V); 110904eeddc0SDimitry Andric continue; 111004eeddc0SDimitry Andric } 111104eeddc0SDimitry Andric 111204eeddc0SDimitry Andric // This PHINode will be used as an output value, so we add it to our list. 111304eeddc0SDimitry Andric Outputs.insert(&PN); 111404eeddc0SDimitry Andric 111504eeddc0SDimitry Andric // Not all of the incoming values should be ignored as other inputs and 111604eeddc0SDimitry Andric // outputs may have uses in outlined region. If they have other uses 111704eeddc0SDimitry Andric // outside of the single PHINode we should not skip over it. 111804eeddc0SDimitry Andric for (unsigned Idx : IncomingVals) { 111904eeddc0SDimitry Andric Value *V = PN.getIncomingValue(Idx); 112004eeddc0SDimitry Andric if (outputHasNonPHI(V, Idx, PN, PotentialExitsFromRegion, RegionBlocks)) { 112104eeddc0SDimitry Andric OutputsWithNonPhiUses.insert(V); 112204eeddc0SDimitry Andric OutputsReplacedByPHINode.erase(V); 112304eeddc0SDimitry Andric continue; 112404eeddc0SDimitry Andric } 112504eeddc0SDimitry Andric if (!OutputsWithNonPhiUses.contains(V)) 112604eeddc0SDimitry Andric OutputsReplacedByPHINode.insert(V); 112704eeddc0SDimitry Andric } 112804eeddc0SDimitry Andric } 112904eeddc0SDimitry Andric } 113004eeddc0SDimitry Andric 113104eeddc0SDimitry Andric // Represents the type for the unsigned number denoting the output number for 113204eeddc0SDimitry Andric // phi node, along with the canonical number for the exit block. 113304eeddc0SDimitry Andric using ArgLocWithBBCanon = std::pair<unsigned, unsigned>; 113404eeddc0SDimitry Andric // The list of canonical numbers for the incoming values to a PHINode. 113504eeddc0SDimitry Andric using CanonList = SmallVector<unsigned, 2>; 113604eeddc0SDimitry Andric // The pair type representing the set of canonical values being combined in the 113704eeddc0SDimitry Andric // PHINode, along with the location data for the PHINode. 113804eeddc0SDimitry Andric using PHINodeData = std::pair<ArgLocWithBBCanon, CanonList>; 113904eeddc0SDimitry Andric 114004eeddc0SDimitry Andric /// Encode \p PND as an integer for easy lookup based on the argument location, 114104eeddc0SDimitry Andric /// the parent BasicBlock canonical numbering, and the canonical numbering of 114204eeddc0SDimitry Andric /// the values stored in the PHINode. 114304eeddc0SDimitry Andric /// 114404eeddc0SDimitry Andric /// \param PND - The data to hash. 114504eeddc0SDimitry Andric /// \returns The hash code of \p PND. 114604eeddc0SDimitry Andric static hash_code encodePHINodeData(PHINodeData &PND) { 114704eeddc0SDimitry Andric return llvm::hash_combine( 114804eeddc0SDimitry Andric llvm::hash_value(PND.first.first), llvm::hash_value(PND.first.second), 114904eeddc0SDimitry Andric llvm::hash_combine_range(PND.second.begin(), PND.second.end())); 115004eeddc0SDimitry Andric } 115104eeddc0SDimitry Andric 115204eeddc0SDimitry Andric /// Create a special GVN for PHINodes that will be used outside of 115304eeddc0SDimitry Andric /// the region. We create a hash code based on the Canonical number of the 115404eeddc0SDimitry Andric /// parent BasicBlock, the canonical numbering of the values stored in the 115504eeddc0SDimitry Andric /// PHINode and the aggregate argument location. This is used to find whether 115604eeddc0SDimitry Andric /// this PHINode type has been given a canonical numbering already. If not, we 115704eeddc0SDimitry Andric /// assign it a value and store it for later use. The value is returned to 115804eeddc0SDimitry Andric /// identify different output schemes for the set of regions. 115904eeddc0SDimitry Andric /// 116004eeddc0SDimitry Andric /// \param Region - The region that \p PN is an output for. 116104eeddc0SDimitry Andric /// \param PN - The PHINode we are analyzing. 1162*81ad6265SDimitry Andric /// \param Blocks - The blocks for the region we are analyzing. 116304eeddc0SDimitry Andric /// \param AggArgIdx - The argument \p PN will be stored into. 116404eeddc0SDimitry Andric /// \returns An optional holding the assigned canonical number, or None if 116504eeddc0SDimitry Andric /// there is some attribute of the PHINode blocking it from being used. 116604eeddc0SDimitry Andric static Optional<unsigned> getGVNForPHINode(OutlinableRegion &Region, 1167*81ad6265SDimitry Andric PHINode *PN, 1168*81ad6265SDimitry Andric DenseSet<BasicBlock *> &Blocks, 1169*81ad6265SDimitry Andric unsigned AggArgIdx) { 117004eeddc0SDimitry Andric OutlinableGroup &Group = *Region.Parent; 117104eeddc0SDimitry Andric IRSimilarityCandidate &Cand = *Region.Candidate; 117204eeddc0SDimitry Andric BasicBlock *PHIBB = PN->getParent(); 117304eeddc0SDimitry Andric CanonList PHIGVNs; 1174*81ad6265SDimitry Andric Value *Incoming; 1175*81ad6265SDimitry Andric BasicBlock *IncomingBlock; 1176*81ad6265SDimitry Andric for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) { 1177*81ad6265SDimitry Andric Incoming = PN->getIncomingValue(Idx); 1178*81ad6265SDimitry Andric IncomingBlock = PN->getIncomingBlock(Idx); 1179*81ad6265SDimitry Andric // If we cannot find a GVN, and the incoming block is included in the region 1180*81ad6265SDimitry Andric // this means that the input to the PHINode is not included in the region we 1181*81ad6265SDimitry Andric // are trying to analyze, meaning, that if it was outlined, we would be 1182*81ad6265SDimitry Andric // adding an extra input. We ignore this case for now, and so ignore the 1183*81ad6265SDimitry Andric // region. 118404eeddc0SDimitry Andric Optional<unsigned> OGVN = Cand.getGVN(Incoming); 1185*81ad6265SDimitry Andric if (!OGVN && Blocks.contains(IncomingBlock)) { 118604eeddc0SDimitry Andric Region.IgnoreRegion = true; 118704eeddc0SDimitry Andric return None; 118804eeddc0SDimitry Andric } 118904eeddc0SDimitry Andric 1190*81ad6265SDimitry Andric // If the incoming block isn't in the region, we don't have to worry about 1191*81ad6265SDimitry Andric // this incoming value. 1192*81ad6265SDimitry Andric if (!Blocks.contains(IncomingBlock)) 1193*81ad6265SDimitry Andric continue; 1194*81ad6265SDimitry Andric 119504eeddc0SDimitry Andric // Collect the canonical numbers of the values in the PHINode. 1196*81ad6265SDimitry Andric unsigned GVN = *OGVN; 119704eeddc0SDimitry Andric OGVN = Cand.getCanonicalNum(GVN); 1198*81ad6265SDimitry Andric assert(OGVN && "No GVN found for incoming value?"); 1199*81ad6265SDimitry Andric PHIGVNs.push_back(*OGVN); 1200*81ad6265SDimitry Andric 1201*81ad6265SDimitry Andric // Find the incoming block and use the canonical numbering as well to define 1202*81ad6265SDimitry Andric // the hash for the PHINode. 1203*81ad6265SDimitry Andric OGVN = Cand.getGVN(IncomingBlock); 1204*81ad6265SDimitry Andric 1205*81ad6265SDimitry Andric // If there is no number for the incoming block, it is becaause we have 1206*81ad6265SDimitry Andric // split the candidate basic blocks. So we use the previous block that it 1207*81ad6265SDimitry Andric // was split from to find the valid global value numbering for the PHINode. 1208*81ad6265SDimitry Andric if (!OGVN) { 1209*81ad6265SDimitry Andric assert(Cand.getStartBB() == IncomingBlock && 1210*81ad6265SDimitry Andric "Unknown basic block used in exit path PHINode."); 1211*81ad6265SDimitry Andric 1212*81ad6265SDimitry Andric BasicBlock *PrevBlock = nullptr; 1213*81ad6265SDimitry Andric // Iterate over the predecessors to the incoming block of the 1214*81ad6265SDimitry Andric // PHINode, when we find a block that is not contained in the region 1215*81ad6265SDimitry Andric // we know that this is the first block that we split from, and should 1216*81ad6265SDimitry Andric // have a valid global value numbering. 1217*81ad6265SDimitry Andric for (BasicBlock *Pred : predecessors(IncomingBlock)) 1218*81ad6265SDimitry Andric if (!Blocks.contains(Pred)) { 1219*81ad6265SDimitry Andric PrevBlock = Pred; 1220*81ad6265SDimitry Andric break; 1221*81ad6265SDimitry Andric } 1222*81ad6265SDimitry Andric assert(PrevBlock && "Expected a predecessor not in the reigon!"); 1223*81ad6265SDimitry Andric OGVN = Cand.getGVN(PrevBlock); 1224*81ad6265SDimitry Andric } 1225*81ad6265SDimitry Andric GVN = *OGVN; 1226*81ad6265SDimitry Andric OGVN = Cand.getCanonicalNum(GVN); 1227*81ad6265SDimitry Andric assert(OGVN && "No GVN found for incoming block?"); 122804eeddc0SDimitry Andric PHIGVNs.push_back(*OGVN); 122904eeddc0SDimitry Andric } 123004eeddc0SDimitry Andric 123104eeddc0SDimitry Andric // Now that we have the GVNs for the incoming values, we are going to combine 123204eeddc0SDimitry Andric // them with the GVN of the incoming bock, and the output location of the 123304eeddc0SDimitry Andric // PHINode to generate a hash value representing this instance of the PHINode. 123404eeddc0SDimitry Andric DenseMap<hash_code, unsigned>::iterator GVNToPHIIt; 123504eeddc0SDimitry Andric DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt; 123604eeddc0SDimitry Andric Optional<unsigned> BBGVN = Cand.getGVN(PHIBB); 1237*81ad6265SDimitry Andric assert(BBGVN && "Could not find GVN for the incoming block!"); 123804eeddc0SDimitry Andric 123904eeddc0SDimitry Andric BBGVN = Cand.getCanonicalNum(BBGVN.getValue()); 1240*81ad6265SDimitry Andric assert(BBGVN && "Could not find canonical number for the incoming block!"); 124104eeddc0SDimitry Andric // Create a pair of the exit block canonical value, and the aggregate 124204eeddc0SDimitry Andric // argument location, connected to the canonical numbers stored in the 124304eeddc0SDimitry Andric // PHINode. 124404eeddc0SDimitry Andric PHINodeData TemporaryPair = 124504eeddc0SDimitry Andric std::make_pair(std::make_pair(BBGVN.getValue(), AggArgIdx), PHIGVNs); 124604eeddc0SDimitry Andric hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair); 124704eeddc0SDimitry Andric 124804eeddc0SDimitry Andric // Look for and create a new entry in our connection between canonical 124904eeddc0SDimitry Andric // numbers for PHINodes, and the set of objects we just created. 125004eeddc0SDimitry Andric GVNToPHIIt = Group.GVNsToPHINodeGVN.find(PHINodeDataHash); 125104eeddc0SDimitry Andric if (GVNToPHIIt == Group.GVNsToPHINodeGVN.end()) { 125204eeddc0SDimitry Andric bool Inserted = false; 125304eeddc0SDimitry Andric std::tie(PHIToGVNIt, Inserted) = Group.PHINodeGVNToGVNs.insert( 125404eeddc0SDimitry Andric std::make_pair(Group.PHINodeGVNTracker, TemporaryPair)); 125504eeddc0SDimitry Andric std::tie(GVNToPHIIt, Inserted) = Group.GVNsToPHINodeGVN.insert( 125604eeddc0SDimitry Andric std::make_pair(PHINodeDataHash, Group.PHINodeGVNTracker--)); 125704eeddc0SDimitry Andric } 125804eeddc0SDimitry Andric 125904eeddc0SDimitry Andric return GVNToPHIIt->second; 126004eeddc0SDimitry Andric } 126104eeddc0SDimitry Andric 1262e8d8bef9SDimitry Andric /// Create a mapping of the output arguments for the \p Region to the output 1263e8d8bef9SDimitry Andric /// arguments of the overall outlined function. 1264e8d8bef9SDimitry Andric /// 1265e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed. 1266e8d8bef9SDimitry Andric /// \param [in] Outputs - The values found by the code extractor. 1267e8d8bef9SDimitry Andric static void 1268e8d8bef9SDimitry Andric findExtractedOutputToOverallOutputMapping(OutlinableRegion &Region, 1269349cc55cSDimitry Andric SetVector<Value *> &Outputs) { 1270e8d8bef9SDimitry Andric OutlinableGroup &Group = *Region.Parent; 1271e8d8bef9SDimitry Andric IRSimilarityCandidate &C = *Region.Candidate; 1272e8d8bef9SDimitry Andric 1273349cc55cSDimitry Andric SmallVector<BasicBlock *> BE; 127404eeddc0SDimitry Andric DenseSet<BasicBlock *> BlocksInRegion; 127504eeddc0SDimitry Andric C.getBasicBlocks(BlocksInRegion, BE); 1276349cc55cSDimitry Andric 1277349cc55cSDimitry Andric // Find the exits to the region. 1278349cc55cSDimitry Andric SmallPtrSet<BasicBlock *, 1> Exits; 1279349cc55cSDimitry Andric for (BasicBlock *Block : BE) 1280349cc55cSDimitry Andric for (BasicBlock *Succ : successors(Block)) 128104eeddc0SDimitry Andric if (!BlocksInRegion.contains(Succ)) 1282349cc55cSDimitry Andric Exits.insert(Succ); 1283349cc55cSDimitry Andric 1284349cc55cSDimitry Andric // After determining which blocks exit to PHINodes, we add these PHINodes to 1285349cc55cSDimitry Andric // the set of outputs to be processed. We also check the incoming values of 1286349cc55cSDimitry Andric // the PHINodes for whether they should no longer be considered outputs. 128704eeddc0SDimitry Andric DenseSet<Value *> OutputsReplacedByPHINode; 128804eeddc0SDimitry Andric DenseSet<Value *> OutputsWithNonPhiUses; 128904eeddc0SDimitry Andric for (BasicBlock *ExitBB : Exits) 129004eeddc0SDimitry Andric analyzeExitPHIsForOutputUses(ExitBB, Exits, BlocksInRegion, Outputs, 129104eeddc0SDimitry Andric OutputsReplacedByPHINode, 129204eeddc0SDimitry Andric OutputsWithNonPhiUses); 1293349cc55cSDimitry Andric 1294e8d8bef9SDimitry Andric // This counts the argument number in the extracted function. 1295e8d8bef9SDimitry Andric unsigned OriginalIndex = Region.NumExtractedInputs; 1296e8d8bef9SDimitry Andric 1297e8d8bef9SDimitry Andric // This counts the argument number in the overall function. 1298e8d8bef9SDimitry Andric unsigned TypeIndex = Group.NumAggregateInputs; 1299e8d8bef9SDimitry Andric bool TypeFound; 1300e8d8bef9SDimitry Andric DenseSet<unsigned> AggArgsUsed; 1301e8d8bef9SDimitry Andric 1302e8d8bef9SDimitry Andric // Iterate over the output types and identify if there is an aggregate pointer 1303e8d8bef9SDimitry Andric // type whose base type matches the current output type. If there is, we mark 1304e8d8bef9SDimitry Andric // that we will use this output register for this value. If not we add another 1305e8d8bef9SDimitry Andric // type to the overall argument type list. We also store the GVNs used for 1306e8d8bef9SDimitry Andric // stores to identify which values will need to be moved into an special 1307e8d8bef9SDimitry Andric // block that holds the stores to the output registers. 1308e8d8bef9SDimitry Andric for (Value *Output : Outputs) { 1309e8d8bef9SDimitry Andric TypeFound = false; 1310e8d8bef9SDimitry Andric // We can do this since it is a result value, and will have a number 1311e8d8bef9SDimitry Andric // that is necessarily the same. BUT if in the future, the instructions 1312e8d8bef9SDimitry Andric // do not have to be in same order, but are functionally the same, we will 1313e8d8bef9SDimitry Andric // have to use a different scheme, as one-to-one correspondence is not 1314e8d8bef9SDimitry Andric // guaranteed. 1315e8d8bef9SDimitry Andric unsigned ArgumentSize = Group.ArgumentTypes.size(); 1316e8d8bef9SDimitry Andric 131704eeddc0SDimitry Andric // If the output is combined in a PHINode, we make sure to skip over it. 131804eeddc0SDimitry Andric if (OutputsReplacedByPHINode.contains(Output)) 131904eeddc0SDimitry Andric continue; 132004eeddc0SDimitry Andric 132104eeddc0SDimitry Andric unsigned AggArgIdx = 0; 1322e8d8bef9SDimitry Andric for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) { 1323e8d8bef9SDimitry Andric if (Group.ArgumentTypes[Jdx] != PointerType::getUnqual(Output->getType())) 1324e8d8bef9SDimitry Andric continue; 1325e8d8bef9SDimitry Andric 1326e8d8bef9SDimitry Andric if (AggArgsUsed.contains(Jdx)) 1327e8d8bef9SDimitry Andric continue; 1328e8d8bef9SDimitry Andric 1329e8d8bef9SDimitry Andric TypeFound = true; 1330e8d8bef9SDimitry Andric AggArgsUsed.insert(Jdx); 1331e8d8bef9SDimitry Andric Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx)); 1332e8d8bef9SDimitry Andric Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex)); 133304eeddc0SDimitry Andric AggArgIdx = Jdx; 1334e8d8bef9SDimitry Andric break; 1335e8d8bef9SDimitry Andric } 1336e8d8bef9SDimitry Andric 1337e8d8bef9SDimitry Andric // We were unable to find an unused type in the output type set that matches 1338e8d8bef9SDimitry Andric // the output, so we add a pointer type to the argument types of the overall 1339e8d8bef9SDimitry Andric // function to handle this output and create a mapping to it. 1340e8d8bef9SDimitry Andric if (!TypeFound) { 1341e8d8bef9SDimitry Andric Group.ArgumentTypes.push_back(PointerType::getUnqual(Output->getType())); 134204eeddc0SDimitry Andric // Mark the new pointer type as the last value in the aggregate argument 134304eeddc0SDimitry Andric // list. 134404eeddc0SDimitry Andric unsigned ArgTypeIdx = Group.ArgumentTypes.size() - 1; 134504eeddc0SDimitry Andric AggArgsUsed.insert(ArgTypeIdx); 1346e8d8bef9SDimitry Andric Region.ExtractedArgToAgg.insert( 134704eeddc0SDimitry Andric std::make_pair(OriginalIndex, ArgTypeIdx)); 1348e8d8bef9SDimitry Andric Region.AggArgToExtracted.insert( 134904eeddc0SDimitry Andric std::make_pair(ArgTypeIdx, OriginalIndex)); 135004eeddc0SDimitry Andric AggArgIdx = ArgTypeIdx; 1351e8d8bef9SDimitry Andric } 1352e8d8bef9SDimitry Andric 135304eeddc0SDimitry Andric // TODO: Adapt to the extra input from the PHINode. 135404eeddc0SDimitry Andric PHINode *PN = dyn_cast<PHINode>(Output); 135504eeddc0SDimitry Andric 135604eeddc0SDimitry Andric Optional<unsigned> GVN; 135704eeddc0SDimitry Andric if (PN && !BlocksInRegion.contains(PN->getParent())) { 135804eeddc0SDimitry Andric // Values outside the region can be combined into PHINode when we 135904eeddc0SDimitry Andric // have multiple exits. We collect both of these into a list to identify 136004eeddc0SDimitry Andric // which values are being used in the PHINode. Each list identifies a 136104eeddc0SDimitry Andric // different PHINode, and a different output. We store the PHINode as it's 136204eeddc0SDimitry Andric // own canonical value. These canonical values are also dependent on the 136304eeddc0SDimitry Andric // output argument it is saved to. 136404eeddc0SDimitry Andric 136504eeddc0SDimitry Andric // If two PHINodes have the same canonical values, but different aggregate 136604eeddc0SDimitry Andric // argument locations, then they will have distinct Canonical Values. 1367*81ad6265SDimitry Andric GVN = getGVNForPHINode(Region, PN, BlocksInRegion, AggArgIdx); 1368*81ad6265SDimitry Andric if (!GVN) 136904eeddc0SDimitry Andric return; 137004eeddc0SDimitry Andric } else { 137104eeddc0SDimitry Andric // If we do not have a PHINode we use the global value numbering for the 137204eeddc0SDimitry Andric // output value, to find the canonical number to add to the set of stored 137304eeddc0SDimitry Andric // values. 137404eeddc0SDimitry Andric GVN = C.getGVN(Output); 137504eeddc0SDimitry Andric GVN = C.getCanonicalNum(*GVN); 137604eeddc0SDimitry Andric } 137704eeddc0SDimitry Andric 137804eeddc0SDimitry Andric // Each region has a potentially unique set of outputs. We save which 137904eeddc0SDimitry Andric // values are output in a list of canonical values so we can differentiate 138004eeddc0SDimitry Andric // among the different store schemes. 138104eeddc0SDimitry Andric Region.GVNStores.push_back(*GVN); 138204eeddc0SDimitry Andric 1383e8d8bef9SDimitry Andric OriginalIndex++; 1384e8d8bef9SDimitry Andric TypeIndex++; 1385e8d8bef9SDimitry Andric } 138604eeddc0SDimitry Andric 138704eeddc0SDimitry Andric // We sort the stored values to make sure that we are not affected by analysis 138804eeddc0SDimitry Andric // order when determining what combination of items were stored. 138904eeddc0SDimitry Andric stable_sort(Region.GVNStores); 1390e8d8bef9SDimitry Andric } 1391e8d8bef9SDimitry Andric 1392e8d8bef9SDimitry Andric void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region, 1393e8d8bef9SDimitry Andric DenseSet<unsigned> &NotSame) { 1394e8d8bef9SDimitry Andric std::vector<unsigned> Inputs; 1395e8d8bef9SDimitry Andric SetVector<Value *> ArgInputs, Outputs; 1396e8d8bef9SDimitry Andric 1397e8d8bef9SDimitry Andric getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs, 1398e8d8bef9SDimitry Andric Outputs); 1399e8d8bef9SDimitry Andric 1400e8d8bef9SDimitry Andric if (Region.IgnoreRegion) 1401e8d8bef9SDimitry Andric return; 1402e8d8bef9SDimitry Andric 1403e8d8bef9SDimitry Andric // Map the inputs found by the CodeExtractor to the arguments found for 1404e8d8bef9SDimitry Andric // the overall function. 1405e8d8bef9SDimitry Andric findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs); 1406e8d8bef9SDimitry Andric 1407e8d8bef9SDimitry Andric // Map the outputs found by the CodeExtractor to the arguments found for 1408e8d8bef9SDimitry Andric // the overall function. 1409349cc55cSDimitry Andric findExtractedOutputToOverallOutputMapping(Region, Outputs); 1410e8d8bef9SDimitry Andric } 1411e8d8bef9SDimitry Andric 1412e8d8bef9SDimitry Andric /// Replace the extracted function in the Region with a call to the overall 1413e8d8bef9SDimitry Andric /// function constructed from the deduplicated similar regions, replacing and 1414e8d8bef9SDimitry Andric /// remapping the values passed to the extracted function as arguments to the 1415e8d8bef9SDimitry Andric /// new arguments of the overall function. 1416e8d8bef9SDimitry Andric /// 1417e8d8bef9SDimitry Andric /// \param [in] M - The module to outline from. 1418e8d8bef9SDimitry Andric /// \param [in] Region - The regions of extracted code to be replaced with a new 1419e8d8bef9SDimitry Andric /// function. 1420e8d8bef9SDimitry Andric /// \returns a call instruction with the replaced function. 1421e8d8bef9SDimitry Andric CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) { 1422e8d8bef9SDimitry Andric std::vector<Value *> NewCallArgs; 1423e8d8bef9SDimitry Andric DenseMap<unsigned, unsigned>::iterator ArgPair; 1424e8d8bef9SDimitry Andric 1425e8d8bef9SDimitry Andric OutlinableGroup &Group = *Region.Parent; 1426e8d8bef9SDimitry Andric CallInst *Call = Region.Call; 1427e8d8bef9SDimitry Andric assert(Call && "Call to replace is nullptr?"); 1428e8d8bef9SDimitry Andric Function *AggFunc = Group.OutlinedFunction; 1429e8d8bef9SDimitry Andric assert(AggFunc && "Function to replace with is nullptr?"); 1430e8d8bef9SDimitry Andric 1431e8d8bef9SDimitry Andric // If the arguments are the same size, there are not values that need to be 1432349cc55cSDimitry Andric // made into an argument, the argument ordering has not been change, or 1433349cc55cSDimitry Andric // different output registers to handle. We can simply replace the called 1434349cc55cSDimitry Andric // function in this case. 1435349cc55cSDimitry Andric if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) { 1436e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to " 1437e8d8bef9SDimitry Andric << *AggFunc << " with same number of arguments\n"); 1438e8d8bef9SDimitry Andric Call->setCalledFunction(AggFunc); 1439e8d8bef9SDimitry Andric return Call; 1440e8d8bef9SDimitry Andric } 1441e8d8bef9SDimitry Andric 1442e8d8bef9SDimitry Andric // We have a different number of arguments than the new function, so 1443e8d8bef9SDimitry Andric // we need to use our previously mappings off extracted argument to overall 1444e8d8bef9SDimitry Andric // function argument, and constants to overall function argument to create the 1445e8d8bef9SDimitry Andric // new argument list. 1446e8d8bef9SDimitry Andric for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) { 1447e8d8bef9SDimitry Andric 1448e8d8bef9SDimitry Andric if (AggArgIdx == AggFunc->arg_size() - 1 && 1449e8d8bef9SDimitry Andric Group.OutputGVNCombinations.size() > 1) { 1450e8d8bef9SDimitry Andric // If we are on the last argument, and we need to differentiate between 1451e8d8bef9SDimitry Andric // output blocks, add an integer to the argument list to determine 1452e8d8bef9SDimitry Andric // what block to take 1453e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Set switch block argument to " 1454e8d8bef9SDimitry Andric << Region.OutputBlockNum << "\n"); 1455e8d8bef9SDimitry Andric NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()), 1456e8d8bef9SDimitry Andric Region.OutputBlockNum)); 1457e8d8bef9SDimitry Andric continue; 1458e8d8bef9SDimitry Andric } 1459e8d8bef9SDimitry Andric 1460e8d8bef9SDimitry Andric ArgPair = Region.AggArgToExtracted.find(AggArgIdx); 1461e8d8bef9SDimitry Andric if (ArgPair != Region.AggArgToExtracted.end()) { 1462e8d8bef9SDimitry Andric Value *ArgumentValue = Call->getArgOperand(ArgPair->second); 1463e8d8bef9SDimitry Andric // If we found the mapping from the extracted function to the overall 1464e8d8bef9SDimitry Andric // function, we simply add it to the argument list. We use the same 1465e8d8bef9SDimitry Andric // value, it just needs to honor the new order of arguments. 1466e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value " 1467e8d8bef9SDimitry Andric << *ArgumentValue << "\n"); 1468e8d8bef9SDimitry Andric NewCallArgs.push_back(ArgumentValue); 1469e8d8bef9SDimitry Andric continue; 1470e8d8bef9SDimitry Andric } 1471e8d8bef9SDimitry Andric 1472e8d8bef9SDimitry Andric // If it is a constant, we simply add it to the argument list as a value. 1473e8d8bef9SDimitry Andric if (Region.AggArgToConstant.find(AggArgIdx) != 1474e8d8bef9SDimitry Andric Region.AggArgToConstant.end()) { 1475e8d8bef9SDimitry Andric Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second; 1476e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value " 1477e8d8bef9SDimitry Andric << *CST << "\n"); 1478e8d8bef9SDimitry Andric NewCallArgs.push_back(CST); 1479e8d8bef9SDimitry Andric continue; 1480e8d8bef9SDimitry Andric } 1481e8d8bef9SDimitry Andric 1482e8d8bef9SDimitry Andric // Add a nullptr value if the argument is not found in the extracted 1483e8d8bef9SDimitry Andric // function. If we cannot find a value, it means it is not in use 1484e8d8bef9SDimitry Andric // for the region, so we should not pass anything to it. 1485e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n"); 1486e8d8bef9SDimitry Andric NewCallArgs.push_back(ConstantPointerNull::get( 1487e8d8bef9SDimitry Andric static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType()))); 1488e8d8bef9SDimitry Andric } 1489e8d8bef9SDimitry Andric 1490e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to " 1491e8d8bef9SDimitry Andric << *AggFunc << " with new set of arguments\n"); 1492e8d8bef9SDimitry Andric // Create the new call instruction and erase the old one. 1493e8d8bef9SDimitry Andric Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "", 1494e8d8bef9SDimitry Andric Call); 1495e8d8bef9SDimitry Andric 1496e8d8bef9SDimitry Andric // It is possible that the call to the outlined function is either the first 1497e8d8bef9SDimitry Andric // instruction is in the new block, the last instruction, or both. If either 1498e8d8bef9SDimitry Andric // of these is the case, we need to make sure that we replace the instruction 1499e8d8bef9SDimitry Andric // in the IRInstructionData struct with the new call. 1500e8d8bef9SDimitry Andric CallInst *OldCall = Region.Call; 1501e8d8bef9SDimitry Andric if (Region.NewFront->Inst == OldCall) 1502e8d8bef9SDimitry Andric Region.NewFront->Inst = Call; 1503e8d8bef9SDimitry Andric if (Region.NewBack->Inst == OldCall) 1504e8d8bef9SDimitry Andric Region.NewBack->Inst = Call; 1505e8d8bef9SDimitry Andric 1506e8d8bef9SDimitry Andric // Transfer any debug information. 1507e8d8bef9SDimitry Andric Call->setDebugLoc(Region.Call->getDebugLoc()); 1508349cc55cSDimitry Andric // Since our output may determine which branch we go to, we make sure to 1509349cc55cSDimitry Andric // propogate this new call value through the module. 1510349cc55cSDimitry Andric OldCall->replaceAllUsesWith(Call); 1511e8d8bef9SDimitry Andric 1512e8d8bef9SDimitry Andric // Remove the old instruction. 1513e8d8bef9SDimitry Andric OldCall->eraseFromParent(); 1514e8d8bef9SDimitry Andric Region.Call = Call; 1515e8d8bef9SDimitry Andric 1516e8d8bef9SDimitry Andric // Make sure that the argument in the new function has the SwiftError 1517e8d8bef9SDimitry Andric // argument. 1518*81ad6265SDimitry Andric if (Group.SwiftErrorArgument) 1519e8d8bef9SDimitry Andric Call->addParamAttr(Group.SwiftErrorArgument.getValue(), 1520e8d8bef9SDimitry Andric Attribute::SwiftError); 1521e8d8bef9SDimitry Andric 1522e8d8bef9SDimitry Andric return Call; 1523e8d8bef9SDimitry Andric } 1524e8d8bef9SDimitry Andric 152504eeddc0SDimitry Andric /// Find or create a BasicBlock in the outlined function containing PhiBlocks 152604eeddc0SDimitry Andric /// for \p RetVal. 152704eeddc0SDimitry Andric /// 152804eeddc0SDimitry Andric /// \param Group - The OutlinableGroup containing the information about the 152904eeddc0SDimitry Andric /// overall outlined function. 153004eeddc0SDimitry Andric /// \param RetVal - The return value or exit option that we are currently 153104eeddc0SDimitry Andric /// evaluating. 153204eeddc0SDimitry Andric /// \returns The found or newly created BasicBlock to contain the needed 153304eeddc0SDimitry Andric /// PHINodes to be used as outputs. 153404eeddc0SDimitry Andric static BasicBlock *findOrCreatePHIBlock(OutlinableGroup &Group, Value *RetVal) { 153504eeddc0SDimitry Andric DenseMap<Value *, BasicBlock *>::iterator PhiBlockForRetVal, 153604eeddc0SDimitry Andric ReturnBlockForRetVal; 153704eeddc0SDimitry Andric PhiBlockForRetVal = Group.PHIBlocks.find(RetVal); 153804eeddc0SDimitry Andric ReturnBlockForRetVal = Group.EndBBs.find(RetVal); 153904eeddc0SDimitry Andric assert(ReturnBlockForRetVal != Group.EndBBs.end() && 154004eeddc0SDimitry Andric "Could not find output value!"); 154104eeddc0SDimitry Andric BasicBlock *ReturnBB = ReturnBlockForRetVal->second; 154204eeddc0SDimitry Andric 154304eeddc0SDimitry Andric // Find if a PHIBlock exists for this return value already. If it is 154404eeddc0SDimitry Andric // the first time we are analyzing this, we will not, so we record it. 154504eeddc0SDimitry Andric PhiBlockForRetVal = Group.PHIBlocks.find(RetVal); 154604eeddc0SDimitry Andric if (PhiBlockForRetVal != Group.PHIBlocks.end()) 154704eeddc0SDimitry Andric return PhiBlockForRetVal->second; 154804eeddc0SDimitry Andric 154904eeddc0SDimitry Andric // If we did not find a block, we create one, and insert it into the 155004eeddc0SDimitry Andric // overall function and record it. 155104eeddc0SDimitry Andric bool Inserted = false; 155204eeddc0SDimitry Andric BasicBlock *PHIBlock = BasicBlock::Create(ReturnBB->getContext(), "phi_block", 155304eeddc0SDimitry Andric ReturnBB->getParent()); 155404eeddc0SDimitry Andric std::tie(PhiBlockForRetVal, Inserted) = 155504eeddc0SDimitry Andric Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock)); 155604eeddc0SDimitry Andric 155704eeddc0SDimitry Andric // We find the predecessors of the return block in the newly created outlined 155804eeddc0SDimitry Andric // function in order to point them to the new PHIBlock rather than the already 155904eeddc0SDimitry Andric // existing return block. 156004eeddc0SDimitry Andric SmallVector<BranchInst *, 2> BranchesToChange; 156104eeddc0SDimitry Andric for (BasicBlock *Pred : predecessors(ReturnBB)) 156204eeddc0SDimitry Andric BranchesToChange.push_back(cast<BranchInst>(Pred->getTerminator())); 156304eeddc0SDimitry Andric 156404eeddc0SDimitry Andric // Now we mark the branch instructions found, and change the references of the 156504eeddc0SDimitry Andric // return block to the newly created PHIBlock. 156604eeddc0SDimitry Andric for (BranchInst *BI : BranchesToChange) 156704eeddc0SDimitry Andric for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ < End; Succ++) { 156804eeddc0SDimitry Andric if (BI->getSuccessor(Succ) != ReturnBB) 156904eeddc0SDimitry Andric continue; 157004eeddc0SDimitry Andric BI->setSuccessor(Succ, PHIBlock); 157104eeddc0SDimitry Andric } 157204eeddc0SDimitry Andric 157304eeddc0SDimitry Andric BranchInst::Create(ReturnBB, PHIBlock); 157404eeddc0SDimitry Andric 157504eeddc0SDimitry Andric return PhiBlockForRetVal->second; 157604eeddc0SDimitry Andric } 157704eeddc0SDimitry Andric 157804eeddc0SDimitry Andric /// For the function call now representing the \p Region, find the passed value 157904eeddc0SDimitry Andric /// to that call that represents Argument \p A at the call location if the 158004eeddc0SDimitry Andric /// call has already been replaced with a call to the overall, aggregate 158104eeddc0SDimitry Andric /// function. 158204eeddc0SDimitry Andric /// 158304eeddc0SDimitry Andric /// \param A - The Argument to get the passed value for. 158404eeddc0SDimitry Andric /// \param Region - The extracted Region corresponding to the outlined function. 158504eeddc0SDimitry Andric /// \returns The Value representing \p A at the call site. 158604eeddc0SDimitry Andric static Value * 158704eeddc0SDimitry Andric getPassedArgumentInAlreadyOutlinedFunction(const Argument *A, 158804eeddc0SDimitry Andric const OutlinableRegion &Region) { 158904eeddc0SDimitry Andric // If we don't need to adjust the argument number at all (since the call 159004eeddc0SDimitry Andric // has already been replaced by a call to the overall outlined function) 159104eeddc0SDimitry Andric // we can just get the specified argument. 159204eeddc0SDimitry Andric return Region.Call->getArgOperand(A->getArgNo()); 159304eeddc0SDimitry Andric } 159404eeddc0SDimitry Andric 159504eeddc0SDimitry Andric /// For the function call now representing the \p Region, find the passed value 159604eeddc0SDimitry Andric /// to that call that represents Argument \p A at the call location if the 159704eeddc0SDimitry Andric /// call has only been replaced by the call to the aggregate function. 159804eeddc0SDimitry Andric /// 159904eeddc0SDimitry Andric /// \param A - The Argument to get the passed value for. 160004eeddc0SDimitry Andric /// \param Region - The extracted Region corresponding to the outlined function. 160104eeddc0SDimitry Andric /// \returns The Value representing \p A at the call site. 160204eeddc0SDimitry Andric static Value * 160304eeddc0SDimitry Andric getPassedArgumentAndAdjustArgumentLocation(const Argument *A, 160404eeddc0SDimitry Andric const OutlinableRegion &Region) { 160504eeddc0SDimitry Andric unsigned ArgNum = A->getArgNo(); 160604eeddc0SDimitry Andric 160704eeddc0SDimitry Andric // If it is a constant, we can look at our mapping from when we created 160804eeddc0SDimitry Andric // the outputs to figure out what the constant value is. 160904eeddc0SDimitry Andric if (Region.AggArgToConstant.count(ArgNum)) 161004eeddc0SDimitry Andric return Region.AggArgToConstant.find(ArgNum)->second; 161104eeddc0SDimitry Andric 161204eeddc0SDimitry Andric // If it is not a constant, and we are not looking at the overall function, we 161304eeddc0SDimitry Andric // need to adjust which argument we are looking at. 161404eeddc0SDimitry Andric ArgNum = Region.AggArgToExtracted.find(ArgNum)->second; 161504eeddc0SDimitry Andric return Region.Call->getArgOperand(ArgNum); 161604eeddc0SDimitry Andric } 161704eeddc0SDimitry Andric 161804eeddc0SDimitry Andric /// Find the canonical numbering for the incoming Values into the PHINode \p PN. 161904eeddc0SDimitry Andric /// 162004eeddc0SDimitry Andric /// \param PN [in] - The PHINode that we are finding the canonical numbers for. 162104eeddc0SDimitry Andric /// \param Region [in] - The OutlinableRegion containing \p PN. 162204eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of output values from outlined 162304eeddc0SDimitry Andric /// region to their original values. 162404eeddc0SDimitry Andric /// \param CanonNums [out] - The canonical numbering for the incoming values to 1625*81ad6265SDimitry Andric /// \p PN paired with their incoming block. 162604eeddc0SDimitry Andric /// \param ReplacedWithOutlinedCall - A flag to use the extracted function call 162704eeddc0SDimitry Andric /// of \p Region rather than the overall function's call. 1628*81ad6265SDimitry Andric static void findCanonNumsForPHI( 1629*81ad6265SDimitry Andric PHINode *PN, OutlinableRegion &Region, 163004eeddc0SDimitry Andric const DenseMap<Value *, Value *> &OutputMappings, 1631*81ad6265SDimitry Andric SmallVector<std::pair<unsigned, BasicBlock *>> &CanonNums, 163204eeddc0SDimitry Andric bool ReplacedWithOutlinedCall = true) { 163304eeddc0SDimitry Andric // Iterate over the incoming values. 163404eeddc0SDimitry Andric for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) { 163504eeddc0SDimitry Andric Value *IVal = PN->getIncomingValue(Idx); 1636*81ad6265SDimitry Andric BasicBlock *IBlock = PN->getIncomingBlock(Idx); 163704eeddc0SDimitry Andric // If we have an argument as incoming value, we need to grab the passed 163804eeddc0SDimitry Andric // value from the call itself. 163904eeddc0SDimitry Andric if (Argument *A = dyn_cast<Argument>(IVal)) { 164004eeddc0SDimitry Andric if (ReplacedWithOutlinedCall) 164104eeddc0SDimitry Andric IVal = getPassedArgumentInAlreadyOutlinedFunction(A, Region); 164204eeddc0SDimitry Andric else 164304eeddc0SDimitry Andric IVal = getPassedArgumentAndAdjustArgumentLocation(A, Region); 164404eeddc0SDimitry Andric } 164504eeddc0SDimitry Andric 164604eeddc0SDimitry Andric // Get the original value if it has been replaced by an output value. 164704eeddc0SDimitry Andric IVal = findOutputMapping(OutputMappings, IVal); 164804eeddc0SDimitry Andric 164904eeddc0SDimitry Andric // Find and add the canonical number for the incoming value. 165004eeddc0SDimitry Andric Optional<unsigned> GVN = Region.Candidate->getGVN(IVal); 1651*81ad6265SDimitry Andric assert(GVN && "No GVN for incoming value"); 165204eeddc0SDimitry Andric Optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN); 1653*81ad6265SDimitry Andric assert(CanonNum && "No Canonical Number for GVN"); 1654*81ad6265SDimitry Andric CanonNums.push_back(std::make_pair(*CanonNum, IBlock)); 165504eeddc0SDimitry Andric } 165604eeddc0SDimitry Andric } 165704eeddc0SDimitry Andric 165804eeddc0SDimitry Andric /// Find, or add PHINode \p PN to the combined PHINode Block \p OverallPHIBlock 165904eeddc0SDimitry Andric /// in order to condense the number of instructions added to the outlined 166004eeddc0SDimitry Andric /// function. 166104eeddc0SDimitry Andric /// 166204eeddc0SDimitry Andric /// \param PN [in] - The PHINode that we are finding the canonical numbers for. 166304eeddc0SDimitry Andric /// \param Region [in] - The OutlinableRegion containing \p PN. 166404eeddc0SDimitry Andric /// \param OverallPhiBlock [in] - The overall PHIBlock we are trying to find 166504eeddc0SDimitry Andric /// \p PN in. 166604eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of output values from outlined 166704eeddc0SDimitry Andric /// region to their original values. 1668*81ad6265SDimitry Andric /// \param UsedPHIs [in, out] - The PHINodes in the block that have already been 1669*81ad6265SDimitry Andric /// matched. 167004eeddc0SDimitry Andric /// \return the newly found or created PHINode in \p OverallPhiBlock. 167104eeddc0SDimitry Andric static PHINode* 167204eeddc0SDimitry Andric findOrCreatePHIInBlock(PHINode &PN, OutlinableRegion &Region, 167304eeddc0SDimitry Andric BasicBlock *OverallPhiBlock, 1674*81ad6265SDimitry Andric const DenseMap<Value *, Value *> &OutputMappings, 1675*81ad6265SDimitry Andric DenseSet<PHINode *> &UsedPHIs) { 167604eeddc0SDimitry Andric OutlinableGroup &Group = *Region.Parent; 167704eeddc0SDimitry Andric 1678*81ad6265SDimitry Andric 1679*81ad6265SDimitry Andric // A list of the canonical numbering assigned to each incoming value, paired 1680*81ad6265SDimitry Andric // with the incoming block for the PHINode passed into this function. 1681*81ad6265SDimitry Andric SmallVector<std::pair<unsigned, BasicBlock *>> PNCanonNums; 1682*81ad6265SDimitry Andric 168304eeddc0SDimitry Andric // We have to use the extracted function since we have merged this region into 168404eeddc0SDimitry Andric // the overall function yet. We make sure to reassign the argument numbering 168504eeddc0SDimitry Andric // since it is possible that the argument ordering is different between the 168604eeddc0SDimitry Andric // functions. 168704eeddc0SDimitry Andric findCanonNumsForPHI(&PN, Region, OutputMappings, PNCanonNums, 168804eeddc0SDimitry Andric /* ReplacedWithOutlinedCall = */ false); 168904eeddc0SDimitry Andric 169004eeddc0SDimitry Andric OutlinableRegion *FirstRegion = Group.Regions[0]; 1691*81ad6265SDimitry Andric 1692*81ad6265SDimitry Andric // A list of the canonical numbering assigned to each incoming value, paired 1693*81ad6265SDimitry Andric // with the incoming block for the PHINode that we are currently comparing 1694*81ad6265SDimitry Andric // the passed PHINode to. 1695*81ad6265SDimitry Andric SmallVector<std::pair<unsigned, BasicBlock *>> CurrentCanonNums; 1696*81ad6265SDimitry Andric 169704eeddc0SDimitry Andric // Find the Canonical Numbering for each PHINode, if it matches, we replace 169804eeddc0SDimitry Andric // the uses of the PHINode we are searching for, with the found PHINode. 169904eeddc0SDimitry Andric for (PHINode &CurrPN : OverallPhiBlock->phis()) { 1700*81ad6265SDimitry Andric // If this PHINode has already been matched to another PHINode to be merged, 1701*81ad6265SDimitry Andric // we skip it. 1702*81ad6265SDimitry Andric if (UsedPHIs.contains(&CurrPN)) 1703*81ad6265SDimitry Andric continue; 1704*81ad6265SDimitry Andric 170504eeddc0SDimitry Andric CurrentCanonNums.clear(); 170604eeddc0SDimitry Andric findCanonNumsForPHI(&CurrPN, *FirstRegion, OutputMappings, CurrentCanonNums, 170704eeddc0SDimitry Andric /* ReplacedWithOutlinedCall = */ true); 170804eeddc0SDimitry Andric 1709*81ad6265SDimitry Andric // If the list of incoming values is not the same length, then they cannot 1710*81ad6265SDimitry Andric // match since there is not an analogue for each incoming value. 1711*81ad6265SDimitry Andric if (PNCanonNums.size() != CurrentCanonNums.size()) 1712*81ad6265SDimitry Andric continue; 1713*81ad6265SDimitry Andric 1714*81ad6265SDimitry Andric bool FoundMatch = true; 1715*81ad6265SDimitry Andric 1716*81ad6265SDimitry Andric // We compare the canonical value for each incoming value in the passed 1717*81ad6265SDimitry Andric // in PHINode to one already present in the outlined region. If the 1718*81ad6265SDimitry Andric // incoming values do not match, then the PHINodes do not match. 1719*81ad6265SDimitry Andric 1720*81ad6265SDimitry Andric // We also check to make sure that the incoming block matches as well by 1721*81ad6265SDimitry Andric // finding the corresponding incoming block in the combined outlined region 1722*81ad6265SDimitry Andric // for the current outlined region. 1723*81ad6265SDimitry Andric for (unsigned Idx = 0, Edx = PNCanonNums.size(); Idx < Edx; ++Idx) { 1724*81ad6265SDimitry Andric std::pair<unsigned, BasicBlock *> ToCompareTo = CurrentCanonNums[Idx]; 1725*81ad6265SDimitry Andric std::pair<unsigned, BasicBlock *> ToAdd = PNCanonNums[Idx]; 1726*81ad6265SDimitry Andric if (ToCompareTo.first != ToAdd.first) { 1727*81ad6265SDimitry Andric FoundMatch = false; 1728*81ad6265SDimitry Andric break; 1729*81ad6265SDimitry Andric } 1730*81ad6265SDimitry Andric 1731*81ad6265SDimitry Andric BasicBlock *CorrespondingBlock = 1732*81ad6265SDimitry Andric Region.findCorrespondingBlockIn(*FirstRegion, ToAdd.second); 1733*81ad6265SDimitry Andric assert(CorrespondingBlock && "Found block is nullptr"); 1734*81ad6265SDimitry Andric if (CorrespondingBlock != ToCompareTo.second) { 1735*81ad6265SDimitry Andric FoundMatch = false; 1736*81ad6265SDimitry Andric break; 1737*81ad6265SDimitry Andric } 1738*81ad6265SDimitry Andric } 1739*81ad6265SDimitry Andric 1740*81ad6265SDimitry Andric // If all incoming values and branches matched, then we can merge 1741*81ad6265SDimitry Andric // into the found PHINode. 1742*81ad6265SDimitry Andric if (FoundMatch) { 1743*81ad6265SDimitry Andric UsedPHIs.insert(&CurrPN); 174404eeddc0SDimitry Andric return &CurrPN; 174504eeddc0SDimitry Andric } 1746*81ad6265SDimitry Andric } 174704eeddc0SDimitry Andric 174804eeddc0SDimitry Andric // If we've made it here, it means we weren't able to replace the PHINode, so 174904eeddc0SDimitry Andric // we must insert it ourselves. 175004eeddc0SDimitry Andric PHINode *NewPN = cast<PHINode>(PN.clone()); 175104eeddc0SDimitry Andric NewPN->insertBefore(&*OverallPhiBlock->begin()); 175204eeddc0SDimitry Andric for (unsigned Idx = 0, Edx = NewPN->getNumIncomingValues(); Idx < Edx; 175304eeddc0SDimitry Andric Idx++) { 175404eeddc0SDimitry Andric Value *IncomingVal = NewPN->getIncomingValue(Idx); 175504eeddc0SDimitry Andric BasicBlock *IncomingBlock = NewPN->getIncomingBlock(Idx); 175604eeddc0SDimitry Andric 175704eeddc0SDimitry Andric // Find corresponding basic block in the overall function for the incoming 175804eeddc0SDimitry Andric // block. 1759*81ad6265SDimitry Andric BasicBlock *BlockToUse = 1760*81ad6265SDimitry Andric Region.findCorrespondingBlockIn(*FirstRegion, IncomingBlock); 176104eeddc0SDimitry Andric NewPN->setIncomingBlock(Idx, BlockToUse); 176204eeddc0SDimitry Andric 176304eeddc0SDimitry Andric // If we have an argument we make sure we replace using the argument from 176404eeddc0SDimitry Andric // the correct function. 176504eeddc0SDimitry Andric if (Argument *A = dyn_cast<Argument>(IncomingVal)) { 176604eeddc0SDimitry Andric Value *Val = Group.OutlinedFunction->getArg(A->getArgNo()); 176704eeddc0SDimitry Andric NewPN->setIncomingValue(Idx, Val); 176804eeddc0SDimitry Andric continue; 176904eeddc0SDimitry Andric } 177004eeddc0SDimitry Andric 177104eeddc0SDimitry Andric // Find the corresponding value in the overall function. 177204eeddc0SDimitry Andric IncomingVal = findOutputMapping(OutputMappings, IncomingVal); 177304eeddc0SDimitry Andric Value *Val = Region.findCorrespondingValueIn(*FirstRegion, IncomingVal); 177404eeddc0SDimitry Andric assert(Val && "Value is nullptr?"); 1775*81ad6265SDimitry Andric DenseMap<Value *, Value *>::iterator RemappedIt = 1776*81ad6265SDimitry Andric FirstRegion->RemappedArguments.find(Val); 1777*81ad6265SDimitry Andric if (RemappedIt != FirstRegion->RemappedArguments.end()) 1778*81ad6265SDimitry Andric Val = RemappedIt->second; 177904eeddc0SDimitry Andric NewPN->setIncomingValue(Idx, Val); 178004eeddc0SDimitry Andric } 178104eeddc0SDimitry Andric return NewPN; 178204eeddc0SDimitry Andric } 178304eeddc0SDimitry Andric 1784e8d8bef9SDimitry Andric // Within an extracted function, replace the argument uses of the extracted 1785e8d8bef9SDimitry Andric // region with the arguments of the function for an OutlinableGroup. 1786e8d8bef9SDimitry Andric // 1787e8d8bef9SDimitry Andric /// \param [in] Region - The region of extracted code to be changed. 1788349cc55cSDimitry Andric /// \param [in,out] OutputBBs - The BasicBlock for the output stores for this 1789e8d8bef9SDimitry Andric /// region. 1790349cc55cSDimitry Andric /// \param [in] FirstFunction - A flag to indicate whether we are using this 1791349cc55cSDimitry Andric /// function to define the overall outlined function for all the regions, or 1792349cc55cSDimitry Andric /// if we are operating on one of the following regions. 1793349cc55cSDimitry Andric static void 1794349cc55cSDimitry Andric replaceArgumentUses(OutlinableRegion &Region, 1795349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> &OutputBBs, 179604eeddc0SDimitry Andric const DenseMap<Value *, Value *> &OutputMappings, 1797349cc55cSDimitry Andric bool FirstFunction = false) { 1798e8d8bef9SDimitry Andric OutlinableGroup &Group = *Region.Parent; 1799e8d8bef9SDimitry Andric assert(Region.ExtractedFunction && "Region has no extracted function?"); 1800e8d8bef9SDimitry Andric 1801349cc55cSDimitry Andric Function *DominatingFunction = Region.ExtractedFunction; 1802349cc55cSDimitry Andric if (FirstFunction) 1803349cc55cSDimitry Andric DominatingFunction = Group.OutlinedFunction; 1804349cc55cSDimitry Andric DominatorTree DT(*DominatingFunction); 1805*81ad6265SDimitry Andric DenseSet<PHINode *> UsedPHIs; 1806349cc55cSDimitry Andric 1807e8d8bef9SDimitry Andric for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size(); 1808e8d8bef9SDimitry Andric ArgIdx++) { 1809e8d8bef9SDimitry Andric assert(Region.ExtractedArgToAgg.find(ArgIdx) != 1810e8d8bef9SDimitry Andric Region.ExtractedArgToAgg.end() && 1811e8d8bef9SDimitry Andric "No mapping from extracted to outlined?"); 1812e8d8bef9SDimitry Andric unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second; 1813e8d8bef9SDimitry Andric Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx); 1814e8d8bef9SDimitry Andric Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx); 1815e8d8bef9SDimitry Andric // The argument is an input, so we can simply replace it with the overall 1816e8d8bef9SDimitry Andric // argument value 1817e8d8bef9SDimitry Andric if (ArgIdx < Region.NumExtractedInputs) { 1818e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function " 1819e8d8bef9SDimitry Andric << *Region.ExtractedFunction << " with " << *AggArg 1820e8d8bef9SDimitry Andric << " in function " << *Group.OutlinedFunction << "\n"); 1821e8d8bef9SDimitry Andric Arg->replaceAllUsesWith(AggArg); 1822*81ad6265SDimitry Andric Value *V = Region.Call->getArgOperand(ArgIdx); 1823*81ad6265SDimitry Andric Region.RemappedArguments.insert(std::make_pair(V, AggArg)); 1824e8d8bef9SDimitry Andric continue; 1825e8d8bef9SDimitry Andric } 1826e8d8bef9SDimitry Andric 1827e8d8bef9SDimitry Andric // If we are replacing an output, we place the store value in its own 1828e8d8bef9SDimitry Andric // block inside the overall function before replacing the use of the output 1829e8d8bef9SDimitry Andric // in the function. 1830e8d8bef9SDimitry Andric assert(Arg->hasOneUse() && "Output argument can only have one use"); 1831e8d8bef9SDimitry Andric User *InstAsUser = Arg->user_back(); 1832e8d8bef9SDimitry Andric assert(InstAsUser && "User is nullptr!"); 1833e8d8bef9SDimitry Andric 1834e8d8bef9SDimitry Andric Instruction *I = cast<Instruction>(InstAsUser); 1835349cc55cSDimitry Andric BasicBlock *BB = I->getParent(); 1836349cc55cSDimitry Andric SmallVector<BasicBlock *, 4> Descendants; 1837349cc55cSDimitry Andric DT.getDescendants(BB, Descendants); 1838349cc55cSDimitry Andric bool EdgeAdded = false; 1839349cc55cSDimitry Andric if (Descendants.size() == 0) { 1840349cc55cSDimitry Andric EdgeAdded = true; 1841349cc55cSDimitry Andric DT.insertEdge(&DominatingFunction->getEntryBlock(), BB); 1842349cc55cSDimitry Andric DT.getDescendants(BB, Descendants); 1843349cc55cSDimitry Andric } 1844349cc55cSDimitry Andric 1845349cc55cSDimitry Andric // Iterate over the following blocks, looking for return instructions, 1846349cc55cSDimitry Andric // if we find one, find the corresponding output block for the return value 1847349cc55cSDimitry Andric // and move our store instruction there. 1848349cc55cSDimitry Andric for (BasicBlock *DescendBB : Descendants) { 1849349cc55cSDimitry Andric ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator()); 1850349cc55cSDimitry Andric if (!RI) 1851349cc55cSDimitry Andric continue; 1852349cc55cSDimitry Andric Value *RetVal = RI->getReturnValue(); 1853349cc55cSDimitry Andric auto VBBIt = OutputBBs.find(RetVal); 1854349cc55cSDimitry Andric assert(VBBIt != OutputBBs.end() && "Could not find output value!"); 1855349cc55cSDimitry Andric 1856349cc55cSDimitry Andric // If this is storing a PHINode, we must make sure it is included in the 1857349cc55cSDimitry Andric // overall function. 1858349cc55cSDimitry Andric StoreInst *SI = cast<StoreInst>(I); 1859349cc55cSDimitry Andric 1860349cc55cSDimitry Andric Value *ValueOperand = SI->getValueOperand(); 1861349cc55cSDimitry Andric 1862349cc55cSDimitry Andric StoreInst *NewI = cast<StoreInst>(I->clone()); 1863349cc55cSDimitry Andric NewI->setDebugLoc(DebugLoc()); 1864349cc55cSDimitry Andric BasicBlock *OutputBB = VBBIt->second; 1865349cc55cSDimitry Andric OutputBB->getInstList().push_back(NewI); 1866e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to " 1867e8d8bef9SDimitry Andric << *OutputBB << "\n"); 1868e8d8bef9SDimitry Andric 186904eeddc0SDimitry Andric // If this is storing a PHINode, we must make sure it is included in the 187004eeddc0SDimitry Andric // overall function. 187104eeddc0SDimitry Andric if (!isa<PHINode>(ValueOperand) || 1872*81ad6265SDimitry Andric Region.Candidate->getGVN(ValueOperand).has_value()) { 1873349cc55cSDimitry Andric if (FirstFunction) 1874349cc55cSDimitry Andric continue; 1875349cc55cSDimitry Andric Value *CorrVal = 1876349cc55cSDimitry Andric Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand); 1877349cc55cSDimitry Andric assert(CorrVal && "Value is nullptr?"); 1878349cc55cSDimitry Andric NewI->setOperand(0, CorrVal); 187904eeddc0SDimitry Andric continue; 188004eeddc0SDimitry Andric } 188104eeddc0SDimitry Andric PHINode *PN = cast<PHINode>(SI->getValueOperand()); 188204eeddc0SDimitry Andric // If it has a value, it was not split by the code extractor, which 188304eeddc0SDimitry Andric // is what we are looking for. 1884*81ad6265SDimitry Andric if (Region.Candidate->getGVN(PN)) 188504eeddc0SDimitry Andric continue; 188604eeddc0SDimitry Andric 188704eeddc0SDimitry Andric // We record the parent block for the PHINode in the Region so that 188804eeddc0SDimitry Andric // we can exclude it from checks later on. 188904eeddc0SDimitry Andric Region.PHIBlocks.insert(std::make_pair(RetVal, PN->getParent())); 189004eeddc0SDimitry Andric 189104eeddc0SDimitry Andric // If this is the first function, we do not need to worry about mergiing 189204eeddc0SDimitry Andric // this with any other block in the overall outlined function, so we can 189304eeddc0SDimitry Andric // just continue. 189404eeddc0SDimitry Andric if (FirstFunction) { 189504eeddc0SDimitry Andric BasicBlock *PHIBlock = PN->getParent(); 189604eeddc0SDimitry Andric Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock)); 189704eeddc0SDimitry Andric continue; 189804eeddc0SDimitry Andric } 189904eeddc0SDimitry Andric 190004eeddc0SDimitry Andric // We look for the aggregate block that contains the PHINodes leading into 190104eeddc0SDimitry Andric // this exit path. If we can't find one, we create one. 190204eeddc0SDimitry Andric BasicBlock *OverallPhiBlock = findOrCreatePHIBlock(Group, RetVal); 190304eeddc0SDimitry Andric 190404eeddc0SDimitry Andric // For our PHINode, we find the combined canonical numbering, and 190504eeddc0SDimitry Andric // attempt to find a matching PHINode in the overall PHIBlock. If we 190604eeddc0SDimitry Andric // cannot, we copy the PHINode and move it into this new block. 1907*81ad6265SDimitry Andric PHINode *NewPN = findOrCreatePHIInBlock(*PN, Region, OverallPhiBlock, 1908*81ad6265SDimitry Andric OutputMappings, UsedPHIs); 190904eeddc0SDimitry Andric NewI->setOperand(0, NewPN); 1910349cc55cSDimitry Andric } 1911349cc55cSDimitry Andric 1912349cc55cSDimitry Andric // If we added an edge for basic blocks without a predecessor, we remove it 1913349cc55cSDimitry Andric // here. 1914349cc55cSDimitry Andric if (EdgeAdded) 1915349cc55cSDimitry Andric DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB); 1916349cc55cSDimitry Andric I->eraseFromParent(); 1917e8d8bef9SDimitry Andric 1918e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function " 1919e8d8bef9SDimitry Andric << *Region.ExtractedFunction << " with " << *AggArg 1920e8d8bef9SDimitry Andric << " in function " << *Group.OutlinedFunction << "\n"); 1921e8d8bef9SDimitry Andric Arg->replaceAllUsesWith(AggArg); 1922e8d8bef9SDimitry Andric } 1923e8d8bef9SDimitry Andric } 1924e8d8bef9SDimitry Andric 1925e8d8bef9SDimitry Andric /// Within an extracted function, replace the constants that need to be lifted 1926e8d8bef9SDimitry Andric /// into arguments with the actual argument. 1927e8d8bef9SDimitry Andric /// 1928e8d8bef9SDimitry Andric /// \param Region [in] - The region of extracted code to be changed. 1929e8d8bef9SDimitry Andric void replaceConstants(OutlinableRegion &Region) { 1930e8d8bef9SDimitry Andric OutlinableGroup &Group = *Region.Parent; 1931e8d8bef9SDimitry Andric // Iterate over the constants that need to be elevated into arguments 1932e8d8bef9SDimitry Andric for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) { 1933e8d8bef9SDimitry Andric unsigned AggArgIdx = Const.first; 1934e8d8bef9SDimitry Andric Function *OutlinedFunction = Group.OutlinedFunction; 1935e8d8bef9SDimitry Andric assert(OutlinedFunction && "Overall Function is not defined?"); 1936e8d8bef9SDimitry Andric Constant *CST = Const.second; 1937e8d8bef9SDimitry Andric Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx); 1938e8d8bef9SDimitry Andric // Identify the argument it will be elevated to, and replace instances of 1939e8d8bef9SDimitry Andric // that constant in the function. 1940e8d8bef9SDimitry Andric 1941e8d8bef9SDimitry Andric // TODO: If in the future constants do not have one global value number, 1942e8d8bef9SDimitry Andric // i.e. a constant 1 could be mapped to several values, this check will 1943e8d8bef9SDimitry Andric // have to be more strict. It cannot be using only replaceUsesWithIf. 1944e8d8bef9SDimitry Andric 1945e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST 1946e8d8bef9SDimitry Andric << " in function " << *OutlinedFunction << " with " 1947e8d8bef9SDimitry Andric << *Arg << "\n"); 1948e8d8bef9SDimitry Andric CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) { 1949e8d8bef9SDimitry Andric if (Instruction *I = dyn_cast<Instruction>(U.getUser())) 1950e8d8bef9SDimitry Andric return I->getFunction() == OutlinedFunction; 1951e8d8bef9SDimitry Andric return false; 1952e8d8bef9SDimitry Andric }); 1953e8d8bef9SDimitry Andric } 1954e8d8bef9SDimitry Andric } 1955e8d8bef9SDimitry Andric 1956e8d8bef9SDimitry Andric /// It is possible that there is a basic block that already performs the same 1957e8d8bef9SDimitry Andric /// stores. This returns a duplicate block, if it exists 1958e8d8bef9SDimitry Andric /// 1959349cc55cSDimitry Andric /// \param OutputBBs [in] the blocks we are looking for a duplicate of. 1960e8d8bef9SDimitry Andric /// \param OutputStoreBBs [in] The existing output blocks. 1961e8d8bef9SDimitry Andric /// \returns an optional value with the number output block if there is a match. 1962349cc55cSDimitry Andric Optional<unsigned> findDuplicateOutputBlock( 1963349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> &OutputBBs, 1964349cc55cSDimitry Andric std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) { 1965e8d8bef9SDimitry Andric 1966349cc55cSDimitry Andric bool Mismatch = false; 1967e8d8bef9SDimitry Andric unsigned MatchingNum = 0; 1968349cc55cSDimitry Andric // We compare the new set output blocks to the other sets of output blocks. 1969349cc55cSDimitry Andric // If they are the same number, and have identical instructions, they are 1970349cc55cSDimitry Andric // considered to be the same. 1971349cc55cSDimitry Andric for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) { 1972349cc55cSDimitry Andric Mismatch = false; 1973349cc55cSDimitry Andric for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) { 1974349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *>::iterator OutputBBIt = 1975349cc55cSDimitry Andric OutputBBs.find(VToB.first); 1976349cc55cSDimitry Andric if (OutputBBIt == OutputBBs.end()) { 1977349cc55cSDimitry Andric Mismatch = true; 1978349cc55cSDimitry Andric break; 1979e8d8bef9SDimitry Andric } 1980e8d8bef9SDimitry Andric 1981349cc55cSDimitry Andric BasicBlock *CompBB = VToB.second; 1982349cc55cSDimitry Andric BasicBlock *OutputBB = OutputBBIt->second; 1983349cc55cSDimitry Andric if (CompBB->size() - 1 != OutputBB->size()) { 1984349cc55cSDimitry Andric Mismatch = true; 1985349cc55cSDimitry Andric break; 1986349cc55cSDimitry Andric } 1987349cc55cSDimitry Andric 1988e8d8bef9SDimitry Andric BasicBlock::iterator NIt = OutputBB->begin(); 1989e8d8bef9SDimitry Andric for (Instruction &I : *CompBB) { 1990e8d8bef9SDimitry Andric if (isa<BranchInst>(&I)) 1991e8d8bef9SDimitry Andric continue; 1992e8d8bef9SDimitry Andric 1993e8d8bef9SDimitry Andric if (!I.isIdenticalTo(&(*NIt))) { 1994349cc55cSDimitry Andric Mismatch = true; 1995e8d8bef9SDimitry Andric break; 1996e8d8bef9SDimitry Andric } 1997e8d8bef9SDimitry Andric 1998e8d8bef9SDimitry Andric NIt++; 1999e8d8bef9SDimitry Andric } 2000349cc55cSDimitry Andric } 2001349cc55cSDimitry Andric 2002349cc55cSDimitry Andric if (!Mismatch) 2003e8d8bef9SDimitry Andric return MatchingNum; 2004e8d8bef9SDimitry Andric 2005e8d8bef9SDimitry Andric MatchingNum++; 2006e8d8bef9SDimitry Andric } 2007e8d8bef9SDimitry Andric 2008e8d8bef9SDimitry Andric return None; 2009e8d8bef9SDimitry Andric } 2010e8d8bef9SDimitry Andric 2011349cc55cSDimitry Andric /// Remove empty output blocks from the outlined region. 2012349cc55cSDimitry Andric /// 2013349cc55cSDimitry Andric /// \param BlocksToPrune - Mapping of return values output blocks for the \p 2014349cc55cSDimitry Andric /// Region. 2015349cc55cSDimitry Andric /// \param Region - The OutlinableRegion we are analyzing. 2016349cc55cSDimitry Andric static bool 2017349cc55cSDimitry Andric analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune, 2018349cc55cSDimitry Andric OutlinableRegion &Region) { 2019349cc55cSDimitry Andric bool AllRemoved = true; 2020349cc55cSDimitry Andric Value *RetValueForBB; 2021349cc55cSDimitry Andric BasicBlock *NewBB; 2022349cc55cSDimitry Andric SmallVector<Value *, 4> ToRemove; 2023349cc55cSDimitry Andric // Iterate over the output blocks created in the outlined section. 2024349cc55cSDimitry Andric for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) { 2025349cc55cSDimitry Andric RetValueForBB = VtoBB.first; 2026349cc55cSDimitry Andric NewBB = VtoBB.second; 2027349cc55cSDimitry Andric 2028349cc55cSDimitry Andric // If there are no instructions, we remove it from the module, and also 2029349cc55cSDimitry Andric // mark the value for removal from the return value to output block mapping. 2030349cc55cSDimitry Andric if (NewBB->size() == 0) { 2031349cc55cSDimitry Andric NewBB->eraseFromParent(); 2032349cc55cSDimitry Andric ToRemove.push_back(RetValueForBB); 2033349cc55cSDimitry Andric continue; 2034349cc55cSDimitry Andric } 2035349cc55cSDimitry Andric 2036349cc55cSDimitry Andric // Mark that we could not remove all the blocks since they were not all 2037349cc55cSDimitry Andric // empty. 2038349cc55cSDimitry Andric AllRemoved = false; 2039349cc55cSDimitry Andric } 2040349cc55cSDimitry Andric 2041349cc55cSDimitry Andric // Remove the return value from the mapping. 2042349cc55cSDimitry Andric for (Value *V : ToRemove) 2043349cc55cSDimitry Andric BlocksToPrune.erase(V); 2044349cc55cSDimitry Andric 2045349cc55cSDimitry Andric // Mark the region as having the no output scheme. 2046349cc55cSDimitry Andric if (AllRemoved) 2047349cc55cSDimitry Andric Region.OutputBlockNum = -1; 2048349cc55cSDimitry Andric 2049349cc55cSDimitry Andric return AllRemoved; 2050349cc55cSDimitry Andric } 2051349cc55cSDimitry Andric 2052e8d8bef9SDimitry Andric /// For the outlined section, move needed the StoreInsts for the output 2053e8d8bef9SDimitry Andric /// registers into their own block. Then, determine if there is a duplicate 2054e8d8bef9SDimitry Andric /// output block already created. 2055e8d8bef9SDimitry Andric /// 2056e8d8bef9SDimitry Andric /// \param [in] OG - The OutlinableGroup of regions to be outlined. 2057e8d8bef9SDimitry Andric /// \param [in] Region - The OutlinableRegion that is being analyzed. 2058349cc55cSDimitry Andric /// \param [in,out] OutputBBs - the blocks that stores for this region will be 2059e8d8bef9SDimitry Andric /// placed in. 2060349cc55cSDimitry Andric /// \param [in] EndBBs - the final blocks of the extracted function. 2061e8d8bef9SDimitry Andric /// \param [in] OutputMappings - OutputMappings the mapping of values that have 2062e8d8bef9SDimitry Andric /// been replaced by a new output value. 2063e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The existing output blocks. 2064349cc55cSDimitry Andric static void alignOutputBlockWithAggFunc( 2065349cc55cSDimitry Andric OutlinableGroup &OG, OutlinableRegion &Region, 2066349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> &OutputBBs, 2067349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> &EndBBs, 2068e8d8bef9SDimitry Andric const DenseMap<Value *, Value *> &OutputMappings, 2069349cc55cSDimitry Andric std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) { 2070349cc55cSDimitry Andric // If none of the output blocks have any instructions, this means that we do 2071349cc55cSDimitry Andric // not have to determine if it matches any of the other output schemes, and we 2072349cc55cSDimitry Andric // don't have to do anything else. 2073349cc55cSDimitry Andric if (analyzeAndPruneOutputBlocks(OutputBBs, Region)) 2074e8d8bef9SDimitry Andric return; 2075e8d8bef9SDimitry Andric 2076349cc55cSDimitry Andric // Determine is there is a duplicate set of blocks. 2077e8d8bef9SDimitry Andric Optional<unsigned> MatchingBB = 2078349cc55cSDimitry Andric findDuplicateOutputBlock(OutputBBs, OutputStoreBBs); 2079e8d8bef9SDimitry Andric 2080349cc55cSDimitry Andric // If there is, we remove the new output blocks. If it does not, 2081349cc55cSDimitry Andric // we add it to our list of sets of output blocks. 2082*81ad6265SDimitry Andric if (MatchingBB) { 2083e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Set output block for region in function" 2084e8d8bef9SDimitry Andric << Region.ExtractedFunction << " to " 2085e8d8bef9SDimitry Andric << MatchingBB.getValue()); 2086e8d8bef9SDimitry Andric 2087e8d8bef9SDimitry Andric Region.OutputBlockNum = MatchingBB.getValue(); 2088349cc55cSDimitry Andric for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) 2089349cc55cSDimitry Andric VtoBB.second->eraseFromParent(); 2090e8d8bef9SDimitry Andric return; 2091e8d8bef9SDimitry Andric } 2092e8d8bef9SDimitry Andric 2093e8d8bef9SDimitry Andric Region.OutputBlockNum = OutputStoreBBs.size(); 2094e8d8bef9SDimitry Andric 2095349cc55cSDimitry Andric Value *RetValueForBB; 2096349cc55cSDimitry Andric BasicBlock *NewBB; 2097349cc55cSDimitry Andric OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>()); 2098349cc55cSDimitry Andric for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) { 2099349cc55cSDimitry Andric RetValueForBB = VtoBB.first; 2100349cc55cSDimitry Andric NewBB = VtoBB.second; 2101349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *>::iterator VBBIt = 2102349cc55cSDimitry Andric EndBBs.find(RetValueForBB); 2103e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Create output block for region in" 2104e8d8bef9SDimitry Andric << Region.ExtractedFunction << " to " 2105349cc55cSDimitry Andric << *NewBB); 2106349cc55cSDimitry Andric BranchInst::Create(VBBIt->second, NewBB); 2107349cc55cSDimitry Andric OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB)); 2108349cc55cSDimitry Andric } 2109349cc55cSDimitry Andric } 2110349cc55cSDimitry Andric 2111349cc55cSDimitry Andric /// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys, 2112349cc55cSDimitry Andric /// before creating a basic block for each \p NewMap, and inserting into the new 2113349cc55cSDimitry Andric /// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>". 2114349cc55cSDimitry Andric /// 2115349cc55cSDimitry Andric /// \param OldMap [in] - The mapping to base the new mapping off of. 2116349cc55cSDimitry Andric /// \param NewMap [out] - The output mapping using the keys of \p OldMap. 2117349cc55cSDimitry Andric /// \param ParentFunc [in] - The function to put the new basic block in. 2118349cc55cSDimitry Andric /// \param BaseName [in] - The start of the BasicBlock names to be appended to 2119349cc55cSDimitry Andric /// by an index value. 2120349cc55cSDimitry Andric static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap, 2121349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> &NewMap, 2122349cc55cSDimitry Andric Function *ParentFunc, Twine BaseName) { 2123349cc55cSDimitry Andric unsigned Idx = 0; 2124349cc55cSDimitry Andric std::vector<Value *> SortedKeys; 2125349cc55cSDimitry Andric 2126349cc55cSDimitry Andric getSortedConstantKeys(SortedKeys, OldMap); 2127349cc55cSDimitry Andric 2128349cc55cSDimitry Andric for (Value *RetVal : SortedKeys) { 2129349cc55cSDimitry Andric BasicBlock *NewBB = BasicBlock::Create( 2130349cc55cSDimitry Andric ParentFunc->getContext(), 2131349cc55cSDimitry Andric Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)), 2132349cc55cSDimitry Andric ParentFunc); 2133349cc55cSDimitry Andric NewMap.insert(std::make_pair(RetVal, NewBB)); 2134349cc55cSDimitry Andric } 2135e8d8bef9SDimitry Andric } 2136e8d8bef9SDimitry Andric 2137e8d8bef9SDimitry Andric /// Create the switch statement for outlined function to differentiate between 2138e8d8bef9SDimitry Andric /// all the output blocks. 2139e8d8bef9SDimitry Andric /// 2140e8d8bef9SDimitry Andric /// For the outlined section, determine if an outlined block already exists that 2141e8d8bef9SDimitry Andric /// matches the needed stores for the extracted section. 2142e8d8bef9SDimitry Andric /// \param [in] M - The module we are outlining from. 2143e8d8bef9SDimitry Andric /// \param [in] OG - The group of regions to be outlined. 2144349cc55cSDimitry Andric /// \param [in] EndBBs - The final blocks of the extracted function. 2145e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The existing output blocks. 2146349cc55cSDimitry Andric void createSwitchStatement( 2147349cc55cSDimitry Andric Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs, 2148349cc55cSDimitry Andric std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) { 2149e8d8bef9SDimitry Andric // We only need the switch statement if there is more than one store 215004eeddc0SDimitry Andric // combination, or there is more than one set of output blocks. The first 215104eeddc0SDimitry Andric // will occur when we store different sets of values for two different 215204eeddc0SDimitry Andric // regions. The second will occur when we have two outputs that are combined 215304eeddc0SDimitry Andric // in a PHINode outside of the region in one outlined instance, and are used 215404eeddc0SDimitry Andric // seaparately in another. This will create the same set of OutputGVNs, but 215504eeddc0SDimitry Andric // will generate two different output schemes. 2156e8d8bef9SDimitry Andric if (OG.OutputGVNCombinations.size() > 1) { 2157e8d8bef9SDimitry Andric Function *AggFunc = OG.OutlinedFunction; 2158349cc55cSDimitry Andric // Create a final block for each different return block. 2159349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> ReturnBBs; 2160349cc55cSDimitry Andric createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block"); 2161349cc55cSDimitry Andric 2162349cc55cSDimitry Andric for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) { 2163349cc55cSDimitry Andric std::pair<Value *, BasicBlock *> &OutputBlock = 2164349cc55cSDimitry Andric *OG.EndBBs.find(RetBlockPair.first); 2165349cc55cSDimitry Andric BasicBlock *ReturnBlock = RetBlockPair.second; 2166349cc55cSDimitry Andric BasicBlock *EndBB = OutputBlock.second; 2167e8d8bef9SDimitry Andric Instruction *Term = EndBB->getTerminator(); 2168349cc55cSDimitry Andric // Move the return value to the final block instead of the original exit 2169349cc55cSDimitry Andric // stub. 2170e8d8bef9SDimitry Andric Term->moveBefore(*ReturnBlock, ReturnBlock->end()); 2171349cc55cSDimitry Andric // Put the switch statement in the old end basic block for the function 2172349cc55cSDimitry Andric // with a fall through to the new return block. 2173e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for " 2174e8d8bef9SDimitry Andric << OutputStoreBBs.size() << "\n"); 2175e8d8bef9SDimitry Andric SwitchInst *SwitchI = 2176e8d8bef9SDimitry Andric SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1), 2177e8d8bef9SDimitry Andric ReturnBlock, OutputStoreBBs.size(), EndBB); 2178e8d8bef9SDimitry Andric 2179e8d8bef9SDimitry Andric unsigned Idx = 0; 2180349cc55cSDimitry Andric for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) { 2181349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *>::iterator OSBBIt = 2182349cc55cSDimitry Andric OutputStoreBB.find(OutputBlock.first); 2183349cc55cSDimitry Andric 2184349cc55cSDimitry Andric if (OSBBIt == OutputStoreBB.end()) 2185349cc55cSDimitry Andric continue; 2186349cc55cSDimitry Andric 2187349cc55cSDimitry Andric BasicBlock *BB = OSBBIt->second; 2188349cc55cSDimitry Andric SwitchI->addCase( 2189349cc55cSDimitry Andric ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB); 2190e8d8bef9SDimitry Andric Term = BB->getTerminator(); 2191e8d8bef9SDimitry Andric Term->setSuccessor(0, ReturnBlock); 2192e8d8bef9SDimitry Andric Idx++; 2193e8d8bef9SDimitry Andric } 2194349cc55cSDimitry Andric } 2195e8d8bef9SDimitry Andric return; 2196e8d8bef9SDimitry Andric } 2197e8d8bef9SDimitry Andric 219804eeddc0SDimitry Andric assert(OutputStoreBBs.size() < 2 && "Different store sets not handled!"); 219904eeddc0SDimitry Andric 2200349cc55cSDimitry Andric // If there needs to be stores, move them from the output blocks to their 220104eeddc0SDimitry Andric // corresponding ending block. We do not check that the OutputGVNCombinations 220204eeddc0SDimitry Andric // is equal to 1 here since that could just been the case where there are 0 220304eeddc0SDimitry Andric // outputs. Instead, we check whether there is more than one set of output 220404eeddc0SDimitry Andric // blocks since this is the only case where we would have to move the 220504eeddc0SDimitry Andric // stores, and erase the extraneous blocks. 2206e8d8bef9SDimitry Andric if (OutputStoreBBs.size() == 1) { 2207e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Move store instructions to the end block in " 2208e8d8bef9SDimitry Andric << *OG.OutlinedFunction << "\n"); 2209349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0]; 2210349cc55cSDimitry Andric for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) { 2211349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *>::iterator EndBBIt = 2212349cc55cSDimitry Andric EndBBs.find(VBPair.first); 2213349cc55cSDimitry Andric assert(EndBBIt != EndBBs.end() && "Could not find end block"); 2214349cc55cSDimitry Andric BasicBlock *EndBB = EndBBIt->second; 2215349cc55cSDimitry Andric BasicBlock *OutputBB = VBPair.second; 2216349cc55cSDimitry Andric Instruction *Term = OutputBB->getTerminator(); 2217e8d8bef9SDimitry Andric Term->eraseFromParent(); 2218e8d8bef9SDimitry Andric Term = EndBB->getTerminator(); 2219349cc55cSDimitry Andric moveBBContents(*OutputBB, *EndBB); 2220e8d8bef9SDimitry Andric Term->moveBefore(*EndBB, EndBB->end()); 2221349cc55cSDimitry Andric OutputBB->eraseFromParent(); 2222349cc55cSDimitry Andric } 2223e8d8bef9SDimitry Andric } 2224e8d8bef9SDimitry Andric } 2225e8d8bef9SDimitry Andric 2226e8d8bef9SDimitry Andric /// Fill the new function that will serve as the replacement function for all of 2227e8d8bef9SDimitry Andric /// the extracted regions of a certain structure from the first region in the 2228e8d8bef9SDimitry Andric /// list of regions. Replace this first region's extracted function with the 2229e8d8bef9SDimitry Andric /// new overall function. 2230e8d8bef9SDimitry Andric /// 2231e8d8bef9SDimitry Andric /// \param [in] M - The module we are outlining from. 2232e8d8bef9SDimitry Andric /// \param [in] CurrentGroup - The group of regions to be outlined. 2233e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The output blocks for each different 2234e8d8bef9SDimitry Andric /// set of stores needed for the different functions. 2235e8d8bef9SDimitry Andric /// \param [in,out] FuncsToRemove - Extracted functions to erase from module 2236e8d8bef9SDimitry Andric /// once outlining is complete. 223704eeddc0SDimitry Andric /// \param [in] OutputMappings - Extracted functions to erase from module 223804eeddc0SDimitry Andric /// once outlining is complete. 2239349cc55cSDimitry Andric static void fillOverallFunction( 2240349cc55cSDimitry Andric Module &M, OutlinableGroup &CurrentGroup, 2241349cc55cSDimitry Andric std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs, 224204eeddc0SDimitry Andric std::vector<Function *> &FuncsToRemove, 224304eeddc0SDimitry Andric const DenseMap<Value *, Value *> &OutputMappings) { 2244e8d8bef9SDimitry Andric OutlinableRegion *CurrentOS = CurrentGroup.Regions[0]; 2245e8d8bef9SDimitry Andric 2246e8d8bef9SDimitry Andric // Move first extracted function's instructions into new function. 2247e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Move instructions from " 2248e8d8bef9SDimitry Andric << *CurrentOS->ExtractedFunction << " to instruction " 2249e8d8bef9SDimitry Andric << *CurrentGroup.OutlinedFunction << "\n"); 2250349cc55cSDimitry Andric moveFunctionData(*CurrentOS->ExtractedFunction, 2251349cc55cSDimitry Andric *CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs); 2252e8d8bef9SDimitry Andric 2253e8d8bef9SDimitry Andric // Transfer the attributes from the function to the new function. 2254349cc55cSDimitry Andric for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs()) 2255e8d8bef9SDimitry Andric CurrentGroup.OutlinedFunction->addFnAttr(A); 2256e8d8bef9SDimitry Andric 2257349cc55cSDimitry Andric // Create a new set of output blocks for the first extracted function. 2258349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> NewBBs; 2259349cc55cSDimitry Andric createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs, 2260349cc55cSDimitry Andric CurrentGroup.OutlinedFunction, "output_block_0"); 2261e8d8bef9SDimitry Andric CurrentOS->OutputBlockNum = 0; 2262e8d8bef9SDimitry Andric 226304eeddc0SDimitry Andric replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings, true); 2264e8d8bef9SDimitry Andric replaceConstants(*CurrentOS); 2265e8d8bef9SDimitry Andric 2266349cc55cSDimitry Andric // We first identify if any output blocks are empty, if they are we remove 2267349cc55cSDimitry Andric // them. We then create a branch instruction to the basic block to the return 2268349cc55cSDimitry Andric // block for the function for each non empty output block. 2269349cc55cSDimitry Andric if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) { 2270349cc55cSDimitry Andric OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>()); 2271349cc55cSDimitry Andric for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) { 2272349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *>::iterator VBBIt = 2273349cc55cSDimitry Andric CurrentGroup.EndBBs.find(VToBB.first); 2274349cc55cSDimitry Andric BasicBlock *EndBB = VBBIt->second; 2275349cc55cSDimitry Andric BranchInst::Create(EndBB, VToBB.second); 2276349cc55cSDimitry Andric OutputStoreBBs.back().insert(VToBB); 2277349cc55cSDimitry Andric } 2278e8d8bef9SDimitry Andric } 2279e8d8bef9SDimitry Andric 2280e8d8bef9SDimitry Andric // Replace the call to the extracted function with the outlined function. 2281e8d8bef9SDimitry Andric CurrentOS->Call = replaceCalledFunction(M, *CurrentOS); 2282e8d8bef9SDimitry Andric 2283e8d8bef9SDimitry Andric // We only delete the extracted functions at the end since we may need to 2284e8d8bef9SDimitry Andric // reference instructions contained in them for mapping purposes. 2285e8d8bef9SDimitry Andric FuncsToRemove.push_back(CurrentOS->ExtractedFunction); 2286e8d8bef9SDimitry Andric } 2287e8d8bef9SDimitry Andric 2288e8d8bef9SDimitry Andric void IROutliner::deduplicateExtractedSections( 2289e8d8bef9SDimitry Andric Module &M, OutlinableGroup &CurrentGroup, 2290e8d8bef9SDimitry Andric std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) { 2291e8d8bef9SDimitry Andric createFunction(M, CurrentGroup, OutlinedFunctionNum); 2292e8d8bef9SDimitry Andric 2293349cc55cSDimitry Andric std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs; 2294e8d8bef9SDimitry Andric 2295e8d8bef9SDimitry Andric OutlinableRegion *CurrentOS; 2296e8d8bef9SDimitry Andric 229704eeddc0SDimitry Andric fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove, 229804eeddc0SDimitry Andric OutputMappings); 2299e8d8bef9SDimitry Andric 2300349cc55cSDimitry Andric std::vector<Value *> SortedKeys; 2301e8d8bef9SDimitry Andric for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) { 2302e8d8bef9SDimitry Andric CurrentOS = CurrentGroup.Regions[Idx]; 2303e8d8bef9SDimitry Andric AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction, 2304e8d8bef9SDimitry Andric *CurrentOS->ExtractedFunction); 2305e8d8bef9SDimitry Andric 2306349cc55cSDimitry Andric // Create a set of BasicBlocks, one for each return block, to hold the 2307349cc55cSDimitry Andric // needed store instructions. 2308349cc55cSDimitry Andric DenseMap<Value *, BasicBlock *> NewBBs; 2309349cc55cSDimitry Andric createAndInsertBasicBlocks( 2310349cc55cSDimitry Andric CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction, 2311349cc55cSDimitry Andric "output_block_" + Twine(static_cast<unsigned>(Idx))); 231204eeddc0SDimitry Andric replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings); 2313349cc55cSDimitry Andric alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs, 2314349cc55cSDimitry Andric CurrentGroup.EndBBs, OutputMappings, 2315e8d8bef9SDimitry Andric OutputStoreBBs); 2316e8d8bef9SDimitry Andric 2317e8d8bef9SDimitry Andric CurrentOS->Call = replaceCalledFunction(M, *CurrentOS); 2318e8d8bef9SDimitry Andric FuncsToRemove.push_back(CurrentOS->ExtractedFunction); 2319e8d8bef9SDimitry Andric } 2320e8d8bef9SDimitry Andric 2321e8d8bef9SDimitry Andric // Create a switch statement to handle the different output schemes. 2322349cc55cSDimitry Andric createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs); 2323e8d8bef9SDimitry Andric 2324e8d8bef9SDimitry Andric OutlinedFunctionNum++; 2325e8d8bef9SDimitry Andric } 2326e8d8bef9SDimitry Andric 2327349cc55cSDimitry Andric /// Checks that the next instruction in the InstructionDataList matches the 2328349cc55cSDimitry Andric /// next instruction in the module. If they do not, there could be the 2329349cc55cSDimitry Andric /// possibility that extra code has been inserted, and we must ignore it. 2330349cc55cSDimitry Andric /// 2331349cc55cSDimitry Andric /// \param ID - The IRInstructionData to check the next instruction of. 2332349cc55cSDimitry Andric /// \returns true if the InstructionDataList and actual instruction match. 2333349cc55cSDimitry Andric static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) { 2334349cc55cSDimitry Andric // We check if there is a discrepancy between the InstructionDataList 2335349cc55cSDimitry Andric // and the actual next instruction in the module. If there is, it means 2336349cc55cSDimitry Andric // that an extra instruction was added, likely by the CodeExtractor. 2337349cc55cSDimitry Andric 2338349cc55cSDimitry Andric // Since we do not have any similarity data about this particular 2339349cc55cSDimitry Andric // instruction, we cannot confidently outline it, and must discard this 2340349cc55cSDimitry Andric // candidate. 2341349cc55cSDimitry Andric IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator()); 2342349cc55cSDimitry Andric Instruction *NextIDLInst = NextIDIt->Inst; 2343349cc55cSDimitry Andric Instruction *NextModuleInst = nullptr; 2344349cc55cSDimitry Andric if (!ID.Inst->isTerminator()) 2345349cc55cSDimitry Andric NextModuleInst = ID.Inst->getNextNonDebugInstruction(); 2346349cc55cSDimitry Andric else if (NextIDLInst != nullptr) 2347349cc55cSDimitry Andric NextModuleInst = 2348349cc55cSDimitry Andric &*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin(); 2349349cc55cSDimitry Andric 2350349cc55cSDimitry Andric if (NextIDLInst && NextIDLInst != NextModuleInst) 2351349cc55cSDimitry Andric return false; 2352349cc55cSDimitry Andric 2353349cc55cSDimitry Andric return true; 2354349cc55cSDimitry Andric } 2355349cc55cSDimitry Andric 2356349cc55cSDimitry Andric bool IROutliner::isCompatibleWithAlreadyOutlinedCode( 2357349cc55cSDimitry Andric const OutlinableRegion &Region) { 2358349cc55cSDimitry Andric IRSimilarityCandidate *IRSC = Region.Candidate; 2359349cc55cSDimitry Andric unsigned StartIdx = IRSC->getStartIdx(); 2360349cc55cSDimitry Andric unsigned EndIdx = IRSC->getEndIdx(); 2361349cc55cSDimitry Andric 2362349cc55cSDimitry Andric // A check to make sure that we are not about to attempt to outline something 2363349cc55cSDimitry Andric // that has already been outlined. 2364349cc55cSDimitry Andric for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++) 2365349cc55cSDimitry Andric if (Outlined.contains(Idx)) 2366349cc55cSDimitry Andric return false; 2367349cc55cSDimitry Andric 2368349cc55cSDimitry Andric // We check if the recorded instruction matches the actual next instruction, 2369349cc55cSDimitry Andric // if it does not, we fix it in the InstructionDataList. 2370349cc55cSDimitry Andric if (!Region.Candidate->backInstruction()->isTerminator()) { 2371349cc55cSDimitry Andric Instruction *NewEndInst = 2372349cc55cSDimitry Andric Region.Candidate->backInstruction()->getNextNonDebugInstruction(); 2373349cc55cSDimitry Andric assert(NewEndInst && "Next instruction is a nullptr?"); 2374349cc55cSDimitry Andric if (Region.Candidate->end()->Inst != NewEndInst) { 2375349cc55cSDimitry Andric IRInstructionDataList *IDL = Region.Candidate->front()->IDL; 2376349cc55cSDimitry Andric IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate()) 2377349cc55cSDimitry Andric IRInstructionData(*NewEndInst, 2378349cc55cSDimitry Andric InstructionClassifier.visit(*NewEndInst), *IDL); 2379349cc55cSDimitry Andric 2380349cc55cSDimitry Andric // Insert the first IRInstructionData of the new region after the 2381349cc55cSDimitry Andric // last IRInstructionData of the IRSimilarityCandidate. 2382349cc55cSDimitry Andric IDL->insert(Region.Candidate->end(), *NewEndIRID); 2383349cc55cSDimitry Andric } 2384349cc55cSDimitry Andric } 2385349cc55cSDimitry Andric 2386349cc55cSDimitry Andric return none_of(*IRSC, [this](IRInstructionData &ID) { 2387349cc55cSDimitry Andric if (!nextIRInstructionDataMatchesNextInst(ID)) 2388349cc55cSDimitry Andric return true; 2389349cc55cSDimitry Andric 2390349cc55cSDimitry Andric return !this->InstructionClassifier.visit(ID.Inst); 2391349cc55cSDimitry Andric }); 2392349cc55cSDimitry Andric } 2393349cc55cSDimitry Andric 2394e8d8bef9SDimitry Andric void IROutliner::pruneIncompatibleRegions( 2395e8d8bef9SDimitry Andric std::vector<IRSimilarityCandidate> &CandidateVec, 2396e8d8bef9SDimitry Andric OutlinableGroup &CurrentGroup) { 2397e8d8bef9SDimitry Andric bool PreviouslyOutlined; 2398e8d8bef9SDimitry Andric 2399e8d8bef9SDimitry Andric // Sort from beginning to end, so the IRSimilarityCandidates are in order. 2400e8d8bef9SDimitry Andric stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS, 2401e8d8bef9SDimitry Andric const IRSimilarityCandidate &RHS) { 2402e8d8bef9SDimitry Andric return LHS.getStartIdx() < RHS.getStartIdx(); 2403e8d8bef9SDimitry Andric }); 2404e8d8bef9SDimitry Andric 2405349cc55cSDimitry Andric IRSimilarityCandidate &FirstCandidate = CandidateVec[0]; 2406349cc55cSDimitry Andric // Since outlining a call and a branch instruction will be the same as only 2407349cc55cSDimitry Andric // outlinining a call instruction, we ignore it as a space saving. 2408349cc55cSDimitry Andric if (FirstCandidate.getLength() == 2) { 2409349cc55cSDimitry Andric if (isa<CallInst>(FirstCandidate.front()->Inst) && 2410349cc55cSDimitry Andric isa<BranchInst>(FirstCandidate.back()->Inst)) 2411349cc55cSDimitry Andric return; 2412349cc55cSDimitry Andric } 2413349cc55cSDimitry Andric 2414e8d8bef9SDimitry Andric unsigned CurrentEndIdx = 0; 2415e8d8bef9SDimitry Andric for (IRSimilarityCandidate &IRSC : CandidateVec) { 2416e8d8bef9SDimitry Andric PreviouslyOutlined = false; 2417e8d8bef9SDimitry Andric unsigned StartIdx = IRSC.getStartIdx(); 2418e8d8bef9SDimitry Andric unsigned EndIdx = IRSC.getEndIdx(); 2419e8d8bef9SDimitry Andric 2420e8d8bef9SDimitry Andric for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++) 2421e8d8bef9SDimitry Andric if (Outlined.contains(Idx)) { 2422e8d8bef9SDimitry Andric PreviouslyOutlined = true; 2423e8d8bef9SDimitry Andric break; 2424e8d8bef9SDimitry Andric } 2425e8d8bef9SDimitry Andric 2426e8d8bef9SDimitry Andric if (PreviouslyOutlined) 2427e8d8bef9SDimitry Andric continue; 2428e8d8bef9SDimitry Andric 2429349cc55cSDimitry Andric // Check over the instructions, and if the basic block has its address 2430349cc55cSDimitry Andric // taken for use somewhere else, we do not outline that block. 2431349cc55cSDimitry Andric bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){ 2432349cc55cSDimitry Andric return ID.Inst->getParent()->hasAddressTaken(); 2433349cc55cSDimitry Andric }); 2434349cc55cSDimitry Andric 2435349cc55cSDimitry Andric if (BBHasAddressTaken) 2436e8d8bef9SDimitry Andric continue; 2437e8d8bef9SDimitry Andric 2438*81ad6265SDimitry Andric if (IRSC.getFunction()->hasOptNone()) 2439*81ad6265SDimitry Andric continue; 2440*81ad6265SDimitry Andric 2441e8d8bef9SDimitry Andric if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() && 2442e8d8bef9SDimitry Andric !OutlineFromLinkODRs) 2443e8d8bef9SDimitry Andric continue; 2444e8d8bef9SDimitry Andric 2445e8d8bef9SDimitry Andric // Greedily prune out any regions that will overlap with already chosen 2446e8d8bef9SDimitry Andric // regions. 2447e8d8bef9SDimitry Andric if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx) 2448e8d8bef9SDimitry Andric continue; 2449e8d8bef9SDimitry Andric 2450e8d8bef9SDimitry Andric bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) { 2451349cc55cSDimitry Andric if (!nextIRInstructionDataMatchesNextInst(ID)) 2452e8d8bef9SDimitry Andric return true; 2453349cc55cSDimitry Andric 2454e8d8bef9SDimitry Andric return !this->InstructionClassifier.visit(ID.Inst); 2455e8d8bef9SDimitry Andric }); 2456e8d8bef9SDimitry Andric 2457e8d8bef9SDimitry Andric if (BadInst) 2458e8d8bef9SDimitry Andric continue; 2459e8d8bef9SDimitry Andric 2460e8d8bef9SDimitry Andric OutlinableRegion *OS = new (RegionAllocator.Allocate()) 2461e8d8bef9SDimitry Andric OutlinableRegion(IRSC, CurrentGroup); 2462e8d8bef9SDimitry Andric CurrentGroup.Regions.push_back(OS); 2463e8d8bef9SDimitry Andric 2464e8d8bef9SDimitry Andric CurrentEndIdx = EndIdx; 2465e8d8bef9SDimitry Andric } 2466e8d8bef9SDimitry Andric } 2467e8d8bef9SDimitry Andric 2468e8d8bef9SDimitry Andric InstructionCost 2469e8d8bef9SDimitry Andric IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) { 2470e8d8bef9SDimitry Andric InstructionCost RegionBenefit = 0; 2471e8d8bef9SDimitry Andric for (OutlinableRegion *Region : CurrentGroup.Regions) { 2472e8d8bef9SDimitry Andric TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent()); 2473e8d8bef9SDimitry Andric // We add the number of instructions in the region to the benefit as an 2474e8d8bef9SDimitry Andric // estimate as to how much will be removed. 2475e8d8bef9SDimitry Andric RegionBenefit += Region->getBenefit(TTI); 2476e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit 2477e8d8bef9SDimitry Andric << " saved instructions to overfall benefit.\n"); 2478e8d8bef9SDimitry Andric } 2479e8d8bef9SDimitry Andric 2480e8d8bef9SDimitry Andric return RegionBenefit; 2481e8d8bef9SDimitry Andric } 2482e8d8bef9SDimitry Andric 248304eeddc0SDimitry Andric /// For the \p OutputCanon number passed in find the value represented by this 248404eeddc0SDimitry Andric /// canonical number. If it is from a PHINode, we pick the first incoming 248504eeddc0SDimitry Andric /// value and return that Value instead. 248604eeddc0SDimitry Andric /// 248704eeddc0SDimitry Andric /// \param Region - The OutlinableRegion to get the Value from. 248804eeddc0SDimitry Andric /// \param OutputCanon - The canonical number to find the Value from. 248904eeddc0SDimitry Andric /// \returns The Value represented by a canonical number \p OutputCanon in \p 249004eeddc0SDimitry Andric /// Region. 249104eeddc0SDimitry Andric static Value *findOutputValueInRegion(OutlinableRegion &Region, 249204eeddc0SDimitry Andric unsigned OutputCanon) { 249304eeddc0SDimitry Andric OutlinableGroup &CurrentGroup = *Region.Parent; 249404eeddc0SDimitry Andric // If the value is greater than the value in the tracker, we have a 249504eeddc0SDimitry Andric // PHINode and will instead use one of the incoming values to find the 249604eeddc0SDimitry Andric // type. 249704eeddc0SDimitry Andric if (OutputCanon > CurrentGroup.PHINodeGVNTracker) { 249804eeddc0SDimitry Andric auto It = CurrentGroup.PHINodeGVNToGVNs.find(OutputCanon); 249904eeddc0SDimitry Andric assert(It != CurrentGroup.PHINodeGVNToGVNs.end() && 250004eeddc0SDimitry Andric "Could not find GVN set for PHINode number!"); 250104eeddc0SDimitry Andric assert(It->second.second.size() > 0 && "PHINode does not have any values!"); 250204eeddc0SDimitry Andric OutputCanon = *It->second.second.begin(); 250304eeddc0SDimitry Andric } 250404eeddc0SDimitry Andric Optional<unsigned> OGVN = Region.Candidate->fromCanonicalNum(OutputCanon); 2505*81ad6265SDimitry Andric assert(OGVN && "Could not find GVN for Canonical Number?"); 250604eeddc0SDimitry Andric Optional<Value *> OV = Region.Candidate->fromGVN(*OGVN); 2507*81ad6265SDimitry Andric assert(OV && "Could not find value for GVN?"); 250804eeddc0SDimitry Andric return *OV; 250904eeddc0SDimitry Andric } 251004eeddc0SDimitry Andric 2511e8d8bef9SDimitry Andric InstructionCost 2512e8d8bef9SDimitry Andric IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) { 2513e8d8bef9SDimitry Andric InstructionCost OverallCost = 0; 2514e8d8bef9SDimitry Andric for (OutlinableRegion *Region : CurrentGroup.Regions) { 2515e8d8bef9SDimitry Andric TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent()); 2516e8d8bef9SDimitry Andric 2517e8d8bef9SDimitry Andric // Each output incurs a load after the call, so we add that to the cost. 251804eeddc0SDimitry Andric for (unsigned OutputCanon : Region->GVNStores) { 251904eeddc0SDimitry Andric Value *V = findOutputValueInRegion(*Region, OutputCanon); 2520e8d8bef9SDimitry Andric InstructionCost LoadCost = 2521e8d8bef9SDimitry Andric TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0, 2522e8d8bef9SDimitry Andric TargetTransformInfo::TCK_CodeSize); 2523e8d8bef9SDimitry Andric 2524e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Adding: " << LoadCost 2525e8d8bef9SDimitry Andric << " instructions to cost for output of type " 2526e8d8bef9SDimitry Andric << *V->getType() << "\n"); 2527e8d8bef9SDimitry Andric OverallCost += LoadCost; 2528e8d8bef9SDimitry Andric } 2529e8d8bef9SDimitry Andric } 2530e8d8bef9SDimitry Andric 2531e8d8bef9SDimitry Andric return OverallCost; 2532e8d8bef9SDimitry Andric } 2533e8d8bef9SDimitry Andric 2534e8d8bef9SDimitry Andric /// Find the extra instructions needed to handle any output values for the 2535e8d8bef9SDimitry Andric /// region. 2536e8d8bef9SDimitry Andric /// 2537e8d8bef9SDimitry Andric /// \param [in] M - The Module to outline from. 2538e8d8bef9SDimitry Andric /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze. 2539e8d8bef9SDimitry Andric /// \param [in] TTI - The TargetTransformInfo used to collect information for 2540e8d8bef9SDimitry Andric /// new instruction costs. 2541e8d8bef9SDimitry Andric /// \returns the additional cost to handle the outputs. 2542e8d8bef9SDimitry Andric static InstructionCost findCostForOutputBlocks(Module &M, 2543e8d8bef9SDimitry Andric OutlinableGroup &CurrentGroup, 2544e8d8bef9SDimitry Andric TargetTransformInfo &TTI) { 2545e8d8bef9SDimitry Andric InstructionCost OutputCost = 0; 2546349cc55cSDimitry Andric unsigned NumOutputBranches = 0; 2547349cc55cSDimitry Andric 254804eeddc0SDimitry Andric OutlinableRegion &FirstRegion = *CurrentGroup.Regions[0]; 2549349cc55cSDimitry Andric IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate; 2550349cc55cSDimitry Andric DenseSet<BasicBlock *> CandidateBlocks; 2551349cc55cSDimitry Andric Candidate.getBasicBlocks(CandidateBlocks); 2552349cc55cSDimitry Andric 2553349cc55cSDimitry Andric // Count the number of different output branches that point to blocks outside 2554349cc55cSDimitry Andric // of the region. 2555349cc55cSDimitry Andric DenseSet<BasicBlock *> FoundBlocks; 2556349cc55cSDimitry Andric for (IRInstructionData &ID : Candidate) { 2557349cc55cSDimitry Andric if (!isa<BranchInst>(ID.Inst)) 2558349cc55cSDimitry Andric continue; 2559349cc55cSDimitry Andric 2560349cc55cSDimitry Andric for (Value *V : ID.OperVals) { 2561349cc55cSDimitry Andric BasicBlock *BB = static_cast<BasicBlock *>(V); 2562*81ad6265SDimitry Andric if (!CandidateBlocks.contains(BB) && FoundBlocks.insert(BB).second) 2563349cc55cSDimitry Andric NumOutputBranches++; 2564349cc55cSDimitry Andric } 2565349cc55cSDimitry Andric } 2566349cc55cSDimitry Andric 2567349cc55cSDimitry Andric CurrentGroup.BranchesToOutside = NumOutputBranches; 2568e8d8bef9SDimitry Andric 2569e8d8bef9SDimitry Andric for (const ArrayRef<unsigned> &OutputUse : 2570e8d8bef9SDimitry Andric CurrentGroup.OutputGVNCombinations) { 257104eeddc0SDimitry Andric for (unsigned OutputCanon : OutputUse) { 257204eeddc0SDimitry Andric Value *V = findOutputValueInRegion(FirstRegion, OutputCanon); 2573e8d8bef9SDimitry Andric InstructionCost StoreCost = 2574e8d8bef9SDimitry Andric TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0, 2575e8d8bef9SDimitry Andric TargetTransformInfo::TCK_CodeSize); 2576e8d8bef9SDimitry Andric 2577e8d8bef9SDimitry Andric // An instruction cost is added for each store set that needs to occur for 2578e8d8bef9SDimitry Andric // various output combinations inside the function, plus a branch to 2579e8d8bef9SDimitry Andric // return to the exit block. 2580e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Adding: " << StoreCost 2581e8d8bef9SDimitry Andric << " instructions to cost for output of type " 2582e8d8bef9SDimitry Andric << *V->getType() << "\n"); 2583349cc55cSDimitry Andric OutputCost += StoreCost * NumOutputBranches; 2584e8d8bef9SDimitry Andric } 2585e8d8bef9SDimitry Andric 2586e8d8bef9SDimitry Andric InstructionCost BranchCost = 2587e8d8bef9SDimitry Andric TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize); 2588e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for" 2589e8d8bef9SDimitry Andric << " a branch instruction\n"); 2590349cc55cSDimitry Andric OutputCost += BranchCost * NumOutputBranches; 2591e8d8bef9SDimitry Andric } 2592e8d8bef9SDimitry Andric 2593e8d8bef9SDimitry Andric // If there is more than one output scheme, we must have a comparison and 2594e8d8bef9SDimitry Andric // branch for each different item in the switch statement. 2595e8d8bef9SDimitry Andric if (CurrentGroup.OutputGVNCombinations.size() > 1) { 2596e8d8bef9SDimitry Andric InstructionCost ComparisonCost = TTI.getCmpSelInstrCost( 2597e8d8bef9SDimitry Andric Instruction::ICmp, Type::getInt32Ty(M.getContext()), 2598e8d8bef9SDimitry Andric Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE, 2599e8d8bef9SDimitry Andric TargetTransformInfo::TCK_CodeSize); 2600e8d8bef9SDimitry Andric InstructionCost BranchCost = 2601e8d8bef9SDimitry Andric TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize); 2602e8d8bef9SDimitry Andric 2603e8d8bef9SDimitry Andric unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size(); 2604e8d8bef9SDimitry Andric InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks; 2605e8d8bef9SDimitry Andric 2606e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Adding: " << TotalCost 2607e8d8bef9SDimitry Andric << " instructions for each switch case for each different" 2608e8d8bef9SDimitry Andric << " output path in a function\n"); 2609349cc55cSDimitry Andric OutputCost += TotalCost * NumOutputBranches; 2610e8d8bef9SDimitry Andric } 2611e8d8bef9SDimitry Andric 2612e8d8bef9SDimitry Andric return OutputCost; 2613e8d8bef9SDimitry Andric } 2614e8d8bef9SDimitry Andric 2615e8d8bef9SDimitry Andric void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) { 2616e8d8bef9SDimitry Andric InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup); 2617e8d8bef9SDimitry Andric CurrentGroup.Benefit += RegionBenefit; 2618e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n"); 2619e8d8bef9SDimitry Andric 2620e8d8bef9SDimitry Andric InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup); 2621e8d8bef9SDimitry Andric CurrentGroup.Cost += OutputReloadCost; 2622e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2623e8d8bef9SDimitry Andric 2624e8d8bef9SDimitry Andric InstructionCost AverageRegionBenefit = 2625e8d8bef9SDimitry Andric RegionBenefit / CurrentGroup.Regions.size(); 2626e8d8bef9SDimitry Andric unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size(); 2627e8d8bef9SDimitry Andric unsigned NumRegions = CurrentGroup.Regions.size(); 2628e8d8bef9SDimitry Andric TargetTransformInfo &TTI = 2629e8d8bef9SDimitry Andric getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction()); 2630e8d8bef9SDimitry Andric 2631e8d8bef9SDimitry Andric // We add one region to the cost once, to account for the instructions added 2632e8d8bef9SDimitry Andric // inside of the newly created function. 2633e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit 2634e8d8bef9SDimitry Andric << " instructions to cost for body of new function.\n"); 2635e8d8bef9SDimitry Andric CurrentGroup.Cost += AverageRegionBenefit; 2636e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2637e8d8bef9SDimitry Andric 2638e8d8bef9SDimitry Andric // For each argument, we must add an instruction for loading the argument 2639e8d8bef9SDimitry Andric // out of the register and into a value inside of the newly outlined function. 2640e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum 2641e8d8bef9SDimitry Andric << " instructions to cost for each argument in the new" 2642e8d8bef9SDimitry Andric << " function.\n"); 2643e8d8bef9SDimitry Andric CurrentGroup.Cost += 2644e8d8bef9SDimitry Andric OverallArgumentNum * TargetTransformInfo::TCC_Basic; 2645e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2646e8d8bef9SDimitry Andric 2647e8d8bef9SDimitry Andric // Each argument needs to either be loaded into a register or onto the stack. 2648e8d8bef9SDimitry Andric // Some arguments will only be loaded into the stack once the argument 2649e8d8bef9SDimitry Andric // registers are filled. 2650e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum 2651e8d8bef9SDimitry Andric << " instructions to cost for each argument in the new" 2652e8d8bef9SDimitry Andric << " function " << NumRegions << " times for the " 2653e8d8bef9SDimitry Andric << "needed argument handling at the call site.\n"); 2654e8d8bef9SDimitry Andric CurrentGroup.Cost += 2655e8d8bef9SDimitry Andric 2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions; 2656e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2657e8d8bef9SDimitry Andric 2658e8d8bef9SDimitry Andric CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI); 2659e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n"); 2660e8d8bef9SDimitry Andric } 2661e8d8bef9SDimitry Andric 2662e8d8bef9SDimitry Andric void IROutliner::updateOutputMapping(OutlinableRegion &Region, 2663e8d8bef9SDimitry Andric ArrayRef<Value *> Outputs, 2664e8d8bef9SDimitry Andric LoadInst *LI) { 2665e8d8bef9SDimitry Andric // For and load instructions following the call 2666e8d8bef9SDimitry Andric Value *Operand = LI->getPointerOperand(); 2667e8d8bef9SDimitry Andric Optional<unsigned> OutputIdx = None; 2668e8d8bef9SDimitry Andric // Find if the operand it is an output register. 2669e8d8bef9SDimitry Andric for (unsigned ArgIdx = Region.NumExtractedInputs; 2670e8d8bef9SDimitry Andric ArgIdx < Region.Call->arg_size(); ArgIdx++) { 2671e8d8bef9SDimitry Andric if (Operand == Region.Call->getArgOperand(ArgIdx)) { 2672e8d8bef9SDimitry Andric OutputIdx = ArgIdx - Region.NumExtractedInputs; 2673e8d8bef9SDimitry Andric break; 2674e8d8bef9SDimitry Andric } 2675e8d8bef9SDimitry Andric } 2676e8d8bef9SDimitry Andric 2677e8d8bef9SDimitry Andric // If we found an output register, place a mapping of the new value 2678e8d8bef9SDimitry Andric // to the original in the mapping. 2679*81ad6265SDimitry Andric if (!OutputIdx) 2680e8d8bef9SDimitry Andric return; 2681e8d8bef9SDimitry Andric 2682e8d8bef9SDimitry Andric if (OutputMappings.find(Outputs[OutputIdx.getValue()]) == 2683e8d8bef9SDimitry Andric OutputMappings.end()) { 2684e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to " 2685e8d8bef9SDimitry Andric << *Outputs[OutputIdx.getValue()] << "\n"); 2686e8d8bef9SDimitry Andric OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.getValue()])); 2687e8d8bef9SDimitry Andric } else { 2688e8d8bef9SDimitry Andric Value *Orig = OutputMappings.find(Outputs[OutputIdx.getValue()])->second; 2689e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to " 2690e8d8bef9SDimitry Andric << *Outputs[OutputIdx.getValue()] << "\n"); 2691e8d8bef9SDimitry Andric OutputMappings.insert(std::make_pair(LI, Orig)); 2692e8d8bef9SDimitry Andric } 2693e8d8bef9SDimitry Andric } 2694e8d8bef9SDimitry Andric 2695e8d8bef9SDimitry Andric bool IROutliner::extractSection(OutlinableRegion &Region) { 2696e8d8bef9SDimitry Andric SetVector<Value *> ArgInputs, Outputs, SinkCands; 2697e8d8bef9SDimitry Andric assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!"); 2698349cc55cSDimitry Andric BasicBlock *InitialStart = Region.StartBB; 2699e8d8bef9SDimitry Andric Function *OrigF = Region.StartBB->getParent(); 2700e8d8bef9SDimitry Andric CodeExtractorAnalysisCache CEAC(*OrigF); 2701349cc55cSDimitry Andric Region.ExtractedFunction = 2702349cc55cSDimitry Andric Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs); 2703e8d8bef9SDimitry Andric 2704e8d8bef9SDimitry Andric // If the extraction was successful, find the BasicBlock, and reassign the 2705e8d8bef9SDimitry Andric // OutlinableRegion blocks 2706e8d8bef9SDimitry Andric if (!Region.ExtractedFunction) { 2707e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB 2708e8d8bef9SDimitry Andric << "\n"); 2709e8d8bef9SDimitry Andric Region.reattachCandidate(); 2710e8d8bef9SDimitry Andric return false; 2711e8d8bef9SDimitry Andric } 2712e8d8bef9SDimitry Andric 2713349cc55cSDimitry Andric // Get the block containing the called branch, and reassign the blocks as 2714349cc55cSDimitry Andric // necessary. If the original block still exists, it is because we ended on 2715349cc55cSDimitry Andric // a branch instruction, and so we move the contents into the block before 2716349cc55cSDimitry Andric // and assign the previous block correctly. 2717349cc55cSDimitry Andric User *InstAsUser = Region.ExtractedFunction->user_back(); 2718349cc55cSDimitry Andric BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent(); 2719349cc55cSDimitry Andric Region.PrevBB = RewrittenBB->getSinglePredecessor(); 2720349cc55cSDimitry Andric assert(Region.PrevBB && "PrevBB is nullptr?"); 2721349cc55cSDimitry Andric if (Region.PrevBB == InitialStart) { 2722349cc55cSDimitry Andric BasicBlock *NewPrev = InitialStart->getSinglePredecessor(); 2723349cc55cSDimitry Andric Instruction *BI = NewPrev->getTerminator(); 2724349cc55cSDimitry Andric BI->eraseFromParent(); 2725349cc55cSDimitry Andric moveBBContents(*InitialStart, *NewPrev); 2726349cc55cSDimitry Andric Region.PrevBB = NewPrev; 2727349cc55cSDimitry Andric InitialStart->eraseFromParent(); 2728349cc55cSDimitry Andric } 2729349cc55cSDimitry Andric 2730e8d8bef9SDimitry Andric Region.StartBB = RewrittenBB; 2731e8d8bef9SDimitry Andric Region.EndBB = RewrittenBB; 2732e8d8bef9SDimitry Andric 2733e8d8bef9SDimitry Andric // The sequences of outlinable regions has now changed. We must fix the 2734e8d8bef9SDimitry Andric // IRInstructionDataList for consistency. Although they may not be illegal 2735e8d8bef9SDimitry Andric // instructions, they should not be compared with anything else as they 2736e8d8bef9SDimitry Andric // should not be outlined in this round. So marking these as illegal is 2737e8d8bef9SDimitry Andric // allowed. 2738e8d8bef9SDimitry Andric IRInstructionDataList *IDL = Region.Candidate->front()->IDL; 2739e8d8bef9SDimitry Andric Instruction *BeginRewritten = &*RewrittenBB->begin(); 2740e8d8bef9SDimitry Andric Instruction *EndRewritten = &*RewrittenBB->begin(); 2741e8d8bef9SDimitry Andric Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData( 2742e8d8bef9SDimitry Andric *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL); 2743e8d8bef9SDimitry Andric Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData( 2744e8d8bef9SDimitry Andric *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL); 2745e8d8bef9SDimitry Andric 2746e8d8bef9SDimitry Andric // Insert the first IRInstructionData of the new region in front of the 2747e8d8bef9SDimitry Andric // first IRInstructionData of the IRSimilarityCandidate. 2748e8d8bef9SDimitry Andric IDL->insert(Region.Candidate->begin(), *Region.NewFront); 2749e8d8bef9SDimitry Andric // Insert the first IRInstructionData of the new region after the 2750e8d8bef9SDimitry Andric // last IRInstructionData of the IRSimilarityCandidate. 2751e8d8bef9SDimitry Andric IDL->insert(Region.Candidate->end(), *Region.NewBack); 2752e8d8bef9SDimitry Andric // Remove the IRInstructionData from the IRSimilarityCandidate. 2753e8d8bef9SDimitry Andric IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end())); 2754e8d8bef9SDimitry Andric 2755e8d8bef9SDimitry Andric assert(RewrittenBB != nullptr && 2756e8d8bef9SDimitry Andric "Could not find a predecessor after extraction!"); 2757e8d8bef9SDimitry Andric 2758e8d8bef9SDimitry Andric // Iterate over the new set of instructions to find the new call 2759e8d8bef9SDimitry Andric // instruction. 2760e8d8bef9SDimitry Andric for (Instruction &I : *RewrittenBB) 2761e8d8bef9SDimitry Andric if (CallInst *CI = dyn_cast<CallInst>(&I)) { 2762e8d8bef9SDimitry Andric if (Region.ExtractedFunction == CI->getCalledFunction()) 2763e8d8bef9SDimitry Andric Region.Call = CI; 2764e8d8bef9SDimitry Andric } else if (LoadInst *LI = dyn_cast<LoadInst>(&I)) 2765e8d8bef9SDimitry Andric updateOutputMapping(Region, Outputs.getArrayRef(), LI); 2766e8d8bef9SDimitry Andric Region.reattachCandidate(); 2767e8d8bef9SDimitry Andric return true; 2768e8d8bef9SDimitry Andric } 2769e8d8bef9SDimitry Andric 2770e8d8bef9SDimitry Andric unsigned IROutliner::doOutline(Module &M) { 2771e8d8bef9SDimitry Andric // Find the possible similarity sections. 2772349cc55cSDimitry Andric InstructionClassifier.EnableBranches = !DisableBranches; 277304eeddc0SDimitry Andric InstructionClassifier.EnableIndirectCalls = !DisableIndirectCalls; 27741fd87a68SDimitry Andric InstructionClassifier.EnableIntrinsics = !DisableIntrinsics; 27751fd87a68SDimitry Andric 2776e8d8bef9SDimitry Andric IRSimilarityIdentifier &Identifier = getIRSI(M); 2777e8d8bef9SDimitry Andric SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity(); 2778e8d8bef9SDimitry Andric 2779e8d8bef9SDimitry Andric // Sort them by size of extracted sections 2780e8d8bef9SDimitry Andric unsigned OutlinedFunctionNum = 0; 2781e8d8bef9SDimitry Andric // If we only have one SimilarityGroup in SimilarityCandidates, we do not have 2782e8d8bef9SDimitry Andric // to sort them by the potential number of instructions to be outlined 2783e8d8bef9SDimitry Andric if (SimilarityCandidates.size() > 1) 2784e8d8bef9SDimitry Andric llvm::stable_sort(SimilarityCandidates, 2785e8d8bef9SDimitry Andric [](const std::vector<IRSimilarityCandidate> &LHS, 2786e8d8bef9SDimitry Andric const std::vector<IRSimilarityCandidate> &RHS) { 2787e8d8bef9SDimitry Andric return LHS[0].getLength() * LHS.size() > 2788e8d8bef9SDimitry Andric RHS[0].getLength() * RHS.size(); 2789e8d8bef9SDimitry Andric }); 2790349cc55cSDimitry Andric // Creating OutlinableGroups for each SimilarityCandidate to be used in 2791349cc55cSDimitry Andric // each of the following for loops to avoid making an allocator. 2792349cc55cSDimitry Andric std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size()); 2793e8d8bef9SDimitry Andric 2794e8d8bef9SDimitry Andric DenseSet<unsigned> NotSame; 2795349cc55cSDimitry Andric std::vector<OutlinableGroup *> NegativeCostGroups; 2796349cc55cSDimitry Andric std::vector<OutlinableRegion *> OutlinedRegions; 2797e8d8bef9SDimitry Andric // Iterate over the possible sets of similarity. 2798349cc55cSDimitry Andric unsigned PotentialGroupIdx = 0; 2799e8d8bef9SDimitry Andric for (SimilarityGroup &CandidateVec : SimilarityCandidates) { 2800349cc55cSDimitry Andric OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++]; 2801e8d8bef9SDimitry Andric 2802e8d8bef9SDimitry Andric // Remove entries that were previously outlined 2803e8d8bef9SDimitry Andric pruneIncompatibleRegions(CandidateVec, CurrentGroup); 2804e8d8bef9SDimitry Andric 2805e8d8bef9SDimitry Andric // We pruned the number of regions to 0 to 1, meaning that it's not worth 2806e8d8bef9SDimitry Andric // trying to outlined since there is no compatible similar instance of this 2807e8d8bef9SDimitry Andric // code. 2808e8d8bef9SDimitry Andric if (CurrentGroup.Regions.size() < 2) 2809e8d8bef9SDimitry Andric continue; 2810e8d8bef9SDimitry Andric 2811e8d8bef9SDimitry Andric // Determine if there are any values that are the same constant throughout 2812e8d8bef9SDimitry Andric // each section in the set. 2813e8d8bef9SDimitry Andric NotSame.clear(); 2814e8d8bef9SDimitry Andric CurrentGroup.findSameConstants(NotSame); 2815e8d8bef9SDimitry Andric 2816e8d8bef9SDimitry Andric if (CurrentGroup.IgnoreGroup) 2817e8d8bef9SDimitry Andric continue; 2818e8d8bef9SDimitry Andric 2819e8d8bef9SDimitry Andric // Create a CodeExtractor for each outlinable region. Identify inputs and 2820e8d8bef9SDimitry Andric // outputs for each section using the code extractor and create the argument 2821e8d8bef9SDimitry Andric // types for the Aggregate Outlining Function. 2822349cc55cSDimitry Andric OutlinedRegions.clear(); 2823e8d8bef9SDimitry Andric for (OutlinableRegion *OS : CurrentGroup.Regions) { 2824e8d8bef9SDimitry Andric // Break the outlinable region out of its parent BasicBlock into its own 2825e8d8bef9SDimitry Andric // BasicBlocks (see function implementation). 2826e8d8bef9SDimitry Andric OS->splitCandidate(); 2827349cc55cSDimitry Andric 2828349cc55cSDimitry Andric // There's a chance that when the region is split, extra instructions are 2829349cc55cSDimitry Andric // added to the region. This makes the region no longer viable 2830349cc55cSDimitry Andric // to be split, so we ignore it for outlining. 2831349cc55cSDimitry Andric if (!OS->CandidateSplit) 2832349cc55cSDimitry Andric continue; 2833349cc55cSDimitry Andric 2834349cc55cSDimitry Andric SmallVector<BasicBlock *> BE; 283504eeddc0SDimitry Andric DenseSet<BasicBlock *> BlocksInRegion; 283604eeddc0SDimitry Andric OS->Candidate->getBasicBlocks(BlocksInRegion, BE); 2837e8d8bef9SDimitry Andric OS->CE = new (ExtractorAllocator.Allocate()) 2838e8d8bef9SDimitry Andric CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false, 2839*81ad6265SDimitry Andric false, nullptr, "outlined"); 2840e8d8bef9SDimitry Andric findAddInputsOutputs(M, *OS, NotSame); 2841e8d8bef9SDimitry Andric if (!OS->IgnoreRegion) 2842e8d8bef9SDimitry Andric OutlinedRegions.push_back(OS); 2843349cc55cSDimitry Andric 2844349cc55cSDimitry Andric // We recombine the blocks together now that we have gathered all the 2845349cc55cSDimitry Andric // needed information. 2846e8d8bef9SDimitry Andric OS->reattachCandidate(); 2847e8d8bef9SDimitry Andric } 2848e8d8bef9SDimitry Andric 2849e8d8bef9SDimitry Andric CurrentGroup.Regions = std::move(OutlinedRegions); 2850e8d8bef9SDimitry Andric 2851e8d8bef9SDimitry Andric if (CurrentGroup.Regions.empty()) 2852e8d8bef9SDimitry Andric continue; 2853e8d8bef9SDimitry Andric 2854e8d8bef9SDimitry Andric CurrentGroup.collectGVNStoreSets(M); 2855e8d8bef9SDimitry Andric 2856e8d8bef9SDimitry Andric if (CostModel) 2857e8d8bef9SDimitry Andric findCostBenefit(M, CurrentGroup); 2858e8d8bef9SDimitry Andric 2859349cc55cSDimitry Andric // If we are adhering to the cost model, skip those groups where the cost 2860349cc55cSDimitry Andric // outweighs the benefits. 2861e8d8bef9SDimitry Andric if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) { 2862349cc55cSDimitry Andric OptimizationRemarkEmitter &ORE = 2863349cc55cSDimitry Andric getORE(*CurrentGroup.Regions[0]->Candidate->getFunction()); 2864e8d8bef9SDimitry Andric ORE.emit([&]() { 2865e8d8bef9SDimitry Andric IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate; 2866e8d8bef9SDimitry Andric OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize", 2867e8d8bef9SDimitry Andric C->frontInstruction()); 2868e8d8bef9SDimitry Andric R << "did not outline " 2869e8d8bef9SDimitry Andric << ore::NV(std::to_string(CurrentGroup.Regions.size())) 2870e8d8bef9SDimitry Andric << " regions due to estimated increase of " 2871e8d8bef9SDimitry Andric << ore::NV("InstructionIncrease", 2872e8d8bef9SDimitry Andric CurrentGroup.Cost - CurrentGroup.Benefit) 2873e8d8bef9SDimitry Andric << " instructions at locations "; 2874e8d8bef9SDimitry Andric interleave( 2875e8d8bef9SDimitry Andric CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(), 2876e8d8bef9SDimitry Andric [&R](OutlinableRegion *Region) { 2877e8d8bef9SDimitry Andric R << ore::NV( 2878e8d8bef9SDimitry Andric "DebugLoc", 2879e8d8bef9SDimitry Andric Region->Candidate->frontInstruction()->getDebugLoc()); 2880e8d8bef9SDimitry Andric }, 2881e8d8bef9SDimitry Andric [&R]() { R << " "; }); 2882e8d8bef9SDimitry Andric return R; 2883e8d8bef9SDimitry Andric }); 2884e8d8bef9SDimitry Andric continue; 2885e8d8bef9SDimitry Andric } 2886e8d8bef9SDimitry Andric 2887349cc55cSDimitry Andric NegativeCostGroups.push_back(&CurrentGroup); 2888349cc55cSDimitry Andric } 2889349cc55cSDimitry Andric 2890349cc55cSDimitry Andric ExtractorAllocator.DestroyAll(); 2891349cc55cSDimitry Andric 2892349cc55cSDimitry Andric if (NegativeCostGroups.size() > 1) 2893349cc55cSDimitry Andric stable_sort(NegativeCostGroups, 2894349cc55cSDimitry Andric [](const OutlinableGroup *LHS, const OutlinableGroup *RHS) { 2895349cc55cSDimitry Andric return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost; 2896349cc55cSDimitry Andric }); 2897349cc55cSDimitry Andric 2898349cc55cSDimitry Andric std::vector<Function *> FuncsToRemove; 2899349cc55cSDimitry Andric for (OutlinableGroup *CG : NegativeCostGroups) { 2900349cc55cSDimitry Andric OutlinableGroup &CurrentGroup = *CG; 2901349cc55cSDimitry Andric 2902349cc55cSDimitry Andric OutlinedRegions.clear(); 2903349cc55cSDimitry Andric for (OutlinableRegion *Region : CurrentGroup.Regions) { 2904349cc55cSDimitry Andric // We check whether our region is compatible with what has already been 2905349cc55cSDimitry Andric // outlined, and whether we need to ignore this item. 2906349cc55cSDimitry Andric if (!isCompatibleWithAlreadyOutlinedCode(*Region)) 2907349cc55cSDimitry Andric continue; 2908349cc55cSDimitry Andric OutlinedRegions.push_back(Region); 2909349cc55cSDimitry Andric } 2910349cc55cSDimitry Andric 2911349cc55cSDimitry Andric if (OutlinedRegions.size() < 2) 2912349cc55cSDimitry Andric continue; 2913349cc55cSDimitry Andric 2914349cc55cSDimitry Andric // Reestimate the cost and benefit of the OutlinableGroup. Continue only if 2915349cc55cSDimitry Andric // we are still outlining enough regions to make up for the added cost. 2916349cc55cSDimitry Andric CurrentGroup.Regions = std::move(OutlinedRegions); 2917349cc55cSDimitry Andric if (CostModel) { 2918349cc55cSDimitry Andric CurrentGroup.Benefit = 0; 2919349cc55cSDimitry Andric CurrentGroup.Cost = 0; 2920349cc55cSDimitry Andric findCostBenefit(M, CurrentGroup); 2921349cc55cSDimitry Andric if (CurrentGroup.Cost >= CurrentGroup.Benefit) 2922349cc55cSDimitry Andric continue; 2923349cc55cSDimitry Andric } 2924349cc55cSDimitry Andric OutlinedRegions.clear(); 2925349cc55cSDimitry Andric for (OutlinableRegion *Region : CurrentGroup.Regions) { 2926349cc55cSDimitry Andric Region->splitCandidate(); 2927349cc55cSDimitry Andric if (!Region->CandidateSplit) 2928349cc55cSDimitry Andric continue; 2929349cc55cSDimitry Andric OutlinedRegions.push_back(Region); 2930349cc55cSDimitry Andric } 2931349cc55cSDimitry Andric 2932349cc55cSDimitry Andric CurrentGroup.Regions = std::move(OutlinedRegions); 2933349cc55cSDimitry Andric if (CurrentGroup.Regions.size() < 2) { 2934349cc55cSDimitry Andric for (OutlinableRegion *R : CurrentGroup.Regions) 2935349cc55cSDimitry Andric R->reattachCandidate(); 2936349cc55cSDimitry Andric continue; 2937349cc55cSDimitry Andric } 2938349cc55cSDimitry Andric 2939e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost 2940e8d8bef9SDimitry Andric << " and benefit " << CurrentGroup.Benefit << "\n"); 2941e8d8bef9SDimitry Andric 2942e8d8bef9SDimitry Andric // Create functions out of all the sections, and mark them as outlined. 2943e8d8bef9SDimitry Andric OutlinedRegions.clear(); 2944e8d8bef9SDimitry Andric for (OutlinableRegion *OS : CurrentGroup.Regions) { 2945349cc55cSDimitry Andric SmallVector<BasicBlock *> BE; 294604eeddc0SDimitry Andric DenseSet<BasicBlock *> BlocksInRegion; 294704eeddc0SDimitry Andric OS->Candidate->getBasicBlocks(BlocksInRegion, BE); 2948349cc55cSDimitry Andric OS->CE = new (ExtractorAllocator.Allocate()) 2949349cc55cSDimitry Andric CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false, 2950*81ad6265SDimitry Andric false, nullptr, "outlined"); 2951e8d8bef9SDimitry Andric bool FunctionOutlined = extractSection(*OS); 2952e8d8bef9SDimitry Andric if (FunctionOutlined) { 2953e8d8bef9SDimitry Andric unsigned StartIdx = OS->Candidate->getStartIdx(); 2954e8d8bef9SDimitry Andric unsigned EndIdx = OS->Candidate->getEndIdx(); 2955e8d8bef9SDimitry Andric for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++) 2956e8d8bef9SDimitry Andric Outlined.insert(Idx); 2957e8d8bef9SDimitry Andric 2958e8d8bef9SDimitry Andric OutlinedRegions.push_back(OS); 2959e8d8bef9SDimitry Andric } 2960e8d8bef9SDimitry Andric } 2961e8d8bef9SDimitry Andric 2962e8d8bef9SDimitry Andric LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size() 2963e8d8bef9SDimitry Andric << " with benefit " << CurrentGroup.Benefit 2964e8d8bef9SDimitry Andric << " and cost " << CurrentGroup.Cost << "\n"); 2965e8d8bef9SDimitry Andric 2966e8d8bef9SDimitry Andric CurrentGroup.Regions = std::move(OutlinedRegions); 2967e8d8bef9SDimitry Andric 2968e8d8bef9SDimitry Andric if (CurrentGroup.Regions.empty()) 2969e8d8bef9SDimitry Andric continue; 2970e8d8bef9SDimitry Andric 2971e8d8bef9SDimitry Andric OptimizationRemarkEmitter &ORE = 2972e8d8bef9SDimitry Andric getORE(*CurrentGroup.Regions[0]->Call->getFunction()); 2973e8d8bef9SDimitry Andric ORE.emit([&]() { 2974e8d8bef9SDimitry Andric IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate; 2975e8d8bef9SDimitry Andric OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst); 2976e8d8bef9SDimitry Andric R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size())) 2977e8d8bef9SDimitry Andric << " regions with decrease of " 2978e8d8bef9SDimitry Andric << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost) 2979e8d8bef9SDimitry Andric << " instructions at locations "; 2980e8d8bef9SDimitry Andric interleave( 2981e8d8bef9SDimitry Andric CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(), 2982e8d8bef9SDimitry Andric [&R](OutlinableRegion *Region) { 2983e8d8bef9SDimitry Andric R << ore::NV("DebugLoc", 2984e8d8bef9SDimitry Andric Region->Candidate->frontInstruction()->getDebugLoc()); 2985e8d8bef9SDimitry Andric }, 2986e8d8bef9SDimitry Andric [&R]() { R << " "; }); 2987e8d8bef9SDimitry Andric return R; 2988e8d8bef9SDimitry Andric }); 2989e8d8bef9SDimitry Andric 2990e8d8bef9SDimitry Andric deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove, 2991e8d8bef9SDimitry Andric OutlinedFunctionNum); 2992e8d8bef9SDimitry Andric } 2993e8d8bef9SDimitry Andric 2994e8d8bef9SDimitry Andric for (Function *F : FuncsToRemove) 2995e8d8bef9SDimitry Andric F->eraseFromParent(); 2996e8d8bef9SDimitry Andric 2997e8d8bef9SDimitry Andric return OutlinedFunctionNum; 2998e8d8bef9SDimitry Andric } 2999e8d8bef9SDimitry Andric 3000e8d8bef9SDimitry Andric bool IROutliner::run(Module &M) { 3001e8d8bef9SDimitry Andric CostModel = !NoCostModel; 3002e8d8bef9SDimitry Andric OutlineFromLinkODRs = EnableLinkOnceODRIROutlining; 3003e8d8bef9SDimitry Andric 3004e8d8bef9SDimitry Andric return doOutline(M) > 0; 3005e8d8bef9SDimitry Andric } 3006e8d8bef9SDimitry Andric 3007e8d8bef9SDimitry Andric // Pass Manager Boilerplate 3008349cc55cSDimitry Andric namespace { 3009e8d8bef9SDimitry Andric class IROutlinerLegacyPass : public ModulePass { 3010e8d8bef9SDimitry Andric public: 3011e8d8bef9SDimitry Andric static char ID; 3012e8d8bef9SDimitry Andric IROutlinerLegacyPass() : ModulePass(ID) { 3013e8d8bef9SDimitry Andric initializeIROutlinerLegacyPassPass(*PassRegistry::getPassRegistry()); 3014e8d8bef9SDimitry Andric } 3015e8d8bef9SDimitry Andric 3016e8d8bef9SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override { 3017e8d8bef9SDimitry Andric AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 3018e8d8bef9SDimitry Andric AU.addRequired<TargetTransformInfoWrapperPass>(); 3019e8d8bef9SDimitry Andric AU.addRequired<IRSimilarityIdentifierWrapperPass>(); 3020e8d8bef9SDimitry Andric } 3021e8d8bef9SDimitry Andric 3022e8d8bef9SDimitry Andric bool runOnModule(Module &M) override; 3023e8d8bef9SDimitry Andric }; 3024349cc55cSDimitry Andric } // namespace 3025e8d8bef9SDimitry Andric 3026e8d8bef9SDimitry Andric bool IROutlinerLegacyPass::runOnModule(Module &M) { 3027e8d8bef9SDimitry Andric if (skipModule(M)) 3028e8d8bef9SDimitry Andric return false; 3029e8d8bef9SDimitry Andric 3030e8d8bef9SDimitry Andric std::unique_ptr<OptimizationRemarkEmitter> ORE; 3031e8d8bef9SDimitry Andric auto GORE = [&ORE](Function &F) -> OptimizationRemarkEmitter & { 3032e8d8bef9SDimitry Andric ORE.reset(new OptimizationRemarkEmitter(&F)); 3033*81ad6265SDimitry Andric return *ORE; 3034e8d8bef9SDimitry Andric }; 3035e8d8bef9SDimitry Andric 3036e8d8bef9SDimitry Andric auto GTTI = [this](Function &F) -> TargetTransformInfo & { 3037e8d8bef9SDimitry Andric return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 3038e8d8bef9SDimitry Andric }; 3039e8d8bef9SDimitry Andric 3040e8d8bef9SDimitry Andric auto GIRSI = [this](Module &) -> IRSimilarityIdentifier & { 3041e8d8bef9SDimitry Andric return this->getAnalysis<IRSimilarityIdentifierWrapperPass>().getIRSI(); 3042e8d8bef9SDimitry Andric }; 3043e8d8bef9SDimitry Andric 3044e8d8bef9SDimitry Andric return IROutliner(GTTI, GIRSI, GORE).run(M); 3045e8d8bef9SDimitry Andric } 3046e8d8bef9SDimitry Andric 3047e8d8bef9SDimitry Andric PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) { 3048e8d8bef9SDimitry Andric auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 3049e8d8bef9SDimitry Andric 3050e8d8bef9SDimitry Andric std::function<TargetTransformInfo &(Function &)> GTTI = 3051e8d8bef9SDimitry Andric [&FAM](Function &F) -> TargetTransformInfo & { 3052e8d8bef9SDimitry Andric return FAM.getResult<TargetIRAnalysis>(F); 3053e8d8bef9SDimitry Andric }; 3054e8d8bef9SDimitry Andric 3055e8d8bef9SDimitry Andric std::function<IRSimilarityIdentifier &(Module &)> GIRSI = 3056e8d8bef9SDimitry Andric [&AM](Module &M) -> IRSimilarityIdentifier & { 3057e8d8bef9SDimitry Andric return AM.getResult<IRSimilarityAnalysis>(M); 3058e8d8bef9SDimitry Andric }; 3059e8d8bef9SDimitry Andric 3060e8d8bef9SDimitry Andric std::unique_ptr<OptimizationRemarkEmitter> ORE; 3061e8d8bef9SDimitry Andric std::function<OptimizationRemarkEmitter &(Function &)> GORE = 3062e8d8bef9SDimitry Andric [&ORE](Function &F) -> OptimizationRemarkEmitter & { 3063e8d8bef9SDimitry Andric ORE.reset(new OptimizationRemarkEmitter(&F)); 3064*81ad6265SDimitry Andric return *ORE; 3065e8d8bef9SDimitry Andric }; 3066e8d8bef9SDimitry Andric 3067e8d8bef9SDimitry Andric if (IROutliner(GTTI, GIRSI, GORE).run(M)) 3068e8d8bef9SDimitry Andric return PreservedAnalyses::none(); 3069e8d8bef9SDimitry Andric return PreservedAnalyses::all(); 3070e8d8bef9SDimitry Andric } 3071e8d8bef9SDimitry Andric 3072e8d8bef9SDimitry Andric char IROutlinerLegacyPass::ID = 0; 3073e8d8bef9SDimitry Andric INITIALIZE_PASS_BEGIN(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false, 3074e8d8bef9SDimitry Andric false) 3075e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass) 3076e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 3077e8d8bef9SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 3078e8d8bef9SDimitry Andric INITIALIZE_PASS_END(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false, 3079e8d8bef9SDimitry Andric false) 3080e8d8bef9SDimitry Andric 3081e8d8bef9SDimitry Andric ModulePass *llvm::createIROutlinerPass() { return new IROutlinerLegacyPass(); } 3082