xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/IPO/IROutliner.cpp (revision 5f757f3ff9144b609b3c433dfd370cc6bdc191ad)
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"
2081ad6265SDimitry Andric #include "llvm/IR/DebugInfo.h"
2181ad6265SDimitry 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/Support/CommandLine.h"
26e8d8bef9SDimitry Andric #include "llvm/Transforms/IPO.h"
27bdd1243dSDimitry Andric #include <optional>
28e8d8bef9SDimitry Andric #include <vector>
29e8d8bef9SDimitry Andric 
30e8d8bef9SDimitry Andric #define DEBUG_TYPE "iroutliner"
31e8d8bef9SDimitry Andric 
32e8d8bef9SDimitry Andric using namespace llvm;
33e8d8bef9SDimitry Andric using namespace IRSimilarity;
34e8d8bef9SDimitry Andric 
35349cc55cSDimitry Andric // A command flag to be used for debugging to exclude branches from similarity
36349cc55cSDimitry Andric // matching and outlining.
3704eeddc0SDimitry Andric namespace llvm {
38349cc55cSDimitry Andric extern cl::opt<bool> DisableBranches;
39349cc55cSDimitry Andric 
4004eeddc0SDimitry Andric // A command flag to be used for debugging to indirect calls from similarity
4104eeddc0SDimitry Andric // matching and outlining.
4204eeddc0SDimitry Andric extern cl::opt<bool> DisableIndirectCalls;
431fd87a68SDimitry Andric 
441fd87a68SDimitry Andric // A command flag to be used for debugging to exclude intrinsics from similarity
451fd87a68SDimitry Andric // matching and outlining.
461fd87a68SDimitry Andric extern cl::opt<bool> DisableIntrinsics;
471fd87a68SDimitry Andric 
4804eeddc0SDimitry Andric } // namespace llvm
4904eeddc0SDimitry Andric 
50e8d8bef9SDimitry Andric // Set to true if the user wants the ir outliner to run on linkonceodr linkage
51e8d8bef9SDimitry Andric // functions. This is false by default because the linker can dedupe linkonceodr
52e8d8bef9SDimitry Andric // functions. Since the outliner is confined to a single module (modulo LTO),
53e8d8bef9SDimitry Andric // this is off by default. It should, however, be the default behavior in
54e8d8bef9SDimitry Andric // LTO.
55e8d8bef9SDimitry Andric static cl::opt<bool> EnableLinkOnceODRIROutlining(
56e8d8bef9SDimitry Andric     "enable-linkonceodr-ir-outlining", cl::Hidden,
57e8d8bef9SDimitry Andric     cl::desc("Enable the IR outliner on linkonceodr functions"),
58e8d8bef9SDimitry Andric     cl::init(false));
59e8d8bef9SDimitry Andric 
60e8d8bef9SDimitry Andric // This is a debug option to test small pieces of code to ensure that outlining
61e8d8bef9SDimitry Andric // works correctly.
62e8d8bef9SDimitry Andric static cl::opt<bool> NoCostModel(
63e8d8bef9SDimitry Andric     "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden,
64e8d8bef9SDimitry Andric     cl::desc("Debug option to outline greedily, without restriction that "
65e8d8bef9SDimitry Andric              "calculated benefit outweighs cost"));
66e8d8bef9SDimitry Andric 
67e8d8bef9SDimitry Andric /// The OutlinableGroup holds all the overarching information for outlining
68e8d8bef9SDimitry Andric /// a set of regions that are structurally similar to one another, such as the
69e8d8bef9SDimitry Andric /// types of the overall function, the output blocks, the sets of stores needed
70e8d8bef9SDimitry Andric /// and a list of the different regions. This information is used in the
71e8d8bef9SDimitry Andric /// deduplication of extracted regions with the same structure.
72e8d8bef9SDimitry Andric struct OutlinableGroup {
73e8d8bef9SDimitry Andric   /// The sections that could be outlined
74e8d8bef9SDimitry Andric   std::vector<OutlinableRegion *> Regions;
75e8d8bef9SDimitry Andric 
76e8d8bef9SDimitry Andric   /// The argument types for the function created as the overall function to
77e8d8bef9SDimitry Andric   /// replace the extracted function for each region.
78e8d8bef9SDimitry Andric   std::vector<Type *> ArgumentTypes;
79e8d8bef9SDimitry Andric   /// The FunctionType for the overall function.
80e8d8bef9SDimitry Andric   FunctionType *OutlinedFunctionType = nullptr;
81e8d8bef9SDimitry Andric   /// The Function for the collective overall function.
82e8d8bef9SDimitry Andric   Function *OutlinedFunction = nullptr;
83e8d8bef9SDimitry Andric 
84e8d8bef9SDimitry Andric   /// Flag for whether we should not consider this group of OutlinableRegions
85e8d8bef9SDimitry Andric   /// for extraction.
86e8d8bef9SDimitry Andric   bool IgnoreGroup = false;
87e8d8bef9SDimitry Andric 
88349cc55cSDimitry Andric   /// The return blocks for the overall function.
89349cc55cSDimitry Andric   DenseMap<Value *, BasicBlock *> EndBBs;
90349cc55cSDimitry Andric 
91349cc55cSDimitry Andric   /// The PHIBlocks with their corresponding return block based on the return
92349cc55cSDimitry Andric   /// value as the key.
93349cc55cSDimitry Andric   DenseMap<Value *, BasicBlock *> PHIBlocks;
94e8d8bef9SDimitry Andric 
95e8d8bef9SDimitry Andric   /// A set containing the different GVN store sets needed. Each array contains
96e8d8bef9SDimitry Andric   /// a sorted list of the different values that need to be stored into output
97e8d8bef9SDimitry Andric   /// registers.
98e8d8bef9SDimitry Andric   DenseSet<ArrayRef<unsigned>> OutputGVNCombinations;
99e8d8bef9SDimitry Andric 
100e8d8bef9SDimitry Andric   /// Flag for whether the \ref ArgumentTypes have been defined after the
101e8d8bef9SDimitry Andric   /// extraction of the first region.
102e8d8bef9SDimitry Andric   bool InputTypesSet = false;
103e8d8bef9SDimitry Andric 
104e8d8bef9SDimitry Andric   /// The number of input values in \ref ArgumentTypes.  Anything after this
105e8d8bef9SDimitry Andric   /// index in ArgumentTypes is an output argument.
106e8d8bef9SDimitry Andric   unsigned NumAggregateInputs = 0;
107e8d8bef9SDimitry Andric 
108349cc55cSDimitry Andric   /// The mapping of the canonical numbering of the values in outlined sections
109349cc55cSDimitry Andric   /// to specific arguments.
110349cc55cSDimitry Andric   DenseMap<unsigned, unsigned> CanonicalNumberToAggArg;
111349cc55cSDimitry Andric 
112349cc55cSDimitry Andric   /// The number of branches in the region target a basic block that is outside
113349cc55cSDimitry Andric   /// of the region.
114349cc55cSDimitry Andric   unsigned BranchesToOutside = 0;
115349cc55cSDimitry Andric 
11604eeddc0SDimitry Andric   /// Tracker counting backwards from the highest unsigned value possible to
11704eeddc0SDimitry Andric   /// avoid conflicting with the GVNs of assigned values.  We start at -3 since
11804eeddc0SDimitry Andric   /// -2 and -1 are assigned by the DenseMap.
11904eeddc0SDimitry Andric   unsigned PHINodeGVNTracker = -3;
12004eeddc0SDimitry Andric 
12104eeddc0SDimitry Andric   DenseMap<unsigned,
12204eeddc0SDimitry Andric            std::pair<std::pair<unsigned, unsigned>, SmallVector<unsigned, 2>>>
12304eeddc0SDimitry Andric       PHINodeGVNToGVNs;
12404eeddc0SDimitry Andric   DenseMap<hash_code, unsigned> GVNsToPHINodeGVN;
12504eeddc0SDimitry Andric 
126e8d8bef9SDimitry Andric   /// The number of instructions that will be outlined by extracting \ref
127e8d8bef9SDimitry Andric   /// Regions.
128e8d8bef9SDimitry Andric   InstructionCost Benefit = 0;
129e8d8bef9SDimitry Andric   /// The number of added instructions needed for the outlining of the \ref
130e8d8bef9SDimitry Andric   /// Regions.
131e8d8bef9SDimitry Andric   InstructionCost Cost = 0;
132e8d8bef9SDimitry Andric 
133e8d8bef9SDimitry Andric   /// The argument that needs to be marked with the swifterr attribute.  If not
134e8d8bef9SDimitry Andric   /// needed, there is no value.
135bdd1243dSDimitry Andric   std::optional<unsigned> SwiftErrorArgument;
136e8d8bef9SDimitry Andric 
137e8d8bef9SDimitry Andric   /// For the \ref Regions, we look at every Value.  If it is a constant,
138e8d8bef9SDimitry Andric   /// we check whether it is the same in Region.
139e8d8bef9SDimitry Andric   ///
140e8d8bef9SDimitry Andric   /// \param [in,out] NotSame contains the global value numbers where the
141e8d8bef9SDimitry Andric   /// constant is not always the same, and must be passed in as an argument.
142e8d8bef9SDimitry Andric   void findSameConstants(DenseSet<unsigned> &NotSame);
143e8d8bef9SDimitry Andric 
144e8d8bef9SDimitry Andric   /// For the regions, look at each set of GVN stores needed and account for
145e8d8bef9SDimitry Andric   /// each combination.  Add an argument to the argument types if there is
146e8d8bef9SDimitry Andric   /// more than one combination.
147e8d8bef9SDimitry Andric   ///
148e8d8bef9SDimitry Andric   /// \param [in] M - The module we are outlining from.
149e8d8bef9SDimitry Andric   void collectGVNStoreSets(Module &M);
150e8d8bef9SDimitry Andric };
151e8d8bef9SDimitry Andric 
152e8d8bef9SDimitry Andric /// Move the contents of \p SourceBB to before the last instruction of \p
153e8d8bef9SDimitry Andric /// TargetBB.
154e8d8bef9SDimitry Andric /// \param SourceBB - the BasicBlock to pull Instructions from.
155e8d8bef9SDimitry Andric /// \param TargetBB - the BasicBlock to put Instruction into.
156e8d8bef9SDimitry Andric static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) {
157349cc55cSDimitry Andric   for (Instruction &I : llvm::make_early_inc_range(SourceBB))
158*5f757f3fSDimitry Andric     I.moveBeforePreserving(TargetBB, TargetBB.end());
159e8d8bef9SDimitry Andric }
160349cc55cSDimitry Andric 
161349cc55cSDimitry Andric /// A function to sort the keys of \p Map, which must be a mapping of constant
162349cc55cSDimitry Andric /// values to basic blocks and return it in \p SortedKeys
163349cc55cSDimitry Andric ///
164349cc55cSDimitry Andric /// \param SortedKeys - The vector the keys will be return in and sorted.
165349cc55cSDimitry Andric /// \param Map - The DenseMap containing keys to sort.
166349cc55cSDimitry Andric static void getSortedConstantKeys(std::vector<Value *> &SortedKeys,
167349cc55cSDimitry Andric                                   DenseMap<Value *, BasicBlock *> &Map) {
168349cc55cSDimitry Andric   for (auto &VtoBB : Map)
169349cc55cSDimitry Andric     SortedKeys.push_back(VtoBB.first);
170349cc55cSDimitry Andric 
171bdd1243dSDimitry Andric   // Here we expect to have either 1 value that is void (nullptr) or multiple
172bdd1243dSDimitry Andric   // values that are all constant integers.
173bdd1243dSDimitry Andric   if (SortedKeys.size() == 1) {
174bdd1243dSDimitry Andric     assert(!SortedKeys[0] && "Expected a single void value.");
175bdd1243dSDimitry Andric     return;
176bdd1243dSDimitry Andric   }
177bdd1243dSDimitry Andric 
178349cc55cSDimitry Andric   stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) {
179bdd1243dSDimitry Andric     assert(LHS && RHS && "Expected non void values.");
18006c3fb27SDimitry Andric     const ConstantInt *LHSC = cast<ConstantInt>(LHS);
18106c3fb27SDimitry Andric     const ConstantInt *RHSC = cast<ConstantInt>(RHS);
182349cc55cSDimitry Andric 
183349cc55cSDimitry Andric     return LHSC->getLimitedValue() < RHSC->getLimitedValue();
184349cc55cSDimitry Andric   });
185349cc55cSDimitry Andric }
186349cc55cSDimitry Andric 
187349cc55cSDimitry Andric Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other,
188349cc55cSDimitry Andric                                                   Value *V) {
189bdd1243dSDimitry Andric   std::optional<unsigned> GVN = Candidate->getGVN(V);
19081ad6265SDimitry Andric   assert(GVN && "No GVN for incoming value");
191bdd1243dSDimitry Andric   std::optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN);
192bdd1243dSDimitry Andric   std::optional<unsigned> FirstGVN =
193bdd1243dSDimitry Andric       Other.Candidate->fromCanonicalNum(*CanonNum);
194bdd1243dSDimitry Andric   std::optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN);
19581ad6265SDimitry Andric   return FoundValueOpt.value_or(nullptr);
19681ad6265SDimitry Andric }
19781ad6265SDimitry Andric 
19881ad6265SDimitry Andric BasicBlock *
19981ad6265SDimitry Andric OutlinableRegion::findCorrespondingBlockIn(const OutlinableRegion &Other,
20081ad6265SDimitry Andric                                            BasicBlock *BB) {
201*5f757f3fSDimitry Andric   Instruction *FirstNonPHI = BB->getFirstNonPHIOrDbg();
20281ad6265SDimitry Andric   assert(FirstNonPHI && "block is empty?");
20381ad6265SDimitry Andric   Value *CorrespondingVal = findCorrespondingValueIn(Other, FirstNonPHI);
20481ad6265SDimitry Andric   if (!CorrespondingVal)
20581ad6265SDimitry Andric     return nullptr;
20681ad6265SDimitry Andric   BasicBlock *CorrespondingBlock =
20781ad6265SDimitry Andric       cast<Instruction>(CorrespondingVal)->getParent();
20881ad6265SDimitry Andric   return CorrespondingBlock;
209e8d8bef9SDimitry Andric }
210e8d8bef9SDimitry Andric 
21104eeddc0SDimitry Andric /// Rewrite the BranchInsts in the incoming blocks to \p PHIBlock that are found
21204eeddc0SDimitry Andric /// in \p Included to branch to BasicBlock \p Replace if they currently branch
21304eeddc0SDimitry Andric /// to the BasicBlock \p Find.  This is used to fix up the incoming basic blocks
21404eeddc0SDimitry Andric /// when PHINodes are included in outlined regions.
21504eeddc0SDimitry Andric ///
21604eeddc0SDimitry Andric /// \param PHIBlock - The BasicBlock containing the PHINodes that need to be
21704eeddc0SDimitry Andric /// checked.
21804eeddc0SDimitry Andric /// \param Find - The successor block to be replaced.
21904eeddc0SDimitry Andric /// \param Replace - The new succesor block to branch to.
22004eeddc0SDimitry Andric /// \param Included - The set of blocks about to be outlined.
22104eeddc0SDimitry Andric static void replaceTargetsFromPHINode(BasicBlock *PHIBlock, BasicBlock *Find,
22204eeddc0SDimitry Andric                                       BasicBlock *Replace,
22304eeddc0SDimitry Andric                                       DenseSet<BasicBlock *> &Included) {
22404eeddc0SDimitry Andric   for (PHINode &PN : PHIBlock->phis()) {
22504eeddc0SDimitry Andric     for (unsigned Idx = 0, PNEnd = PN.getNumIncomingValues(); Idx != PNEnd;
22604eeddc0SDimitry Andric          ++Idx) {
22704eeddc0SDimitry Andric       // Check if the incoming block is included in the set of blocks being
22804eeddc0SDimitry Andric       // outlined.
22904eeddc0SDimitry Andric       BasicBlock *Incoming = PN.getIncomingBlock(Idx);
23004eeddc0SDimitry Andric       if (!Included.contains(Incoming))
23104eeddc0SDimitry Andric         continue;
23204eeddc0SDimitry Andric 
23304eeddc0SDimitry Andric       BranchInst *BI = dyn_cast<BranchInst>(Incoming->getTerminator());
23404eeddc0SDimitry Andric       assert(BI && "Not a branch instruction?");
23504eeddc0SDimitry Andric       // Look over the branching instructions into this block to see if we
23604eeddc0SDimitry Andric       // used to branch to Find in this outlined block.
23704eeddc0SDimitry Andric       for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ != End;
23804eeddc0SDimitry Andric            Succ++) {
23904eeddc0SDimitry Andric         // If we have found the block to replace, we do so here.
24004eeddc0SDimitry Andric         if (BI->getSuccessor(Succ) != Find)
24104eeddc0SDimitry Andric           continue;
24204eeddc0SDimitry Andric         BI->setSuccessor(Succ, Replace);
24304eeddc0SDimitry Andric       }
24404eeddc0SDimitry Andric     }
24504eeddc0SDimitry Andric   }
24604eeddc0SDimitry Andric }
24704eeddc0SDimitry Andric 
24804eeddc0SDimitry Andric 
249e8d8bef9SDimitry Andric void OutlinableRegion::splitCandidate() {
250e8d8bef9SDimitry Andric   assert(!CandidateSplit && "Candidate already split!");
251e8d8bef9SDimitry Andric 
252349cc55cSDimitry Andric   Instruction *BackInst = Candidate->backInstruction();
253349cc55cSDimitry Andric 
254349cc55cSDimitry Andric   Instruction *EndInst = nullptr;
255349cc55cSDimitry Andric   // Check whether the last instruction is a terminator, if it is, we do
256349cc55cSDimitry Andric   // not split on the following instruction. We leave the block as it is.  We
257349cc55cSDimitry Andric   // also check that this is not the last instruction in the Module, otherwise
258349cc55cSDimitry Andric   // the check for whether the current following instruction matches the
259349cc55cSDimitry Andric   // previously recorded instruction will be incorrect.
260349cc55cSDimitry Andric   if (!BackInst->isTerminator() ||
261349cc55cSDimitry Andric       BackInst->getParent() != &BackInst->getFunction()->back()) {
262349cc55cSDimitry Andric     EndInst = Candidate->end()->Inst;
263349cc55cSDimitry Andric     assert(EndInst && "Expected an end instruction?");
264349cc55cSDimitry Andric   }
265349cc55cSDimitry Andric 
266349cc55cSDimitry Andric   // We check if the current instruction following the last instruction in the
267349cc55cSDimitry Andric   // region is the same as the recorded instruction following the last
268349cc55cSDimitry Andric   // instruction. If they do not match, there could be problems in rewriting
269349cc55cSDimitry Andric   // the program after outlining, so we ignore it.
270349cc55cSDimitry Andric   if (!BackInst->isTerminator() &&
271349cc55cSDimitry Andric       EndInst != BackInst->getNextNonDebugInstruction())
272349cc55cSDimitry Andric     return;
273349cc55cSDimitry Andric 
274e8d8bef9SDimitry Andric   Instruction *StartInst = (*Candidate->begin()).Inst;
275349cc55cSDimitry Andric   assert(StartInst && "Expected a start instruction?");
276e8d8bef9SDimitry Andric   StartBB = StartInst->getParent();
277e8d8bef9SDimitry Andric   PrevBB = StartBB;
278e8d8bef9SDimitry Andric 
27904eeddc0SDimitry Andric   DenseSet<BasicBlock *> BBSet;
28004eeddc0SDimitry Andric   Candidate->getBasicBlocks(BBSet);
28104eeddc0SDimitry Andric 
28204eeddc0SDimitry Andric   // We iterate over the instructions in the region, if we find a PHINode, we
28304eeddc0SDimitry Andric   // check if there are predecessors outside of the region, if there are,
28404eeddc0SDimitry Andric   // we ignore this region since we are unable to handle the severing of the
28504eeddc0SDimitry Andric   // phi node right now.
28681ad6265SDimitry Andric 
28781ad6265SDimitry Andric   // TODO: Handle extraneous inputs for PHINodes through variable number of
28881ad6265SDimitry Andric   // inputs, similar to how outputs are handled.
28904eeddc0SDimitry Andric   BasicBlock::iterator It = StartInst->getIterator();
29081ad6265SDimitry Andric   EndBB = BackInst->getParent();
29181ad6265SDimitry Andric   BasicBlock *IBlock;
29281ad6265SDimitry Andric   BasicBlock *PHIPredBlock = nullptr;
29381ad6265SDimitry Andric   bool EndBBTermAndBackInstDifferent = EndBB->getTerminator() != BackInst;
29404eeddc0SDimitry Andric   while (PHINode *PN = dyn_cast<PHINode>(&*It)) {
29504eeddc0SDimitry Andric     unsigned NumPredsOutsideRegion = 0;
29681ad6265SDimitry Andric     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
29781ad6265SDimitry Andric       if (!BBSet.contains(PN->getIncomingBlock(i))) {
29881ad6265SDimitry Andric         PHIPredBlock = PN->getIncomingBlock(i);
29904eeddc0SDimitry Andric         ++NumPredsOutsideRegion;
30081ad6265SDimitry Andric         continue;
30181ad6265SDimitry Andric       }
30281ad6265SDimitry Andric 
30381ad6265SDimitry Andric       // We must consider the case there the incoming block to the PHINode is
30481ad6265SDimitry Andric       // the same as the final block of the OutlinableRegion.  If this is the
30581ad6265SDimitry Andric       // case, the branch from this block must also be outlined to be valid.
30681ad6265SDimitry Andric       IBlock = PN->getIncomingBlock(i);
30781ad6265SDimitry Andric       if (IBlock == EndBB && EndBBTermAndBackInstDifferent) {
30881ad6265SDimitry Andric         PHIPredBlock = PN->getIncomingBlock(i);
30981ad6265SDimitry Andric         ++NumPredsOutsideRegion;
31081ad6265SDimitry Andric       }
31181ad6265SDimitry Andric     }
31204eeddc0SDimitry Andric 
31304eeddc0SDimitry Andric     if (NumPredsOutsideRegion > 1)
31404eeddc0SDimitry Andric       return;
31504eeddc0SDimitry Andric 
31604eeddc0SDimitry Andric     It++;
31704eeddc0SDimitry Andric   }
31804eeddc0SDimitry Andric 
31904eeddc0SDimitry Andric   // If the region starts with a PHINode, but is not the initial instruction of
32004eeddc0SDimitry Andric   // the BasicBlock, we ignore this region for now.
32104eeddc0SDimitry Andric   if (isa<PHINode>(StartInst) && StartInst != &*StartBB->begin())
32204eeddc0SDimitry Andric     return;
32304eeddc0SDimitry Andric 
32404eeddc0SDimitry Andric   // If the region ends with a PHINode, but does not contain all of the phi node
32504eeddc0SDimitry Andric   // instructions of the region, we ignore it for now.
32681ad6265SDimitry Andric   if (isa<PHINode>(BackInst) &&
32781ad6265SDimitry Andric       BackInst != &*std::prev(EndBB->getFirstInsertionPt()))
32804eeddc0SDimitry Andric     return;
32904eeddc0SDimitry Andric 
330e8d8bef9SDimitry Andric   // The basic block gets split like so:
331e8d8bef9SDimitry Andric   // block:                 block:
332e8d8bef9SDimitry Andric   //   inst1                  inst1
333e8d8bef9SDimitry Andric   //   inst2                  inst2
334e8d8bef9SDimitry Andric   //   region1               br block_to_outline
335e8d8bef9SDimitry Andric   //   region2              block_to_outline:
336e8d8bef9SDimitry Andric   //   region3          ->    region1
337e8d8bef9SDimitry Andric   //   region4                region2
338e8d8bef9SDimitry Andric   //   inst3                  region3
339e8d8bef9SDimitry Andric   //   inst4                  region4
340e8d8bef9SDimitry Andric   //                          br block_after_outline
341e8d8bef9SDimitry Andric   //                        block_after_outline:
342e8d8bef9SDimitry Andric   //                          inst3
343e8d8bef9SDimitry Andric   //                          inst4
344e8d8bef9SDimitry Andric 
345e8d8bef9SDimitry Andric   std::string OriginalName = PrevBB->getName().str();
346e8d8bef9SDimitry Andric 
347e8d8bef9SDimitry Andric   StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline");
348349cc55cSDimitry Andric   PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB);
34981ad6265SDimitry Andric   // If there was a PHINode with an incoming block outside the region,
35081ad6265SDimitry Andric   // make sure is correctly updated in the newly split block.
35181ad6265SDimitry Andric   if (PHIPredBlock)
35281ad6265SDimitry Andric     PrevBB->replaceSuccessorsPhiUsesWith(PHIPredBlock, PrevBB);
353e8d8bef9SDimitry Andric 
354e8d8bef9SDimitry Andric   CandidateSplit = true;
355349cc55cSDimitry Andric   if (!BackInst->isTerminator()) {
356349cc55cSDimitry Andric     EndBB = EndInst->getParent();
357349cc55cSDimitry Andric     FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline");
358349cc55cSDimitry Andric     EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB);
359349cc55cSDimitry Andric     FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB);
36004eeddc0SDimitry Andric   } else {
361349cc55cSDimitry Andric     EndBB = BackInst->getParent();
362349cc55cSDimitry Andric     EndsInBranch = true;
363349cc55cSDimitry Andric     FollowBB = nullptr;
364e8d8bef9SDimitry Andric   }
365e8d8bef9SDimitry Andric 
36604eeddc0SDimitry Andric   // Refind the basic block set.
36704eeddc0SDimitry Andric   BBSet.clear();
36804eeddc0SDimitry Andric   Candidate->getBasicBlocks(BBSet);
36904eeddc0SDimitry Andric   // For the phi nodes in the new starting basic block of the region, we
37004eeddc0SDimitry Andric   // reassign the targets of the basic blocks branching instructions.
37104eeddc0SDimitry Andric   replaceTargetsFromPHINode(StartBB, PrevBB, StartBB, BBSet);
37204eeddc0SDimitry Andric   if (FollowBB)
37304eeddc0SDimitry Andric     replaceTargetsFromPHINode(FollowBB, EndBB, FollowBB, BBSet);
37404eeddc0SDimitry Andric }
37504eeddc0SDimitry Andric 
376e8d8bef9SDimitry Andric void OutlinableRegion::reattachCandidate() {
377e8d8bef9SDimitry Andric   assert(CandidateSplit && "Candidate is not split!");
378e8d8bef9SDimitry Andric 
379e8d8bef9SDimitry Andric   // The basic block gets reattached like so:
380e8d8bef9SDimitry Andric   // block:                        block:
381e8d8bef9SDimitry Andric   //   inst1                         inst1
382e8d8bef9SDimitry Andric   //   inst2                         inst2
383e8d8bef9SDimitry Andric   //   br block_to_outline           region1
384e8d8bef9SDimitry Andric   // block_to_outline:        ->     region2
385e8d8bef9SDimitry Andric   //   region1                       region3
386e8d8bef9SDimitry Andric   //   region2                       region4
387e8d8bef9SDimitry Andric   //   region3                       inst3
388e8d8bef9SDimitry Andric   //   region4                       inst4
389e8d8bef9SDimitry Andric   //   br block_after_outline
390e8d8bef9SDimitry Andric   // block_after_outline:
391e8d8bef9SDimitry Andric   //   inst3
392e8d8bef9SDimitry Andric   //   inst4
393e8d8bef9SDimitry Andric   assert(StartBB != nullptr && "StartBB for Candidate is not defined!");
394e8d8bef9SDimitry Andric 
395e8d8bef9SDimitry Andric   assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!");
39681ad6265SDimitry Andric   // Make sure PHINode references to the block we are merging into are
39781ad6265SDimitry Andric   // updated to be incoming blocks from the predecessor to the current block.
39881ad6265SDimitry Andric 
39981ad6265SDimitry Andric   // NOTE: If this is updated such that the outlined block can have more than
40081ad6265SDimitry Andric   // one incoming block to a PHINode, this logic will have to updated
40181ad6265SDimitry Andric   // to handle multiple precessors instead.
40281ad6265SDimitry Andric 
40381ad6265SDimitry Andric   // We only need to update this if the outlined section contains a PHINode, if
40481ad6265SDimitry Andric   // it does not, then the incoming block was never changed in the first place.
40581ad6265SDimitry Andric   // On the other hand, if PrevBB has no predecessors, it means that all
40681ad6265SDimitry Andric   // incoming blocks to the first block are contained in the region, and there
40781ad6265SDimitry Andric   // will be nothing to update.
40881ad6265SDimitry Andric   Instruction *StartInst = (*Candidate->begin()).Inst;
40981ad6265SDimitry Andric   if (isa<PHINode>(StartInst) && !PrevBB->hasNPredecessors(0)) {
41081ad6265SDimitry Andric     assert(!PrevBB->hasNPredecessorsOrMore(2) &&
41181ad6265SDimitry Andric          "PrevBB has more than one predecessor. Should be 0 or 1.");
41281ad6265SDimitry Andric     BasicBlock *BeforePrevBB = PrevBB->getSinglePredecessor();
41381ad6265SDimitry Andric     PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, BeforePrevBB);
41481ad6265SDimitry Andric   }
415e8d8bef9SDimitry Andric   PrevBB->getTerminator()->eraseFromParent();
416e8d8bef9SDimitry Andric 
41704eeddc0SDimitry Andric   // If we reattaching after outlining, we iterate over the phi nodes to
41804eeddc0SDimitry Andric   // the initial block, and reassign the branch instructions of the incoming
41904eeddc0SDimitry Andric   // blocks to the block we are remerging into.
42004eeddc0SDimitry Andric   if (!ExtractedFunction) {
42104eeddc0SDimitry Andric     DenseSet<BasicBlock *> BBSet;
42204eeddc0SDimitry Andric     Candidate->getBasicBlocks(BBSet);
42304eeddc0SDimitry Andric 
42404eeddc0SDimitry Andric     replaceTargetsFromPHINode(StartBB, StartBB, PrevBB, BBSet);
42504eeddc0SDimitry Andric     if (!EndsInBranch)
42604eeddc0SDimitry Andric       replaceTargetsFromPHINode(FollowBB, FollowBB, EndBB, BBSet);
42704eeddc0SDimitry Andric   }
42804eeddc0SDimitry Andric 
429e8d8bef9SDimitry Andric   moveBBContents(*StartBB, *PrevBB);
430e8d8bef9SDimitry Andric 
431e8d8bef9SDimitry Andric   BasicBlock *PlacementBB = PrevBB;
432e8d8bef9SDimitry Andric   if (StartBB != EndBB)
433e8d8bef9SDimitry Andric     PlacementBB = EndBB;
434349cc55cSDimitry Andric   if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) {
435349cc55cSDimitry Andric     assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!");
436349cc55cSDimitry Andric     assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!");
437349cc55cSDimitry Andric     PlacementBB->getTerminator()->eraseFromParent();
438e8d8bef9SDimitry Andric     moveBBContents(*FollowBB, *PlacementBB);
439349cc55cSDimitry Andric     PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB);
440349cc55cSDimitry Andric     FollowBB->eraseFromParent();
441349cc55cSDimitry Andric   }
442e8d8bef9SDimitry Andric 
443e8d8bef9SDimitry Andric   PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB);
444e8d8bef9SDimitry Andric   StartBB->eraseFromParent();
445e8d8bef9SDimitry Andric 
446e8d8bef9SDimitry Andric   // Make sure to save changes back to the StartBB.
447e8d8bef9SDimitry Andric   StartBB = PrevBB;
448e8d8bef9SDimitry Andric   EndBB = nullptr;
449e8d8bef9SDimitry Andric   PrevBB = nullptr;
450e8d8bef9SDimitry Andric   FollowBB = nullptr;
451e8d8bef9SDimitry Andric 
452e8d8bef9SDimitry Andric   CandidateSplit = false;
453e8d8bef9SDimitry Andric }
454e8d8bef9SDimitry Andric 
455e8d8bef9SDimitry Andric /// Find whether \p V matches the Constants previously found for the \p GVN.
456e8d8bef9SDimitry Andric ///
457e8d8bef9SDimitry Andric /// \param V - The value to check for consistency.
458e8d8bef9SDimitry Andric /// \param GVN - The global value number assigned to \p V.
459e8d8bef9SDimitry Andric /// \param GVNToConstant - The mapping of global value number to Constants.
460e8d8bef9SDimitry Andric /// \returns true if the Value matches the Constant mapped to by V and false if
461e8d8bef9SDimitry Andric /// it \p V is a Constant but does not match.
462bdd1243dSDimitry Andric /// \returns std::nullopt if \p V is not a Constant.
463bdd1243dSDimitry Andric static std::optional<bool>
464e8d8bef9SDimitry Andric constantMatches(Value *V, unsigned GVN,
465e8d8bef9SDimitry Andric                 DenseMap<unsigned, Constant *> &GVNToConstant) {
466e8d8bef9SDimitry Andric   // See if we have a constants
467e8d8bef9SDimitry Andric   Constant *CST = dyn_cast<Constant>(V);
468e8d8bef9SDimitry Andric   if (!CST)
469bdd1243dSDimitry Andric     return std::nullopt;
470e8d8bef9SDimitry Andric 
471e8d8bef9SDimitry Andric   // Holds a mapping from a global value number to a Constant.
472e8d8bef9SDimitry Andric   DenseMap<unsigned, Constant *>::iterator GVNToConstantIt;
473e8d8bef9SDimitry Andric   bool Inserted;
474e8d8bef9SDimitry Andric 
475e8d8bef9SDimitry Andric 
476e8d8bef9SDimitry Andric   // If we have a constant, try to make a new entry in the GVNToConstant.
477e8d8bef9SDimitry Andric   std::tie(GVNToConstantIt, Inserted) =
478e8d8bef9SDimitry Andric       GVNToConstant.insert(std::make_pair(GVN, CST));
479e8d8bef9SDimitry Andric   // If it was found and is not equal, it is not the same. We do not
480e8d8bef9SDimitry Andric   // handle this case yet, and exit early.
481e8d8bef9SDimitry Andric   if (Inserted || (GVNToConstantIt->second == CST))
482e8d8bef9SDimitry Andric     return true;
483e8d8bef9SDimitry Andric 
484e8d8bef9SDimitry Andric   return false;
485e8d8bef9SDimitry Andric }
486e8d8bef9SDimitry Andric 
487e8d8bef9SDimitry Andric InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) {
488e8d8bef9SDimitry Andric   InstructionCost Benefit = 0;
489e8d8bef9SDimitry Andric 
490e8d8bef9SDimitry Andric   // Estimate the benefit of outlining a specific sections of the program.  We
491e8d8bef9SDimitry Andric   // delegate mostly this task to the TargetTransformInfo so that if the target
492e8d8bef9SDimitry Andric   // has specific changes, we can have a more accurate estimate.
493e8d8bef9SDimitry Andric 
494e8d8bef9SDimitry Andric   // However, getInstructionCost delegates the code size calculation for
495e8d8bef9SDimitry Andric   // arithmetic instructions to getArithmeticInstrCost in
496e8d8bef9SDimitry Andric   // include/Analysis/TargetTransformImpl.h, where it always estimates that the
497e8d8bef9SDimitry Andric   // code size for a division and remainder instruction to be equal to 4, and
498e8d8bef9SDimitry Andric   // everything else to 1.  This is not an accurate representation of the
499e8d8bef9SDimitry Andric   // division instruction for targets that have a native division instruction.
500e8d8bef9SDimitry Andric   // To be overly conservative, we only add 1 to the number of instructions for
501e8d8bef9SDimitry Andric   // each division instruction.
502349cc55cSDimitry Andric   for (IRInstructionData &ID : *Candidate) {
503349cc55cSDimitry Andric     Instruction *I = ID.Inst;
504349cc55cSDimitry Andric     switch (I->getOpcode()) {
505e8d8bef9SDimitry Andric     case Instruction::FDiv:
506e8d8bef9SDimitry Andric     case Instruction::FRem:
507e8d8bef9SDimitry Andric     case Instruction::SDiv:
508e8d8bef9SDimitry Andric     case Instruction::SRem:
509e8d8bef9SDimitry Andric     case Instruction::UDiv:
510e8d8bef9SDimitry Andric     case Instruction::URem:
511e8d8bef9SDimitry Andric       Benefit += 1;
512e8d8bef9SDimitry Andric       break;
513e8d8bef9SDimitry Andric     default:
514349cc55cSDimitry Andric       Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize);
515e8d8bef9SDimitry Andric       break;
516e8d8bef9SDimitry Andric     }
517e8d8bef9SDimitry Andric   }
518e8d8bef9SDimitry Andric 
519e8d8bef9SDimitry Andric   return Benefit;
520e8d8bef9SDimitry Andric }
521e8d8bef9SDimitry Andric 
52204eeddc0SDimitry Andric /// Check the \p OutputMappings structure for value \p Input, if it exists
52304eeddc0SDimitry Andric /// it has been used as an output for outlining, and has been renamed, and we
52404eeddc0SDimitry Andric /// return the new value, otherwise, we return the same value.
52504eeddc0SDimitry Andric ///
52604eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of values to their renamed value
52704eeddc0SDimitry Andric /// after being used as an output for an outlined region.
52804eeddc0SDimitry Andric /// \param Input [in] - The value to find the remapped value of, if it exists.
52904eeddc0SDimitry Andric /// \return The remapped value if it has been renamed, and the same value if has
53004eeddc0SDimitry Andric /// not.
53104eeddc0SDimitry Andric static Value *findOutputMapping(const DenseMap<Value *, Value *> OutputMappings,
53204eeddc0SDimitry Andric                                 Value *Input) {
53304eeddc0SDimitry Andric   DenseMap<Value *, Value *>::const_iterator OutputMapping =
53404eeddc0SDimitry Andric       OutputMappings.find(Input);
53504eeddc0SDimitry Andric   if (OutputMapping != OutputMappings.end())
53604eeddc0SDimitry Andric     return OutputMapping->second;
53704eeddc0SDimitry Andric   return Input;
53804eeddc0SDimitry Andric }
53904eeddc0SDimitry Andric 
540e8d8bef9SDimitry Andric /// Find whether \p Region matches the global value numbering to Constant
541e8d8bef9SDimitry Andric /// mapping found so far.
542e8d8bef9SDimitry Andric ///
543e8d8bef9SDimitry Andric /// \param Region - The OutlinableRegion we are checking for constants
544e8d8bef9SDimitry Andric /// \param GVNToConstant - The mapping of global value number to Constants.
545e8d8bef9SDimitry Andric /// \param NotSame - The set of global value numbers that do not have the same
546e8d8bef9SDimitry Andric /// constant in each region.
547e8d8bef9SDimitry Andric /// \returns true if all Constants are the same in every use of a Constant in \p
548e8d8bef9SDimitry Andric /// Region and false if not
549e8d8bef9SDimitry Andric static bool
550e8d8bef9SDimitry Andric collectRegionsConstants(OutlinableRegion &Region,
551e8d8bef9SDimitry Andric                         DenseMap<unsigned, Constant *> &GVNToConstant,
552e8d8bef9SDimitry Andric                         DenseSet<unsigned> &NotSame) {
553e8d8bef9SDimitry Andric   bool ConstantsTheSame = true;
554e8d8bef9SDimitry Andric 
555e8d8bef9SDimitry Andric   IRSimilarityCandidate &C = *Region.Candidate;
556e8d8bef9SDimitry Andric   for (IRInstructionData &ID : C) {
557e8d8bef9SDimitry Andric 
558e8d8bef9SDimitry Andric     // Iterate over the operands in an instruction. If the global value number,
559e8d8bef9SDimitry Andric     // assigned by the IRSimilarityCandidate, has been seen before, we check if
560*5f757f3fSDimitry Andric     // the number has been found to be not the same value in each instance.
561e8d8bef9SDimitry Andric     for (Value *V : ID.OperVals) {
562bdd1243dSDimitry Andric       std::optional<unsigned> GVNOpt = C.getGVN(V);
56381ad6265SDimitry Andric       assert(GVNOpt && "Expected a GVN for operand?");
564bdd1243dSDimitry Andric       unsigned GVN = *GVNOpt;
565e8d8bef9SDimitry Andric 
566e8d8bef9SDimitry Andric       // Check if this global value has been found to not be the same already.
567e8d8bef9SDimitry Andric       if (NotSame.contains(GVN)) {
568e8d8bef9SDimitry Andric         if (isa<Constant>(V))
569e8d8bef9SDimitry Andric           ConstantsTheSame = false;
570e8d8bef9SDimitry Andric         continue;
571e8d8bef9SDimitry Andric       }
572e8d8bef9SDimitry Andric 
573e8d8bef9SDimitry Andric       // If it has been the same so far, we check the value for if the
574e8d8bef9SDimitry Andric       // associated Constant value match the previous instances of the same
575e8d8bef9SDimitry Andric       // global value number.  If the global value does not map to a Constant,
576e8d8bef9SDimitry Andric       // it is considered to not be the same value.
577bdd1243dSDimitry Andric       std::optional<bool> ConstantMatches =
578bdd1243dSDimitry Andric           constantMatches(V, GVN, GVNToConstant);
57981ad6265SDimitry Andric       if (ConstantMatches) {
580bdd1243dSDimitry Andric         if (*ConstantMatches)
581e8d8bef9SDimitry Andric           continue;
582e8d8bef9SDimitry Andric         else
583e8d8bef9SDimitry Andric           ConstantsTheSame = false;
584e8d8bef9SDimitry Andric       }
585e8d8bef9SDimitry Andric 
586e8d8bef9SDimitry Andric       // While this value is a register, it might not have been previously,
587e8d8bef9SDimitry Andric       // make sure we don't already have a constant mapped to this global value
588e8d8bef9SDimitry Andric       // number.
58906c3fb27SDimitry Andric       if (GVNToConstant.contains(GVN))
590e8d8bef9SDimitry Andric         ConstantsTheSame = false;
591e8d8bef9SDimitry Andric 
592e8d8bef9SDimitry Andric       NotSame.insert(GVN);
593e8d8bef9SDimitry Andric     }
594e8d8bef9SDimitry Andric   }
595e8d8bef9SDimitry Andric 
596e8d8bef9SDimitry Andric   return ConstantsTheSame;
597e8d8bef9SDimitry Andric }
598e8d8bef9SDimitry Andric 
599e8d8bef9SDimitry Andric void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) {
600e8d8bef9SDimitry Andric   DenseMap<unsigned, Constant *> GVNToConstant;
601e8d8bef9SDimitry Andric 
602e8d8bef9SDimitry Andric   for (OutlinableRegion *Region : Regions)
603e8d8bef9SDimitry Andric     collectRegionsConstants(*Region, GVNToConstant, NotSame);
604e8d8bef9SDimitry Andric }
605e8d8bef9SDimitry Andric 
606e8d8bef9SDimitry Andric void OutlinableGroup::collectGVNStoreSets(Module &M) {
607e8d8bef9SDimitry Andric   for (OutlinableRegion *OS : Regions)
608e8d8bef9SDimitry Andric     OutputGVNCombinations.insert(OS->GVNStores);
609e8d8bef9SDimitry Andric 
610e8d8bef9SDimitry Andric   // We are adding an extracted argument to decide between which output path
611e8d8bef9SDimitry Andric   // to use in the basic block.  It is used in a switch statement and only
612e8d8bef9SDimitry Andric   // needs to be an integer.
613e8d8bef9SDimitry Andric   if (OutputGVNCombinations.size() > 1)
614e8d8bef9SDimitry Andric     ArgumentTypes.push_back(Type::getInt32Ty(M.getContext()));
615e8d8bef9SDimitry Andric }
616e8d8bef9SDimitry Andric 
617fe6060f1SDimitry Andric /// Get the subprogram if it exists for one of the outlined regions.
618fe6060f1SDimitry Andric ///
619fe6060f1SDimitry Andric /// \param [in] Group - The set of regions to find a subprogram for.
620fe6060f1SDimitry Andric /// \returns the subprogram if it exists, or nullptr.
621fe6060f1SDimitry Andric static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) {
622fe6060f1SDimitry Andric   for (OutlinableRegion *OS : Group.Regions)
623fe6060f1SDimitry Andric     if (Function *F = OS->Call->getFunction())
624fe6060f1SDimitry Andric       if (DISubprogram *SP = F->getSubprogram())
625fe6060f1SDimitry Andric         return SP;
626fe6060f1SDimitry Andric 
627fe6060f1SDimitry Andric   return nullptr;
628fe6060f1SDimitry Andric }
629fe6060f1SDimitry Andric 
630e8d8bef9SDimitry Andric Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,
631e8d8bef9SDimitry Andric                                      unsigned FunctionNameSuffix) {
632e8d8bef9SDimitry Andric   assert(!Group.OutlinedFunction && "Function is already defined!");
633e8d8bef9SDimitry Andric 
634349cc55cSDimitry Andric   Type *RetTy = Type::getVoidTy(M.getContext());
635349cc55cSDimitry Andric   // All extracted functions _should_ have the same return type at this point
636349cc55cSDimitry Andric   // since the similarity identifier ensures that all branches outside of the
637349cc55cSDimitry Andric   // region occur in the same place.
638349cc55cSDimitry Andric 
639349cc55cSDimitry Andric   // NOTE: Should we ever move to the model that uses a switch at every point
640349cc55cSDimitry Andric   // needed, meaning that we could branch within the region or out, it is
641349cc55cSDimitry Andric   // possible that we will need to switch to using the most general case all of
642349cc55cSDimitry Andric   // the time.
643349cc55cSDimitry Andric   for (OutlinableRegion *R : Group.Regions) {
644349cc55cSDimitry Andric     Type *ExtractedFuncType = R->ExtractedFunction->getReturnType();
645349cc55cSDimitry Andric     if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) ||
646349cc55cSDimitry Andric         (RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16)))
647349cc55cSDimitry Andric       RetTy = ExtractedFuncType;
648349cc55cSDimitry Andric   }
649349cc55cSDimitry Andric 
650e8d8bef9SDimitry Andric   Group.OutlinedFunctionType = FunctionType::get(
651349cc55cSDimitry Andric       RetTy, Group.ArgumentTypes, false);
652e8d8bef9SDimitry Andric 
653e8d8bef9SDimitry Andric   // These functions will only be called from within the same module, so
654e8d8bef9SDimitry Andric   // we can set an internal linkage.
655e8d8bef9SDimitry Andric   Group.OutlinedFunction = Function::Create(
656e8d8bef9SDimitry Andric       Group.OutlinedFunctionType, GlobalValue::InternalLinkage,
657e8d8bef9SDimitry Andric       "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);
658e8d8bef9SDimitry Andric 
659e8d8bef9SDimitry Andric   // Transfer the swifterr attribute to the correct function parameter.
66081ad6265SDimitry Andric   if (Group.SwiftErrorArgument)
661bdd1243dSDimitry Andric     Group.OutlinedFunction->addParamAttr(*Group.SwiftErrorArgument,
662e8d8bef9SDimitry Andric                                          Attribute::SwiftError);
663e8d8bef9SDimitry Andric 
664e8d8bef9SDimitry Andric   Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);
665e8d8bef9SDimitry Andric   Group.OutlinedFunction->addFnAttr(Attribute::MinSize);
666e8d8bef9SDimitry Andric 
667fe6060f1SDimitry Andric   // If there's a DISubprogram associated with this outlined function, then
668fe6060f1SDimitry Andric   // emit debug info for the outlined function.
669fe6060f1SDimitry Andric   if (DISubprogram *SP = getSubprogramOrNull(Group)) {
670fe6060f1SDimitry Andric     Function *F = Group.OutlinedFunction;
671fe6060f1SDimitry Andric     // We have a DISubprogram. Get its DICompileUnit.
672fe6060f1SDimitry Andric     DICompileUnit *CU = SP->getUnit();
673fe6060f1SDimitry Andric     DIBuilder DB(M, true, CU);
674fe6060f1SDimitry Andric     DIFile *Unit = SP->getFile();
675fe6060f1SDimitry Andric     Mangler Mg;
676fe6060f1SDimitry Andric     // Get the mangled name of the function for the linkage name.
677fe6060f1SDimitry Andric     std::string Dummy;
678fe6060f1SDimitry Andric     llvm::raw_string_ostream MangledNameStream(Dummy);
679fe6060f1SDimitry Andric     Mg.getNameWithPrefix(MangledNameStream, F, false);
680fe6060f1SDimitry Andric 
681fe6060f1SDimitry Andric     DISubprogram *OutlinedSP = DB.createFunction(
682fe6060f1SDimitry Andric         Unit /* Context */, F->getName(), MangledNameStream.str(),
683fe6060f1SDimitry Andric         Unit /* File */,
684fe6060f1SDimitry Andric         0 /* Line 0 is reserved for compiler-generated code. */,
685bdd1243dSDimitry Andric         DB.createSubroutineType(
686bdd1243dSDimitry Andric             DB.getOrCreateTypeArray(std::nullopt)), /* void type */
687fe6060f1SDimitry Andric         0, /* Line 0 is reserved for compiler-generated code. */
688fe6060f1SDimitry Andric         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
689fe6060f1SDimitry Andric         /* Outlined code is optimized code by definition. */
690fe6060f1SDimitry Andric         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
691fe6060f1SDimitry Andric 
692fe6060f1SDimitry Andric     // Don't add any new variables to the subprogram.
693fe6060f1SDimitry Andric     DB.finalizeSubprogram(OutlinedSP);
694fe6060f1SDimitry Andric 
695fe6060f1SDimitry Andric     // Attach subprogram to the function.
696fe6060f1SDimitry Andric     F->setSubprogram(OutlinedSP);
697fe6060f1SDimitry Andric     // We're done with the DIBuilder.
698fe6060f1SDimitry Andric     DB.finalize();
699fe6060f1SDimitry Andric   }
700fe6060f1SDimitry Andric 
701e8d8bef9SDimitry Andric   return Group.OutlinedFunction;
702e8d8bef9SDimitry Andric }
703e8d8bef9SDimitry Andric 
704e8d8bef9SDimitry Andric /// Move each BasicBlock in \p Old to \p New.
705e8d8bef9SDimitry Andric ///
706fe6060f1SDimitry Andric /// \param [in] Old - The function to move the basic blocks from.
707e8d8bef9SDimitry Andric /// \param [in] New - The function to move the basic blocks to.
708349cc55cSDimitry Andric /// \param [out] NewEnds - The return blocks of the new overall function.
709349cc55cSDimitry Andric static void moveFunctionData(Function &Old, Function &New,
710349cc55cSDimitry Andric                              DenseMap<Value *, BasicBlock *> &NewEnds) {
711349cc55cSDimitry Andric   for (BasicBlock &CurrBB : llvm::make_early_inc_range(Old)) {
712349cc55cSDimitry Andric     CurrBB.removeFromParent();
713349cc55cSDimitry Andric     CurrBB.insertInto(&New);
714349cc55cSDimitry Andric     Instruction *I = CurrBB.getTerminator();
715fe6060f1SDimitry Andric 
716349cc55cSDimitry Andric     // For each block we find a return instruction is, it is a potential exit
717349cc55cSDimitry Andric     // path for the function.  We keep track of each block based on the return
718349cc55cSDimitry Andric     // value here.
719349cc55cSDimitry Andric     if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
720349cc55cSDimitry Andric       NewEnds.insert(std::make_pair(RI->getReturnValue(), &CurrBB));
721349cc55cSDimitry Andric 
722349cc55cSDimitry Andric     std::vector<Instruction *> DebugInsts;
723349cc55cSDimitry Andric 
724349cc55cSDimitry Andric     for (Instruction &Val : CurrBB) {
725fe6060f1SDimitry Andric       // We must handle the scoping of called functions differently than
726fe6060f1SDimitry Andric       // other outlined instructions.
727fe6060f1SDimitry Andric       if (!isa<CallInst>(&Val)) {
728fe6060f1SDimitry Andric         // Remove the debug information for outlined functions.
729fe6060f1SDimitry Andric         Val.setDebugLoc(DebugLoc());
73081ad6265SDimitry Andric 
73181ad6265SDimitry Andric         // Loop info metadata may contain line locations. Update them to have no
73281ad6265SDimitry Andric         // value in the new subprogram since the outlined code could be from
73381ad6265SDimitry Andric         // several locations.
73481ad6265SDimitry Andric         auto updateLoopInfoLoc = [&New](Metadata *MD) -> Metadata * {
73581ad6265SDimitry Andric           if (DISubprogram *SP = New.getSubprogram())
73681ad6265SDimitry Andric             if (auto *Loc = dyn_cast_or_null<DILocation>(MD))
73781ad6265SDimitry Andric               return DILocation::get(New.getContext(), Loc->getLine(),
73881ad6265SDimitry Andric                                      Loc->getColumn(), SP, nullptr);
73981ad6265SDimitry Andric           return MD;
74081ad6265SDimitry Andric         };
74181ad6265SDimitry Andric         updateLoopMetadataDebugLocations(Val, updateLoopInfoLoc);
742fe6060f1SDimitry Andric         continue;
743fe6060f1SDimitry Andric       }
744fe6060f1SDimitry Andric 
745fe6060f1SDimitry Andric       // From this point we are only handling call instructions.
746fe6060f1SDimitry Andric       CallInst *CI = cast<CallInst>(&Val);
747fe6060f1SDimitry Andric 
748fe6060f1SDimitry Andric       // We add any debug statements here, to be removed after.  Since the
749fe6060f1SDimitry Andric       // instructions originate from many different locations in the program,
750fe6060f1SDimitry Andric       // it will cause incorrect reporting from a debugger if we keep the
751fe6060f1SDimitry Andric       // same debug instructions.
752fe6060f1SDimitry Andric       if (isa<DbgInfoIntrinsic>(CI)) {
753fe6060f1SDimitry Andric         DebugInsts.push_back(&Val);
754fe6060f1SDimitry Andric         continue;
755fe6060f1SDimitry Andric       }
756fe6060f1SDimitry Andric 
757fe6060f1SDimitry Andric       // Edit the scope of called functions inside of outlined functions.
758fe6060f1SDimitry Andric       if (DISubprogram *SP = New.getSubprogram()) {
759fe6060f1SDimitry Andric         DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP);
760fe6060f1SDimitry Andric         Val.setDebugLoc(DI);
761fe6060f1SDimitry Andric       }
762fe6060f1SDimitry Andric     }
763fe6060f1SDimitry Andric 
764fe6060f1SDimitry Andric     for (Instruction *I : DebugInsts)
765fe6060f1SDimitry Andric       I->eraseFromParent();
766e8d8bef9SDimitry Andric   }
767e8d8bef9SDimitry Andric }
768e8d8bef9SDimitry Andric 
769*5f757f3fSDimitry Andric /// Find the constants that will need to be lifted into arguments
770e8d8bef9SDimitry Andric /// as they are not the same in each instance of the region.
771e8d8bef9SDimitry Andric ///
772e8d8bef9SDimitry Andric /// \param [in] C - The IRSimilarityCandidate containing the region we are
773e8d8bef9SDimitry Andric /// analyzing.
774e8d8bef9SDimitry Andric /// \param [in] NotSame - The set of global value numbers that do not have a
775e8d8bef9SDimitry Andric /// single Constant across all OutlinableRegions similar to \p C.
776e8d8bef9SDimitry Andric /// \param [out] Inputs - The list containing the global value numbers of the
777e8d8bef9SDimitry Andric /// arguments needed for the region of code.
778e8d8bef9SDimitry Andric static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame,
779e8d8bef9SDimitry Andric                           std::vector<unsigned> &Inputs) {
780e8d8bef9SDimitry Andric   DenseSet<unsigned> Seen;
781e8d8bef9SDimitry Andric   // Iterate over the instructions, and find what constants will need to be
782e8d8bef9SDimitry Andric   // extracted into arguments.
783e8d8bef9SDimitry Andric   for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end();
784e8d8bef9SDimitry Andric        IDIt != EndIDIt; IDIt++) {
785e8d8bef9SDimitry Andric     for (Value *V : (*IDIt).OperVals) {
786e8d8bef9SDimitry Andric       // Since these are stored before any outlining, they will be in the
787e8d8bef9SDimitry Andric       // global value numbering.
78881ad6265SDimitry Andric       unsigned GVN = *C.getGVN(V);
789e8d8bef9SDimitry Andric       if (isa<Constant>(V))
790e8d8bef9SDimitry Andric         if (NotSame.contains(GVN) && !Seen.contains(GVN)) {
791e8d8bef9SDimitry Andric           Inputs.push_back(GVN);
792e8d8bef9SDimitry Andric           Seen.insert(GVN);
793e8d8bef9SDimitry Andric         }
794e8d8bef9SDimitry Andric     }
795e8d8bef9SDimitry Andric   }
796e8d8bef9SDimitry Andric }
797e8d8bef9SDimitry Andric 
798e8d8bef9SDimitry Andric /// Find the GVN for the inputs that have been found by the CodeExtractor.
799e8d8bef9SDimitry Andric ///
800e8d8bef9SDimitry Andric /// \param [in] C - The IRSimilarityCandidate containing the region we are
801e8d8bef9SDimitry Andric /// analyzing.
802e8d8bef9SDimitry Andric /// \param [in] CurrentInputs - The set of inputs found by the
803e8d8bef9SDimitry Andric /// CodeExtractor.
804e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced
805e8d8bef9SDimitry Andric /// by a new output value.
806fe6060f1SDimitry Andric /// \param [out] EndInputNumbers - The global value numbers for the extracted
807e8d8bef9SDimitry Andric /// arguments.
808e8d8bef9SDimitry Andric static void mapInputsToGVNs(IRSimilarityCandidate &C,
809e8d8bef9SDimitry Andric                             SetVector<Value *> &CurrentInputs,
810e8d8bef9SDimitry Andric                             const DenseMap<Value *, Value *> &OutputMappings,
811e8d8bef9SDimitry Andric                             std::vector<unsigned> &EndInputNumbers) {
812e8d8bef9SDimitry Andric   // Get the Global Value Number for each input.  We check if the Value has been
813e8d8bef9SDimitry Andric   // replaced by a different value at output, and use the original value before
814e8d8bef9SDimitry Andric   // replacement.
815e8d8bef9SDimitry Andric   for (Value *Input : CurrentInputs) {
816e8d8bef9SDimitry Andric     assert(Input && "Have a nullptr as an input");
81706c3fb27SDimitry Andric     if (OutputMappings.contains(Input))
818e8d8bef9SDimitry Andric       Input = OutputMappings.find(Input)->second;
81981ad6265SDimitry Andric     assert(C.getGVN(Input) && "Could not find a numbering for the given input");
820bdd1243dSDimitry Andric     EndInputNumbers.push_back(*C.getGVN(Input));
821e8d8bef9SDimitry Andric   }
822e8d8bef9SDimitry Andric }
823e8d8bef9SDimitry Andric 
824e8d8bef9SDimitry Andric /// Find the original value for the \p ArgInput values if any one of them was
825e8d8bef9SDimitry Andric /// replaced during a previous extraction.
826e8d8bef9SDimitry Andric ///
827e8d8bef9SDimitry Andric /// \param [in] ArgInputs - The inputs to be extracted by the code extractor.
828e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced
829e8d8bef9SDimitry Andric /// by a new output value.
830e8d8bef9SDimitry Andric /// \param [out] RemappedArgInputs - The remapped values according to
831e8d8bef9SDimitry Andric /// \p OutputMappings that will be extracted.
832e8d8bef9SDimitry Andric static void
833e8d8bef9SDimitry Andric remapExtractedInputs(const ArrayRef<Value *> ArgInputs,
834e8d8bef9SDimitry Andric                      const DenseMap<Value *, Value *> &OutputMappings,
835e8d8bef9SDimitry Andric                      SetVector<Value *> &RemappedArgInputs) {
836e8d8bef9SDimitry Andric   // Get the global value number for each input that will be extracted as an
837e8d8bef9SDimitry Andric   // argument by the code extractor, remapping if needed for reloaded values.
838e8d8bef9SDimitry Andric   for (Value *Input : ArgInputs) {
83906c3fb27SDimitry Andric     if (OutputMappings.contains(Input))
840e8d8bef9SDimitry Andric       Input = OutputMappings.find(Input)->second;
841e8d8bef9SDimitry Andric     RemappedArgInputs.insert(Input);
842e8d8bef9SDimitry Andric   }
843e8d8bef9SDimitry Andric }
844e8d8bef9SDimitry Andric 
845e8d8bef9SDimitry Andric /// Find the input GVNs and the output values for a region of Instructions.
846e8d8bef9SDimitry Andric /// Using the code extractor, we collect the inputs to the extracted function.
847e8d8bef9SDimitry Andric ///
848e8d8bef9SDimitry Andric /// The \p Region can be identified as needing to be ignored in this function.
849e8d8bef9SDimitry Andric /// It should be checked whether it should be ignored after a call to this
850e8d8bef9SDimitry Andric /// function.
851e8d8bef9SDimitry Andric ///
852e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed.
853e8d8bef9SDimitry Andric /// \param [out] InputGVNs - The global value numbers for the extracted
854e8d8bef9SDimitry Andric /// arguments.
855e8d8bef9SDimitry Andric /// \param [in] NotSame - The global value numbers in the region that do not
856e8d8bef9SDimitry Andric /// have the same constant value in the regions structurally similar to
857e8d8bef9SDimitry Andric /// \p Region.
858e8d8bef9SDimitry Andric /// \param [in] OutputMappings - The mapping of values that have been replaced
859e8d8bef9SDimitry Andric /// by a new output value after extraction.
860e8d8bef9SDimitry Andric /// \param [out] ArgInputs - The values of the inputs to the extracted function.
861e8d8bef9SDimitry Andric /// \param [out] Outputs - The set of values extracted by the CodeExtractor
862e8d8bef9SDimitry Andric /// as outputs.
863e8d8bef9SDimitry Andric static void getCodeExtractorArguments(
864e8d8bef9SDimitry Andric     OutlinableRegion &Region, std::vector<unsigned> &InputGVNs,
865e8d8bef9SDimitry Andric     DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings,
866e8d8bef9SDimitry Andric     SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) {
867e8d8bef9SDimitry Andric   IRSimilarityCandidate &C = *Region.Candidate;
868e8d8bef9SDimitry Andric 
869e8d8bef9SDimitry Andric   // OverallInputs are the inputs to the region found by the CodeExtractor,
870e8d8bef9SDimitry Andric   // SinkCands and HoistCands are used by the CodeExtractor to find sunken
871e8d8bef9SDimitry Andric   // allocas of values whose lifetimes are contained completely within the
872e8d8bef9SDimitry Andric   // outlined region. PremappedInputs are the arguments found by the
873e8d8bef9SDimitry Andric   // CodeExtractor, removing conditions such as sunken allocas, but that
874e8d8bef9SDimitry Andric   // may need to be remapped due to the extracted output values replacing
875e8d8bef9SDimitry Andric   // the original values. We use DummyOutputs for this first run of finding
876e8d8bef9SDimitry Andric   // inputs and outputs since the outputs could change during findAllocas,
877e8d8bef9SDimitry Andric   // the correct set of extracted outputs will be in the final Outputs ValueSet.
878e8d8bef9SDimitry Andric   SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands,
879e8d8bef9SDimitry Andric       DummyOutputs;
880e8d8bef9SDimitry Andric 
881e8d8bef9SDimitry Andric   // Use the code extractor to get the inputs and outputs, without sunken
882e8d8bef9SDimitry Andric   // allocas or removing llvm.assumes.
883e8d8bef9SDimitry Andric   CodeExtractor *CE = Region.CE;
884e8d8bef9SDimitry Andric   CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands);
885e8d8bef9SDimitry Andric   assert(Region.StartBB && "Region must have a start BasicBlock!");
886e8d8bef9SDimitry Andric   Function *OrigF = Region.StartBB->getParent();
887e8d8bef9SDimitry Andric   CodeExtractorAnalysisCache CEAC(*OrigF);
888e8d8bef9SDimitry Andric   BasicBlock *Dummy = nullptr;
889e8d8bef9SDimitry Andric 
890e8d8bef9SDimitry Andric   // The region may be ineligible due to VarArgs in the parent function. In this
891e8d8bef9SDimitry Andric   // case we ignore the region.
892e8d8bef9SDimitry Andric   if (!CE->isEligible()) {
893e8d8bef9SDimitry Andric     Region.IgnoreRegion = true;
894e8d8bef9SDimitry Andric     return;
895e8d8bef9SDimitry Andric   }
896e8d8bef9SDimitry Andric 
897e8d8bef9SDimitry Andric   // Find if any values are going to be sunk into the function when extracted
898e8d8bef9SDimitry Andric   CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy);
899e8d8bef9SDimitry Andric   CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands);
900e8d8bef9SDimitry Andric 
901e8d8bef9SDimitry Andric   // TODO: Support regions with sunken allocas: values whose lifetimes are
902e8d8bef9SDimitry Andric   // contained completely within the outlined region.  These are not guaranteed
903e8d8bef9SDimitry Andric   // to be the same in every region, so we must elevate them all to arguments
904e8d8bef9SDimitry Andric   // when they appear.  If these values are not equal, it means there is some
905e8d8bef9SDimitry Andric   // Input in OverallInputs that was removed for ArgInputs.
906e8d8bef9SDimitry Andric   if (OverallInputs.size() != PremappedInputs.size()) {
907e8d8bef9SDimitry Andric     Region.IgnoreRegion = true;
908e8d8bef9SDimitry Andric     return;
909e8d8bef9SDimitry Andric   }
910e8d8bef9SDimitry Andric 
911e8d8bef9SDimitry Andric   findConstants(C, NotSame, InputGVNs);
912e8d8bef9SDimitry Andric 
913e8d8bef9SDimitry Andric   mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs);
914e8d8bef9SDimitry Andric 
915e8d8bef9SDimitry Andric   remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings,
916e8d8bef9SDimitry Andric                        ArgInputs);
917e8d8bef9SDimitry Andric 
918e8d8bef9SDimitry Andric   // Sort the GVNs, since we now have constants included in the \ref InputGVNs
919e8d8bef9SDimitry Andric   // we need to make sure they are in a deterministic order.
920e8d8bef9SDimitry Andric   stable_sort(InputGVNs);
921e8d8bef9SDimitry Andric }
922e8d8bef9SDimitry Andric 
923e8d8bef9SDimitry Andric /// Look over the inputs and map each input argument to an argument in the
924e8d8bef9SDimitry Andric /// overall function for the OutlinableRegions.  This creates a way to replace
925e8d8bef9SDimitry Andric /// the arguments of the extracted function with the arguments of the new
926e8d8bef9SDimitry Andric /// overall function.
927e8d8bef9SDimitry Andric ///
928e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed.
929fe6060f1SDimitry Andric /// \param [in] InputGVNs - The global value numbering of the input values
930e8d8bef9SDimitry Andric /// collected.
931e8d8bef9SDimitry Andric /// \param [in] ArgInputs - The values of the arguments to the extracted
932e8d8bef9SDimitry Andric /// function.
933e8d8bef9SDimitry Andric static void
934e8d8bef9SDimitry Andric findExtractedInputToOverallInputMapping(OutlinableRegion &Region,
935e8d8bef9SDimitry Andric                                         std::vector<unsigned> &InputGVNs,
936e8d8bef9SDimitry Andric                                         SetVector<Value *> &ArgInputs) {
937e8d8bef9SDimitry Andric 
938e8d8bef9SDimitry Andric   IRSimilarityCandidate &C = *Region.Candidate;
939e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
940e8d8bef9SDimitry Andric 
941e8d8bef9SDimitry Andric   // This counts the argument number in the overall function.
942e8d8bef9SDimitry Andric   unsigned TypeIndex = 0;
943e8d8bef9SDimitry Andric 
944e8d8bef9SDimitry Andric   // This counts the argument number in the extracted function.
945e8d8bef9SDimitry Andric   unsigned OriginalIndex = 0;
946e8d8bef9SDimitry Andric 
947e8d8bef9SDimitry Andric   // Find the mapping of the extracted arguments to the arguments for the
948e8d8bef9SDimitry Andric   // overall function. Since there may be extra arguments in the overall
949e8d8bef9SDimitry Andric   // function to account for the extracted constants, we have two different
950e8d8bef9SDimitry Andric   // counters as we find extracted arguments, and as we come across overall
951e8d8bef9SDimitry Andric   // arguments.
952349cc55cSDimitry Andric 
953349cc55cSDimitry Andric   // Additionally, in our first pass, for the first extracted function,
954349cc55cSDimitry Andric   // we find argument locations for the canonical value numbering.  This
955349cc55cSDimitry Andric   // numbering overrides any discovered location for the extracted code.
956e8d8bef9SDimitry Andric   for (unsigned InputVal : InputGVNs) {
957bdd1243dSDimitry Andric     std::optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);
95881ad6265SDimitry Andric     assert(CanonicalNumberOpt && "Canonical number not found?");
959bdd1243dSDimitry Andric     unsigned CanonicalNumber = *CanonicalNumberOpt;
960349cc55cSDimitry Andric 
961bdd1243dSDimitry Andric     std::optional<Value *> InputOpt = C.fromGVN(InputVal);
96281ad6265SDimitry Andric     assert(InputOpt && "Global value number not found?");
963bdd1243dSDimitry Andric     Value *Input = *InputOpt;
964e8d8bef9SDimitry Andric 
965349cc55cSDimitry Andric     DenseMap<unsigned, unsigned>::iterator AggArgIt =
966349cc55cSDimitry Andric         Group.CanonicalNumberToAggArg.find(CanonicalNumber);
967349cc55cSDimitry Andric 
968e8d8bef9SDimitry Andric     if (!Group.InputTypesSet) {
969e8d8bef9SDimitry Andric       Group.ArgumentTypes.push_back(Input->getType());
970e8d8bef9SDimitry Andric       // If the input value has a swifterr attribute, make sure to mark the
971e8d8bef9SDimitry Andric       // argument in the overall function.
972e8d8bef9SDimitry Andric       if (Input->isSwiftError()) {
973e8d8bef9SDimitry Andric         assert(
97481ad6265SDimitry Andric             !Group.SwiftErrorArgument &&
975e8d8bef9SDimitry Andric             "Argument already marked with swifterr for this OutlinableGroup!");
976e8d8bef9SDimitry Andric         Group.SwiftErrorArgument = TypeIndex;
977e8d8bef9SDimitry Andric       }
978e8d8bef9SDimitry Andric     }
979e8d8bef9SDimitry Andric 
980e8d8bef9SDimitry Andric     // Check if we have a constant. If we do add it to the overall argument
981e8d8bef9SDimitry Andric     // number to Constant map for the region, and continue to the next input.
982e8d8bef9SDimitry Andric     if (Constant *CST = dyn_cast<Constant>(Input)) {
983349cc55cSDimitry Andric       if (AggArgIt != Group.CanonicalNumberToAggArg.end())
984349cc55cSDimitry Andric         Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST));
985349cc55cSDimitry Andric       else {
986349cc55cSDimitry Andric         Group.CanonicalNumberToAggArg.insert(
987349cc55cSDimitry Andric             std::make_pair(CanonicalNumber, TypeIndex));
988e8d8bef9SDimitry Andric         Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST));
989349cc55cSDimitry Andric       }
990e8d8bef9SDimitry Andric       TypeIndex++;
991e8d8bef9SDimitry Andric       continue;
992e8d8bef9SDimitry Andric     }
993e8d8bef9SDimitry Andric 
994e8d8bef9SDimitry Andric     // It is not a constant, we create the mapping from extracted argument list
995349cc55cSDimitry Andric     // to the overall argument list, using the canonical location, if it exists.
996e8d8bef9SDimitry Andric     assert(ArgInputs.count(Input) && "Input cannot be found!");
997e8d8bef9SDimitry Andric 
998349cc55cSDimitry Andric     if (AggArgIt != Group.CanonicalNumberToAggArg.end()) {
999349cc55cSDimitry Andric       if (OriginalIndex != AggArgIt->second)
1000349cc55cSDimitry Andric         Region.ChangedArgOrder = true;
1001349cc55cSDimitry Andric       Region.ExtractedArgToAgg.insert(
1002349cc55cSDimitry Andric           std::make_pair(OriginalIndex, AggArgIt->second));
1003349cc55cSDimitry Andric       Region.AggArgToExtracted.insert(
1004349cc55cSDimitry Andric           std::make_pair(AggArgIt->second, OriginalIndex));
1005349cc55cSDimitry Andric     } else {
1006349cc55cSDimitry Andric       Group.CanonicalNumberToAggArg.insert(
1007349cc55cSDimitry Andric           std::make_pair(CanonicalNumber, TypeIndex));
1008e8d8bef9SDimitry Andric       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex));
1009e8d8bef9SDimitry Andric       Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex));
1010349cc55cSDimitry Andric     }
1011e8d8bef9SDimitry Andric     OriginalIndex++;
1012e8d8bef9SDimitry Andric     TypeIndex++;
1013e8d8bef9SDimitry Andric   }
1014e8d8bef9SDimitry Andric 
1015e8d8bef9SDimitry Andric   // If the function type definitions for the OutlinableGroup holding the region
1016e8d8bef9SDimitry Andric   // have not been set, set the length of the inputs here.  We should have the
1017e8d8bef9SDimitry Andric   // same inputs for all of the different regions contained in the
1018e8d8bef9SDimitry Andric   // OutlinableGroup since they are all structurally similar to one another.
1019e8d8bef9SDimitry Andric   if (!Group.InputTypesSet) {
1020e8d8bef9SDimitry Andric     Group.NumAggregateInputs = TypeIndex;
1021e8d8bef9SDimitry Andric     Group.InputTypesSet = true;
1022e8d8bef9SDimitry Andric   }
1023e8d8bef9SDimitry Andric 
1024e8d8bef9SDimitry Andric   Region.NumExtractedInputs = OriginalIndex;
1025e8d8bef9SDimitry Andric }
1026e8d8bef9SDimitry Andric 
102704eeddc0SDimitry Andric /// Check if the \p V has any uses outside of the region other than \p PN.
102804eeddc0SDimitry Andric ///
102904eeddc0SDimitry Andric /// \param V [in] - The value to check.
103004eeddc0SDimitry Andric /// \param PHILoc [in] - The location in the PHINode of \p V.
103104eeddc0SDimitry Andric /// \param PN [in] - The PHINode using \p V.
103204eeddc0SDimitry Andric /// \param Exits [in] - The potential blocks we exit to from the outlined
103304eeddc0SDimitry Andric /// region.
103404eeddc0SDimitry Andric /// \param BlocksInRegion [in] - The basic blocks contained in the region.
103504eeddc0SDimitry Andric /// \returns true if \p V has any use soutside its region other than \p PN.
103604eeddc0SDimitry Andric static bool outputHasNonPHI(Value *V, unsigned PHILoc, PHINode &PN,
103704eeddc0SDimitry Andric                             SmallPtrSet<BasicBlock *, 1> &Exits,
103804eeddc0SDimitry Andric                             DenseSet<BasicBlock *> &BlocksInRegion) {
103904eeddc0SDimitry Andric   // We check to see if the value is used by the PHINode from some other
104004eeddc0SDimitry Andric   // predecessor not included in the region.  If it is, we make sure
104104eeddc0SDimitry Andric   // to keep it as an output.
104281ad6265SDimitry Andric   if (any_of(llvm::seq<unsigned>(0, PN.getNumIncomingValues()),
104381ad6265SDimitry Andric              [PHILoc, &PN, V, &BlocksInRegion](unsigned Idx) {
104404eeddc0SDimitry Andric                return (Idx != PHILoc && V == PN.getIncomingValue(Idx) &&
104504eeddc0SDimitry Andric                        !BlocksInRegion.contains(PN.getIncomingBlock(Idx)));
104604eeddc0SDimitry Andric              }))
104704eeddc0SDimitry Andric     return true;
104804eeddc0SDimitry Andric 
104904eeddc0SDimitry Andric   // Check if the value is used by any other instructions outside the region.
105004eeddc0SDimitry Andric   return any_of(V->users(), [&Exits, &BlocksInRegion](User *U) {
105104eeddc0SDimitry Andric     Instruction *I = dyn_cast<Instruction>(U);
105204eeddc0SDimitry Andric     if (!I)
105304eeddc0SDimitry Andric       return false;
105404eeddc0SDimitry Andric 
105504eeddc0SDimitry Andric     // If the use of the item is inside the region, we skip it.  Uses
105604eeddc0SDimitry Andric     // inside the region give us useful information about how the item could be
105704eeddc0SDimitry Andric     // used as an output.
105804eeddc0SDimitry Andric     BasicBlock *Parent = I->getParent();
105904eeddc0SDimitry Andric     if (BlocksInRegion.contains(Parent))
106004eeddc0SDimitry Andric       return false;
106104eeddc0SDimitry Andric 
106204eeddc0SDimitry Andric     // If it's not a PHINode then we definitely know the use matters.  This
106304eeddc0SDimitry Andric     // output value will not completely combined with another item in a PHINode
106404eeddc0SDimitry Andric     // as it is directly reference by another non-phi instruction
106504eeddc0SDimitry Andric     if (!isa<PHINode>(I))
106604eeddc0SDimitry Andric       return true;
106704eeddc0SDimitry Andric 
106804eeddc0SDimitry Andric     // If we have a PHINode outside one of the exit locations, then it
106904eeddc0SDimitry Andric     // can be considered an outside use as well.  If there is a PHINode
107004eeddc0SDimitry Andric     // contained in the Exit where this values use matters, it will be
107104eeddc0SDimitry Andric     // caught when we analyze that PHINode.
107204eeddc0SDimitry Andric     if (!Exits.contains(Parent))
107304eeddc0SDimitry Andric       return true;
107404eeddc0SDimitry Andric 
107504eeddc0SDimitry Andric     return false;
107604eeddc0SDimitry Andric   });
107704eeddc0SDimitry Andric }
107804eeddc0SDimitry Andric 
107904eeddc0SDimitry Andric /// Test whether \p CurrentExitFromRegion contains any PhiNodes that should be
108004eeddc0SDimitry Andric /// considered outputs. A PHINodes is an output when more than one incoming
108104eeddc0SDimitry Andric /// value has been marked by the CodeExtractor as an output.
108204eeddc0SDimitry Andric ///
108304eeddc0SDimitry Andric /// \param CurrentExitFromRegion [in] - The block to analyze.
108404eeddc0SDimitry Andric /// \param PotentialExitsFromRegion [in] - The potential exit blocks from the
108504eeddc0SDimitry Andric /// region.
108604eeddc0SDimitry Andric /// \param RegionBlocks [in] - The basic blocks in the region.
108704eeddc0SDimitry Andric /// \param Outputs [in, out] - The existing outputs for the region, we may add
108804eeddc0SDimitry Andric /// PHINodes to this as we find that they replace output values.
108904eeddc0SDimitry Andric /// \param OutputsReplacedByPHINode [out] - A set containing outputs that are
109004eeddc0SDimitry Andric /// totally replaced  by a PHINode.
109104eeddc0SDimitry Andric /// \param OutputsWithNonPhiUses [out] - A set containing outputs that are used
109204eeddc0SDimitry Andric /// in PHINodes, but have other uses, and should still be considered outputs.
109304eeddc0SDimitry Andric static void analyzeExitPHIsForOutputUses(
109404eeddc0SDimitry Andric     BasicBlock *CurrentExitFromRegion,
109504eeddc0SDimitry Andric     SmallPtrSet<BasicBlock *, 1> &PotentialExitsFromRegion,
109604eeddc0SDimitry Andric     DenseSet<BasicBlock *> &RegionBlocks, SetVector<Value *> &Outputs,
109704eeddc0SDimitry Andric     DenseSet<Value *> &OutputsReplacedByPHINode,
109804eeddc0SDimitry Andric     DenseSet<Value *> &OutputsWithNonPhiUses) {
109904eeddc0SDimitry Andric   for (PHINode &PN : CurrentExitFromRegion->phis()) {
110004eeddc0SDimitry Andric     // Find all incoming values from the outlining region.
110104eeddc0SDimitry Andric     SmallVector<unsigned, 2> IncomingVals;
110204eeddc0SDimitry Andric     for (unsigned I = 0, E = PN.getNumIncomingValues(); I < E; ++I)
110304eeddc0SDimitry Andric       if (RegionBlocks.contains(PN.getIncomingBlock(I)))
110404eeddc0SDimitry Andric         IncomingVals.push_back(I);
110504eeddc0SDimitry Andric 
110604eeddc0SDimitry Andric     // Do not process PHI if there are no predecessors from region.
110704eeddc0SDimitry Andric     unsigned NumIncomingVals = IncomingVals.size();
110804eeddc0SDimitry Andric     if (NumIncomingVals == 0)
110904eeddc0SDimitry Andric       continue;
111004eeddc0SDimitry Andric 
111104eeddc0SDimitry Andric     // If there is one predecessor, we mark it as a value that needs to be kept
111204eeddc0SDimitry Andric     // as an output.
111304eeddc0SDimitry Andric     if (NumIncomingVals == 1) {
111404eeddc0SDimitry Andric       Value *V = PN.getIncomingValue(*IncomingVals.begin());
111504eeddc0SDimitry Andric       OutputsWithNonPhiUses.insert(V);
111604eeddc0SDimitry Andric       OutputsReplacedByPHINode.erase(V);
111704eeddc0SDimitry Andric       continue;
111804eeddc0SDimitry Andric     }
111904eeddc0SDimitry Andric 
112004eeddc0SDimitry Andric     // This PHINode will be used as an output value, so we add it to our list.
112104eeddc0SDimitry Andric     Outputs.insert(&PN);
112204eeddc0SDimitry Andric 
112304eeddc0SDimitry Andric     // Not all of the incoming values should be ignored as other inputs and
112404eeddc0SDimitry Andric     // outputs may have uses in outlined region.  If they have other uses
112504eeddc0SDimitry Andric     // outside of the single PHINode we should not skip over it.
112604eeddc0SDimitry Andric     for (unsigned Idx : IncomingVals) {
112704eeddc0SDimitry Andric       Value *V = PN.getIncomingValue(Idx);
112804eeddc0SDimitry Andric       if (outputHasNonPHI(V, Idx, PN, PotentialExitsFromRegion, RegionBlocks)) {
112904eeddc0SDimitry Andric         OutputsWithNonPhiUses.insert(V);
113004eeddc0SDimitry Andric         OutputsReplacedByPHINode.erase(V);
113104eeddc0SDimitry Andric         continue;
113204eeddc0SDimitry Andric       }
113304eeddc0SDimitry Andric       if (!OutputsWithNonPhiUses.contains(V))
113404eeddc0SDimitry Andric         OutputsReplacedByPHINode.insert(V);
113504eeddc0SDimitry Andric     }
113604eeddc0SDimitry Andric   }
113704eeddc0SDimitry Andric }
113804eeddc0SDimitry Andric 
113904eeddc0SDimitry Andric // Represents the type for the unsigned number denoting the output number for
114004eeddc0SDimitry Andric // phi node, along with the canonical number for the exit block.
114104eeddc0SDimitry Andric using ArgLocWithBBCanon = std::pair<unsigned, unsigned>;
114204eeddc0SDimitry Andric // The list of canonical numbers for the incoming values to a PHINode.
114304eeddc0SDimitry Andric using CanonList = SmallVector<unsigned, 2>;
114404eeddc0SDimitry Andric // The pair type representing the set of canonical values being combined in the
114504eeddc0SDimitry Andric // PHINode, along with the location data for the PHINode.
114604eeddc0SDimitry Andric using PHINodeData = std::pair<ArgLocWithBBCanon, CanonList>;
114704eeddc0SDimitry Andric 
114804eeddc0SDimitry Andric /// Encode \p PND as an integer for easy lookup based on the argument location,
114904eeddc0SDimitry Andric /// the parent BasicBlock canonical numbering, and the canonical numbering of
115004eeddc0SDimitry Andric /// the values stored in the PHINode.
115104eeddc0SDimitry Andric ///
115204eeddc0SDimitry Andric /// \param PND - The data to hash.
115304eeddc0SDimitry Andric /// \returns The hash code of \p PND.
115404eeddc0SDimitry Andric static hash_code encodePHINodeData(PHINodeData &PND) {
115504eeddc0SDimitry Andric   return llvm::hash_combine(
115604eeddc0SDimitry Andric       llvm::hash_value(PND.first.first), llvm::hash_value(PND.first.second),
115704eeddc0SDimitry Andric       llvm::hash_combine_range(PND.second.begin(), PND.second.end()));
115804eeddc0SDimitry Andric }
115904eeddc0SDimitry Andric 
116004eeddc0SDimitry Andric /// Create a special GVN for PHINodes that will be used outside of
116104eeddc0SDimitry Andric /// the region.  We create a hash code based on the Canonical number of the
116204eeddc0SDimitry Andric /// parent BasicBlock, the canonical numbering of the values stored in the
116304eeddc0SDimitry Andric /// PHINode and the aggregate argument location.  This is used to find whether
116404eeddc0SDimitry Andric /// this PHINode type has been given a canonical numbering already.  If not, we
116504eeddc0SDimitry Andric /// assign it a value and store it for later use.  The value is returned to
116604eeddc0SDimitry Andric /// identify different output schemes for the set of regions.
116704eeddc0SDimitry Andric ///
116804eeddc0SDimitry Andric /// \param Region - The region that \p PN is an output for.
116904eeddc0SDimitry Andric /// \param PN - The PHINode we are analyzing.
117081ad6265SDimitry Andric /// \param Blocks - The blocks for the region we are analyzing.
117104eeddc0SDimitry Andric /// \param AggArgIdx - The argument \p PN will be stored into.
1172bdd1243dSDimitry Andric /// \returns An optional holding the assigned canonical number, or std::nullopt
1173bdd1243dSDimitry Andric /// if there is some attribute of the PHINode blocking it from being used.
1174bdd1243dSDimitry Andric static std::optional<unsigned> getGVNForPHINode(OutlinableRegion &Region,
117581ad6265SDimitry Andric                                                 PHINode *PN,
117681ad6265SDimitry Andric                                                 DenseSet<BasicBlock *> &Blocks,
117781ad6265SDimitry Andric                                                 unsigned AggArgIdx) {
117804eeddc0SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
117904eeddc0SDimitry Andric   IRSimilarityCandidate &Cand = *Region.Candidate;
118004eeddc0SDimitry Andric   BasicBlock *PHIBB = PN->getParent();
118104eeddc0SDimitry Andric   CanonList PHIGVNs;
118281ad6265SDimitry Andric   Value *Incoming;
118381ad6265SDimitry Andric   BasicBlock *IncomingBlock;
118481ad6265SDimitry Andric   for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
118581ad6265SDimitry Andric     Incoming = PN->getIncomingValue(Idx);
118681ad6265SDimitry Andric     IncomingBlock = PN->getIncomingBlock(Idx);
118781ad6265SDimitry Andric     // If we cannot find a GVN, and the incoming block is included in the region
118881ad6265SDimitry Andric     // this means that the input to the PHINode is not included in the region we
118981ad6265SDimitry Andric     // are trying to analyze, meaning, that if it was outlined, we would be
119081ad6265SDimitry Andric     // adding an extra input.  We ignore this case for now, and so ignore the
119181ad6265SDimitry Andric     // region.
1192bdd1243dSDimitry Andric     std::optional<unsigned> OGVN = Cand.getGVN(Incoming);
119381ad6265SDimitry Andric     if (!OGVN && Blocks.contains(IncomingBlock)) {
119404eeddc0SDimitry Andric       Region.IgnoreRegion = true;
1195bdd1243dSDimitry Andric       return std::nullopt;
119604eeddc0SDimitry Andric     }
119704eeddc0SDimitry Andric 
119881ad6265SDimitry Andric     // If the incoming block isn't in the region, we don't have to worry about
119981ad6265SDimitry Andric     // this incoming value.
120081ad6265SDimitry Andric     if (!Blocks.contains(IncomingBlock))
120181ad6265SDimitry Andric       continue;
120281ad6265SDimitry Andric 
120304eeddc0SDimitry Andric     // Collect the canonical numbers of the values in the PHINode.
120481ad6265SDimitry Andric     unsigned GVN = *OGVN;
120504eeddc0SDimitry Andric     OGVN = Cand.getCanonicalNum(GVN);
120681ad6265SDimitry Andric     assert(OGVN && "No GVN found for incoming value?");
120781ad6265SDimitry Andric     PHIGVNs.push_back(*OGVN);
120881ad6265SDimitry Andric 
120981ad6265SDimitry Andric     // Find the incoming block and use the canonical numbering as well to define
121081ad6265SDimitry Andric     // the hash for the PHINode.
121181ad6265SDimitry Andric     OGVN = Cand.getGVN(IncomingBlock);
121281ad6265SDimitry Andric 
1213bdd1243dSDimitry Andric     // If there is no number for the incoming block, it is because we have
121481ad6265SDimitry Andric     // split the candidate basic blocks.  So we use the previous block that it
121581ad6265SDimitry Andric     // was split from to find the valid global value numbering for the PHINode.
121681ad6265SDimitry Andric     if (!OGVN) {
121781ad6265SDimitry Andric       assert(Cand.getStartBB() == IncomingBlock &&
121881ad6265SDimitry Andric              "Unknown basic block used in exit path PHINode.");
121981ad6265SDimitry Andric 
122081ad6265SDimitry Andric       BasicBlock *PrevBlock = nullptr;
122181ad6265SDimitry Andric       // Iterate over the predecessors to the incoming block of the
122281ad6265SDimitry Andric       // PHINode, when we find a block that is not contained in the region
122381ad6265SDimitry Andric       // we know that this is the first block that we split from, and should
122481ad6265SDimitry Andric       // have a valid global value numbering.
122581ad6265SDimitry Andric       for (BasicBlock *Pred : predecessors(IncomingBlock))
122681ad6265SDimitry Andric         if (!Blocks.contains(Pred)) {
122781ad6265SDimitry Andric           PrevBlock = Pred;
122881ad6265SDimitry Andric           break;
122981ad6265SDimitry Andric         }
123081ad6265SDimitry Andric       assert(PrevBlock && "Expected a predecessor not in the reigon!");
123181ad6265SDimitry Andric       OGVN = Cand.getGVN(PrevBlock);
123281ad6265SDimitry Andric     }
123381ad6265SDimitry Andric     GVN = *OGVN;
123481ad6265SDimitry Andric     OGVN = Cand.getCanonicalNum(GVN);
123581ad6265SDimitry Andric     assert(OGVN && "No GVN found for incoming block?");
123604eeddc0SDimitry Andric     PHIGVNs.push_back(*OGVN);
123704eeddc0SDimitry Andric   }
123804eeddc0SDimitry Andric 
123904eeddc0SDimitry Andric   // Now that we have the GVNs for the incoming values, we are going to combine
124004eeddc0SDimitry Andric   // them with the GVN of the incoming bock, and the output location of the
124104eeddc0SDimitry Andric   // PHINode to generate a hash value representing this instance of the PHINode.
124204eeddc0SDimitry Andric   DenseMap<hash_code, unsigned>::iterator GVNToPHIIt;
124304eeddc0SDimitry Andric   DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt;
1244bdd1243dSDimitry Andric   std::optional<unsigned> BBGVN = Cand.getGVN(PHIBB);
124581ad6265SDimitry Andric   assert(BBGVN && "Could not find GVN for the incoming block!");
124604eeddc0SDimitry Andric 
1247bdd1243dSDimitry Andric   BBGVN = Cand.getCanonicalNum(*BBGVN);
124881ad6265SDimitry Andric   assert(BBGVN && "Could not find canonical number for the incoming block!");
124904eeddc0SDimitry Andric   // Create a pair of the exit block canonical value, and the aggregate
125004eeddc0SDimitry Andric   // argument location, connected to the canonical numbers stored in the
125104eeddc0SDimitry Andric   // PHINode.
125204eeddc0SDimitry Andric   PHINodeData TemporaryPair =
1253bdd1243dSDimitry Andric       std::make_pair(std::make_pair(*BBGVN, AggArgIdx), PHIGVNs);
125404eeddc0SDimitry Andric   hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair);
125504eeddc0SDimitry Andric 
125604eeddc0SDimitry Andric   // Look for and create a new entry in our connection between canonical
125704eeddc0SDimitry Andric   // numbers for PHINodes, and the set of objects we just created.
125804eeddc0SDimitry Andric   GVNToPHIIt = Group.GVNsToPHINodeGVN.find(PHINodeDataHash);
125904eeddc0SDimitry Andric   if (GVNToPHIIt == Group.GVNsToPHINodeGVN.end()) {
126004eeddc0SDimitry Andric     bool Inserted = false;
126104eeddc0SDimitry Andric     std::tie(PHIToGVNIt, Inserted) = Group.PHINodeGVNToGVNs.insert(
126204eeddc0SDimitry Andric         std::make_pair(Group.PHINodeGVNTracker, TemporaryPair));
126304eeddc0SDimitry Andric     std::tie(GVNToPHIIt, Inserted) = Group.GVNsToPHINodeGVN.insert(
126404eeddc0SDimitry Andric         std::make_pair(PHINodeDataHash, Group.PHINodeGVNTracker--));
126504eeddc0SDimitry Andric   }
126604eeddc0SDimitry Andric 
126704eeddc0SDimitry Andric   return GVNToPHIIt->second;
126804eeddc0SDimitry Andric }
126904eeddc0SDimitry Andric 
1270e8d8bef9SDimitry Andric /// Create a mapping of the output arguments for the \p Region to the output
1271e8d8bef9SDimitry Andric /// arguments of the overall outlined function.
1272e8d8bef9SDimitry Andric ///
1273e8d8bef9SDimitry Andric /// \param [in,out] Region - The region of code to be analyzed.
1274e8d8bef9SDimitry Andric /// \param [in] Outputs - The values found by the code extractor.
1275e8d8bef9SDimitry Andric static void
1276bdd1243dSDimitry Andric findExtractedOutputToOverallOutputMapping(Module &M, OutlinableRegion &Region,
1277349cc55cSDimitry Andric                                           SetVector<Value *> &Outputs) {
1278e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
1279e8d8bef9SDimitry Andric   IRSimilarityCandidate &C = *Region.Candidate;
1280e8d8bef9SDimitry Andric 
1281349cc55cSDimitry Andric   SmallVector<BasicBlock *> BE;
128204eeddc0SDimitry Andric   DenseSet<BasicBlock *> BlocksInRegion;
128304eeddc0SDimitry Andric   C.getBasicBlocks(BlocksInRegion, BE);
1284349cc55cSDimitry Andric 
1285349cc55cSDimitry Andric   // Find the exits to the region.
1286349cc55cSDimitry Andric   SmallPtrSet<BasicBlock *, 1> Exits;
1287349cc55cSDimitry Andric   for (BasicBlock *Block : BE)
1288349cc55cSDimitry Andric     for (BasicBlock *Succ : successors(Block))
128904eeddc0SDimitry Andric       if (!BlocksInRegion.contains(Succ))
1290349cc55cSDimitry Andric         Exits.insert(Succ);
1291349cc55cSDimitry Andric 
1292349cc55cSDimitry Andric   // After determining which blocks exit to PHINodes, we add these PHINodes to
1293349cc55cSDimitry Andric   // the set of outputs to be processed.  We also check the incoming values of
1294349cc55cSDimitry Andric   // the PHINodes for whether they should no longer be considered outputs.
129504eeddc0SDimitry Andric   DenseSet<Value *> OutputsReplacedByPHINode;
129604eeddc0SDimitry Andric   DenseSet<Value *> OutputsWithNonPhiUses;
129704eeddc0SDimitry Andric   for (BasicBlock *ExitBB : Exits)
129804eeddc0SDimitry Andric     analyzeExitPHIsForOutputUses(ExitBB, Exits, BlocksInRegion, Outputs,
129904eeddc0SDimitry Andric                                  OutputsReplacedByPHINode,
130004eeddc0SDimitry Andric                                  OutputsWithNonPhiUses);
1301349cc55cSDimitry Andric 
1302e8d8bef9SDimitry Andric   // This counts the argument number in the extracted function.
1303e8d8bef9SDimitry Andric   unsigned OriginalIndex = Region.NumExtractedInputs;
1304e8d8bef9SDimitry Andric 
1305e8d8bef9SDimitry Andric   // This counts the argument number in the overall function.
1306e8d8bef9SDimitry Andric   unsigned TypeIndex = Group.NumAggregateInputs;
1307e8d8bef9SDimitry Andric   bool TypeFound;
1308e8d8bef9SDimitry Andric   DenseSet<unsigned> AggArgsUsed;
1309e8d8bef9SDimitry Andric 
1310e8d8bef9SDimitry Andric   // Iterate over the output types and identify if there is an aggregate pointer
1311e8d8bef9SDimitry Andric   // type whose base type matches the current output type. If there is, we mark
1312e8d8bef9SDimitry Andric   // that we will use this output register for this value. If not we add another
1313e8d8bef9SDimitry Andric   // type to the overall argument type list. We also store the GVNs used for
1314e8d8bef9SDimitry Andric   // stores to identify which values will need to be moved into an special
1315e8d8bef9SDimitry Andric   // block that holds the stores to the output registers.
1316e8d8bef9SDimitry Andric   for (Value *Output : Outputs) {
1317e8d8bef9SDimitry Andric     TypeFound = false;
1318e8d8bef9SDimitry Andric     // We can do this since it is a result value, and will have a number
1319e8d8bef9SDimitry Andric     // that is necessarily the same. BUT if in the future, the instructions
1320e8d8bef9SDimitry Andric     // do not have to be in same order, but are functionally the same, we will
1321e8d8bef9SDimitry Andric     // have to use a different scheme, as one-to-one correspondence is not
1322e8d8bef9SDimitry Andric     // guaranteed.
1323e8d8bef9SDimitry Andric     unsigned ArgumentSize = Group.ArgumentTypes.size();
1324e8d8bef9SDimitry Andric 
132504eeddc0SDimitry Andric     // If the output is combined in a PHINode, we make sure to skip over it.
132604eeddc0SDimitry Andric     if (OutputsReplacedByPHINode.contains(Output))
132704eeddc0SDimitry Andric       continue;
132804eeddc0SDimitry Andric 
132904eeddc0SDimitry Andric     unsigned AggArgIdx = 0;
1330e8d8bef9SDimitry Andric     for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) {
133106c3fb27SDimitry Andric       if (!isa<PointerType>(Group.ArgumentTypes[Jdx]))
1332e8d8bef9SDimitry Andric         continue;
1333e8d8bef9SDimitry Andric 
1334e8d8bef9SDimitry Andric       if (AggArgsUsed.contains(Jdx))
1335e8d8bef9SDimitry Andric         continue;
1336e8d8bef9SDimitry Andric 
1337e8d8bef9SDimitry Andric       TypeFound = true;
1338e8d8bef9SDimitry Andric       AggArgsUsed.insert(Jdx);
1339e8d8bef9SDimitry Andric       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx));
1340e8d8bef9SDimitry Andric       Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex));
134104eeddc0SDimitry Andric       AggArgIdx = Jdx;
1342e8d8bef9SDimitry Andric       break;
1343e8d8bef9SDimitry Andric     }
1344e8d8bef9SDimitry Andric 
1345e8d8bef9SDimitry Andric     // We were unable to find an unused type in the output type set that matches
1346e8d8bef9SDimitry Andric     // the output, so we add a pointer type to the argument types of the overall
1347e8d8bef9SDimitry Andric     // function to handle this output and create a mapping to it.
1348e8d8bef9SDimitry Andric     if (!TypeFound) {
1349*5f757f3fSDimitry Andric       Group.ArgumentTypes.push_back(PointerType::get(Output->getContext(),
1350bdd1243dSDimitry Andric           M.getDataLayout().getAllocaAddrSpace()));
135104eeddc0SDimitry Andric       // Mark the new pointer type as the last value in the aggregate argument
135204eeddc0SDimitry Andric       // list.
135304eeddc0SDimitry Andric       unsigned ArgTypeIdx = Group.ArgumentTypes.size() - 1;
135404eeddc0SDimitry Andric       AggArgsUsed.insert(ArgTypeIdx);
1355e8d8bef9SDimitry Andric       Region.ExtractedArgToAgg.insert(
135604eeddc0SDimitry Andric           std::make_pair(OriginalIndex, ArgTypeIdx));
1357e8d8bef9SDimitry Andric       Region.AggArgToExtracted.insert(
135804eeddc0SDimitry Andric           std::make_pair(ArgTypeIdx, OriginalIndex));
135904eeddc0SDimitry Andric       AggArgIdx = ArgTypeIdx;
1360e8d8bef9SDimitry Andric     }
1361e8d8bef9SDimitry Andric 
136204eeddc0SDimitry Andric     // TODO: Adapt to the extra input from the PHINode.
136304eeddc0SDimitry Andric     PHINode *PN = dyn_cast<PHINode>(Output);
136404eeddc0SDimitry Andric 
1365bdd1243dSDimitry Andric     std::optional<unsigned> GVN;
136604eeddc0SDimitry Andric     if (PN && !BlocksInRegion.contains(PN->getParent())) {
136704eeddc0SDimitry Andric       // Values outside the region can be combined into PHINode when we
136804eeddc0SDimitry Andric       // have multiple exits. We collect both of these into a list to identify
136904eeddc0SDimitry Andric       // which values are being used in the PHINode. Each list identifies a
137004eeddc0SDimitry Andric       // different PHINode, and a different output. We store the PHINode as it's
137104eeddc0SDimitry Andric       // own canonical value.  These canonical values are also dependent on the
137204eeddc0SDimitry Andric       // output argument it is saved to.
137304eeddc0SDimitry Andric 
137404eeddc0SDimitry Andric       // If two PHINodes have the same canonical values, but different aggregate
137504eeddc0SDimitry Andric       // argument locations, then they will have distinct Canonical Values.
137681ad6265SDimitry Andric       GVN = getGVNForPHINode(Region, PN, BlocksInRegion, AggArgIdx);
137781ad6265SDimitry Andric       if (!GVN)
137804eeddc0SDimitry Andric         return;
137904eeddc0SDimitry Andric     } else {
138004eeddc0SDimitry Andric       // If we do not have a PHINode we use the global value numbering for the
138104eeddc0SDimitry Andric       // output value, to find the canonical number to add to the set of stored
138204eeddc0SDimitry Andric       // values.
138304eeddc0SDimitry Andric       GVN = C.getGVN(Output);
138404eeddc0SDimitry Andric       GVN = C.getCanonicalNum(*GVN);
138504eeddc0SDimitry Andric     }
138604eeddc0SDimitry Andric 
138704eeddc0SDimitry Andric     // Each region has a potentially unique set of outputs.  We save which
138804eeddc0SDimitry Andric     // values are output in a list of canonical values so we can differentiate
138904eeddc0SDimitry Andric     // among the different store schemes.
139004eeddc0SDimitry Andric     Region.GVNStores.push_back(*GVN);
139104eeddc0SDimitry Andric 
1392e8d8bef9SDimitry Andric     OriginalIndex++;
1393e8d8bef9SDimitry Andric     TypeIndex++;
1394e8d8bef9SDimitry Andric   }
139504eeddc0SDimitry Andric 
139604eeddc0SDimitry Andric   // We sort the stored values to make sure that we are not affected by analysis
139704eeddc0SDimitry Andric   // order when determining what combination of items were stored.
139804eeddc0SDimitry Andric   stable_sort(Region.GVNStores);
1399e8d8bef9SDimitry Andric }
1400e8d8bef9SDimitry Andric 
1401e8d8bef9SDimitry Andric void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region,
1402e8d8bef9SDimitry Andric                                       DenseSet<unsigned> &NotSame) {
1403e8d8bef9SDimitry Andric   std::vector<unsigned> Inputs;
1404e8d8bef9SDimitry Andric   SetVector<Value *> ArgInputs, Outputs;
1405e8d8bef9SDimitry Andric 
1406e8d8bef9SDimitry Andric   getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs,
1407e8d8bef9SDimitry Andric                             Outputs);
1408e8d8bef9SDimitry Andric 
1409e8d8bef9SDimitry Andric   if (Region.IgnoreRegion)
1410e8d8bef9SDimitry Andric     return;
1411e8d8bef9SDimitry Andric 
1412e8d8bef9SDimitry Andric   // Map the inputs found by the CodeExtractor to the arguments found for
1413e8d8bef9SDimitry Andric   // the overall function.
1414e8d8bef9SDimitry Andric   findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs);
1415e8d8bef9SDimitry Andric 
1416e8d8bef9SDimitry Andric   // Map the outputs found by the CodeExtractor to the arguments found for
1417e8d8bef9SDimitry Andric   // the overall function.
1418bdd1243dSDimitry Andric   findExtractedOutputToOverallOutputMapping(M, Region, Outputs);
1419e8d8bef9SDimitry Andric }
1420e8d8bef9SDimitry Andric 
1421e8d8bef9SDimitry Andric /// Replace the extracted function in the Region with a call to the overall
1422e8d8bef9SDimitry Andric /// function constructed from the deduplicated similar regions, replacing and
1423e8d8bef9SDimitry Andric /// remapping the values passed to the extracted function as arguments to the
1424e8d8bef9SDimitry Andric /// new arguments of the overall function.
1425e8d8bef9SDimitry Andric ///
1426e8d8bef9SDimitry Andric /// \param [in] M - The module to outline from.
1427e8d8bef9SDimitry Andric /// \param [in] Region - The regions of extracted code to be replaced with a new
1428e8d8bef9SDimitry Andric /// function.
1429e8d8bef9SDimitry Andric /// \returns a call instruction with the replaced function.
1430e8d8bef9SDimitry Andric CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {
1431e8d8bef9SDimitry Andric   std::vector<Value *> NewCallArgs;
1432e8d8bef9SDimitry Andric   DenseMap<unsigned, unsigned>::iterator ArgPair;
1433e8d8bef9SDimitry Andric 
1434e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
1435e8d8bef9SDimitry Andric   CallInst *Call = Region.Call;
1436e8d8bef9SDimitry Andric   assert(Call && "Call to replace is nullptr?");
1437e8d8bef9SDimitry Andric   Function *AggFunc = Group.OutlinedFunction;
1438e8d8bef9SDimitry Andric   assert(AggFunc && "Function to replace with is nullptr?");
1439e8d8bef9SDimitry Andric 
1440e8d8bef9SDimitry Andric   // If the arguments are the same size, there are not values that need to be
1441349cc55cSDimitry Andric   // made into an argument, the argument ordering has not been change, or
1442349cc55cSDimitry Andric   // different output registers to handle.  We can simply replace the called
1443349cc55cSDimitry Andric   // function in this case.
1444349cc55cSDimitry Andric   if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) {
1445e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
1446e8d8bef9SDimitry Andric                       << *AggFunc << " with same number of arguments\n");
1447e8d8bef9SDimitry Andric     Call->setCalledFunction(AggFunc);
1448e8d8bef9SDimitry Andric     return Call;
1449e8d8bef9SDimitry Andric   }
1450e8d8bef9SDimitry Andric 
1451e8d8bef9SDimitry Andric   // We have a different number of arguments than the new function, so
1452e8d8bef9SDimitry Andric   // we need to use our previously mappings off extracted argument to overall
1453e8d8bef9SDimitry Andric   // function argument, and constants to overall function argument to create the
1454e8d8bef9SDimitry Andric   // new argument list.
1455e8d8bef9SDimitry Andric   for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) {
1456e8d8bef9SDimitry Andric 
1457e8d8bef9SDimitry Andric     if (AggArgIdx == AggFunc->arg_size() - 1 &&
1458e8d8bef9SDimitry Andric         Group.OutputGVNCombinations.size() > 1) {
1459e8d8bef9SDimitry Andric       // If we are on the last argument, and we need to differentiate between
1460e8d8bef9SDimitry Andric       // output blocks, add an integer to the argument list to determine
1461e8d8bef9SDimitry Andric       // what block to take
1462e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Set switch block argument to "
1463e8d8bef9SDimitry Andric                         << Region.OutputBlockNum << "\n");
1464e8d8bef9SDimitry Andric       NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()),
1465e8d8bef9SDimitry Andric                                              Region.OutputBlockNum));
1466e8d8bef9SDimitry Andric       continue;
1467e8d8bef9SDimitry Andric     }
1468e8d8bef9SDimitry Andric 
1469e8d8bef9SDimitry Andric     ArgPair = Region.AggArgToExtracted.find(AggArgIdx);
1470e8d8bef9SDimitry Andric     if (ArgPair != Region.AggArgToExtracted.end()) {
1471e8d8bef9SDimitry Andric       Value *ArgumentValue = Call->getArgOperand(ArgPair->second);
1472e8d8bef9SDimitry Andric       // If we found the mapping from the extracted function to the overall
1473e8d8bef9SDimitry Andric       // function, we simply add it to the argument list.  We use the same
1474e8d8bef9SDimitry Andric       // value, it just needs to honor the new order of arguments.
1475e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1476e8d8bef9SDimitry Andric                         << *ArgumentValue << "\n");
1477e8d8bef9SDimitry Andric       NewCallArgs.push_back(ArgumentValue);
1478e8d8bef9SDimitry Andric       continue;
1479e8d8bef9SDimitry Andric     }
1480e8d8bef9SDimitry Andric 
1481e8d8bef9SDimitry Andric     // If it is a constant, we simply add it to the argument list as a value.
148206c3fb27SDimitry Andric     if (Region.AggArgToConstant.contains(AggArgIdx)) {
1483e8d8bef9SDimitry Andric       Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second;
1484e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1485e8d8bef9SDimitry Andric                         << *CST << "\n");
1486e8d8bef9SDimitry Andric       NewCallArgs.push_back(CST);
1487e8d8bef9SDimitry Andric       continue;
1488e8d8bef9SDimitry Andric     }
1489e8d8bef9SDimitry Andric 
1490e8d8bef9SDimitry Andric     // Add a nullptr value if the argument is not found in the extracted
1491e8d8bef9SDimitry Andric     // function.  If we cannot find a value, it means it is not in use
1492e8d8bef9SDimitry Andric     // for the region, so we should not pass anything to it.
1493e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n");
1494e8d8bef9SDimitry Andric     NewCallArgs.push_back(ConstantPointerNull::get(
1495e8d8bef9SDimitry Andric         static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType())));
1496e8d8bef9SDimitry Andric   }
1497e8d8bef9SDimitry Andric 
1498e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
1499e8d8bef9SDimitry Andric                     << *AggFunc << " with new set of arguments\n");
1500e8d8bef9SDimitry Andric   // Create the new call instruction and erase the old one.
1501e8d8bef9SDimitry Andric   Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "",
1502e8d8bef9SDimitry Andric                           Call);
1503e8d8bef9SDimitry Andric 
1504e8d8bef9SDimitry Andric   // It is possible that the call to the outlined function is either the first
1505e8d8bef9SDimitry Andric   // instruction is in the new block, the last instruction, or both.  If either
1506e8d8bef9SDimitry Andric   // of these is the case, we need to make sure that we replace the instruction
1507e8d8bef9SDimitry Andric   // in the IRInstructionData struct with the new call.
1508e8d8bef9SDimitry Andric   CallInst *OldCall = Region.Call;
1509e8d8bef9SDimitry Andric   if (Region.NewFront->Inst == OldCall)
1510e8d8bef9SDimitry Andric     Region.NewFront->Inst = Call;
1511e8d8bef9SDimitry Andric   if (Region.NewBack->Inst == OldCall)
1512e8d8bef9SDimitry Andric     Region.NewBack->Inst = Call;
1513e8d8bef9SDimitry Andric 
1514e8d8bef9SDimitry Andric   // Transfer any debug information.
1515e8d8bef9SDimitry Andric   Call->setDebugLoc(Region.Call->getDebugLoc());
1516349cc55cSDimitry Andric   // Since our output may determine which branch we go to, we make sure to
1517349cc55cSDimitry Andric   // propogate this new call value through the module.
1518349cc55cSDimitry Andric   OldCall->replaceAllUsesWith(Call);
1519e8d8bef9SDimitry Andric 
1520e8d8bef9SDimitry Andric   // Remove the old instruction.
1521e8d8bef9SDimitry Andric   OldCall->eraseFromParent();
1522e8d8bef9SDimitry Andric   Region.Call = Call;
1523e8d8bef9SDimitry Andric 
1524e8d8bef9SDimitry Andric   // Make sure that the argument in the new function has the SwiftError
1525e8d8bef9SDimitry Andric   // argument.
152681ad6265SDimitry Andric   if (Group.SwiftErrorArgument)
1527bdd1243dSDimitry Andric     Call->addParamAttr(*Group.SwiftErrorArgument, Attribute::SwiftError);
1528e8d8bef9SDimitry Andric 
1529e8d8bef9SDimitry Andric   return Call;
1530e8d8bef9SDimitry Andric }
1531e8d8bef9SDimitry Andric 
153204eeddc0SDimitry Andric /// Find or create a BasicBlock in the outlined function containing PhiBlocks
153304eeddc0SDimitry Andric /// for \p RetVal.
153404eeddc0SDimitry Andric ///
153504eeddc0SDimitry Andric /// \param Group - The OutlinableGroup containing the information about the
153604eeddc0SDimitry Andric /// overall outlined function.
153704eeddc0SDimitry Andric /// \param RetVal - The return value or exit option that we are currently
153804eeddc0SDimitry Andric /// evaluating.
153904eeddc0SDimitry Andric /// \returns The found or newly created BasicBlock to contain the needed
154004eeddc0SDimitry Andric /// PHINodes to be used as outputs.
154104eeddc0SDimitry Andric static BasicBlock *findOrCreatePHIBlock(OutlinableGroup &Group, Value *RetVal) {
154204eeddc0SDimitry Andric   DenseMap<Value *, BasicBlock *>::iterator PhiBlockForRetVal,
154304eeddc0SDimitry Andric       ReturnBlockForRetVal;
154404eeddc0SDimitry Andric   PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
154504eeddc0SDimitry Andric   ReturnBlockForRetVal = Group.EndBBs.find(RetVal);
154604eeddc0SDimitry Andric   assert(ReturnBlockForRetVal != Group.EndBBs.end() &&
154704eeddc0SDimitry Andric          "Could not find output value!");
154804eeddc0SDimitry Andric   BasicBlock *ReturnBB = ReturnBlockForRetVal->second;
154904eeddc0SDimitry Andric 
155004eeddc0SDimitry Andric   // Find if a PHIBlock exists for this return value already.  If it is
155104eeddc0SDimitry Andric   // the first time we are analyzing this, we will not, so we record it.
155204eeddc0SDimitry Andric   PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
155304eeddc0SDimitry Andric   if (PhiBlockForRetVal != Group.PHIBlocks.end())
155404eeddc0SDimitry Andric     return PhiBlockForRetVal->second;
155504eeddc0SDimitry Andric 
155604eeddc0SDimitry Andric   // If we did not find a block, we create one, and insert it into the
155704eeddc0SDimitry Andric   // overall function and record it.
155804eeddc0SDimitry Andric   bool Inserted = false;
155904eeddc0SDimitry Andric   BasicBlock *PHIBlock = BasicBlock::Create(ReturnBB->getContext(), "phi_block",
156004eeddc0SDimitry Andric                                             ReturnBB->getParent());
156104eeddc0SDimitry Andric   std::tie(PhiBlockForRetVal, Inserted) =
156204eeddc0SDimitry Andric       Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
156304eeddc0SDimitry Andric 
156404eeddc0SDimitry Andric   // We find the predecessors of the return block in the newly created outlined
156504eeddc0SDimitry Andric   // function in order to point them to the new PHIBlock rather than the already
156604eeddc0SDimitry Andric   // existing return block.
156704eeddc0SDimitry Andric   SmallVector<BranchInst *, 2> BranchesToChange;
156804eeddc0SDimitry Andric   for (BasicBlock *Pred : predecessors(ReturnBB))
156904eeddc0SDimitry Andric     BranchesToChange.push_back(cast<BranchInst>(Pred->getTerminator()));
157004eeddc0SDimitry Andric 
157104eeddc0SDimitry Andric   // Now we mark the branch instructions found, and change the references of the
157204eeddc0SDimitry Andric   // return block to the newly created PHIBlock.
157304eeddc0SDimitry Andric   for (BranchInst *BI : BranchesToChange)
157404eeddc0SDimitry Andric     for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ < End; Succ++) {
157504eeddc0SDimitry Andric       if (BI->getSuccessor(Succ) != ReturnBB)
157604eeddc0SDimitry Andric         continue;
157704eeddc0SDimitry Andric       BI->setSuccessor(Succ, PHIBlock);
157804eeddc0SDimitry Andric     }
157904eeddc0SDimitry Andric 
158004eeddc0SDimitry Andric   BranchInst::Create(ReturnBB, PHIBlock);
158104eeddc0SDimitry Andric 
158204eeddc0SDimitry Andric   return PhiBlockForRetVal->second;
158304eeddc0SDimitry Andric }
158404eeddc0SDimitry Andric 
158504eeddc0SDimitry Andric /// For the function call now representing the \p Region, find the passed value
158604eeddc0SDimitry Andric /// to that call that represents Argument \p A at the call location if the
158704eeddc0SDimitry Andric /// call has already been replaced with a call to the  overall, aggregate
158804eeddc0SDimitry Andric /// function.
158904eeddc0SDimitry Andric ///
159004eeddc0SDimitry Andric /// \param A - The Argument to get the passed value for.
159104eeddc0SDimitry Andric /// \param Region - The extracted Region corresponding to the outlined function.
159204eeddc0SDimitry Andric /// \returns The Value representing \p A at the call site.
159304eeddc0SDimitry Andric static Value *
159404eeddc0SDimitry Andric getPassedArgumentInAlreadyOutlinedFunction(const Argument *A,
159504eeddc0SDimitry Andric                                            const OutlinableRegion &Region) {
159604eeddc0SDimitry Andric   // If we don't need to adjust the argument number at all (since the call
159704eeddc0SDimitry Andric   // has already been replaced by a call to the overall outlined function)
159804eeddc0SDimitry Andric   // we can just get the specified argument.
159904eeddc0SDimitry Andric   return Region.Call->getArgOperand(A->getArgNo());
160004eeddc0SDimitry Andric }
160104eeddc0SDimitry Andric 
160204eeddc0SDimitry Andric /// For the function call now representing the \p Region, find the passed value
160304eeddc0SDimitry Andric /// to that call that represents Argument \p A at the call location if the
160404eeddc0SDimitry Andric /// call has only been replaced by the call to the aggregate function.
160504eeddc0SDimitry Andric ///
160604eeddc0SDimitry Andric /// \param A - The Argument to get the passed value for.
160704eeddc0SDimitry Andric /// \param Region - The extracted Region corresponding to the outlined function.
160804eeddc0SDimitry Andric /// \returns The Value representing \p A at the call site.
160904eeddc0SDimitry Andric static Value *
161004eeddc0SDimitry Andric getPassedArgumentAndAdjustArgumentLocation(const Argument *A,
161104eeddc0SDimitry Andric                                            const OutlinableRegion &Region) {
161204eeddc0SDimitry Andric   unsigned ArgNum = A->getArgNo();
161304eeddc0SDimitry Andric 
161404eeddc0SDimitry Andric   // If it is a constant, we can look at our mapping from when we created
161504eeddc0SDimitry Andric   // the outputs to figure out what the constant value is.
161604eeddc0SDimitry Andric   if (Region.AggArgToConstant.count(ArgNum))
161704eeddc0SDimitry Andric     return Region.AggArgToConstant.find(ArgNum)->second;
161804eeddc0SDimitry Andric 
161904eeddc0SDimitry Andric   // If it is not a constant, and we are not looking at the overall function, we
162004eeddc0SDimitry Andric   // need to adjust which argument we are looking at.
162104eeddc0SDimitry Andric   ArgNum = Region.AggArgToExtracted.find(ArgNum)->second;
162204eeddc0SDimitry Andric   return Region.Call->getArgOperand(ArgNum);
162304eeddc0SDimitry Andric }
162404eeddc0SDimitry Andric 
162504eeddc0SDimitry Andric /// Find the canonical numbering for the incoming Values into the PHINode \p PN.
162604eeddc0SDimitry Andric ///
162704eeddc0SDimitry Andric /// \param PN [in] - The PHINode that we are finding the canonical numbers for.
162804eeddc0SDimitry Andric /// \param Region [in] - The OutlinableRegion containing \p PN.
162904eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of output values from outlined
163004eeddc0SDimitry Andric /// region to their original values.
163104eeddc0SDimitry Andric /// \param CanonNums [out] - The canonical numbering for the incoming values to
163281ad6265SDimitry Andric /// \p PN paired with their incoming block.
163304eeddc0SDimitry Andric /// \param ReplacedWithOutlinedCall - A flag to use the extracted function call
163404eeddc0SDimitry Andric /// of \p Region rather than the overall function's call.
163581ad6265SDimitry Andric static void findCanonNumsForPHI(
163681ad6265SDimitry Andric     PHINode *PN, OutlinableRegion &Region,
163704eeddc0SDimitry Andric     const DenseMap<Value *, Value *> &OutputMappings,
163881ad6265SDimitry Andric     SmallVector<std::pair<unsigned, BasicBlock *>> &CanonNums,
163904eeddc0SDimitry Andric     bool ReplacedWithOutlinedCall = true) {
164004eeddc0SDimitry Andric   // Iterate over the incoming values.
164104eeddc0SDimitry Andric   for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
164204eeddc0SDimitry Andric     Value *IVal = PN->getIncomingValue(Idx);
164381ad6265SDimitry Andric     BasicBlock *IBlock = PN->getIncomingBlock(Idx);
164404eeddc0SDimitry Andric     // If we have an argument as incoming value, we need to grab the passed
164504eeddc0SDimitry Andric     // value from the call itself.
164604eeddc0SDimitry Andric     if (Argument *A = dyn_cast<Argument>(IVal)) {
164704eeddc0SDimitry Andric       if (ReplacedWithOutlinedCall)
164804eeddc0SDimitry Andric         IVal = getPassedArgumentInAlreadyOutlinedFunction(A, Region);
164904eeddc0SDimitry Andric       else
165004eeddc0SDimitry Andric         IVal = getPassedArgumentAndAdjustArgumentLocation(A, Region);
165104eeddc0SDimitry Andric     }
165204eeddc0SDimitry Andric 
165304eeddc0SDimitry Andric     // Get the original value if it has been replaced by an output value.
165404eeddc0SDimitry Andric     IVal = findOutputMapping(OutputMappings, IVal);
165504eeddc0SDimitry Andric 
165604eeddc0SDimitry Andric     // Find and add the canonical number for the incoming value.
1657bdd1243dSDimitry Andric     std::optional<unsigned> GVN = Region.Candidate->getGVN(IVal);
165881ad6265SDimitry Andric     assert(GVN && "No GVN for incoming value");
1659bdd1243dSDimitry Andric     std::optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN);
166081ad6265SDimitry Andric     assert(CanonNum && "No Canonical Number for GVN");
166181ad6265SDimitry Andric     CanonNums.push_back(std::make_pair(*CanonNum, IBlock));
166204eeddc0SDimitry Andric   }
166304eeddc0SDimitry Andric }
166404eeddc0SDimitry Andric 
166504eeddc0SDimitry Andric /// Find, or add PHINode \p PN to the combined PHINode Block \p OverallPHIBlock
166604eeddc0SDimitry Andric /// in order to condense the number of instructions added to the outlined
166704eeddc0SDimitry Andric /// function.
166804eeddc0SDimitry Andric ///
166904eeddc0SDimitry Andric /// \param PN [in] - The PHINode that we are finding the canonical numbers for.
167004eeddc0SDimitry Andric /// \param Region [in] - The OutlinableRegion containing \p PN.
167104eeddc0SDimitry Andric /// \param OverallPhiBlock [in] - The overall PHIBlock we are trying to find
167204eeddc0SDimitry Andric /// \p PN in.
167304eeddc0SDimitry Andric /// \param OutputMappings [in] - The mapping of output values from outlined
167404eeddc0SDimitry Andric /// region to their original values.
167581ad6265SDimitry Andric /// \param UsedPHIs [in, out] - The PHINodes in the block that have already been
167681ad6265SDimitry Andric /// matched.
167704eeddc0SDimitry Andric /// \return the newly found or created PHINode in \p OverallPhiBlock.
167804eeddc0SDimitry Andric static PHINode*
167904eeddc0SDimitry Andric findOrCreatePHIInBlock(PHINode &PN, OutlinableRegion &Region,
168004eeddc0SDimitry Andric                        BasicBlock *OverallPhiBlock,
168181ad6265SDimitry Andric                        const DenseMap<Value *, Value *> &OutputMappings,
168281ad6265SDimitry Andric                        DenseSet<PHINode *> &UsedPHIs) {
168304eeddc0SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
168404eeddc0SDimitry Andric 
168581ad6265SDimitry Andric 
168681ad6265SDimitry Andric   // A list of the canonical numbering assigned to each incoming value, paired
168781ad6265SDimitry Andric   // with the incoming block for the PHINode passed into this function.
168881ad6265SDimitry Andric   SmallVector<std::pair<unsigned, BasicBlock *>> PNCanonNums;
168981ad6265SDimitry Andric 
169004eeddc0SDimitry Andric   // We have to use the extracted function since we have merged this region into
169104eeddc0SDimitry Andric   // the overall function yet.  We make sure to reassign the argument numbering
169204eeddc0SDimitry Andric   // since it is possible that the argument ordering is different between the
169304eeddc0SDimitry Andric   // functions.
169404eeddc0SDimitry Andric   findCanonNumsForPHI(&PN, Region, OutputMappings, PNCanonNums,
169504eeddc0SDimitry Andric                       /* ReplacedWithOutlinedCall = */ false);
169604eeddc0SDimitry Andric 
169704eeddc0SDimitry Andric   OutlinableRegion *FirstRegion = Group.Regions[0];
169881ad6265SDimitry Andric 
169981ad6265SDimitry Andric   // A list of the canonical numbering assigned to each incoming value, paired
170081ad6265SDimitry Andric   // with the incoming block for the PHINode that we are currently comparing
170181ad6265SDimitry Andric   // the passed PHINode to.
170281ad6265SDimitry Andric   SmallVector<std::pair<unsigned, BasicBlock *>> CurrentCanonNums;
170381ad6265SDimitry Andric 
170404eeddc0SDimitry Andric   // Find the Canonical Numbering for each PHINode, if it matches, we replace
170504eeddc0SDimitry Andric   // the uses of the PHINode we are searching for, with the found PHINode.
170604eeddc0SDimitry Andric   for (PHINode &CurrPN : OverallPhiBlock->phis()) {
170781ad6265SDimitry Andric     // If this PHINode has already been matched to another PHINode to be merged,
170881ad6265SDimitry Andric     // we skip it.
170981ad6265SDimitry Andric     if (UsedPHIs.contains(&CurrPN))
171081ad6265SDimitry Andric       continue;
171181ad6265SDimitry Andric 
171204eeddc0SDimitry Andric     CurrentCanonNums.clear();
171304eeddc0SDimitry Andric     findCanonNumsForPHI(&CurrPN, *FirstRegion, OutputMappings, CurrentCanonNums,
171404eeddc0SDimitry Andric                         /* ReplacedWithOutlinedCall = */ true);
171504eeddc0SDimitry Andric 
171681ad6265SDimitry Andric     // If the list of incoming values is not the same length, then they cannot
171781ad6265SDimitry Andric     // match since there is not an analogue for each incoming value.
171881ad6265SDimitry Andric     if (PNCanonNums.size() != CurrentCanonNums.size())
171981ad6265SDimitry Andric       continue;
172081ad6265SDimitry Andric 
172181ad6265SDimitry Andric     bool FoundMatch = true;
172281ad6265SDimitry Andric 
172381ad6265SDimitry Andric     // We compare the canonical value for each incoming value in the passed
172481ad6265SDimitry Andric     // in PHINode to one already present in the outlined region.  If the
172581ad6265SDimitry Andric     // incoming values do not match, then the PHINodes do not match.
172681ad6265SDimitry Andric 
172781ad6265SDimitry Andric     // We also check to make sure that the incoming block matches as well by
172881ad6265SDimitry Andric     // finding the corresponding incoming block in the combined outlined region
172981ad6265SDimitry Andric     // for the current outlined region.
173081ad6265SDimitry Andric     for (unsigned Idx = 0, Edx = PNCanonNums.size(); Idx < Edx; ++Idx) {
173181ad6265SDimitry Andric       std::pair<unsigned, BasicBlock *> ToCompareTo = CurrentCanonNums[Idx];
173281ad6265SDimitry Andric       std::pair<unsigned, BasicBlock *> ToAdd = PNCanonNums[Idx];
173381ad6265SDimitry Andric       if (ToCompareTo.first != ToAdd.first) {
173481ad6265SDimitry Andric         FoundMatch = false;
173581ad6265SDimitry Andric         break;
173681ad6265SDimitry Andric       }
173781ad6265SDimitry Andric 
173881ad6265SDimitry Andric       BasicBlock *CorrespondingBlock =
173981ad6265SDimitry Andric           Region.findCorrespondingBlockIn(*FirstRegion, ToAdd.second);
174081ad6265SDimitry Andric       assert(CorrespondingBlock && "Found block is nullptr");
174181ad6265SDimitry Andric       if (CorrespondingBlock != ToCompareTo.second) {
174281ad6265SDimitry Andric         FoundMatch = false;
174381ad6265SDimitry Andric         break;
174481ad6265SDimitry Andric       }
174581ad6265SDimitry Andric     }
174681ad6265SDimitry Andric 
174781ad6265SDimitry Andric     // If all incoming values and branches matched, then we can merge
174881ad6265SDimitry Andric     // into the found PHINode.
174981ad6265SDimitry Andric     if (FoundMatch) {
175081ad6265SDimitry Andric       UsedPHIs.insert(&CurrPN);
175104eeddc0SDimitry Andric       return &CurrPN;
175204eeddc0SDimitry Andric     }
175381ad6265SDimitry Andric   }
175404eeddc0SDimitry Andric 
175504eeddc0SDimitry Andric   // If we've made it here, it means we weren't able to replace the PHINode, so
175604eeddc0SDimitry Andric   // we must insert it ourselves.
175704eeddc0SDimitry Andric   PHINode *NewPN = cast<PHINode>(PN.clone());
175804eeddc0SDimitry Andric   NewPN->insertBefore(&*OverallPhiBlock->begin());
175904eeddc0SDimitry Andric   for (unsigned Idx = 0, Edx = NewPN->getNumIncomingValues(); Idx < Edx;
176004eeddc0SDimitry Andric        Idx++) {
176104eeddc0SDimitry Andric     Value *IncomingVal = NewPN->getIncomingValue(Idx);
176204eeddc0SDimitry Andric     BasicBlock *IncomingBlock = NewPN->getIncomingBlock(Idx);
176304eeddc0SDimitry Andric 
176404eeddc0SDimitry Andric     // Find corresponding basic block in the overall function for the incoming
176504eeddc0SDimitry Andric     // block.
176681ad6265SDimitry Andric     BasicBlock *BlockToUse =
176781ad6265SDimitry Andric         Region.findCorrespondingBlockIn(*FirstRegion, IncomingBlock);
176804eeddc0SDimitry Andric     NewPN->setIncomingBlock(Idx, BlockToUse);
176904eeddc0SDimitry Andric 
177004eeddc0SDimitry Andric     // If we have an argument we make sure we replace using the argument from
177104eeddc0SDimitry Andric     // the correct function.
177204eeddc0SDimitry Andric     if (Argument *A = dyn_cast<Argument>(IncomingVal)) {
177304eeddc0SDimitry Andric       Value *Val = Group.OutlinedFunction->getArg(A->getArgNo());
177404eeddc0SDimitry Andric       NewPN->setIncomingValue(Idx, Val);
177504eeddc0SDimitry Andric       continue;
177604eeddc0SDimitry Andric     }
177704eeddc0SDimitry Andric 
177804eeddc0SDimitry Andric     // Find the corresponding value in the overall function.
177904eeddc0SDimitry Andric     IncomingVal = findOutputMapping(OutputMappings, IncomingVal);
178004eeddc0SDimitry Andric     Value *Val = Region.findCorrespondingValueIn(*FirstRegion, IncomingVal);
178104eeddc0SDimitry Andric     assert(Val && "Value is nullptr?");
178281ad6265SDimitry Andric     DenseMap<Value *, Value *>::iterator RemappedIt =
178381ad6265SDimitry Andric         FirstRegion->RemappedArguments.find(Val);
178481ad6265SDimitry Andric     if (RemappedIt != FirstRegion->RemappedArguments.end())
178581ad6265SDimitry Andric       Val = RemappedIt->second;
178604eeddc0SDimitry Andric     NewPN->setIncomingValue(Idx, Val);
178704eeddc0SDimitry Andric   }
178804eeddc0SDimitry Andric   return NewPN;
178904eeddc0SDimitry Andric }
179004eeddc0SDimitry Andric 
1791e8d8bef9SDimitry Andric // Within an extracted function, replace the argument uses of the extracted
1792e8d8bef9SDimitry Andric // region with the arguments of the function for an OutlinableGroup.
1793e8d8bef9SDimitry Andric //
1794e8d8bef9SDimitry Andric /// \param [in] Region - The region of extracted code to be changed.
1795349cc55cSDimitry Andric /// \param [in,out] OutputBBs - The BasicBlock for the output stores for this
1796e8d8bef9SDimitry Andric /// region.
1797349cc55cSDimitry Andric /// \param [in] FirstFunction - A flag to indicate whether we are using this
1798349cc55cSDimitry Andric /// function to define the overall outlined function for all the regions, or
1799349cc55cSDimitry Andric /// if we are operating on one of the following regions.
1800349cc55cSDimitry Andric static void
1801349cc55cSDimitry Andric replaceArgumentUses(OutlinableRegion &Region,
1802349cc55cSDimitry Andric                     DenseMap<Value *, BasicBlock *> &OutputBBs,
180304eeddc0SDimitry Andric                     const DenseMap<Value *, Value *> &OutputMappings,
1804349cc55cSDimitry Andric                     bool FirstFunction = false) {
1805e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
1806e8d8bef9SDimitry Andric   assert(Region.ExtractedFunction && "Region has no extracted function?");
1807e8d8bef9SDimitry Andric 
1808349cc55cSDimitry Andric   Function *DominatingFunction = Region.ExtractedFunction;
1809349cc55cSDimitry Andric   if (FirstFunction)
1810349cc55cSDimitry Andric     DominatingFunction = Group.OutlinedFunction;
1811349cc55cSDimitry Andric   DominatorTree DT(*DominatingFunction);
181281ad6265SDimitry Andric   DenseSet<PHINode *> UsedPHIs;
1813349cc55cSDimitry Andric 
1814e8d8bef9SDimitry Andric   for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size();
1815e8d8bef9SDimitry Andric        ArgIdx++) {
181606c3fb27SDimitry Andric     assert(Region.ExtractedArgToAgg.contains(ArgIdx) &&
1817e8d8bef9SDimitry Andric            "No mapping from extracted to outlined?");
1818e8d8bef9SDimitry Andric     unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second;
1819e8d8bef9SDimitry Andric     Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx);
1820e8d8bef9SDimitry Andric     Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx);
1821e8d8bef9SDimitry Andric     // The argument is an input, so we can simply replace it with the overall
1822e8d8bef9SDimitry Andric     // argument value
1823e8d8bef9SDimitry Andric     if (ArgIdx < Region.NumExtractedInputs) {
1824e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function "
1825e8d8bef9SDimitry Andric                         << *Region.ExtractedFunction << " with " << *AggArg
1826e8d8bef9SDimitry Andric                         << " in function " << *Group.OutlinedFunction << "\n");
1827e8d8bef9SDimitry Andric       Arg->replaceAllUsesWith(AggArg);
182881ad6265SDimitry Andric       Value *V = Region.Call->getArgOperand(ArgIdx);
182981ad6265SDimitry Andric       Region.RemappedArguments.insert(std::make_pair(V, AggArg));
1830e8d8bef9SDimitry Andric       continue;
1831e8d8bef9SDimitry Andric     }
1832e8d8bef9SDimitry Andric 
1833e8d8bef9SDimitry Andric     // If we are replacing an output, we place the store value in its own
1834e8d8bef9SDimitry Andric     // block inside the overall function before replacing the use of the output
1835e8d8bef9SDimitry Andric     // in the function.
1836e8d8bef9SDimitry Andric     assert(Arg->hasOneUse() && "Output argument can only have one use");
1837e8d8bef9SDimitry Andric     User *InstAsUser = Arg->user_back();
1838e8d8bef9SDimitry Andric     assert(InstAsUser && "User is nullptr!");
1839e8d8bef9SDimitry Andric 
1840e8d8bef9SDimitry Andric     Instruction *I = cast<Instruction>(InstAsUser);
1841349cc55cSDimitry Andric     BasicBlock *BB = I->getParent();
1842349cc55cSDimitry Andric     SmallVector<BasicBlock *, 4> Descendants;
1843349cc55cSDimitry Andric     DT.getDescendants(BB, Descendants);
1844349cc55cSDimitry Andric     bool EdgeAdded = false;
1845349cc55cSDimitry Andric     if (Descendants.size() == 0) {
1846349cc55cSDimitry Andric       EdgeAdded = true;
1847349cc55cSDimitry Andric       DT.insertEdge(&DominatingFunction->getEntryBlock(), BB);
1848349cc55cSDimitry Andric       DT.getDescendants(BB, Descendants);
1849349cc55cSDimitry Andric     }
1850349cc55cSDimitry Andric 
1851349cc55cSDimitry Andric     // Iterate over the following blocks, looking for return instructions,
1852349cc55cSDimitry Andric     // if we find one, find the corresponding output block for the return value
1853349cc55cSDimitry Andric     // and move our store instruction there.
1854349cc55cSDimitry Andric     for (BasicBlock *DescendBB : Descendants) {
1855349cc55cSDimitry Andric       ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator());
1856349cc55cSDimitry Andric       if (!RI)
1857349cc55cSDimitry Andric         continue;
1858349cc55cSDimitry Andric       Value *RetVal = RI->getReturnValue();
1859349cc55cSDimitry Andric       auto VBBIt = OutputBBs.find(RetVal);
1860349cc55cSDimitry Andric       assert(VBBIt != OutputBBs.end() && "Could not find output value!");
1861349cc55cSDimitry Andric 
1862349cc55cSDimitry Andric       // If this is storing a PHINode, we must make sure it is included in the
1863349cc55cSDimitry Andric       // overall function.
1864349cc55cSDimitry Andric       StoreInst *SI = cast<StoreInst>(I);
1865349cc55cSDimitry Andric 
1866349cc55cSDimitry Andric       Value *ValueOperand = SI->getValueOperand();
1867349cc55cSDimitry Andric 
1868349cc55cSDimitry Andric       StoreInst *NewI = cast<StoreInst>(I->clone());
1869349cc55cSDimitry Andric       NewI->setDebugLoc(DebugLoc());
1870349cc55cSDimitry Andric       BasicBlock *OutputBB = VBBIt->second;
1871bdd1243dSDimitry Andric       NewI->insertInto(OutputBB, OutputBB->end());
1872e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to "
1873e8d8bef9SDimitry Andric                         << *OutputBB << "\n");
1874e8d8bef9SDimitry Andric 
187504eeddc0SDimitry Andric       // If this is storing a PHINode, we must make sure it is included in the
187604eeddc0SDimitry Andric       // overall function.
187704eeddc0SDimitry Andric       if (!isa<PHINode>(ValueOperand) ||
187881ad6265SDimitry Andric           Region.Candidate->getGVN(ValueOperand).has_value()) {
1879349cc55cSDimitry Andric         if (FirstFunction)
1880349cc55cSDimitry Andric           continue;
1881349cc55cSDimitry Andric         Value *CorrVal =
1882349cc55cSDimitry Andric             Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand);
1883349cc55cSDimitry Andric         assert(CorrVal && "Value is nullptr?");
1884349cc55cSDimitry Andric         NewI->setOperand(0, CorrVal);
188504eeddc0SDimitry Andric         continue;
188604eeddc0SDimitry Andric       }
188704eeddc0SDimitry Andric       PHINode *PN = cast<PHINode>(SI->getValueOperand());
188804eeddc0SDimitry Andric       // If it has a value, it was not split by the code extractor, which
188904eeddc0SDimitry Andric       // is what we are looking for.
189081ad6265SDimitry Andric       if (Region.Candidate->getGVN(PN))
189104eeddc0SDimitry Andric         continue;
189204eeddc0SDimitry Andric 
189304eeddc0SDimitry Andric       // We record the parent block for the PHINode in the Region so that
189404eeddc0SDimitry Andric       // we can exclude it from checks later on.
189504eeddc0SDimitry Andric       Region.PHIBlocks.insert(std::make_pair(RetVal, PN->getParent()));
189604eeddc0SDimitry Andric 
189704eeddc0SDimitry Andric       // If this is the first function, we do not need to worry about mergiing
189804eeddc0SDimitry Andric       // this with any other block in the overall outlined function, so we can
189904eeddc0SDimitry Andric       // just continue.
190004eeddc0SDimitry Andric       if (FirstFunction) {
190104eeddc0SDimitry Andric         BasicBlock *PHIBlock = PN->getParent();
190204eeddc0SDimitry Andric         Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
190304eeddc0SDimitry Andric         continue;
190404eeddc0SDimitry Andric       }
190504eeddc0SDimitry Andric 
190604eeddc0SDimitry Andric       // We look for the aggregate block that contains the PHINodes leading into
190704eeddc0SDimitry Andric       // this exit path. If we can't find one, we create one.
190804eeddc0SDimitry Andric       BasicBlock *OverallPhiBlock = findOrCreatePHIBlock(Group, RetVal);
190904eeddc0SDimitry Andric 
191004eeddc0SDimitry Andric       // For our PHINode, we find the combined canonical numbering, and
191104eeddc0SDimitry Andric       // attempt to find a matching PHINode in the overall PHIBlock.  If we
191204eeddc0SDimitry Andric       // cannot, we copy the PHINode and move it into this new block.
191381ad6265SDimitry Andric       PHINode *NewPN = findOrCreatePHIInBlock(*PN, Region, OverallPhiBlock,
191481ad6265SDimitry Andric                                               OutputMappings, UsedPHIs);
191504eeddc0SDimitry Andric       NewI->setOperand(0, NewPN);
1916349cc55cSDimitry Andric     }
1917349cc55cSDimitry Andric 
1918349cc55cSDimitry Andric     // If we added an edge for basic blocks without a predecessor, we remove it
1919349cc55cSDimitry Andric     // here.
1920349cc55cSDimitry Andric     if (EdgeAdded)
1921349cc55cSDimitry Andric       DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB);
1922349cc55cSDimitry Andric     I->eraseFromParent();
1923e8d8bef9SDimitry Andric 
1924e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function "
1925e8d8bef9SDimitry Andric                       << *Region.ExtractedFunction << " with " << *AggArg
1926e8d8bef9SDimitry Andric                       << " in function " << *Group.OutlinedFunction << "\n");
1927e8d8bef9SDimitry Andric     Arg->replaceAllUsesWith(AggArg);
1928e8d8bef9SDimitry Andric   }
1929e8d8bef9SDimitry Andric }
1930e8d8bef9SDimitry Andric 
1931e8d8bef9SDimitry Andric /// Within an extracted function, replace the constants that need to be lifted
1932e8d8bef9SDimitry Andric /// into arguments with the actual argument.
1933e8d8bef9SDimitry Andric ///
1934e8d8bef9SDimitry Andric /// \param Region [in] - The region of extracted code to be changed.
1935e8d8bef9SDimitry Andric void replaceConstants(OutlinableRegion &Region) {
1936e8d8bef9SDimitry Andric   OutlinableGroup &Group = *Region.Parent;
1937e8d8bef9SDimitry Andric   // Iterate over the constants that need to be elevated into arguments
1938e8d8bef9SDimitry Andric   for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) {
1939e8d8bef9SDimitry Andric     unsigned AggArgIdx = Const.first;
1940e8d8bef9SDimitry Andric     Function *OutlinedFunction = Group.OutlinedFunction;
1941e8d8bef9SDimitry Andric     assert(OutlinedFunction && "Overall Function is not defined?");
1942e8d8bef9SDimitry Andric     Constant *CST = Const.second;
1943e8d8bef9SDimitry Andric     Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx);
1944e8d8bef9SDimitry Andric     // Identify the argument it will be elevated to, and replace instances of
1945e8d8bef9SDimitry Andric     // that constant in the function.
1946e8d8bef9SDimitry Andric 
1947e8d8bef9SDimitry Andric     // TODO: If in the future constants do not have one global value number,
1948e8d8bef9SDimitry Andric     // i.e. a constant 1 could be mapped to several values, this check will
1949e8d8bef9SDimitry Andric     // have to be more strict.  It cannot be using only replaceUsesWithIf.
1950e8d8bef9SDimitry Andric 
1951e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST
1952e8d8bef9SDimitry Andric                       << " in function " << *OutlinedFunction << " with "
1953e8d8bef9SDimitry Andric                       << *Arg << "\n");
1954e8d8bef9SDimitry Andric     CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) {
1955e8d8bef9SDimitry Andric       if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1956e8d8bef9SDimitry Andric         return I->getFunction() == OutlinedFunction;
1957e8d8bef9SDimitry Andric       return false;
1958e8d8bef9SDimitry Andric     });
1959e8d8bef9SDimitry Andric   }
1960e8d8bef9SDimitry Andric }
1961e8d8bef9SDimitry Andric 
1962e8d8bef9SDimitry Andric /// It is possible that there is a basic block that already performs the same
1963e8d8bef9SDimitry Andric /// stores. This returns a duplicate block, if it exists
1964e8d8bef9SDimitry Andric ///
1965349cc55cSDimitry Andric /// \param OutputBBs [in] the blocks we are looking for a duplicate of.
1966e8d8bef9SDimitry Andric /// \param OutputStoreBBs [in] The existing output blocks.
1967e8d8bef9SDimitry Andric /// \returns an optional value with the number output block if there is a match.
1968bdd1243dSDimitry Andric std::optional<unsigned> findDuplicateOutputBlock(
1969349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> &OutputBBs,
1970349cc55cSDimitry Andric     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1971e8d8bef9SDimitry Andric 
1972349cc55cSDimitry Andric   bool Mismatch = false;
1973e8d8bef9SDimitry Andric   unsigned MatchingNum = 0;
1974349cc55cSDimitry Andric   // We compare the new set output blocks to the other sets of output blocks.
1975349cc55cSDimitry Andric   // If they are the same number, and have identical instructions, they are
1976349cc55cSDimitry Andric   // considered to be the same.
1977349cc55cSDimitry Andric   for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) {
1978349cc55cSDimitry Andric     Mismatch = false;
1979349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) {
1980349cc55cSDimitry Andric       DenseMap<Value *, BasicBlock *>::iterator OutputBBIt =
1981349cc55cSDimitry Andric           OutputBBs.find(VToB.first);
1982349cc55cSDimitry Andric       if (OutputBBIt == OutputBBs.end()) {
1983349cc55cSDimitry Andric         Mismatch = true;
1984349cc55cSDimitry Andric         break;
1985e8d8bef9SDimitry Andric       }
1986e8d8bef9SDimitry Andric 
1987349cc55cSDimitry Andric       BasicBlock *CompBB = VToB.second;
1988349cc55cSDimitry Andric       BasicBlock *OutputBB = OutputBBIt->second;
1989349cc55cSDimitry Andric       if (CompBB->size() - 1 != OutputBB->size()) {
1990349cc55cSDimitry Andric         Mismatch = true;
1991349cc55cSDimitry Andric         break;
1992349cc55cSDimitry Andric       }
1993349cc55cSDimitry Andric 
1994e8d8bef9SDimitry Andric       BasicBlock::iterator NIt = OutputBB->begin();
1995e8d8bef9SDimitry Andric       for (Instruction &I : *CompBB) {
1996e8d8bef9SDimitry Andric         if (isa<BranchInst>(&I))
1997e8d8bef9SDimitry Andric           continue;
1998e8d8bef9SDimitry Andric 
1999e8d8bef9SDimitry Andric         if (!I.isIdenticalTo(&(*NIt))) {
2000349cc55cSDimitry Andric           Mismatch = true;
2001e8d8bef9SDimitry Andric           break;
2002e8d8bef9SDimitry Andric         }
2003e8d8bef9SDimitry Andric 
2004e8d8bef9SDimitry Andric         NIt++;
2005e8d8bef9SDimitry Andric       }
2006349cc55cSDimitry Andric     }
2007349cc55cSDimitry Andric 
2008349cc55cSDimitry Andric     if (!Mismatch)
2009e8d8bef9SDimitry Andric       return MatchingNum;
2010e8d8bef9SDimitry Andric 
2011e8d8bef9SDimitry Andric     MatchingNum++;
2012e8d8bef9SDimitry Andric   }
2013e8d8bef9SDimitry Andric 
2014bdd1243dSDimitry Andric   return std::nullopt;
2015e8d8bef9SDimitry Andric }
2016e8d8bef9SDimitry Andric 
2017349cc55cSDimitry Andric /// Remove empty output blocks from the outlined region.
2018349cc55cSDimitry Andric ///
2019349cc55cSDimitry Andric /// \param BlocksToPrune - Mapping of return values output blocks for the \p
2020349cc55cSDimitry Andric /// Region.
2021349cc55cSDimitry Andric /// \param Region - The OutlinableRegion we are analyzing.
2022349cc55cSDimitry Andric static bool
2023349cc55cSDimitry Andric analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune,
2024349cc55cSDimitry Andric                             OutlinableRegion &Region) {
2025349cc55cSDimitry Andric   bool AllRemoved = true;
2026349cc55cSDimitry Andric   Value *RetValueForBB;
2027349cc55cSDimitry Andric   BasicBlock *NewBB;
2028349cc55cSDimitry Andric   SmallVector<Value *, 4> ToRemove;
2029349cc55cSDimitry Andric   // Iterate over the output blocks created in the outlined section.
2030349cc55cSDimitry Andric   for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) {
2031349cc55cSDimitry Andric     RetValueForBB = VtoBB.first;
2032349cc55cSDimitry Andric     NewBB = VtoBB.second;
2033349cc55cSDimitry Andric 
2034349cc55cSDimitry Andric     // If there are no instructions, we remove it from the module, and also
2035349cc55cSDimitry Andric     // mark the value for removal from the return value to output block mapping.
2036349cc55cSDimitry Andric     if (NewBB->size() == 0) {
2037349cc55cSDimitry Andric       NewBB->eraseFromParent();
2038349cc55cSDimitry Andric       ToRemove.push_back(RetValueForBB);
2039349cc55cSDimitry Andric       continue;
2040349cc55cSDimitry Andric     }
2041349cc55cSDimitry Andric 
2042349cc55cSDimitry Andric     // Mark that we could not remove all the blocks since they were not all
2043349cc55cSDimitry Andric     // empty.
2044349cc55cSDimitry Andric     AllRemoved = false;
2045349cc55cSDimitry Andric   }
2046349cc55cSDimitry Andric 
2047349cc55cSDimitry Andric   // Remove the return value from the mapping.
2048349cc55cSDimitry Andric   for (Value *V : ToRemove)
2049349cc55cSDimitry Andric     BlocksToPrune.erase(V);
2050349cc55cSDimitry Andric 
2051349cc55cSDimitry Andric   // Mark the region as having the no output scheme.
2052349cc55cSDimitry Andric   if (AllRemoved)
2053349cc55cSDimitry Andric     Region.OutputBlockNum = -1;
2054349cc55cSDimitry Andric 
2055349cc55cSDimitry Andric   return AllRemoved;
2056349cc55cSDimitry Andric }
2057349cc55cSDimitry Andric 
2058e8d8bef9SDimitry Andric /// For the outlined section, move needed the StoreInsts for the output
2059e8d8bef9SDimitry Andric /// registers into their own block. Then, determine if there is a duplicate
2060e8d8bef9SDimitry Andric /// output block already created.
2061e8d8bef9SDimitry Andric ///
2062e8d8bef9SDimitry Andric /// \param [in] OG - The OutlinableGroup of regions to be outlined.
2063e8d8bef9SDimitry Andric /// \param [in] Region - The OutlinableRegion that is being analyzed.
2064349cc55cSDimitry Andric /// \param [in,out] OutputBBs - the blocks that stores for this region will be
2065e8d8bef9SDimitry Andric /// placed in.
2066349cc55cSDimitry Andric /// \param [in] EndBBs - the final blocks of the extracted function.
2067e8d8bef9SDimitry Andric /// \param [in] OutputMappings - OutputMappings the mapping of values that have
2068e8d8bef9SDimitry Andric /// been replaced by a new output value.
2069e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The existing output blocks.
2070349cc55cSDimitry Andric static void alignOutputBlockWithAggFunc(
2071349cc55cSDimitry Andric     OutlinableGroup &OG, OutlinableRegion &Region,
2072349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> &OutputBBs,
2073349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> &EndBBs,
2074e8d8bef9SDimitry Andric     const DenseMap<Value *, Value *> &OutputMappings,
2075349cc55cSDimitry Andric     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
2076349cc55cSDimitry Andric   // If none of the output blocks have any instructions, this means that we do
2077349cc55cSDimitry Andric   // not have to determine if it matches any of the other output schemes, and we
2078349cc55cSDimitry Andric   // don't have to do anything else.
2079349cc55cSDimitry Andric   if (analyzeAndPruneOutputBlocks(OutputBBs, Region))
2080e8d8bef9SDimitry Andric     return;
2081e8d8bef9SDimitry Andric 
2082349cc55cSDimitry Andric   // Determine is there is a duplicate set of blocks.
2083bdd1243dSDimitry Andric   std::optional<unsigned> MatchingBB =
2084349cc55cSDimitry Andric       findDuplicateOutputBlock(OutputBBs, OutputStoreBBs);
2085e8d8bef9SDimitry Andric 
2086349cc55cSDimitry Andric   // If there is, we remove the new output blocks.  If it does not,
2087349cc55cSDimitry Andric   // we add it to our list of sets of output blocks.
208881ad6265SDimitry Andric   if (MatchingBB) {
2089e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Set output block for region in function"
2090bdd1243dSDimitry Andric                       << Region.ExtractedFunction << " to " << *MatchingBB);
2091e8d8bef9SDimitry Andric 
2092bdd1243dSDimitry Andric     Region.OutputBlockNum = *MatchingBB;
2093349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)
2094349cc55cSDimitry Andric       VtoBB.second->eraseFromParent();
2095e8d8bef9SDimitry Andric     return;
2096e8d8bef9SDimitry Andric   }
2097e8d8bef9SDimitry Andric 
2098e8d8bef9SDimitry Andric   Region.OutputBlockNum = OutputStoreBBs.size();
2099e8d8bef9SDimitry Andric 
2100349cc55cSDimitry Andric   Value *RetValueForBB;
2101349cc55cSDimitry Andric   BasicBlock *NewBB;
2102349cc55cSDimitry Andric   OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
2103349cc55cSDimitry Andric   for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) {
2104349cc55cSDimitry Andric     RetValueForBB = VtoBB.first;
2105349cc55cSDimitry Andric     NewBB = VtoBB.second;
2106349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *>::iterator VBBIt =
2107349cc55cSDimitry Andric         EndBBs.find(RetValueForBB);
2108e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Create output block for region in"
2109e8d8bef9SDimitry Andric                       << Region.ExtractedFunction << " to "
2110349cc55cSDimitry Andric                       << *NewBB);
2111349cc55cSDimitry Andric     BranchInst::Create(VBBIt->second, NewBB);
2112349cc55cSDimitry Andric     OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB));
2113349cc55cSDimitry Andric   }
2114349cc55cSDimitry Andric }
2115349cc55cSDimitry Andric 
2116349cc55cSDimitry Andric /// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys,
2117349cc55cSDimitry Andric /// before creating a basic block for each \p NewMap, and inserting into the new
2118349cc55cSDimitry Andric /// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>".
2119349cc55cSDimitry Andric ///
2120349cc55cSDimitry Andric /// \param OldMap [in] - The mapping to base the new mapping off of.
2121349cc55cSDimitry Andric /// \param NewMap [out] - The output mapping using the keys of \p OldMap.
2122349cc55cSDimitry Andric /// \param ParentFunc [in] - The function to put the new basic block in.
2123349cc55cSDimitry Andric /// \param BaseName [in] - The start of the BasicBlock names to be appended to
2124349cc55cSDimitry Andric /// by an index value.
2125349cc55cSDimitry Andric static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap,
2126349cc55cSDimitry Andric                                        DenseMap<Value *, BasicBlock *> &NewMap,
2127349cc55cSDimitry Andric                                        Function *ParentFunc, Twine BaseName) {
2128349cc55cSDimitry Andric   unsigned Idx = 0;
2129349cc55cSDimitry Andric   std::vector<Value *> SortedKeys;
2130349cc55cSDimitry Andric 
2131349cc55cSDimitry Andric   getSortedConstantKeys(SortedKeys, OldMap);
2132349cc55cSDimitry Andric 
2133349cc55cSDimitry Andric   for (Value *RetVal : SortedKeys) {
2134349cc55cSDimitry Andric     BasicBlock *NewBB = BasicBlock::Create(
2135349cc55cSDimitry Andric         ParentFunc->getContext(),
2136349cc55cSDimitry Andric         Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)),
2137349cc55cSDimitry Andric         ParentFunc);
2138349cc55cSDimitry Andric     NewMap.insert(std::make_pair(RetVal, NewBB));
2139349cc55cSDimitry Andric   }
2140e8d8bef9SDimitry Andric }
2141e8d8bef9SDimitry Andric 
2142e8d8bef9SDimitry Andric /// Create the switch statement for outlined function to differentiate between
2143e8d8bef9SDimitry Andric /// all the output blocks.
2144e8d8bef9SDimitry Andric ///
2145e8d8bef9SDimitry Andric /// For the outlined section, determine if an outlined block already exists that
2146e8d8bef9SDimitry Andric /// matches the needed stores for the extracted section.
2147e8d8bef9SDimitry Andric /// \param [in] M - The module we are outlining from.
2148e8d8bef9SDimitry Andric /// \param [in] OG - The group of regions to be outlined.
2149349cc55cSDimitry Andric /// \param [in] EndBBs - The final blocks of the extracted function.
2150e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The existing output blocks.
2151349cc55cSDimitry Andric void createSwitchStatement(
2152349cc55cSDimitry Andric     Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs,
2153349cc55cSDimitry Andric     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
2154e8d8bef9SDimitry Andric   // We only need the switch statement if there is more than one store
215504eeddc0SDimitry Andric   // combination, or there is more than one set of output blocks.  The first
215604eeddc0SDimitry Andric   // will occur when we store different sets of values for two different
215704eeddc0SDimitry Andric   // regions.  The second will occur when we have two outputs that are combined
215804eeddc0SDimitry Andric   // in a PHINode outside of the region in one outlined instance, and are used
215904eeddc0SDimitry Andric   // seaparately in another. This will create the same set of OutputGVNs, but
216004eeddc0SDimitry Andric   // will generate two different output schemes.
2161e8d8bef9SDimitry Andric   if (OG.OutputGVNCombinations.size() > 1) {
2162e8d8bef9SDimitry Andric     Function *AggFunc = OG.OutlinedFunction;
2163349cc55cSDimitry Andric     // Create a final block for each different return block.
2164349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> ReturnBBs;
2165349cc55cSDimitry Andric     createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block");
2166349cc55cSDimitry Andric 
2167349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) {
2168349cc55cSDimitry Andric       std::pair<Value *, BasicBlock *> &OutputBlock =
2169349cc55cSDimitry Andric           *OG.EndBBs.find(RetBlockPair.first);
2170349cc55cSDimitry Andric       BasicBlock *ReturnBlock = RetBlockPair.second;
2171349cc55cSDimitry Andric       BasicBlock *EndBB = OutputBlock.second;
2172e8d8bef9SDimitry Andric       Instruction *Term = EndBB->getTerminator();
2173349cc55cSDimitry Andric       // Move the return value to the final block instead of the original exit
2174349cc55cSDimitry Andric       // stub.
2175e8d8bef9SDimitry Andric       Term->moveBefore(*ReturnBlock, ReturnBlock->end());
2176349cc55cSDimitry Andric       // Put the switch statement in the old end basic block for the function
2177349cc55cSDimitry Andric       // with a fall through to the new return block.
2178e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for "
2179e8d8bef9SDimitry Andric                         << OutputStoreBBs.size() << "\n");
2180e8d8bef9SDimitry Andric       SwitchInst *SwitchI =
2181e8d8bef9SDimitry Andric           SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1),
2182e8d8bef9SDimitry Andric                              ReturnBlock, OutputStoreBBs.size(), EndBB);
2183e8d8bef9SDimitry Andric 
2184e8d8bef9SDimitry Andric       unsigned Idx = 0;
2185349cc55cSDimitry Andric       for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) {
2186349cc55cSDimitry Andric         DenseMap<Value *, BasicBlock *>::iterator OSBBIt =
2187349cc55cSDimitry Andric             OutputStoreBB.find(OutputBlock.first);
2188349cc55cSDimitry Andric 
2189349cc55cSDimitry Andric         if (OSBBIt == OutputStoreBB.end())
2190349cc55cSDimitry Andric           continue;
2191349cc55cSDimitry Andric 
2192349cc55cSDimitry Andric         BasicBlock *BB = OSBBIt->second;
2193349cc55cSDimitry Andric         SwitchI->addCase(
2194349cc55cSDimitry Andric             ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB);
2195e8d8bef9SDimitry Andric         Term = BB->getTerminator();
2196e8d8bef9SDimitry Andric         Term->setSuccessor(0, ReturnBlock);
2197e8d8bef9SDimitry Andric         Idx++;
2198e8d8bef9SDimitry Andric       }
2199349cc55cSDimitry Andric     }
2200e8d8bef9SDimitry Andric     return;
2201e8d8bef9SDimitry Andric   }
2202e8d8bef9SDimitry Andric 
220304eeddc0SDimitry Andric   assert(OutputStoreBBs.size() < 2 && "Different store sets not handled!");
220404eeddc0SDimitry Andric 
2205349cc55cSDimitry Andric   // If there needs to be stores, move them from the output blocks to their
220604eeddc0SDimitry Andric   // corresponding ending block.  We do not check that the OutputGVNCombinations
220704eeddc0SDimitry Andric   // is equal to 1 here since that could just been the case where there are 0
220804eeddc0SDimitry Andric   // outputs. Instead, we check whether there is more than one set of output
220904eeddc0SDimitry Andric   // blocks since this is the only case where we would have to move the
221004eeddc0SDimitry Andric   // stores, and erase the extraneous blocks.
2211e8d8bef9SDimitry Andric   if (OutputStoreBBs.size() == 1) {
2212e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Move store instructions to the end block in "
2213e8d8bef9SDimitry Andric                       << *OG.OutlinedFunction << "\n");
2214349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0];
2215349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) {
2216349cc55cSDimitry Andric       DenseMap<Value *, BasicBlock *>::iterator EndBBIt =
2217349cc55cSDimitry Andric           EndBBs.find(VBPair.first);
2218349cc55cSDimitry Andric       assert(EndBBIt != EndBBs.end() && "Could not find end block");
2219349cc55cSDimitry Andric       BasicBlock *EndBB = EndBBIt->second;
2220349cc55cSDimitry Andric       BasicBlock *OutputBB = VBPair.second;
2221349cc55cSDimitry Andric       Instruction *Term = OutputBB->getTerminator();
2222e8d8bef9SDimitry Andric       Term->eraseFromParent();
2223e8d8bef9SDimitry Andric       Term = EndBB->getTerminator();
2224349cc55cSDimitry Andric       moveBBContents(*OutputBB, *EndBB);
2225e8d8bef9SDimitry Andric       Term->moveBefore(*EndBB, EndBB->end());
2226349cc55cSDimitry Andric       OutputBB->eraseFromParent();
2227349cc55cSDimitry Andric     }
2228e8d8bef9SDimitry Andric   }
2229e8d8bef9SDimitry Andric }
2230e8d8bef9SDimitry Andric 
2231e8d8bef9SDimitry Andric /// Fill the new function that will serve as the replacement function for all of
2232e8d8bef9SDimitry Andric /// the extracted regions of a certain structure from the first region in the
2233e8d8bef9SDimitry Andric /// list of regions.  Replace this first region's extracted function with the
2234e8d8bef9SDimitry Andric /// new overall function.
2235e8d8bef9SDimitry Andric ///
2236e8d8bef9SDimitry Andric /// \param [in] M - The module we are outlining from.
2237e8d8bef9SDimitry Andric /// \param [in] CurrentGroup - The group of regions to be outlined.
2238e8d8bef9SDimitry Andric /// \param [in,out] OutputStoreBBs - The output blocks for each different
2239e8d8bef9SDimitry Andric /// set of stores needed for the different functions.
2240e8d8bef9SDimitry Andric /// \param [in,out] FuncsToRemove - Extracted functions to erase from module
2241e8d8bef9SDimitry Andric /// once outlining is complete.
224204eeddc0SDimitry Andric /// \param [in] OutputMappings - Extracted functions to erase from module
224304eeddc0SDimitry Andric /// once outlining is complete.
2244349cc55cSDimitry Andric static void fillOverallFunction(
2245349cc55cSDimitry Andric     Module &M, OutlinableGroup &CurrentGroup,
2246349cc55cSDimitry Andric     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs,
224704eeddc0SDimitry Andric     std::vector<Function *> &FuncsToRemove,
224804eeddc0SDimitry Andric     const DenseMap<Value *, Value *> &OutputMappings) {
2249e8d8bef9SDimitry Andric   OutlinableRegion *CurrentOS = CurrentGroup.Regions[0];
2250e8d8bef9SDimitry Andric 
2251e8d8bef9SDimitry Andric   // Move first extracted function's instructions into new function.
2252e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Move instructions from "
2253e8d8bef9SDimitry Andric                     << *CurrentOS->ExtractedFunction << " to instruction "
2254e8d8bef9SDimitry Andric                     << *CurrentGroup.OutlinedFunction << "\n");
2255349cc55cSDimitry Andric   moveFunctionData(*CurrentOS->ExtractedFunction,
2256349cc55cSDimitry Andric                    *CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs);
2257e8d8bef9SDimitry Andric 
2258e8d8bef9SDimitry Andric   // Transfer the attributes from the function to the new function.
2259349cc55cSDimitry Andric   for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs())
2260e8d8bef9SDimitry Andric     CurrentGroup.OutlinedFunction->addFnAttr(A);
2261e8d8bef9SDimitry Andric 
2262349cc55cSDimitry Andric   // Create a new set of output blocks for the first extracted function.
2263349cc55cSDimitry Andric   DenseMap<Value *, BasicBlock *> NewBBs;
2264349cc55cSDimitry Andric   createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs,
2265349cc55cSDimitry Andric                              CurrentGroup.OutlinedFunction, "output_block_0");
2266e8d8bef9SDimitry Andric   CurrentOS->OutputBlockNum = 0;
2267e8d8bef9SDimitry Andric 
226804eeddc0SDimitry Andric   replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings, true);
2269e8d8bef9SDimitry Andric   replaceConstants(*CurrentOS);
2270e8d8bef9SDimitry Andric 
2271349cc55cSDimitry Andric   // We first identify if any output blocks are empty, if they are we remove
2272349cc55cSDimitry Andric   // them. We then create a branch instruction to the basic block to the return
2273349cc55cSDimitry Andric   // block for the function for each non empty output block.
2274349cc55cSDimitry Andric   if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) {
2275349cc55cSDimitry Andric     OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
2276349cc55cSDimitry Andric     for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) {
2277349cc55cSDimitry Andric       DenseMap<Value *, BasicBlock *>::iterator VBBIt =
2278349cc55cSDimitry Andric           CurrentGroup.EndBBs.find(VToBB.first);
2279349cc55cSDimitry Andric       BasicBlock *EndBB = VBBIt->second;
2280349cc55cSDimitry Andric       BranchInst::Create(EndBB, VToBB.second);
2281349cc55cSDimitry Andric       OutputStoreBBs.back().insert(VToBB);
2282349cc55cSDimitry Andric     }
2283e8d8bef9SDimitry Andric   }
2284e8d8bef9SDimitry Andric 
2285e8d8bef9SDimitry Andric   // Replace the call to the extracted function with the outlined function.
2286e8d8bef9SDimitry Andric   CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
2287e8d8bef9SDimitry Andric 
2288e8d8bef9SDimitry Andric   // We only delete the extracted functions at the end since we may need to
2289e8d8bef9SDimitry Andric   // reference instructions contained in them for mapping purposes.
2290e8d8bef9SDimitry Andric   FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
2291e8d8bef9SDimitry Andric }
2292e8d8bef9SDimitry Andric 
2293e8d8bef9SDimitry Andric void IROutliner::deduplicateExtractedSections(
2294e8d8bef9SDimitry Andric     Module &M, OutlinableGroup &CurrentGroup,
2295e8d8bef9SDimitry Andric     std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) {
2296e8d8bef9SDimitry Andric   createFunction(M, CurrentGroup, OutlinedFunctionNum);
2297e8d8bef9SDimitry Andric 
2298349cc55cSDimitry Andric   std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs;
2299e8d8bef9SDimitry Andric 
2300e8d8bef9SDimitry Andric   OutlinableRegion *CurrentOS;
2301e8d8bef9SDimitry Andric 
230204eeddc0SDimitry Andric   fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove,
230304eeddc0SDimitry Andric                       OutputMappings);
2304e8d8bef9SDimitry Andric 
2305349cc55cSDimitry Andric   std::vector<Value *> SortedKeys;
2306e8d8bef9SDimitry Andric   for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) {
2307e8d8bef9SDimitry Andric     CurrentOS = CurrentGroup.Regions[Idx];
2308e8d8bef9SDimitry Andric     AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction,
2309e8d8bef9SDimitry Andric                                                *CurrentOS->ExtractedFunction);
2310e8d8bef9SDimitry Andric 
2311349cc55cSDimitry Andric     // Create a set of BasicBlocks, one for each return block, to hold the
2312349cc55cSDimitry Andric     // needed store instructions.
2313349cc55cSDimitry Andric     DenseMap<Value *, BasicBlock *> NewBBs;
2314349cc55cSDimitry Andric     createAndInsertBasicBlocks(
2315349cc55cSDimitry Andric         CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction,
2316349cc55cSDimitry Andric         "output_block_" + Twine(static_cast<unsigned>(Idx)));
231704eeddc0SDimitry Andric     replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings);
2318349cc55cSDimitry Andric     alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs,
2319349cc55cSDimitry Andric                                 CurrentGroup.EndBBs, OutputMappings,
2320e8d8bef9SDimitry Andric                                 OutputStoreBBs);
2321e8d8bef9SDimitry Andric 
2322e8d8bef9SDimitry Andric     CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
2323e8d8bef9SDimitry Andric     FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
2324e8d8bef9SDimitry Andric   }
2325e8d8bef9SDimitry Andric 
2326e8d8bef9SDimitry Andric   // Create a switch statement to handle the different output schemes.
2327349cc55cSDimitry Andric   createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs);
2328e8d8bef9SDimitry Andric 
2329e8d8bef9SDimitry Andric   OutlinedFunctionNum++;
2330e8d8bef9SDimitry Andric }
2331e8d8bef9SDimitry Andric 
2332349cc55cSDimitry Andric /// Checks that the next instruction in the InstructionDataList matches the
2333349cc55cSDimitry Andric /// next instruction in the module.  If they do not, there could be the
2334349cc55cSDimitry Andric /// possibility that extra code has been inserted, and we must ignore it.
2335349cc55cSDimitry Andric ///
2336349cc55cSDimitry Andric /// \param ID - The IRInstructionData to check the next instruction of.
2337349cc55cSDimitry Andric /// \returns true if the InstructionDataList and actual instruction match.
2338349cc55cSDimitry Andric static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) {
2339349cc55cSDimitry Andric   // We check if there is a discrepancy between the InstructionDataList
2340349cc55cSDimitry Andric   // and the actual next instruction in the module.  If there is, it means
2341349cc55cSDimitry Andric   // that an extra instruction was added, likely by the CodeExtractor.
2342349cc55cSDimitry Andric 
2343349cc55cSDimitry Andric   // Since we do not have any similarity data about this particular
2344349cc55cSDimitry Andric   // instruction, we cannot confidently outline it, and must discard this
2345349cc55cSDimitry Andric   // candidate.
2346349cc55cSDimitry Andric   IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator());
2347349cc55cSDimitry Andric   Instruction *NextIDLInst = NextIDIt->Inst;
2348349cc55cSDimitry Andric   Instruction *NextModuleInst = nullptr;
2349349cc55cSDimitry Andric   if (!ID.Inst->isTerminator())
2350349cc55cSDimitry Andric     NextModuleInst = ID.Inst->getNextNonDebugInstruction();
2351349cc55cSDimitry Andric   else if (NextIDLInst != nullptr)
2352349cc55cSDimitry Andric     NextModuleInst =
2353349cc55cSDimitry Andric         &*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin();
2354349cc55cSDimitry Andric 
2355349cc55cSDimitry Andric   if (NextIDLInst && NextIDLInst != NextModuleInst)
2356349cc55cSDimitry Andric     return false;
2357349cc55cSDimitry Andric 
2358349cc55cSDimitry Andric   return true;
2359349cc55cSDimitry Andric }
2360349cc55cSDimitry Andric 
2361349cc55cSDimitry Andric bool IROutliner::isCompatibleWithAlreadyOutlinedCode(
2362349cc55cSDimitry Andric     const OutlinableRegion &Region) {
2363349cc55cSDimitry Andric   IRSimilarityCandidate *IRSC = Region.Candidate;
2364349cc55cSDimitry Andric   unsigned StartIdx = IRSC->getStartIdx();
2365349cc55cSDimitry Andric   unsigned EndIdx = IRSC->getEndIdx();
2366349cc55cSDimitry Andric 
2367349cc55cSDimitry Andric   // A check to make sure that we are not about to attempt to outline something
2368349cc55cSDimitry Andric   // that has already been outlined.
2369349cc55cSDimitry Andric   for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2370349cc55cSDimitry Andric     if (Outlined.contains(Idx))
2371349cc55cSDimitry Andric       return false;
2372349cc55cSDimitry Andric 
2373349cc55cSDimitry Andric   // We check if the recorded instruction matches the actual next instruction,
2374349cc55cSDimitry Andric   // if it does not, we fix it in the InstructionDataList.
2375349cc55cSDimitry Andric   if (!Region.Candidate->backInstruction()->isTerminator()) {
2376349cc55cSDimitry Andric     Instruction *NewEndInst =
2377349cc55cSDimitry Andric         Region.Candidate->backInstruction()->getNextNonDebugInstruction();
2378349cc55cSDimitry Andric     assert(NewEndInst && "Next instruction is a nullptr?");
2379349cc55cSDimitry Andric     if (Region.Candidate->end()->Inst != NewEndInst) {
2380349cc55cSDimitry Andric       IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
2381349cc55cSDimitry Andric       IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate())
2382349cc55cSDimitry Andric           IRInstructionData(*NewEndInst,
2383349cc55cSDimitry Andric                             InstructionClassifier.visit(*NewEndInst), *IDL);
2384349cc55cSDimitry Andric 
2385349cc55cSDimitry Andric       // Insert the first IRInstructionData of the new region after the
2386349cc55cSDimitry Andric       // last IRInstructionData of the IRSimilarityCandidate.
2387349cc55cSDimitry Andric       IDL->insert(Region.Candidate->end(), *NewEndIRID);
2388349cc55cSDimitry Andric     }
2389349cc55cSDimitry Andric   }
2390349cc55cSDimitry Andric 
2391349cc55cSDimitry Andric   return none_of(*IRSC, [this](IRInstructionData &ID) {
2392349cc55cSDimitry Andric     if (!nextIRInstructionDataMatchesNextInst(ID))
2393349cc55cSDimitry Andric       return true;
2394349cc55cSDimitry Andric 
2395349cc55cSDimitry Andric     return !this->InstructionClassifier.visit(ID.Inst);
2396349cc55cSDimitry Andric   });
2397349cc55cSDimitry Andric }
2398349cc55cSDimitry Andric 
2399e8d8bef9SDimitry Andric void IROutliner::pruneIncompatibleRegions(
2400e8d8bef9SDimitry Andric     std::vector<IRSimilarityCandidate> &CandidateVec,
2401e8d8bef9SDimitry Andric     OutlinableGroup &CurrentGroup) {
2402e8d8bef9SDimitry Andric   bool PreviouslyOutlined;
2403e8d8bef9SDimitry Andric 
2404e8d8bef9SDimitry Andric   // Sort from beginning to end, so the IRSimilarityCandidates are in order.
2405e8d8bef9SDimitry Andric   stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS,
2406e8d8bef9SDimitry Andric                                const IRSimilarityCandidate &RHS) {
2407e8d8bef9SDimitry Andric     return LHS.getStartIdx() < RHS.getStartIdx();
2408e8d8bef9SDimitry Andric   });
2409e8d8bef9SDimitry Andric 
2410349cc55cSDimitry Andric   IRSimilarityCandidate &FirstCandidate = CandidateVec[0];
2411349cc55cSDimitry Andric   // Since outlining a call and a branch instruction will be the same as only
2412349cc55cSDimitry Andric   // outlinining a call instruction, we ignore it as a space saving.
2413349cc55cSDimitry Andric   if (FirstCandidate.getLength() == 2) {
2414349cc55cSDimitry Andric     if (isa<CallInst>(FirstCandidate.front()->Inst) &&
2415349cc55cSDimitry Andric         isa<BranchInst>(FirstCandidate.back()->Inst))
2416349cc55cSDimitry Andric       return;
2417349cc55cSDimitry Andric   }
2418349cc55cSDimitry Andric 
2419e8d8bef9SDimitry Andric   unsigned CurrentEndIdx = 0;
2420e8d8bef9SDimitry Andric   for (IRSimilarityCandidate &IRSC : CandidateVec) {
2421e8d8bef9SDimitry Andric     PreviouslyOutlined = false;
2422e8d8bef9SDimitry Andric     unsigned StartIdx = IRSC.getStartIdx();
2423e8d8bef9SDimitry Andric     unsigned EndIdx = IRSC.getEndIdx();
2424bdd1243dSDimitry Andric     const Function &FnForCurrCand = *IRSC.getFunction();
2425e8d8bef9SDimitry Andric 
2426e8d8bef9SDimitry Andric     for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2427e8d8bef9SDimitry Andric       if (Outlined.contains(Idx)) {
2428e8d8bef9SDimitry Andric         PreviouslyOutlined = true;
2429e8d8bef9SDimitry Andric         break;
2430e8d8bef9SDimitry Andric       }
2431e8d8bef9SDimitry Andric 
2432e8d8bef9SDimitry Andric     if (PreviouslyOutlined)
2433e8d8bef9SDimitry Andric       continue;
2434e8d8bef9SDimitry Andric 
2435349cc55cSDimitry Andric     // Check over the instructions, and if the basic block has its address
2436349cc55cSDimitry Andric     // taken for use somewhere else, we do not outline that block.
2437349cc55cSDimitry Andric     bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){
2438349cc55cSDimitry Andric       return ID.Inst->getParent()->hasAddressTaken();
2439349cc55cSDimitry Andric     });
2440349cc55cSDimitry Andric 
2441349cc55cSDimitry Andric     if (BBHasAddressTaken)
2442e8d8bef9SDimitry Andric       continue;
2443e8d8bef9SDimitry Andric 
2444bdd1243dSDimitry Andric     if (FnForCurrCand.hasOptNone())
244581ad6265SDimitry Andric       continue;
244681ad6265SDimitry Andric 
2447bdd1243dSDimitry Andric     if (FnForCurrCand.hasFnAttribute("nooutline")) {
2448bdd1243dSDimitry Andric       LLVM_DEBUG({
2449bdd1243dSDimitry Andric         dbgs() << "... Skipping function with nooutline attribute: "
2450bdd1243dSDimitry Andric                << FnForCurrCand.getName() << "\n";
2451bdd1243dSDimitry Andric       });
2452bdd1243dSDimitry Andric       continue;
2453bdd1243dSDimitry Andric     }
2454bdd1243dSDimitry Andric 
2455e8d8bef9SDimitry Andric     if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() &&
2456e8d8bef9SDimitry Andric         !OutlineFromLinkODRs)
2457e8d8bef9SDimitry Andric       continue;
2458e8d8bef9SDimitry Andric 
2459e8d8bef9SDimitry Andric     // Greedily prune out any regions that will overlap with already chosen
2460e8d8bef9SDimitry Andric     // regions.
2461e8d8bef9SDimitry Andric     if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx)
2462e8d8bef9SDimitry Andric       continue;
2463e8d8bef9SDimitry Andric 
2464e8d8bef9SDimitry Andric     bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) {
2465349cc55cSDimitry Andric       if (!nextIRInstructionDataMatchesNextInst(ID))
2466e8d8bef9SDimitry Andric         return true;
2467349cc55cSDimitry Andric 
2468e8d8bef9SDimitry Andric       return !this->InstructionClassifier.visit(ID.Inst);
2469e8d8bef9SDimitry Andric     });
2470e8d8bef9SDimitry Andric 
2471e8d8bef9SDimitry Andric     if (BadInst)
2472e8d8bef9SDimitry Andric       continue;
2473e8d8bef9SDimitry Andric 
2474e8d8bef9SDimitry Andric     OutlinableRegion *OS = new (RegionAllocator.Allocate())
2475e8d8bef9SDimitry Andric         OutlinableRegion(IRSC, CurrentGroup);
2476e8d8bef9SDimitry Andric     CurrentGroup.Regions.push_back(OS);
2477e8d8bef9SDimitry Andric 
2478e8d8bef9SDimitry Andric     CurrentEndIdx = EndIdx;
2479e8d8bef9SDimitry Andric   }
2480e8d8bef9SDimitry Andric }
2481e8d8bef9SDimitry Andric 
2482e8d8bef9SDimitry Andric InstructionCost
2483e8d8bef9SDimitry Andric IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) {
2484e8d8bef9SDimitry Andric   InstructionCost RegionBenefit = 0;
2485e8d8bef9SDimitry Andric   for (OutlinableRegion *Region : CurrentGroup.Regions) {
2486e8d8bef9SDimitry Andric     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
2487e8d8bef9SDimitry Andric     // We add the number of instructions in the region to the benefit as an
2488e8d8bef9SDimitry Andric     // estimate as to how much will be removed.
2489e8d8bef9SDimitry Andric     RegionBenefit += Region->getBenefit(TTI);
2490e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit
2491e8d8bef9SDimitry Andric                       << " saved instructions to overfall benefit.\n");
2492e8d8bef9SDimitry Andric   }
2493e8d8bef9SDimitry Andric 
2494e8d8bef9SDimitry Andric   return RegionBenefit;
2495e8d8bef9SDimitry Andric }
2496e8d8bef9SDimitry Andric 
249704eeddc0SDimitry Andric /// For the \p OutputCanon number passed in find the value represented by this
249804eeddc0SDimitry Andric /// canonical number. If it is from a PHINode, we pick the first incoming
249904eeddc0SDimitry Andric /// value and return that Value instead.
250004eeddc0SDimitry Andric ///
250104eeddc0SDimitry Andric /// \param Region - The OutlinableRegion to get the Value from.
250204eeddc0SDimitry Andric /// \param OutputCanon - The canonical number to find the Value from.
250304eeddc0SDimitry Andric /// \returns The Value represented by a canonical number \p OutputCanon in \p
250404eeddc0SDimitry Andric /// Region.
250504eeddc0SDimitry Andric static Value *findOutputValueInRegion(OutlinableRegion &Region,
250604eeddc0SDimitry Andric                                       unsigned OutputCanon) {
250704eeddc0SDimitry Andric   OutlinableGroup &CurrentGroup = *Region.Parent;
250804eeddc0SDimitry Andric   // If the value is greater than the value in the tracker, we have a
250904eeddc0SDimitry Andric   // PHINode and will instead use one of the incoming values to find the
251004eeddc0SDimitry Andric   // type.
251104eeddc0SDimitry Andric   if (OutputCanon > CurrentGroup.PHINodeGVNTracker) {
251204eeddc0SDimitry Andric     auto It = CurrentGroup.PHINodeGVNToGVNs.find(OutputCanon);
251304eeddc0SDimitry Andric     assert(It != CurrentGroup.PHINodeGVNToGVNs.end() &&
251404eeddc0SDimitry Andric            "Could not find GVN set for PHINode number!");
251504eeddc0SDimitry Andric     assert(It->second.second.size() > 0 && "PHINode does not have any values!");
251604eeddc0SDimitry Andric     OutputCanon = *It->second.second.begin();
251704eeddc0SDimitry Andric   }
2518bdd1243dSDimitry Andric   std::optional<unsigned> OGVN =
2519bdd1243dSDimitry Andric       Region.Candidate->fromCanonicalNum(OutputCanon);
252081ad6265SDimitry Andric   assert(OGVN && "Could not find GVN for Canonical Number?");
2521bdd1243dSDimitry Andric   std::optional<Value *> OV = Region.Candidate->fromGVN(*OGVN);
252281ad6265SDimitry Andric   assert(OV && "Could not find value for GVN?");
252304eeddc0SDimitry Andric   return *OV;
252404eeddc0SDimitry Andric }
252504eeddc0SDimitry Andric 
2526e8d8bef9SDimitry Andric InstructionCost
2527e8d8bef9SDimitry Andric IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) {
2528e8d8bef9SDimitry Andric   InstructionCost OverallCost = 0;
2529e8d8bef9SDimitry Andric   for (OutlinableRegion *Region : CurrentGroup.Regions) {
2530e8d8bef9SDimitry Andric     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
2531e8d8bef9SDimitry Andric 
2532e8d8bef9SDimitry Andric     // Each output incurs a load after the call, so we add that to the cost.
253304eeddc0SDimitry Andric     for (unsigned OutputCanon : Region->GVNStores) {
253404eeddc0SDimitry Andric       Value *V = findOutputValueInRegion(*Region, OutputCanon);
2535e8d8bef9SDimitry Andric       InstructionCost LoadCost =
2536e8d8bef9SDimitry Andric           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
2537e8d8bef9SDimitry Andric                               TargetTransformInfo::TCK_CodeSize);
2538e8d8bef9SDimitry Andric 
2539e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Adding: " << LoadCost
2540e8d8bef9SDimitry Andric                         << " instructions to cost for output of type "
2541e8d8bef9SDimitry Andric                         << *V->getType() << "\n");
2542e8d8bef9SDimitry Andric       OverallCost += LoadCost;
2543e8d8bef9SDimitry Andric     }
2544e8d8bef9SDimitry Andric   }
2545e8d8bef9SDimitry Andric 
2546e8d8bef9SDimitry Andric   return OverallCost;
2547e8d8bef9SDimitry Andric }
2548e8d8bef9SDimitry Andric 
2549e8d8bef9SDimitry Andric /// Find the extra instructions needed to handle any output values for the
2550e8d8bef9SDimitry Andric /// region.
2551e8d8bef9SDimitry Andric ///
2552e8d8bef9SDimitry Andric /// \param [in] M - The Module to outline from.
2553e8d8bef9SDimitry Andric /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze.
2554e8d8bef9SDimitry Andric /// \param [in] TTI - The TargetTransformInfo used to collect information for
2555e8d8bef9SDimitry Andric /// new instruction costs.
2556e8d8bef9SDimitry Andric /// \returns the additional cost to handle the outputs.
2557e8d8bef9SDimitry Andric static InstructionCost findCostForOutputBlocks(Module &M,
2558e8d8bef9SDimitry Andric                                                OutlinableGroup &CurrentGroup,
2559e8d8bef9SDimitry Andric                                                TargetTransformInfo &TTI) {
2560e8d8bef9SDimitry Andric   InstructionCost OutputCost = 0;
2561349cc55cSDimitry Andric   unsigned NumOutputBranches = 0;
2562349cc55cSDimitry Andric 
256304eeddc0SDimitry Andric   OutlinableRegion &FirstRegion = *CurrentGroup.Regions[0];
2564349cc55cSDimitry Andric   IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate;
2565349cc55cSDimitry Andric   DenseSet<BasicBlock *> CandidateBlocks;
2566349cc55cSDimitry Andric   Candidate.getBasicBlocks(CandidateBlocks);
2567349cc55cSDimitry Andric 
2568349cc55cSDimitry Andric   // Count the number of different output branches that point to blocks outside
2569349cc55cSDimitry Andric   // of the region.
2570349cc55cSDimitry Andric   DenseSet<BasicBlock *> FoundBlocks;
2571349cc55cSDimitry Andric   for (IRInstructionData &ID : Candidate) {
2572349cc55cSDimitry Andric     if (!isa<BranchInst>(ID.Inst))
2573349cc55cSDimitry Andric       continue;
2574349cc55cSDimitry Andric 
2575349cc55cSDimitry Andric     for (Value *V : ID.OperVals) {
2576349cc55cSDimitry Andric       BasicBlock *BB = static_cast<BasicBlock *>(V);
257781ad6265SDimitry Andric       if (!CandidateBlocks.contains(BB) && FoundBlocks.insert(BB).second)
2578349cc55cSDimitry Andric         NumOutputBranches++;
2579349cc55cSDimitry Andric     }
2580349cc55cSDimitry Andric   }
2581349cc55cSDimitry Andric 
2582349cc55cSDimitry Andric   CurrentGroup.BranchesToOutside = NumOutputBranches;
2583e8d8bef9SDimitry Andric 
2584e8d8bef9SDimitry Andric   for (const ArrayRef<unsigned> &OutputUse :
2585e8d8bef9SDimitry Andric        CurrentGroup.OutputGVNCombinations) {
258604eeddc0SDimitry Andric     for (unsigned OutputCanon : OutputUse) {
258704eeddc0SDimitry Andric       Value *V = findOutputValueInRegion(FirstRegion, OutputCanon);
2588e8d8bef9SDimitry Andric       InstructionCost StoreCost =
2589e8d8bef9SDimitry Andric           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
2590e8d8bef9SDimitry Andric                               TargetTransformInfo::TCK_CodeSize);
2591e8d8bef9SDimitry Andric 
2592e8d8bef9SDimitry Andric       // An instruction cost is added for each store set that needs to occur for
2593e8d8bef9SDimitry Andric       // various output combinations inside the function, plus a branch to
2594e8d8bef9SDimitry Andric       // return to the exit block.
2595e8d8bef9SDimitry Andric       LLVM_DEBUG(dbgs() << "Adding: " << StoreCost
2596e8d8bef9SDimitry Andric                         << " instructions to cost for output of type "
2597e8d8bef9SDimitry Andric                         << *V->getType() << "\n");
2598349cc55cSDimitry Andric       OutputCost += StoreCost * NumOutputBranches;
2599e8d8bef9SDimitry Andric     }
2600e8d8bef9SDimitry Andric 
2601e8d8bef9SDimitry Andric     InstructionCost BranchCost =
2602e8d8bef9SDimitry Andric         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
2603e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for"
2604e8d8bef9SDimitry Andric                       << " a branch instruction\n");
2605349cc55cSDimitry Andric     OutputCost += BranchCost * NumOutputBranches;
2606e8d8bef9SDimitry Andric   }
2607e8d8bef9SDimitry Andric 
2608e8d8bef9SDimitry Andric   // If there is more than one output scheme, we must have a comparison and
2609e8d8bef9SDimitry Andric   // branch for each different item in the switch statement.
2610e8d8bef9SDimitry Andric   if (CurrentGroup.OutputGVNCombinations.size() > 1) {
2611e8d8bef9SDimitry Andric     InstructionCost ComparisonCost = TTI.getCmpSelInstrCost(
2612e8d8bef9SDimitry Andric         Instruction::ICmp, Type::getInt32Ty(M.getContext()),
2613e8d8bef9SDimitry Andric         Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE,
2614e8d8bef9SDimitry Andric         TargetTransformInfo::TCK_CodeSize);
2615e8d8bef9SDimitry Andric     InstructionCost BranchCost =
2616e8d8bef9SDimitry Andric         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
2617e8d8bef9SDimitry Andric 
2618e8d8bef9SDimitry Andric     unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size();
2619e8d8bef9SDimitry Andric     InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks;
2620e8d8bef9SDimitry Andric 
2621e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Adding: " << TotalCost
2622e8d8bef9SDimitry Andric                       << " instructions for each switch case for each different"
2623e8d8bef9SDimitry Andric                       << " output path in a function\n");
2624349cc55cSDimitry Andric     OutputCost += TotalCost * NumOutputBranches;
2625e8d8bef9SDimitry Andric   }
2626e8d8bef9SDimitry Andric 
2627e8d8bef9SDimitry Andric   return OutputCost;
2628e8d8bef9SDimitry Andric }
2629e8d8bef9SDimitry Andric 
2630e8d8bef9SDimitry Andric void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) {
2631e8d8bef9SDimitry Andric   InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup);
2632e8d8bef9SDimitry Andric   CurrentGroup.Benefit += RegionBenefit;
2633e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n");
2634e8d8bef9SDimitry Andric 
2635e8d8bef9SDimitry Andric   InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup);
2636e8d8bef9SDimitry Andric   CurrentGroup.Cost += OutputReloadCost;
2637e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2638e8d8bef9SDimitry Andric 
2639e8d8bef9SDimitry Andric   InstructionCost AverageRegionBenefit =
2640e8d8bef9SDimitry Andric       RegionBenefit / CurrentGroup.Regions.size();
2641e8d8bef9SDimitry Andric   unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size();
2642e8d8bef9SDimitry Andric   unsigned NumRegions = CurrentGroup.Regions.size();
2643e8d8bef9SDimitry Andric   TargetTransformInfo &TTI =
2644e8d8bef9SDimitry Andric       getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction());
2645e8d8bef9SDimitry Andric 
2646e8d8bef9SDimitry Andric   // We add one region to the cost once, to account for the instructions added
2647e8d8bef9SDimitry Andric   // inside of the newly created function.
2648e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit
2649e8d8bef9SDimitry Andric                     << " instructions to cost for body of new function.\n");
2650e8d8bef9SDimitry Andric   CurrentGroup.Cost += AverageRegionBenefit;
2651e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2652e8d8bef9SDimitry Andric 
2653e8d8bef9SDimitry Andric   // For each argument, we must add an instruction for loading the argument
2654e8d8bef9SDimitry Andric   // out of the register and into a value inside of the newly outlined function.
2655e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
2656e8d8bef9SDimitry Andric                     << " instructions to cost for each argument in the new"
2657e8d8bef9SDimitry Andric                     << " function.\n");
2658e8d8bef9SDimitry Andric   CurrentGroup.Cost +=
2659e8d8bef9SDimitry Andric       OverallArgumentNum * TargetTransformInfo::TCC_Basic;
2660e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2661e8d8bef9SDimitry Andric 
2662e8d8bef9SDimitry Andric   // Each argument needs to either be loaded into a register or onto the stack.
2663e8d8bef9SDimitry Andric   // Some arguments will only be loaded into the stack once the argument
2664e8d8bef9SDimitry Andric   // registers are filled.
2665e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
2666e8d8bef9SDimitry Andric                     << " instructions to cost for each argument in the new"
2667e8d8bef9SDimitry Andric                     << " function " << NumRegions << " times for the "
2668e8d8bef9SDimitry Andric                     << "needed argument handling at the call site.\n");
2669e8d8bef9SDimitry Andric   CurrentGroup.Cost +=
2670e8d8bef9SDimitry Andric       2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions;
2671e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2672e8d8bef9SDimitry Andric 
2673e8d8bef9SDimitry Andric   CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI);
2674e8d8bef9SDimitry Andric   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2675e8d8bef9SDimitry Andric }
2676e8d8bef9SDimitry Andric 
2677e8d8bef9SDimitry Andric void IROutliner::updateOutputMapping(OutlinableRegion &Region,
2678e8d8bef9SDimitry Andric                                      ArrayRef<Value *> Outputs,
2679e8d8bef9SDimitry Andric                                      LoadInst *LI) {
2680e8d8bef9SDimitry Andric   // For and load instructions following the call
2681e8d8bef9SDimitry Andric   Value *Operand = LI->getPointerOperand();
2682bdd1243dSDimitry Andric   std::optional<unsigned> OutputIdx;
2683e8d8bef9SDimitry Andric   // Find if the operand it is an output register.
2684e8d8bef9SDimitry Andric   for (unsigned ArgIdx = Region.NumExtractedInputs;
2685e8d8bef9SDimitry Andric        ArgIdx < Region.Call->arg_size(); ArgIdx++) {
2686e8d8bef9SDimitry Andric     if (Operand == Region.Call->getArgOperand(ArgIdx)) {
2687e8d8bef9SDimitry Andric       OutputIdx = ArgIdx - Region.NumExtractedInputs;
2688e8d8bef9SDimitry Andric       break;
2689e8d8bef9SDimitry Andric     }
2690e8d8bef9SDimitry Andric   }
2691e8d8bef9SDimitry Andric 
2692e8d8bef9SDimitry Andric   // If we found an output register, place a mapping of the new value
2693e8d8bef9SDimitry Andric   // to the original in the mapping.
269481ad6265SDimitry Andric   if (!OutputIdx)
2695e8d8bef9SDimitry Andric     return;
2696e8d8bef9SDimitry Andric 
269706c3fb27SDimitry Andric   if (!OutputMappings.contains(Outputs[*OutputIdx])) {
2698e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "
2699bdd1243dSDimitry Andric                       << *Outputs[*OutputIdx] << "\n");
2700bdd1243dSDimitry Andric     OutputMappings.insert(std::make_pair(LI, Outputs[*OutputIdx]));
2701e8d8bef9SDimitry Andric   } else {
2702bdd1243dSDimitry Andric     Value *Orig = OutputMappings.find(Outputs[*OutputIdx])->second;
2703e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "
2704bdd1243dSDimitry Andric                       << *Outputs[*OutputIdx] << "\n");
2705e8d8bef9SDimitry Andric     OutputMappings.insert(std::make_pair(LI, Orig));
2706e8d8bef9SDimitry Andric   }
2707e8d8bef9SDimitry Andric }
2708e8d8bef9SDimitry Andric 
2709e8d8bef9SDimitry Andric bool IROutliner::extractSection(OutlinableRegion &Region) {
2710e8d8bef9SDimitry Andric   SetVector<Value *> ArgInputs, Outputs, SinkCands;
2711e8d8bef9SDimitry Andric   assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!");
2712349cc55cSDimitry Andric   BasicBlock *InitialStart = Region.StartBB;
2713e8d8bef9SDimitry Andric   Function *OrigF = Region.StartBB->getParent();
2714e8d8bef9SDimitry Andric   CodeExtractorAnalysisCache CEAC(*OrigF);
2715349cc55cSDimitry Andric   Region.ExtractedFunction =
2716349cc55cSDimitry Andric       Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs);
2717e8d8bef9SDimitry Andric 
2718e8d8bef9SDimitry Andric   // If the extraction was successful, find the BasicBlock, and reassign the
2719e8d8bef9SDimitry Andric   // OutlinableRegion blocks
2720e8d8bef9SDimitry Andric   if (!Region.ExtractedFunction) {
2721e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB
2722e8d8bef9SDimitry Andric                       << "\n");
2723e8d8bef9SDimitry Andric     Region.reattachCandidate();
2724e8d8bef9SDimitry Andric     return false;
2725e8d8bef9SDimitry Andric   }
2726e8d8bef9SDimitry Andric 
2727349cc55cSDimitry Andric   // Get the block containing the called branch, and reassign the blocks as
2728349cc55cSDimitry Andric   // necessary.  If the original block still exists, it is because we ended on
2729349cc55cSDimitry Andric   // a branch instruction, and so we move the contents into the block before
2730349cc55cSDimitry Andric   // and assign the previous block correctly.
2731349cc55cSDimitry Andric   User *InstAsUser = Region.ExtractedFunction->user_back();
2732349cc55cSDimitry Andric   BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent();
2733349cc55cSDimitry Andric   Region.PrevBB = RewrittenBB->getSinglePredecessor();
2734349cc55cSDimitry Andric   assert(Region.PrevBB && "PrevBB is nullptr?");
2735349cc55cSDimitry Andric   if (Region.PrevBB == InitialStart) {
2736349cc55cSDimitry Andric     BasicBlock *NewPrev = InitialStart->getSinglePredecessor();
2737349cc55cSDimitry Andric     Instruction *BI = NewPrev->getTerminator();
2738349cc55cSDimitry Andric     BI->eraseFromParent();
2739349cc55cSDimitry Andric     moveBBContents(*InitialStart, *NewPrev);
2740349cc55cSDimitry Andric     Region.PrevBB = NewPrev;
2741349cc55cSDimitry Andric     InitialStart->eraseFromParent();
2742349cc55cSDimitry Andric   }
2743349cc55cSDimitry Andric 
2744e8d8bef9SDimitry Andric   Region.StartBB = RewrittenBB;
2745e8d8bef9SDimitry Andric   Region.EndBB = RewrittenBB;
2746e8d8bef9SDimitry Andric 
2747e8d8bef9SDimitry Andric   // The sequences of outlinable regions has now changed.  We must fix the
2748e8d8bef9SDimitry Andric   // IRInstructionDataList for consistency.  Although they may not be illegal
2749e8d8bef9SDimitry Andric   // instructions, they should not be compared with anything else as they
2750e8d8bef9SDimitry Andric   // should not be outlined in this round.  So marking these as illegal is
2751e8d8bef9SDimitry Andric   // allowed.
2752e8d8bef9SDimitry Andric   IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
2753e8d8bef9SDimitry Andric   Instruction *BeginRewritten = &*RewrittenBB->begin();
2754e8d8bef9SDimitry Andric   Instruction *EndRewritten = &*RewrittenBB->begin();
2755e8d8bef9SDimitry Andric   Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData(
2756e8d8bef9SDimitry Andric       *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL);
2757e8d8bef9SDimitry Andric   Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData(
2758e8d8bef9SDimitry Andric       *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL);
2759e8d8bef9SDimitry Andric 
2760e8d8bef9SDimitry Andric   // Insert the first IRInstructionData of the new region in front of the
2761e8d8bef9SDimitry Andric   // first IRInstructionData of the IRSimilarityCandidate.
2762e8d8bef9SDimitry Andric   IDL->insert(Region.Candidate->begin(), *Region.NewFront);
2763e8d8bef9SDimitry Andric   // Insert the first IRInstructionData of the new region after the
2764e8d8bef9SDimitry Andric   // last IRInstructionData of the IRSimilarityCandidate.
2765e8d8bef9SDimitry Andric   IDL->insert(Region.Candidate->end(), *Region.NewBack);
2766e8d8bef9SDimitry Andric   // Remove the IRInstructionData from the IRSimilarityCandidate.
2767e8d8bef9SDimitry Andric   IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end()));
2768e8d8bef9SDimitry Andric 
2769e8d8bef9SDimitry Andric   assert(RewrittenBB != nullptr &&
2770e8d8bef9SDimitry Andric          "Could not find a predecessor after extraction!");
2771e8d8bef9SDimitry Andric 
2772e8d8bef9SDimitry Andric   // Iterate over the new set of instructions to find the new call
2773e8d8bef9SDimitry Andric   // instruction.
2774e8d8bef9SDimitry Andric   for (Instruction &I : *RewrittenBB)
2775e8d8bef9SDimitry Andric     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2776e8d8bef9SDimitry Andric       if (Region.ExtractedFunction == CI->getCalledFunction())
2777e8d8bef9SDimitry Andric         Region.Call = CI;
2778e8d8bef9SDimitry Andric     } else if (LoadInst *LI = dyn_cast<LoadInst>(&I))
2779e8d8bef9SDimitry Andric       updateOutputMapping(Region, Outputs.getArrayRef(), LI);
2780e8d8bef9SDimitry Andric   Region.reattachCandidate();
2781e8d8bef9SDimitry Andric   return true;
2782e8d8bef9SDimitry Andric }
2783e8d8bef9SDimitry Andric 
2784e8d8bef9SDimitry Andric unsigned IROutliner::doOutline(Module &M) {
2785e8d8bef9SDimitry Andric   // Find the possible similarity sections.
2786349cc55cSDimitry Andric   InstructionClassifier.EnableBranches = !DisableBranches;
278704eeddc0SDimitry Andric   InstructionClassifier.EnableIndirectCalls = !DisableIndirectCalls;
27881fd87a68SDimitry Andric   InstructionClassifier.EnableIntrinsics = !DisableIntrinsics;
27891fd87a68SDimitry Andric 
2790e8d8bef9SDimitry Andric   IRSimilarityIdentifier &Identifier = getIRSI(M);
2791e8d8bef9SDimitry Andric   SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity();
2792e8d8bef9SDimitry Andric 
2793e8d8bef9SDimitry Andric   // Sort them by size of extracted sections
2794e8d8bef9SDimitry Andric   unsigned OutlinedFunctionNum = 0;
2795e8d8bef9SDimitry Andric   // If we only have one SimilarityGroup in SimilarityCandidates, we do not have
2796e8d8bef9SDimitry Andric   // to sort them by the potential number of instructions to be outlined
2797e8d8bef9SDimitry Andric   if (SimilarityCandidates.size() > 1)
2798e8d8bef9SDimitry Andric     llvm::stable_sort(SimilarityCandidates,
2799e8d8bef9SDimitry Andric                       [](const std::vector<IRSimilarityCandidate> &LHS,
2800e8d8bef9SDimitry Andric                          const std::vector<IRSimilarityCandidate> &RHS) {
2801e8d8bef9SDimitry Andric                         return LHS[0].getLength() * LHS.size() >
2802e8d8bef9SDimitry Andric                                RHS[0].getLength() * RHS.size();
2803e8d8bef9SDimitry Andric                       });
2804349cc55cSDimitry Andric   // Creating OutlinableGroups for each SimilarityCandidate to be used in
2805349cc55cSDimitry Andric   // each of the following for loops to avoid making an allocator.
2806349cc55cSDimitry Andric   std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size());
2807e8d8bef9SDimitry Andric 
2808e8d8bef9SDimitry Andric   DenseSet<unsigned> NotSame;
2809349cc55cSDimitry Andric   std::vector<OutlinableGroup *> NegativeCostGroups;
2810349cc55cSDimitry Andric   std::vector<OutlinableRegion *> OutlinedRegions;
2811e8d8bef9SDimitry Andric   // Iterate over the possible sets of similarity.
2812349cc55cSDimitry Andric   unsigned PotentialGroupIdx = 0;
2813e8d8bef9SDimitry Andric   for (SimilarityGroup &CandidateVec : SimilarityCandidates) {
2814349cc55cSDimitry Andric     OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++];
2815e8d8bef9SDimitry Andric 
2816e8d8bef9SDimitry Andric     // Remove entries that were previously outlined
2817e8d8bef9SDimitry Andric     pruneIncompatibleRegions(CandidateVec, CurrentGroup);
2818e8d8bef9SDimitry Andric 
2819e8d8bef9SDimitry Andric     // We pruned the number of regions to 0 to 1, meaning that it's not worth
2820e8d8bef9SDimitry Andric     // trying to outlined since there is no compatible similar instance of this
2821e8d8bef9SDimitry Andric     // code.
2822e8d8bef9SDimitry Andric     if (CurrentGroup.Regions.size() < 2)
2823e8d8bef9SDimitry Andric       continue;
2824e8d8bef9SDimitry Andric 
2825e8d8bef9SDimitry Andric     // Determine if there are any values that are the same constant throughout
2826e8d8bef9SDimitry Andric     // each section in the set.
2827e8d8bef9SDimitry Andric     NotSame.clear();
2828e8d8bef9SDimitry Andric     CurrentGroup.findSameConstants(NotSame);
2829e8d8bef9SDimitry Andric 
2830e8d8bef9SDimitry Andric     if (CurrentGroup.IgnoreGroup)
2831e8d8bef9SDimitry Andric       continue;
2832e8d8bef9SDimitry Andric 
2833e8d8bef9SDimitry Andric     // Create a CodeExtractor for each outlinable region. Identify inputs and
2834e8d8bef9SDimitry Andric     // outputs for each section using the code extractor and create the argument
2835e8d8bef9SDimitry Andric     // types for the Aggregate Outlining Function.
2836349cc55cSDimitry Andric     OutlinedRegions.clear();
2837e8d8bef9SDimitry Andric     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2838e8d8bef9SDimitry Andric       // Break the outlinable region out of its parent BasicBlock into its own
2839e8d8bef9SDimitry Andric       // BasicBlocks (see function implementation).
2840e8d8bef9SDimitry Andric       OS->splitCandidate();
2841349cc55cSDimitry Andric 
2842349cc55cSDimitry Andric       // There's a chance that when the region is split, extra instructions are
2843349cc55cSDimitry Andric       // added to the region. This makes the region no longer viable
2844349cc55cSDimitry Andric       // to be split, so we ignore it for outlining.
2845349cc55cSDimitry Andric       if (!OS->CandidateSplit)
2846349cc55cSDimitry Andric         continue;
2847349cc55cSDimitry Andric 
2848349cc55cSDimitry Andric       SmallVector<BasicBlock *> BE;
284904eeddc0SDimitry Andric       DenseSet<BasicBlock *> BlocksInRegion;
285004eeddc0SDimitry Andric       OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
2851e8d8bef9SDimitry Andric       OS->CE = new (ExtractorAllocator.Allocate())
2852e8d8bef9SDimitry Andric           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
285381ad6265SDimitry Andric                         false, nullptr, "outlined");
2854e8d8bef9SDimitry Andric       findAddInputsOutputs(M, *OS, NotSame);
2855e8d8bef9SDimitry Andric       if (!OS->IgnoreRegion)
2856e8d8bef9SDimitry Andric         OutlinedRegions.push_back(OS);
2857349cc55cSDimitry Andric 
2858349cc55cSDimitry Andric       // We recombine the blocks together now that we have gathered all the
2859349cc55cSDimitry Andric       // needed information.
2860e8d8bef9SDimitry Andric       OS->reattachCandidate();
2861e8d8bef9SDimitry Andric     }
2862e8d8bef9SDimitry Andric 
2863e8d8bef9SDimitry Andric     CurrentGroup.Regions = std::move(OutlinedRegions);
2864e8d8bef9SDimitry Andric 
2865e8d8bef9SDimitry Andric     if (CurrentGroup.Regions.empty())
2866e8d8bef9SDimitry Andric       continue;
2867e8d8bef9SDimitry Andric 
2868e8d8bef9SDimitry Andric     CurrentGroup.collectGVNStoreSets(M);
2869e8d8bef9SDimitry Andric 
2870e8d8bef9SDimitry Andric     if (CostModel)
2871e8d8bef9SDimitry Andric       findCostBenefit(M, CurrentGroup);
2872e8d8bef9SDimitry Andric 
2873349cc55cSDimitry Andric     // If we are adhering to the cost model, skip those groups where the cost
2874349cc55cSDimitry Andric     // outweighs the benefits.
2875e8d8bef9SDimitry Andric     if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) {
2876349cc55cSDimitry Andric       OptimizationRemarkEmitter &ORE =
2877349cc55cSDimitry Andric           getORE(*CurrentGroup.Regions[0]->Candidate->getFunction());
2878e8d8bef9SDimitry Andric       ORE.emit([&]() {
2879e8d8bef9SDimitry Andric         IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2880e8d8bef9SDimitry Andric         OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize",
2881e8d8bef9SDimitry Andric                                    C->frontInstruction());
2882e8d8bef9SDimitry Andric         R << "did not outline "
2883e8d8bef9SDimitry Andric           << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2884e8d8bef9SDimitry Andric           << " regions due to estimated increase of "
2885e8d8bef9SDimitry Andric           << ore::NV("InstructionIncrease",
2886e8d8bef9SDimitry Andric                      CurrentGroup.Cost - CurrentGroup.Benefit)
2887e8d8bef9SDimitry Andric           << " instructions at locations ";
2888e8d8bef9SDimitry Andric         interleave(
2889e8d8bef9SDimitry Andric             CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2890e8d8bef9SDimitry Andric             [&R](OutlinableRegion *Region) {
2891e8d8bef9SDimitry Andric               R << ore::NV(
2892e8d8bef9SDimitry Andric                   "DebugLoc",
2893e8d8bef9SDimitry Andric                   Region->Candidate->frontInstruction()->getDebugLoc());
2894e8d8bef9SDimitry Andric             },
2895e8d8bef9SDimitry Andric             [&R]() { R << " "; });
2896e8d8bef9SDimitry Andric         return R;
2897e8d8bef9SDimitry Andric       });
2898e8d8bef9SDimitry Andric       continue;
2899e8d8bef9SDimitry Andric     }
2900e8d8bef9SDimitry Andric 
2901349cc55cSDimitry Andric     NegativeCostGroups.push_back(&CurrentGroup);
2902349cc55cSDimitry Andric   }
2903349cc55cSDimitry Andric 
2904349cc55cSDimitry Andric   ExtractorAllocator.DestroyAll();
2905349cc55cSDimitry Andric 
2906349cc55cSDimitry Andric   if (NegativeCostGroups.size() > 1)
2907349cc55cSDimitry Andric     stable_sort(NegativeCostGroups,
2908349cc55cSDimitry Andric                 [](const OutlinableGroup *LHS, const OutlinableGroup *RHS) {
2909349cc55cSDimitry Andric                   return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost;
2910349cc55cSDimitry Andric                 });
2911349cc55cSDimitry Andric 
2912349cc55cSDimitry Andric   std::vector<Function *> FuncsToRemove;
2913349cc55cSDimitry Andric   for (OutlinableGroup *CG : NegativeCostGroups) {
2914349cc55cSDimitry Andric     OutlinableGroup &CurrentGroup = *CG;
2915349cc55cSDimitry Andric 
2916349cc55cSDimitry Andric     OutlinedRegions.clear();
2917349cc55cSDimitry Andric     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2918349cc55cSDimitry Andric       // We check whether our region is compatible with what has already been
2919349cc55cSDimitry Andric       // outlined, and whether we need to ignore this item.
2920349cc55cSDimitry Andric       if (!isCompatibleWithAlreadyOutlinedCode(*Region))
2921349cc55cSDimitry Andric         continue;
2922349cc55cSDimitry Andric       OutlinedRegions.push_back(Region);
2923349cc55cSDimitry Andric     }
2924349cc55cSDimitry Andric 
2925349cc55cSDimitry Andric     if (OutlinedRegions.size() < 2)
2926349cc55cSDimitry Andric       continue;
2927349cc55cSDimitry Andric 
2928349cc55cSDimitry Andric     // Reestimate the cost and benefit of the OutlinableGroup. Continue only if
2929349cc55cSDimitry Andric     // we are still outlining enough regions to make up for the added cost.
2930349cc55cSDimitry Andric     CurrentGroup.Regions = std::move(OutlinedRegions);
2931349cc55cSDimitry Andric     if (CostModel) {
2932349cc55cSDimitry Andric       CurrentGroup.Benefit = 0;
2933349cc55cSDimitry Andric       CurrentGroup.Cost = 0;
2934349cc55cSDimitry Andric       findCostBenefit(M, CurrentGroup);
2935349cc55cSDimitry Andric       if (CurrentGroup.Cost >= CurrentGroup.Benefit)
2936349cc55cSDimitry Andric         continue;
2937349cc55cSDimitry Andric     }
2938349cc55cSDimitry Andric     OutlinedRegions.clear();
2939349cc55cSDimitry Andric     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2940349cc55cSDimitry Andric       Region->splitCandidate();
2941349cc55cSDimitry Andric       if (!Region->CandidateSplit)
2942349cc55cSDimitry Andric         continue;
2943349cc55cSDimitry Andric       OutlinedRegions.push_back(Region);
2944349cc55cSDimitry Andric     }
2945349cc55cSDimitry Andric 
2946349cc55cSDimitry Andric     CurrentGroup.Regions = std::move(OutlinedRegions);
2947349cc55cSDimitry Andric     if (CurrentGroup.Regions.size() < 2) {
2948349cc55cSDimitry Andric       for (OutlinableRegion *R : CurrentGroup.Regions)
2949349cc55cSDimitry Andric         R->reattachCandidate();
2950349cc55cSDimitry Andric       continue;
2951349cc55cSDimitry Andric     }
2952349cc55cSDimitry Andric 
2953e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost
2954e8d8bef9SDimitry Andric                       << " and benefit " << CurrentGroup.Benefit << "\n");
2955e8d8bef9SDimitry Andric 
2956e8d8bef9SDimitry Andric     // Create functions out of all the sections, and mark them as outlined.
2957e8d8bef9SDimitry Andric     OutlinedRegions.clear();
2958e8d8bef9SDimitry Andric     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2959349cc55cSDimitry Andric       SmallVector<BasicBlock *> BE;
296004eeddc0SDimitry Andric       DenseSet<BasicBlock *> BlocksInRegion;
296104eeddc0SDimitry Andric       OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
2962349cc55cSDimitry Andric       OS->CE = new (ExtractorAllocator.Allocate())
2963349cc55cSDimitry Andric           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
296481ad6265SDimitry Andric                         false, nullptr, "outlined");
2965e8d8bef9SDimitry Andric       bool FunctionOutlined = extractSection(*OS);
2966e8d8bef9SDimitry Andric       if (FunctionOutlined) {
2967e8d8bef9SDimitry Andric         unsigned StartIdx = OS->Candidate->getStartIdx();
2968e8d8bef9SDimitry Andric         unsigned EndIdx = OS->Candidate->getEndIdx();
2969e8d8bef9SDimitry Andric         for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2970e8d8bef9SDimitry Andric           Outlined.insert(Idx);
2971e8d8bef9SDimitry Andric 
2972e8d8bef9SDimitry Andric         OutlinedRegions.push_back(OS);
2973e8d8bef9SDimitry Andric       }
2974e8d8bef9SDimitry Andric     }
2975e8d8bef9SDimitry Andric 
2976e8d8bef9SDimitry Andric     LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size()
2977e8d8bef9SDimitry Andric                       << " with benefit " << CurrentGroup.Benefit
2978e8d8bef9SDimitry Andric                       << " and cost " << CurrentGroup.Cost << "\n");
2979e8d8bef9SDimitry Andric 
2980e8d8bef9SDimitry Andric     CurrentGroup.Regions = std::move(OutlinedRegions);
2981e8d8bef9SDimitry Andric 
2982e8d8bef9SDimitry Andric     if (CurrentGroup.Regions.empty())
2983e8d8bef9SDimitry Andric       continue;
2984e8d8bef9SDimitry Andric 
2985e8d8bef9SDimitry Andric     OptimizationRemarkEmitter &ORE =
2986e8d8bef9SDimitry Andric         getORE(*CurrentGroup.Regions[0]->Call->getFunction());
2987e8d8bef9SDimitry Andric     ORE.emit([&]() {
2988e8d8bef9SDimitry Andric       IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2989e8d8bef9SDimitry Andric       OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst);
2990e8d8bef9SDimitry Andric       R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2991e8d8bef9SDimitry Andric         << " regions with decrease of "
2992e8d8bef9SDimitry Andric         << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost)
2993e8d8bef9SDimitry Andric         << " instructions at locations ";
2994e8d8bef9SDimitry Andric       interleave(
2995e8d8bef9SDimitry Andric           CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2996e8d8bef9SDimitry Andric           [&R](OutlinableRegion *Region) {
2997e8d8bef9SDimitry Andric             R << ore::NV("DebugLoc",
2998e8d8bef9SDimitry Andric                          Region->Candidate->frontInstruction()->getDebugLoc());
2999e8d8bef9SDimitry Andric           },
3000e8d8bef9SDimitry Andric           [&R]() { R << " "; });
3001e8d8bef9SDimitry Andric       return R;
3002e8d8bef9SDimitry Andric     });
3003e8d8bef9SDimitry Andric 
3004e8d8bef9SDimitry Andric     deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove,
3005e8d8bef9SDimitry Andric                                  OutlinedFunctionNum);
3006e8d8bef9SDimitry Andric   }
3007e8d8bef9SDimitry Andric 
3008e8d8bef9SDimitry Andric   for (Function *F : FuncsToRemove)
3009e8d8bef9SDimitry Andric     F->eraseFromParent();
3010e8d8bef9SDimitry Andric 
3011e8d8bef9SDimitry Andric   return OutlinedFunctionNum;
3012e8d8bef9SDimitry Andric }
3013e8d8bef9SDimitry Andric 
3014e8d8bef9SDimitry Andric bool IROutliner::run(Module &M) {
3015e8d8bef9SDimitry Andric   CostModel = !NoCostModel;
3016e8d8bef9SDimitry Andric   OutlineFromLinkODRs = EnableLinkOnceODRIROutlining;
3017e8d8bef9SDimitry Andric 
3018e8d8bef9SDimitry Andric   return doOutline(M) > 0;
3019e8d8bef9SDimitry Andric }
3020e8d8bef9SDimitry Andric 
3021e8d8bef9SDimitry Andric PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) {
3022e8d8bef9SDimitry Andric   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
3023e8d8bef9SDimitry Andric 
3024e8d8bef9SDimitry Andric   std::function<TargetTransformInfo &(Function &)> GTTI =
3025e8d8bef9SDimitry Andric       [&FAM](Function &F) -> TargetTransformInfo & {
3026e8d8bef9SDimitry Andric     return FAM.getResult<TargetIRAnalysis>(F);
3027e8d8bef9SDimitry Andric   };
3028e8d8bef9SDimitry Andric 
3029e8d8bef9SDimitry Andric   std::function<IRSimilarityIdentifier &(Module &)> GIRSI =
3030e8d8bef9SDimitry Andric       [&AM](Module &M) -> IRSimilarityIdentifier & {
3031e8d8bef9SDimitry Andric     return AM.getResult<IRSimilarityAnalysis>(M);
3032e8d8bef9SDimitry Andric   };
3033e8d8bef9SDimitry Andric 
3034e8d8bef9SDimitry Andric   std::unique_ptr<OptimizationRemarkEmitter> ORE;
3035e8d8bef9SDimitry Andric   std::function<OptimizationRemarkEmitter &(Function &)> GORE =
3036e8d8bef9SDimitry Andric       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
3037e8d8bef9SDimitry Andric     ORE.reset(new OptimizationRemarkEmitter(&F));
303881ad6265SDimitry Andric     return *ORE;
3039e8d8bef9SDimitry Andric   };
3040e8d8bef9SDimitry Andric 
3041e8d8bef9SDimitry Andric   if (IROutliner(GTTI, GIRSI, GORE).run(M))
3042e8d8bef9SDimitry Andric     return PreservedAnalyses::none();
3043e8d8bef9SDimitry Andric   return PreservedAnalyses::all();
3044e8d8bef9SDimitry Andric }
3045