1 //===- IROutliner.cpp -- Outline Similar Regions ----------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 // Implementation for the IROutliner which is used by the IROutliner Pass.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/IROutliner.h"
15 #include "llvm/Analysis/IRSimilarityIdentifier.h"
16 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
17 #include "llvm/Analysis/TargetTransformInfo.h"
18 #include "llvm/IR/Attributes.h"
19 #include "llvm/IR/DebugInfoMetadata.h"
20 #include "llvm/IR/DIBuilder.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/Mangler.h"
23 #include "llvm/IR/PassManager.h"
24 #include "llvm/InitializePasses.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Transforms/IPO.h"
28 #include <map>
29 #include <set>
30 #include <vector>
31 
32 #define DEBUG_TYPE "iroutliner"
33 
34 using namespace llvm;
35 using namespace IRSimilarity;
36 
37 // A command flag to be used for debugging to exclude branches from similarity
38 // matching and outlining.
39 extern cl::opt<bool> DisableBranches;
40 
41 // Set to true if the user wants the ir outliner to run on linkonceodr linkage
42 // functions. This is false by default because the linker can dedupe linkonceodr
43 // functions. Since the outliner is confined to a single module (modulo LTO),
44 // this is off by default. It should, however, be the default behavior in
45 // LTO.
46 static cl::opt<bool> EnableLinkOnceODRIROutlining(
47     "enable-linkonceodr-ir-outlining", cl::Hidden,
48     cl::desc("Enable the IR outliner on linkonceodr functions"),
49     cl::init(false));
50 
51 // This is a debug option to test small pieces of code to ensure that outlining
52 // works correctly.
53 static cl::opt<bool> NoCostModel(
54     "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden,
55     cl::desc("Debug option to outline greedily, without restriction that "
56              "calculated benefit outweighs cost"));
57 
58 /// The OutlinableGroup holds all the overarching information for outlining
59 /// a set of regions that are structurally similar to one another, such as the
60 /// types of the overall function, the output blocks, the sets of stores needed
61 /// and a list of the different regions. This information is used in the
62 /// deduplication of extracted regions with the same structure.
63 struct OutlinableGroup {
64   /// The sections that could be outlined
65   std::vector<OutlinableRegion *> Regions;
66 
67   /// The argument types for the function created as the overall function to
68   /// replace the extracted function for each region.
69   std::vector<Type *> ArgumentTypes;
70   /// The FunctionType for the overall function.
71   FunctionType *OutlinedFunctionType = nullptr;
72   /// The Function for the collective overall function.
73   Function *OutlinedFunction = nullptr;
74 
75   /// Flag for whether we should not consider this group of OutlinableRegions
76   /// for extraction.
77   bool IgnoreGroup = false;
78 
79   /// The return blocks for the overall function.
80   DenseMap<Value *, BasicBlock *> EndBBs;
81 
82   /// The PHIBlocks with their corresponding return block based on the return
83   /// value as the key.
84   DenseMap<Value *, BasicBlock *> PHIBlocks;
85 
86   /// A set containing the different GVN store sets needed. Each array contains
87   /// a sorted list of the different values that need to be stored into output
88   /// registers.
89   DenseSet<ArrayRef<unsigned>> OutputGVNCombinations;
90 
91   /// Flag for whether the \ref ArgumentTypes have been defined after the
92   /// extraction of the first region.
93   bool InputTypesSet = false;
94 
95   /// The number of input values in \ref ArgumentTypes.  Anything after this
96   /// index in ArgumentTypes is an output argument.
97   unsigned NumAggregateInputs = 0;
98 
99   /// The mapping of the canonical numbering of the values in outlined sections
100   /// to specific arguments.
101   DenseMap<unsigned, unsigned> CanonicalNumberToAggArg;
102 
103   /// The number of branches in the region target a basic block that is outside
104   /// of the region.
105   unsigned BranchesToOutside = 0;
106 
107   /// The number of instructions that will be outlined by extracting \ref
108   /// Regions.
109   InstructionCost Benefit = 0;
110   /// The number of added instructions needed for the outlining of the \ref
111   /// Regions.
112   InstructionCost Cost = 0;
113 
114   /// The argument that needs to be marked with the swifterr attribute.  If not
115   /// needed, there is no value.
116   Optional<unsigned> SwiftErrorArgument;
117 
118   /// For the \ref Regions, we look at every Value.  If it is a constant,
119   /// we check whether it is the same in Region.
120   ///
121   /// \param [in,out] NotSame contains the global value numbers where the
122   /// constant is not always the same, and must be passed in as an argument.
123   void findSameConstants(DenseSet<unsigned> &NotSame);
124 
125   /// For the regions, look at each set of GVN stores needed and account for
126   /// each combination.  Add an argument to the argument types if there is
127   /// more than one combination.
128   ///
129   /// \param [in] M - The module we are outlining from.
130   void collectGVNStoreSets(Module &M);
131 };
132 
133 /// Move the contents of \p SourceBB to before the last instruction of \p
134 /// TargetBB.
135 /// \param SourceBB - the BasicBlock to pull Instructions from.
136 /// \param TargetBB - the BasicBlock to put Instruction into.
137 static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) {
138   for (Instruction &I : llvm::make_early_inc_range(SourceBB))
139     I.moveBefore(TargetBB, TargetBB.end());
140 }
141 
142 /// A function to sort the keys of \p Map, which must be a mapping of constant
143 /// values to basic blocks and return it in \p SortedKeys
144 ///
145 /// \param SortedKeys - The vector the keys will be return in and sorted.
146 /// \param Map - The DenseMap containing keys to sort.
147 static void getSortedConstantKeys(std::vector<Value *> &SortedKeys,
148                                   DenseMap<Value *, BasicBlock *> &Map) {
149   for (auto &VtoBB : Map)
150     SortedKeys.push_back(VtoBB.first);
151 
152   stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) {
153     const ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS);
154     const ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS);
155     assert(RHSC && "Not a constant integer in return value?");
156     assert(LHSC && "Not a constant integer in return value?");
157 
158     return LHSC->getLimitedValue() < RHSC->getLimitedValue();
159   });
160 }
161 
162 Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other,
163                                                   Value *V) {
164   Optional<unsigned> GVN = Candidate->getGVN(V);
165   assert(GVN.hasValue() && "No GVN for incoming value");
166   Optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN);
167   Optional<unsigned> FirstGVN = Other.Candidate->fromCanonicalNum(*CanonNum);
168   Optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN);
169   return FoundValueOpt.getValueOr(nullptr);
170 }
171 
172 void OutlinableRegion::splitCandidate() {
173   assert(!CandidateSplit && "Candidate already split!");
174 
175   Instruction *BackInst = Candidate->backInstruction();
176 
177   Instruction *EndInst = nullptr;
178   // Check whether the last instruction is a terminator, if it is, we do
179   // not split on the following instruction. We leave the block as it is.  We
180   // also check that this is not the last instruction in the Module, otherwise
181   // the check for whether the current following instruction matches the
182   // previously recorded instruction will be incorrect.
183   if (!BackInst->isTerminator() ||
184       BackInst->getParent() != &BackInst->getFunction()->back()) {
185     EndInst = Candidate->end()->Inst;
186     assert(EndInst && "Expected an end instruction?");
187   }
188 
189   // We check if the current instruction following the last instruction in the
190   // region is the same as the recorded instruction following the last
191   // instruction. If they do not match, there could be problems in rewriting
192   // the program after outlining, so we ignore it.
193   if (!BackInst->isTerminator() &&
194       EndInst != BackInst->getNextNonDebugInstruction())
195     return;
196 
197   Instruction *StartInst = (*Candidate->begin()).Inst;
198   assert(StartInst && "Expected a start instruction?");
199   StartBB = StartInst->getParent();
200   PrevBB = StartBB;
201 
202   // The basic block gets split like so:
203   // block:                 block:
204   //   inst1                  inst1
205   //   inst2                  inst2
206   //   region1               br block_to_outline
207   //   region2              block_to_outline:
208   //   region3          ->    region1
209   //   region4                region2
210   //   inst3                  region3
211   //   inst4                  region4
212   //                          br block_after_outline
213   //                        block_after_outline:
214   //                          inst3
215   //                          inst4
216 
217   std::string OriginalName = PrevBB->getName().str();
218 
219   StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline");
220   PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB);
221 
222   CandidateSplit = true;
223   if (!BackInst->isTerminator()) {
224     EndBB = EndInst->getParent();
225     FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline");
226     EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB);
227     FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB);
228     return;
229   }
230 
231   EndBB = BackInst->getParent();
232   EndsInBranch = true;
233   FollowBB = nullptr;
234 }
235 
236 void OutlinableRegion::reattachCandidate() {
237   assert(CandidateSplit && "Candidate is not split!");
238 
239   // The basic block gets reattached like so:
240   // block:                        block:
241   //   inst1                         inst1
242   //   inst2                         inst2
243   //   br block_to_outline           region1
244   // block_to_outline:        ->     region2
245   //   region1                       region3
246   //   region2                       region4
247   //   region3                       inst3
248   //   region4                       inst4
249   //   br block_after_outline
250   // block_after_outline:
251   //   inst3
252   //   inst4
253   assert(StartBB != nullptr && "StartBB for Candidate is not defined!");
254 
255   // StartBB should only have one predecessor since we put an unconditional
256   // branch at the end of PrevBB when we split the BasicBlock.
257   PrevBB = StartBB->getSinglePredecessor();
258   assert(PrevBB != nullptr &&
259          "No Predecessor for the region start basic block!");
260 
261   assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!");
262   PrevBB->getTerminator()->eraseFromParent();
263 
264   moveBBContents(*StartBB, *PrevBB);
265 
266   BasicBlock *PlacementBB = PrevBB;
267   if (StartBB != EndBB)
268     PlacementBB = EndBB;
269   if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) {
270     assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!");
271     assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!");
272     PlacementBB->getTerminator()->eraseFromParent();
273     moveBBContents(*FollowBB, *PlacementBB);
274     PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB);
275     FollowBB->eraseFromParent();
276   }
277 
278   PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB);
279   StartBB->eraseFromParent();
280 
281   // Make sure to save changes back to the StartBB.
282   StartBB = PrevBB;
283   EndBB = nullptr;
284   PrevBB = nullptr;
285   FollowBB = nullptr;
286 
287   CandidateSplit = false;
288 }
289 
290 /// Find whether \p V matches the Constants previously found for the \p GVN.
291 ///
292 /// \param V - The value to check for consistency.
293 /// \param GVN - The global value number assigned to \p V.
294 /// \param GVNToConstant - The mapping of global value number to Constants.
295 /// \returns true if the Value matches the Constant mapped to by V and false if
296 /// it \p V is a Constant but does not match.
297 /// \returns None if \p V is not a Constant.
298 static Optional<bool>
299 constantMatches(Value *V, unsigned GVN,
300                 DenseMap<unsigned, Constant *> &GVNToConstant) {
301   // See if we have a constants
302   Constant *CST = dyn_cast<Constant>(V);
303   if (!CST)
304     return None;
305 
306   // Holds a mapping from a global value number to a Constant.
307   DenseMap<unsigned, Constant *>::iterator GVNToConstantIt;
308   bool Inserted;
309 
310 
311   // If we have a constant, try to make a new entry in the GVNToConstant.
312   std::tie(GVNToConstantIt, Inserted) =
313       GVNToConstant.insert(std::make_pair(GVN, CST));
314   // If it was found and is not equal, it is not the same. We do not
315   // handle this case yet, and exit early.
316   if (Inserted || (GVNToConstantIt->second == CST))
317     return true;
318 
319   return false;
320 }
321 
322 InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) {
323   InstructionCost Benefit = 0;
324 
325   // Estimate the benefit of outlining a specific sections of the program.  We
326   // delegate mostly this task to the TargetTransformInfo so that if the target
327   // has specific changes, we can have a more accurate estimate.
328 
329   // However, getInstructionCost delegates the code size calculation for
330   // arithmetic instructions to getArithmeticInstrCost in
331   // include/Analysis/TargetTransformImpl.h, where it always estimates that the
332   // code size for a division and remainder instruction to be equal to 4, and
333   // everything else to 1.  This is not an accurate representation of the
334   // division instruction for targets that have a native division instruction.
335   // To be overly conservative, we only add 1 to the number of instructions for
336   // each division instruction.
337   for (IRInstructionData &ID : *Candidate) {
338     Instruction *I = ID.Inst;
339     switch (I->getOpcode()) {
340     case Instruction::FDiv:
341     case Instruction::FRem:
342     case Instruction::SDiv:
343     case Instruction::SRem:
344     case Instruction::UDiv:
345     case Instruction::URem:
346       Benefit += 1;
347       break;
348     default:
349       Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize);
350       break;
351     }
352   }
353 
354   return Benefit;
355 }
356 
357 /// Find whether \p Region matches the global value numbering to Constant
358 /// mapping found so far.
359 ///
360 /// \param Region - The OutlinableRegion we are checking for constants
361 /// \param GVNToConstant - The mapping of global value number to Constants.
362 /// \param NotSame - The set of global value numbers that do not have the same
363 /// constant in each region.
364 /// \returns true if all Constants are the same in every use of a Constant in \p
365 /// Region and false if not
366 static bool
367 collectRegionsConstants(OutlinableRegion &Region,
368                         DenseMap<unsigned, Constant *> &GVNToConstant,
369                         DenseSet<unsigned> &NotSame) {
370   bool ConstantsTheSame = true;
371 
372   IRSimilarityCandidate &C = *Region.Candidate;
373   for (IRInstructionData &ID : C) {
374 
375     // Iterate over the operands in an instruction. If the global value number,
376     // assigned by the IRSimilarityCandidate, has been seen before, we check if
377     // the the number has been found to be not the same value in each instance.
378     for (Value *V : ID.OperVals) {
379       Optional<unsigned> GVNOpt = C.getGVN(V);
380       assert(GVNOpt.hasValue() && "Expected a GVN for operand?");
381       unsigned GVN = GVNOpt.getValue();
382 
383       // Check if this global value has been found to not be the same already.
384       if (NotSame.contains(GVN)) {
385         if (isa<Constant>(V))
386           ConstantsTheSame = false;
387         continue;
388       }
389 
390       // If it has been the same so far, we check the value for if the
391       // associated Constant value match the previous instances of the same
392       // global value number.  If the global value does not map to a Constant,
393       // it is considered to not be the same value.
394       Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant);
395       if (ConstantMatches.hasValue()) {
396         if (ConstantMatches.getValue())
397           continue;
398         else
399           ConstantsTheSame = false;
400       }
401 
402       // While this value is a register, it might not have been previously,
403       // make sure we don't already have a constant mapped to this global value
404       // number.
405       if (GVNToConstant.find(GVN) != GVNToConstant.end())
406         ConstantsTheSame = false;
407 
408       NotSame.insert(GVN);
409     }
410   }
411 
412   return ConstantsTheSame;
413 }
414 
415 void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) {
416   DenseMap<unsigned, Constant *> GVNToConstant;
417 
418   for (OutlinableRegion *Region : Regions)
419     collectRegionsConstants(*Region, GVNToConstant, NotSame);
420 }
421 
422 void OutlinableGroup::collectGVNStoreSets(Module &M) {
423   for (OutlinableRegion *OS : Regions)
424     OutputGVNCombinations.insert(OS->GVNStores);
425 
426   // We are adding an extracted argument to decide between which output path
427   // to use in the basic block.  It is used in a switch statement and only
428   // needs to be an integer.
429   if (OutputGVNCombinations.size() > 1)
430     ArgumentTypes.push_back(Type::getInt32Ty(M.getContext()));
431 }
432 
433 /// Get the subprogram if it exists for one of the outlined regions.
434 ///
435 /// \param [in] Group - The set of regions to find a subprogram for.
436 /// \returns the subprogram if it exists, or nullptr.
437 static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) {
438   for (OutlinableRegion *OS : Group.Regions)
439     if (Function *F = OS->Call->getFunction())
440       if (DISubprogram *SP = F->getSubprogram())
441         return SP;
442 
443   return nullptr;
444 }
445 
446 Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,
447                                      unsigned FunctionNameSuffix) {
448   assert(!Group.OutlinedFunction && "Function is already defined!");
449 
450   Type *RetTy = Type::getVoidTy(M.getContext());
451   // All extracted functions _should_ have the same return type at this point
452   // since the similarity identifier ensures that all branches outside of the
453   // region occur in the same place.
454 
455   // NOTE: Should we ever move to the model that uses a switch at every point
456   // needed, meaning that we could branch within the region or out, it is
457   // possible that we will need to switch to using the most general case all of
458   // the time.
459   for (OutlinableRegion *R : Group.Regions) {
460     Type *ExtractedFuncType = R->ExtractedFunction->getReturnType();
461     if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) ||
462         (RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16)))
463       RetTy = ExtractedFuncType;
464   }
465 
466   Group.OutlinedFunctionType = FunctionType::get(
467       RetTy, Group.ArgumentTypes, false);
468 
469   // These functions will only be called from within the same module, so
470   // we can set an internal linkage.
471   Group.OutlinedFunction = Function::Create(
472       Group.OutlinedFunctionType, GlobalValue::InternalLinkage,
473       "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);
474 
475   // Transfer the swifterr attribute to the correct function parameter.
476   if (Group.SwiftErrorArgument.hasValue())
477     Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.getValue(),
478                                          Attribute::SwiftError);
479 
480   Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);
481   Group.OutlinedFunction->addFnAttr(Attribute::MinSize);
482 
483   // If there's a DISubprogram associated with this outlined function, then
484   // emit debug info for the outlined function.
485   if (DISubprogram *SP = getSubprogramOrNull(Group)) {
486     Function *F = Group.OutlinedFunction;
487     // We have a DISubprogram. Get its DICompileUnit.
488     DICompileUnit *CU = SP->getUnit();
489     DIBuilder DB(M, true, CU);
490     DIFile *Unit = SP->getFile();
491     Mangler Mg;
492     // Get the mangled name of the function for the linkage name.
493     std::string Dummy;
494     llvm::raw_string_ostream MangledNameStream(Dummy);
495     Mg.getNameWithPrefix(MangledNameStream, F, false);
496 
497     DISubprogram *OutlinedSP = DB.createFunction(
498         Unit /* Context */, F->getName(), MangledNameStream.str(),
499         Unit /* File */,
500         0 /* Line 0 is reserved for compiler-generated code. */,
501         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
502         0, /* Line 0 is reserved for compiler-generated code. */
503         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
504         /* Outlined code is optimized code by definition. */
505         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
506 
507     // Don't add any new variables to the subprogram.
508     DB.finalizeSubprogram(OutlinedSP);
509 
510     // Attach subprogram to the function.
511     F->setSubprogram(OutlinedSP);
512     // We're done with the DIBuilder.
513     DB.finalize();
514   }
515 
516   return Group.OutlinedFunction;
517 }
518 
519 /// Move each BasicBlock in \p Old to \p New.
520 ///
521 /// \param [in] Old - The function to move the basic blocks from.
522 /// \param [in] New - The function to move the basic blocks to.
523 /// \param [out] NewEnds - The return blocks of the new overall function.
524 static void moveFunctionData(Function &Old, Function &New,
525                              DenseMap<Value *, BasicBlock *> &NewEnds) {
526   Function::iterator CurrBB, NextBB, FinalBB;
527   for (CurrBB = Old.begin(), FinalBB = Old.end(); CurrBB != FinalBB;
528        CurrBB = NextBB) {
529     NextBB = std::next(CurrBB);
530     CurrBB->removeFromParent();
531     CurrBB->insertInto(&New);
532     Instruction *I = CurrBB->getTerminator();
533 
534     // For each block we find a return instruction is, it is a potential exit
535     // path for the function.  We keep track of each block based on the return
536     // value here.
537     if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
538       NewEnds.insert(std::make_pair(RI->getReturnValue(), &(*CurrBB)));
539 
540     std::vector<Instruction *> DebugInsts;
541 
542     for (Instruction &Val : *CurrBB) {
543       // We must handle the scoping of called functions differently than
544       // other outlined instructions.
545       if (!isa<CallInst>(&Val)) {
546         // Remove the debug information for outlined functions.
547         Val.setDebugLoc(DebugLoc());
548         continue;
549       }
550 
551       // From this point we are only handling call instructions.
552       CallInst *CI = cast<CallInst>(&Val);
553 
554       // We add any debug statements here, to be removed after.  Since the
555       // instructions originate from many different locations in the program,
556       // it will cause incorrect reporting from a debugger if we keep the
557       // same debug instructions.
558       if (isa<DbgInfoIntrinsic>(CI)) {
559         DebugInsts.push_back(&Val);
560         continue;
561       }
562 
563       // Edit the scope of called functions inside of outlined functions.
564       if (DISubprogram *SP = New.getSubprogram()) {
565         DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP);
566         Val.setDebugLoc(DI);
567       }
568     }
569 
570     for (Instruction *I : DebugInsts)
571       I->eraseFromParent();
572   }
573 
574   assert(NewEnds.size() > 0 && "No return instruction for new function?");
575 }
576 
577 /// Find the the constants that will need to be lifted into arguments
578 /// as they are not the same in each instance of the region.
579 ///
580 /// \param [in] C - The IRSimilarityCandidate containing the region we are
581 /// analyzing.
582 /// \param [in] NotSame - The set of global value numbers that do not have a
583 /// single Constant across all OutlinableRegions similar to \p C.
584 /// \param [out] Inputs - The list containing the global value numbers of the
585 /// arguments needed for the region of code.
586 static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame,
587                           std::vector<unsigned> &Inputs) {
588   DenseSet<unsigned> Seen;
589   // Iterate over the instructions, and find what constants will need to be
590   // extracted into arguments.
591   for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end();
592        IDIt != EndIDIt; IDIt++) {
593     for (Value *V : (*IDIt).OperVals) {
594       // Since these are stored before any outlining, they will be in the
595       // global value numbering.
596       unsigned GVN = C.getGVN(V).getValue();
597       if (isa<Constant>(V))
598         if (NotSame.contains(GVN) && !Seen.contains(GVN)) {
599           Inputs.push_back(GVN);
600           Seen.insert(GVN);
601         }
602     }
603   }
604 }
605 
606 /// Find the GVN for the inputs that have been found by the CodeExtractor.
607 ///
608 /// \param [in] C - The IRSimilarityCandidate containing the region we are
609 /// analyzing.
610 /// \param [in] CurrentInputs - The set of inputs found by the
611 /// CodeExtractor.
612 /// \param [in] OutputMappings - The mapping of values that have been replaced
613 /// by a new output value.
614 /// \param [out] EndInputNumbers - The global value numbers for the extracted
615 /// arguments.
616 static void mapInputsToGVNs(IRSimilarityCandidate &C,
617                             SetVector<Value *> &CurrentInputs,
618                             const DenseMap<Value *, Value *> &OutputMappings,
619                             std::vector<unsigned> &EndInputNumbers) {
620   // Get the Global Value Number for each input.  We check if the Value has been
621   // replaced by a different value at output, and use the original value before
622   // replacement.
623   for (Value *Input : CurrentInputs) {
624     assert(Input && "Have a nullptr as an input");
625     if (OutputMappings.find(Input) != OutputMappings.end())
626       Input = OutputMappings.find(Input)->second;
627     assert(C.getGVN(Input).hasValue() &&
628            "Could not find a numbering for the given input");
629     EndInputNumbers.push_back(C.getGVN(Input).getValue());
630   }
631 }
632 
633 /// Find the original value for the \p ArgInput values if any one of them was
634 /// replaced during a previous extraction.
635 ///
636 /// \param [in] ArgInputs - The inputs to be extracted by the code extractor.
637 /// \param [in] OutputMappings - The mapping of values that have been replaced
638 /// by a new output value.
639 /// \param [out] RemappedArgInputs - The remapped values according to
640 /// \p OutputMappings that will be extracted.
641 static void
642 remapExtractedInputs(const ArrayRef<Value *> ArgInputs,
643                      const DenseMap<Value *, Value *> &OutputMappings,
644                      SetVector<Value *> &RemappedArgInputs) {
645   // Get the global value number for each input that will be extracted as an
646   // argument by the code extractor, remapping if needed for reloaded values.
647   for (Value *Input : ArgInputs) {
648     if (OutputMappings.find(Input) != OutputMappings.end())
649       Input = OutputMappings.find(Input)->second;
650     RemappedArgInputs.insert(Input);
651   }
652 }
653 
654 /// Find the input GVNs and the output values for a region of Instructions.
655 /// Using the code extractor, we collect the inputs to the extracted function.
656 ///
657 /// The \p Region can be identified as needing to be ignored in this function.
658 /// It should be checked whether it should be ignored after a call to this
659 /// function.
660 ///
661 /// \param [in,out] Region - The region of code to be analyzed.
662 /// \param [out] InputGVNs - The global value numbers for the extracted
663 /// arguments.
664 /// \param [in] NotSame - The global value numbers in the region that do not
665 /// have the same constant value in the regions structurally similar to
666 /// \p Region.
667 /// \param [in] OutputMappings - The mapping of values that have been replaced
668 /// by a new output value after extraction.
669 /// \param [out] ArgInputs - The values of the inputs to the extracted function.
670 /// \param [out] Outputs - The set of values extracted by the CodeExtractor
671 /// as outputs.
672 static void getCodeExtractorArguments(
673     OutlinableRegion &Region, std::vector<unsigned> &InputGVNs,
674     DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings,
675     SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) {
676   IRSimilarityCandidate &C = *Region.Candidate;
677 
678   // OverallInputs are the inputs to the region found by the CodeExtractor,
679   // SinkCands and HoistCands are used by the CodeExtractor to find sunken
680   // allocas of values whose lifetimes are contained completely within the
681   // outlined region. PremappedInputs are the arguments found by the
682   // CodeExtractor, removing conditions such as sunken allocas, but that
683   // may need to be remapped due to the extracted output values replacing
684   // the original values. We use DummyOutputs for this first run of finding
685   // inputs and outputs since the outputs could change during findAllocas,
686   // the correct set of extracted outputs will be in the final Outputs ValueSet.
687   SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands,
688       DummyOutputs;
689 
690   // Use the code extractor to get the inputs and outputs, without sunken
691   // allocas or removing llvm.assumes.
692   CodeExtractor *CE = Region.CE;
693   CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands);
694   assert(Region.StartBB && "Region must have a start BasicBlock!");
695   Function *OrigF = Region.StartBB->getParent();
696   CodeExtractorAnalysisCache CEAC(*OrigF);
697   BasicBlock *Dummy = nullptr;
698 
699   // The region may be ineligible due to VarArgs in the parent function. In this
700   // case we ignore the region.
701   if (!CE->isEligible()) {
702     Region.IgnoreRegion = true;
703     return;
704   }
705 
706   // Find if any values are going to be sunk into the function when extracted
707   CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy);
708   CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands);
709 
710   // TODO: Support regions with sunken allocas: values whose lifetimes are
711   // contained completely within the outlined region.  These are not guaranteed
712   // to be the same in every region, so we must elevate them all to arguments
713   // when they appear.  If these values are not equal, it means there is some
714   // Input in OverallInputs that was removed for ArgInputs.
715   if (OverallInputs.size() != PremappedInputs.size()) {
716     Region.IgnoreRegion = true;
717     return;
718   }
719 
720   findConstants(C, NotSame, InputGVNs);
721 
722   mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs);
723 
724   remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings,
725                        ArgInputs);
726 
727   // Sort the GVNs, since we now have constants included in the \ref InputGVNs
728   // we need to make sure they are in a deterministic order.
729   stable_sort(InputGVNs);
730 }
731 
732 /// Look over the inputs and map each input argument to an argument in the
733 /// overall function for the OutlinableRegions.  This creates a way to replace
734 /// the arguments of the extracted function with the arguments of the new
735 /// overall function.
736 ///
737 /// \param [in,out] Region - The region of code to be analyzed.
738 /// \param [in] InputGVNs - The global value numbering of the input values
739 /// collected.
740 /// \param [in] ArgInputs - The values of the arguments to the extracted
741 /// function.
742 static void
743 findExtractedInputToOverallInputMapping(OutlinableRegion &Region,
744                                         std::vector<unsigned> &InputGVNs,
745                                         SetVector<Value *> &ArgInputs) {
746 
747   IRSimilarityCandidate &C = *Region.Candidate;
748   OutlinableGroup &Group = *Region.Parent;
749 
750   // This counts the argument number in the overall function.
751   unsigned TypeIndex = 0;
752 
753   // This counts the argument number in the extracted function.
754   unsigned OriginalIndex = 0;
755 
756   // Find the mapping of the extracted arguments to the arguments for the
757   // overall function. Since there may be extra arguments in the overall
758   // function to account for the extracted constants, we have two different
759   // counters as we find extracted arguments, and as we come across overall
760   // arguments.
761 
762   // Additionally, in our first pass, for the first extracted function,
763   // we find argument locations for the canonical value numbering.  This
764   // numbering overrides any discovered location for the extracted code.
765   for (unsigned InputVal : InputGVNs) {
766     Optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);
767     assert(CanonicalNumberOpt.hasValue() && "Canonical number not found?");
768     unsigned CanonicalNumber = CanonicalNumberOpt.getValue();
769 
770     Optional<Value *> InputOpt = C.fromGVN(InputVal);
771     assert(InputOpt.hasValue() && "Global value number not found?");
772     Value *Input = InputOpt.getValue();
773 
774     DenseMap<unsigned, unsigned>::iterator AggArgIt =
775         Group.CanonicalNumberToAggArg.find(CanonicalNumber);
776 
777     if (!Group.InputTypesSet) {
778       Group.ArgumentTypes.push_back(Input->getType());
779       // If the input value has a swifterr attribute, make sure to mark the
780       // argument in the overall function.
781       if (Input->isSwiftError()) {
782         assert(
783             !Group.SwiftErrorArgument.hasValue() &&
784             "Argument already marked with swifterr for this OutlinableGroup!");
785         Group.SwiftErrorArgument = TypeIndex;
786       }
787     }
788 
789     // Check if we have a constant. If we do add it to the overall argument
790     // number to Constant map for the region, and continue to the next input.
791     if (Constant *CST = dyn_cast<Constant>(Input)) {
792       if (AggArgIt != Group.CanonicalNumberToAggArg.end())
793         Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST));
794       else {
795         Group.CanonicalNumberToAggArg.insert(
796             std::make_pair(CanonicalNumber, TypeIndex));
797         Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST));
798       }
799       TypeIndex++;
800       continue;
801     }
802 
803     // It is not a constant, we create the mapping from extracted argument list
804     // to the overall argument list, using the canonical location, if it exists.
805     assert(ArgInputs.count(Input) && "Input cannot be found!");
806 
807     if (AggArgIt != Group.CanonicalNumberToAggArg.end()) {
808       if (OriginalIndex != AggArgIt->second)
809         Region.ChangedArgOrder = true;
810       Region.ExtractedArgToAgg.insert(
811           std::make_pair(OriginalIndex, AggArgIt->second));
812       Region.AggArgToExtracted.insert(
813           std::make_pair(AggArgIt->second, OriginalIndex));
814     } else {
815       Group.CanonicalNumberToAggArg.insert(
816           std::make_pair(CanonicalNumber, TypeIndex));
817       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex));
818       Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex));
819     }
820     OriginalIndex++;
821     TypeIndex++;
822   }
823 
824   // If the function type definitions for the OutlinableGroup holding the region
825   // have not been set, set the length of the inputs here.  We should have the
826   // same inputs for all of the different regions contained in the
827   // OutlinableGroup since they are all structurally similar to one another.
828   if (!Group.InputTypesSet) {
829     Group.NumAggregateInputs = TypeIndex;
830     Group.InputTypesSet = true;
831   }
832 
833   Region.NumExtractedInputs = OriginalIndex;
834 }
835 
836 /// Create a mapping of the output arguments for the \p Region to the output
837 /// arguments of the overall outlined function.
838 ///
839 /// \param [in,out] Region - The region of code to be analyzed.
840 /// \param [in] Outputs - The values found by the code extractor.
841 static void
842 findExtractedOutputToOverallOutputMapping(OutlinableRegion &Region,
843                                           SetVector<Value *> &Outputs) {
844   OutlinableGroup &Group = *Region.Parent;
845   IRSimilarityCandidate &C = *Region.Candidate;
846 
847   SmallVector<BasicBlock *> BE;
848   DenseSet<BasicBlock *> BBSet;
849   C.getBasicBlocks(BBSet, BE);
850 
851   // Find the exits to the region.
852   SmallPtrSet<BasicBlock *, 1> Exits;
853   for (BasicBlock *Block : BE)
854     for (BasicBlock *Succ : successors(Block))
855       if (!BBSet.contains(Succ))
856         Exits.insert(Succ);
857 
858   // After determining which blocks exit to PHINodes, we add these PHINodes to
859   // the set of outputs to be processed.  We also check the incoming values of
860   // the PHINodes for whether they should no longer be considered outputs.
861   for (BasicBlock *ExitBB : Exits) {
862     for (PHINode &PN : ExitBB->phis()) {
863       // Find all incoming values from the outlining region.
864       SmallVector<unsigned, 2> IncomingVals;
865       for (unsigned Idx = 0; Idx < PN.getNumIncomingValues(); ++Idx)
866         if (BBSet.contains(PN.getIncomingBlock(Idx)))
867           IncomingVals.push_back(Idx);
868 
869       // Do not process PHI if there is one (or fewer) predecessor from region.
870       if (IncomingVals.size() <= 1)
871         continue;
872 
873       Region.IgnoreRegion = true;
874       return;
875     }
876   }
877 
878   // This counts the argument number in the extracted function.
879   unsigned OriginalIndex = Region.NumExtractedInputs;
880 
881   // This counts the argument number in the overall function.
882   unsigned TypeIndex = Group.NumAggregateInputs;
883   bool TypeFound;
884   DenseSet<unsigned> AggArgsUsed;
885 
886   // Iterate over the output types and identify if there is an aggregate pointer
887   // type whose base type matches the current output type. If there is, we mark
888   // that we will use this output register for this value. If not we add another
889   // type to the overall argument type list. We also store the GVNs used for
890   // stores to identify which values will need to be moved into an special
891   // block that holds the stores to the output registers.
892   for (Value *Output : Outputs) {
893     TypeFound = false;
894     // We can do this since it is a result value, and will have a number
895     // that is necessarily the same. BUT if in the future, the instructions
896     // do not have to be in same order, but are functionally the same, we will
897     // have to use a different scheme, as one-to-one correspondence is not
898     // guaranteed.
899     unsigned GlobalValue = C.getGVN(Output).getValue();
900     unsigned ArgumentSize = Group.ArgumentTypes.size();
901 
902     for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) {
903       if (Group.ArgumentTypes[Jdx] != PointerType::getUnqual(Output->getType()))
904         continue;
905 
906       if (AggArgsUsed.contains(Jdx))
907         continue;
908 
909       TypeFound = true;
910       AggArgsUsed.insert(Jdx);
911       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx));
912       Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex));
913       Region.GVNStores.push_back(GlobalValue);
914       break;
915     }
916 
917     // We were unable to find an unused type in the output type set that matches
918     // the output, so we add a pointer type to the argument types of the overall
919     // function to handle this output and create a mapping to it.
920     if (!TypeFound) {
921       Group.ArgumentTypes.push_back(PointerType::getUnqual(Output->getType()));
922       AggArgsUsed.insert(Group.ArgumentTypes.size() - 1);
923       Region.ExtractedArgToAgg.insert(
924           std::make_pair(OriginalIndex, Group.ArgumentTypes.size() - 1));
925       Region.AggArgToExtracted.insert(
926           std::make_pair(Group.ArgumentTypes.size() - 1, OriginalIndex));
927       Region.GVNStores.push_back(GlobalValue);
928     }
929 
930     stable_sort(Region.GVNStores);
931     OriginalIndex++;
932     TypeIndex++;
933   }
934 }
935 
936 void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region,
937                                       DenseSet<unsigned> &NotSame) {
938   std::vector<unsigned> Inputs;
939   SetVector<Value *> ArgInputs, Outputs;
940 
941   getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs,
942                             Outputs);
943 
944   if (Region.IgnoreRegion)
945     return;
946 
947   // Map the inputs found by the CodeExtractor to the arguments found for
948   // the overall function.
949   findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs);
950 
951   // Map the outputs found by the CodeExtractor to the arguments found for
952   // the overall function.
953   findExtractedOutputToOverallOutputMapping(Region, Outputs);
954 }
955 
956 /// Replace the extracted function in the Region with a call to the overall
957 /// function constructed from the deduplicated similar regions, replacing and
958 /// remapping the values passed to the extracted function as arguments to the
959 /// new arguments of the overall function.
960 ///
961 /// \param [in] M - The module to outline from.
962 /// \param [in] Region - The regions of extracted code to be replaced with a new
963 /// function.
964 /// \returns a call instruction with the replaced function.
965 CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {
966   std::vector<Value *> NewCallArgs;
967   DenseMap<unsigned, unsigned>::iterator ArgPair;
968 
969   OutlinableGroup &Group = *Region.Parent;
970   CallInst *Call = Region.Call;
971   assert(Call && "Call to replace is nullptr?");
972   Function *AggFunc = Group.OutlinedFunction;
973   assert(AggFunc && "Function to replace with is nullptr?");
974 
975   // If the arguments are the same size, there are not values that need to be
976   // made into an argument, the argument ordering has not been change, or
977   // different output registers to handle.  We can simply replace the called
978   // function in this case.
979   if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) {
980     LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
981                       << *AggFunc << " with same number of arguments\n");
982     Call->setCalledFunction(AggFunc);
983     return Call;
984   }
985 
986   // We have a different number of arguments than the new function, so
987   // we need to use our previously mappings off extracted argument to overall
988   // function argument, and constants to overall function argument to create the
989   // new argument list.
990   for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) {
991 
992     if (AggArgIdx == AggFunc->arg_size() - 1 &&
993         Group.OutputGVNCombinations.size() > 1) {
994       // If we are on the last argument, and we need to differentiate between
995       // output blocks, add an integer to the argument list to determine
996       // what block to take
997       LLVM_DEBUG(dbgs() << "Set switch block argument to "
998                         << Region.OutputBlockNum << "\n");
999       NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()),
1000                                              Region.OutputBlockNum));
1001       continue;
1002     }
1003 
1004     ArgPair = Region.AggArgToExtracted.find(AggArgIdx);
1005     if (ArgPair != Region.AggArgToExtracted.end()) {
1006       Value *ArgumentValue = Call->getArgOperand(ArgPair->second);
1007       // If we found the mapping from the extracted function to the overall
1008       // function, we simply add it to the argument list.  We use the same
1009       // value, it just needs to honor the new order of arguments.
1010       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1011                         << *ArgumentValue << "\n");
1012       NewCallArgs.push_back(ArgumentValue);
1013       continue;
1014     }
1015 
1016     // If it is a constant, we simply add it to the argument list as a value.
1017     if (Region.AggArgToConstant.find(AggArgIdx) !=
1018         Region.AggArgToConstant.end()) {
1019       Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second;
1020       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1021                         << *CST << "\n");
1022       NewCallArgs.push_back(CST);
1023       continue;
1024     }
1025 
1026     // Add a nullptr value if the argument is not found in the extracted
1027     // function.  If we cannot find a value, it means it is not in use
1028     // for the region, so we should not pass anything to it.
1029     LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n");
1030     NewCallArgs.push_back(ConstantPointerNull::get(
1031         static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType())));
1032   }
1033 
1034   LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
1035                     << *AggFunc << " with new set of arguments\n");
1036   // Create the new call instruction and erase the old one.
1037   Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "",
1038                           Call);
1039 
1040   // It is possible that the call to the outlined function is either the first
1041   // instruction is in the new block, the last instruction, or both.  If either
1042   // of these is the case, we need to make sure that we replace the instruction
1043   // in the IRInstructionData struct with the new call.
1044   CallInst *OldCall = Region.Call;
1045   if (Region.NewFront->Inst == OldCall)
1046     Region.NewFront->Inst = Call;
1047   if (Region.NewBack->Inst == OldCall)
1048     Region.NewBack->Inst = Call;
1049 
1050   // Transfer any debug information.
1051   Call->setDebugLoc(Region.Call->getDebugLoc());
1052   // Since our output may determine which branch we go to, we make sure to
1053   // propogate this new call value through the module.
1054   OldCall->replaceAllUsesWith(Call);
1055 
1056   // Remove the old instruction.
1057   OldCall->eraseFromParent();
1058   Region.Call = Call;
1059 
1060   // Make sure that the argument in the new function has the SwiftError
1061   // argument.
1062   if (Group.SwiftErrorArgument.hasValue())
1063     Call->addParamAttr(Group.SwiftErrorArgument.getValue(),
1064                        Attribute::SwiftError);
1065 
1066   return Call;
1067 }
1068 
1069 // Within an extracted function, replace the argument uses of the extracted
1070 // region with the arguments of the function for an OutlinableGroup.
1071 //
1072 /// \param [in] Region - The region of extracted code to be changed.
1073 /// \param [in,out] OutputBBs - The BasicBlock for the output stores for this
1074 /// region.
1075 /// \param [in] FirstFunction - A flag to indicate whether we are using this
1076 /// function to define the overall outlined function for all the regions, or
1077 /// if we are operating on one of the following regions.
1078 static void
1079 replaceArgumentUses(OutlinableRegion &Region,
1080                     DenseMap<Value *, BasicBlock *> &OutputBBs,
1081                     bool FirstFunction = false) {
1082   OutlinableGroup &Group = *Region.Parent;
1083   assert(Region.ExtractedFunction && "Region has no extracted function?");
1084 
1085   Function *DominatingFunction = Region.ExtractedFunction;
1086   if (FirstFunction)
1087     DominatingFunction = Group.OutlinedFunction;
1088   DominatorTree DT(*DominatingFunction);
1089 
1090   for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size();
1091        ArgIdx++) {
1092     assert(Region.ExtractedArgToAgg.find(ArgIdx) !=
1093                Region.ExtractedArgToAgg.end() &&
1094            "No mapping from extracted to outlined?");
1095     unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second;
1096     Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx);
1097     Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx);
1098     // The argument is an input, so we can simply replace it with the overall
1099     // argument value
1100     if (ArgIdx < Region.NumExtractedInputs) {
1101       LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function "
1102                         << *Region.ExtractedFunction << " with " << *AggArg
1103                         << " in function " << *Group.OutlinedFunction << "\n");
1104       Arg->replaceAllUsesWith(AggArg);
1105       continue;
1106     }
1107 
1108     // If we are replacing an output, we place the store value in its own
1109     // block inside the overall function before replacing the use of the output
1110     // in the function.
1111     assert(Arg->hasOneUse() && "Output argument can only have one use");
1112     User *InstAsUser = Arg->user_back();
1113     assert(InstAsUser && "User is nullptr!");
1114 
1115     Instruction *I = cast<Instruction>(InstAsUser);
1116     BasicBlock *BB = I->getParent();
1117     SmallVector<BasicBlock *, 4> Descendants;
1118     DT.getDescendants(BB, Descendants);
1119     bool EdgeAdded = false;
1120     if (Descendants.size() == 0) {
1121       EdgeAdded = true;
1122       DT.insertEdge(&DominatingFunction->getEntryBlock(), BB);
1123       DT.getDescendants(BB, Descendants);
1124     }
1125 
1126     // Iterate over the following blocks, looking for return instructions,
1127     // if we find one, find the corresponding output block for the return value
1128     // and move our store instruction there.
1129     for (BasicBlock *DescendBB : Descendants) {
1130       ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator());
1131       if (!RI)
1132         continue;
1133       Value *RetVal = RI->getReturnValue();
1134       auto VBBIt = OutputBBs.find(RetVal);
1135       assert(VBBIt != OutputBBs.end() && "Could not find output value!");
1136 
1137       // If this is storing a PHINode, we must make sure it is included in the
1138       // overall function.
1139       StoreInst *SI = cast<StoreInst>(I);
1140 
1141       Value *ValueOperand = SI->getValueOperand();
1142 
1143       StoreInst *NewI = cast<StoreInst>(I->clone());
1144       NewI->setDebugLoc(DebugLoc());
1145       BasicBlock *OutputBB = VBBIt->second;
1146       OutputBB->getInstList().push_back(NewI);
1147       LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to "
1148                         << *OutputBB << "\n");
1149 
1150       if (FirstFunction)
1151         continue;
1152       Value *CorrVal =
1153           Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand);
1154       assert(CorrVal && "Value is nullptr?");
1155       NewI->setOperand(0, CorrVal);
1156     }
1157 
1158     // If we added an edge for basic blocks without a predecessor, we remove it
1159     // here.
1160     if (EdgeAdded)
1161       DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB);
1162     I->eraseFromParent();
1163 
1164     LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function "
1165                       << *Region.ExtractedFunction << " with " << *AggArg
1166                       << " in function " << *Group.OutlinedFunction << "\n");
1167     Arg->replaceAllUsesWith(AggArg);
1168   }
1169 }
1170 
1171 /// Within an extracted function, replace the constants that need to be lifted
1172 /// into arguments with the actual argument.
1173 ///
1174 /// \param Region [in] - The region of extracted code to be changed.
1175 void replaceConstants(OutlinableRegion &Region) {
1176   OutlinableGroup &Group = *Region.Parent;
1177   // Iterate over the constants that need to be elevated into arguments
1178   for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) {
1179     unsigned AggArgIdx = Const.first;
1180     Function *OutlinedFunction = Group.OutlinedFunction;
1181     assert(OutlinedFunction && "Overall Function is not defined?");
1182     Constant *CST = Const.second;
1183     Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx);
1184     // Identify the argument it will be elevated to, and replace instances of
1185     // that constant in the function.
1186 
1187     // TODO: If in the future constants do not have one global value number,
1188     // i.e. a constant 1 could be mapped to several values, this check will
1189     // have to be more strict.  It cannot be using only replaceUsesWithIf.
1190 
1191     LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST
1192                       << " in function " << *OutlinedFunction << " with "
1193                       << *Arg << "\n");
1194     CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) {
1195       if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1196         return I->getFunction() == OutlinedFunction;
1197       return false;
1198     });
1199   }
1200 }
1201 
1202 /// It is possible that there is a basic block that already performs the same
1203 /// stores. This returns a duplicate block, if it exists
1204 ///
1205 /// \param OutputBBs [in] the blocks we are looking for a duplicate of.
1206 /// \param OutputStoreBBs [in] The existing output blocks.
1207 /// \returns an optional value with the number output block if there is a match.
1208 Optional<unsigned> findDuplicateOutputBlock(
1209     DenseMap<Value *, BasicBlock *> &OutputBBs,
1210     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1211 
1212   bool Mismatch = false;
1213   unsigned MatchingNum = 0;
1214   // We compare the new set output blocks to the other sets of output blocks.
1215   // If they are the same number, and have identical instructions, they are
1216   // considered to be the same.
1217   for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) {
1218     Mismatch = false;
1219     for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) {
1220       DenseMap<Value *, BasicBlock *>::iterator OutputBBIt =
1221           OutputBBs.find(VToB.first);
1222       if (OutputBBIt == OutputBBs.end()) {
1223         Mismatch = true;
1224         break;
1225       }
1226 
1227       BasicBlock *CompBB = VToB.second;
1228       BasicBlock *OutputBB = OutputBBIt->second;
1229       if (CompBB->size() - 1 != OutputBB->size()) {
1230         Mismatch = true;
1231         break;
1232       }
1233 
1234       BasicBlock::iterator NIt = OutputBB->begin();
1235       for (Instruction &I : *CompBB) {
1236         if (isa<BranchInst>(&I))
1237           continue;
1238 
1239         if (!I.isIdenticalTo(&(*NIt))) {
1240           Mismatch = true;
1241           break;
1242         }
1243 
1244         NIt++;
1245       }
1246     }
1247 
1248     if (!Mismatch)
1249       return MatchingNum;
1250 
1251     MatchingNum++;
1252   }
1253 
1254   return None;
1255 }
1256 
1257 /// Remove empty output blocks from the outlined region.
1258 ///
1259 /// \param BlocksToPrune - Mapping of return values output blocks for the \p
1260 /// Region.
1261 /// \param Region - The OutlinableRegion we are analyzing.
1262 static bool
1263 analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune,
1264                             OutlinableRegion &Region) {
1265   bool AllRemoved = true;
1266   Value *RetValueForBB;
1267   BasicBlock *NewBB;
1268   SmallVector<Value *, 4> ToRemove;
1269   // Iterate over the output blocks created in the outlined section.
1270   for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) {
1271     RetValueForBB = VtoBB.first;
1272     NewBB = VtoBB.second;
1273 
1274     // If there are no instructions, we remove it from the module, and also
1275     // mark the value for removal from the return value to output block mapping.
1276     if (NewBB->size() == 0) {
1277       NewBB->eraseFromParent();
1278       ToRemove.push_back(RetValueForBB);
1279       continue;
1280     }
1281 
1282     // Mark that we could not remove all the blocks since they were not all
1283     // empty.
1284     AllRemoved = false;
1285   }
1286 
1287   // Remove the return value from the mapping.
1288   for (Value *V : ToRemove)
1289     BlocksToPrune.erase(V);
1290 
1291   // Mark the region as having the no output scheme.
1292   if (AllRemoved)
1293     Region.OutputBlockNum = -1;
1294 
1295   return AllRemoved;
1296 }
1297 
1298 /// For the outlined section, move needed the StoreInsts for the output
1299 /// registers into their own block. Then, determine if there is a duplicate
1300 /// output block already created.
1301 ///
1302 /// \param [in] OG - The OutlinableGroup of regions to be outlined.
1303 /// \param [in] Region - The OutlinableRegion that is being analyzed.
1304 /// \param [in,out] OutputBBs - the blocks that stores for this region will be
1305 /// placed in.
1306 /// \param [in] EndBBs - the final blocks of the extracted function.
1307 /// \param [in] OutputMappings - OutputMappings the mapping of values that have
1308 /// been replaced by a new output value.
1309 /// \param [in,out] OutputStoreBBs - The existing output blocks.
1310 static void alignOutputBlockWithAggFunc(
1311     OutlinableGroup &OG, OutlinableRegion &Region,
1312     DenseMap<Value *, BasicBlock *> &OutputBBs,
1313     DenseMap<Value *, BasicBlock *> &EndBBs,
1314     const DenseMap<Value *, Value *> &OutputMappings,
1315     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1316   // If none of the output blocks have any instructions, this means that we do
1317   // not have to determine if it matches any of the other output schemes, and we
1318   // don't have to do anything else.
1319   if (analyzeAndPruneOutputBlocks(OutputBBs, Region))
1320     return;
1321 
1322   // Determine is there is a duplicate set of blocks.
1323   Optional<unsigned> MatchingBB =
1324       findDuplicateOutputBlock(OutputBBs, OutputStoreBBs);
1325 
1326   // If there is, we remove the new output blocks.  If it does not,
1327   // we add it to our list of sets of output blocks.
1328   if (MatchingBB.hasValue()) {
1329     LLVM_DEBUG(dbgs() << "Set output block for region in function"
1330                       << Region.ExtractedFunction << " to "
1331                       << MatchingBB.getValue());
1332 
1333     Region.OutputBlockNum = MatchingBB.getValue();
1334     for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)
1335       VtoBB.second->eraseFromParent();
1336     return;
1337   }
1338 
1339   Region.OutputBlockNum = OutputStoreBBs.size();
1340 
1341   Value *RetValueForBB;
1342   BasicBlock *NewBB;
1343   OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
1344   for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) {
1345     RetValueForBB = VtoBB.first;
1346     NewBB = VtoBB.second;
1347     DenseMap<Value *, BasicBlock *>::iterator VBBIt =
1348         EndBBs.find(RetValueForBB);
1349     LLVM_DEBUG(dbgs() << "Create output block for region in"
1350                       << Region.ExtractedFunction << " to "
1351                       << *NewBB);
1352     BranchInst::Create(VBBIt->second, NewBB);
1353     OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB));
1354   }
1355 }
1356 
1357 /// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys,
1358 /// before creating a basic block for each \p NewMap, and inserting into the new
1359 /// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>".
1360 ///
1361 /// \param OldMap [in] - The mapping to base the new mapping off of.
1362 /// \param NewMap [out] - The output mapping using the keys of \p OldMap.
1363 /// \param ParentFunc [in] - The function to put the new basic block in.
1364 /// \param BaseName [in] - The start of the BasicBlock names to be appended to
1365 /// by an index value.
1366 static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap,
1367                                        DenseMap<Value *, BasicBlock *> &NewMap,
1368                                        Function *ParentFunc, Twine BaseName) {
1369   unsigned Idx = 0;
1370   std::vector<Value *> SortedKeys;
1371 
1372   getSortedConstantKeys(SortedKeys, OldMap);
1373 
1374   for (Value *RetVal : SortedKeys) {
1375     BasicBlock *NewBB = BasicBlock::Create(
1376         ParentFunc->getContext(),
1377         Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)),
1378         ParentFunc);
1379     NewMap.insert(std::make_pair(RetVal, NewBB));
1380   }
1381 }
1382 
1383 /// Create the switch statement for outlined function to differentiate between
1384 /// all the output blocks.
1385 ///
1386 /// For the outlined section, determine if an outlined block already exists that
1387 /// matches the needed stores for the extracted section.
1388 /// \param [in] M - The module we are outlining from.
1389 /// \param [in] OG - The group of regions to be outlined.
1390 /// \param [in] EndBBs - The final blocks of the extracted function.
1391 /// \param [in,out] OutputStoreBBs - The existing output blocks.
1392 void createSwitchStatement(
1393     Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs,
1394     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1395   // We only need the switch statement if there is more than one store
1396   // combination.
1397   if (OG.OutputGVNCombinations.size() > 1) {
1398     Function *AggFunc = OG.OutlinedFunction;
1399     // Create a final block for each different return block.
1400     DenseMap<Value *, BasicBlock *> ReturnBBs;
1401     createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block");
1402 
1403     for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) {
1404       std::pair<Value *, BasicBlock *> &OutputBlock =
1405           *OG.EndBBs.find(RetBlockPair.first);
1406       BasicBlock *ReturnBlock = RetBlockPair.second;
1407       BasicBlock *EndBB = OutputBlock.second;
1408       Instruction *Term = EndBB->getTerminator();
1409       // Move the return value to the final block instead of the original exit
1410       // stub.
1411       Term->moveBefore(*ReturnBlock, ReturnBlock->end());
1412       // Put the switch statement in the old end basic block for the function
1413       // with a fall through to the new return block.
1414       LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for "
1415                         << OutputStoreBBs.size() << "\n");
1416       SwitchInst *SwitchI =
1417           SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1),
1418                              ReturnBlock, OutputStoreBBs.size(), EndBB);
1419 
1420       unsigned Idx = 0;
1421       for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) {
1422         DenseMap<Value *, BasicBlock *>::iterator OSBBIt =
1423             OutputStoreBB.find(OutputBlock.first);
1424 
1425         if (OSBBIt == OutputStoreBB.end())
1426           continue;
1427 
1428         BasicBlock *BB = OSBBIt->second;
1429         SwitchI->addCase(
1430             ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB);
1431         Term = BB->getTerminator();
1432         Term->setSuccessor(0, ReturnBlock);
1433         Idx++;
1434       }
1435     }
1436     return;
1437   }
1438 
1439   // If there needs to be stores, move them from the output blocks to their
1440   // corresponding ending block.
1441   if (OutputStoreBBs.size() == 1) {
1442     LLVM_DEBUG(dbgs() << "Move store instructions to the end block in "
1443                       << *OG.OutlinedFunction << "\n");
1444     DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0];
1445     for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) {
1446       DenseMap<Value *, BasicBlock *>::iterator EndBBIt =
1447           EndBBs.find(VBPair.first);
1448       assert(EndBBIt != EndBBs.end() && "Could not find end block");
1449       BasicBlock *EndBB = EndBBIt->second;
1450       BasicBlock *OutputBB = VBPair.second;
1451       Instruction *Term = OutputBB->getTerminator();
1452       Term->eraseFromParent();
1453       Term = EndBB->getTerminator();
1454       moveBBContents(*OutputBB, *EndBB);
1455       Term->moveBefore(*EndBB, EndBB->end());
1456       OutputBB->eraseFromParent();
1457     }
1458   }
1459 }
1460 
1461 /// Fill the new function that will serve as the replacement function for all of
1462 /// the extracted regions of a certain structure from the first region in the
1463 /// list of regions.  Replace this first region's extracted function with the
1464 /// new overall function.
1465 ///
1466 /// \param [in] M - The module we are outlining from.
1467 /// \param [in] CurrentGroup - The group of regions to be outlined.
1468 /// \param [in,out] OutputStoreBBs - The output blocks for each different
1469 /// set of stores needed for the different functions.
1470 /// \param [in,out] FuncsToRemove - Extracted functions to erase from module
1471 /// once outlining is complete.
1472 static void fillOverallFunction(
1473     Module &M, OutlinableGroup &CurrentGroup,
1474     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs,
1475     std::vector<Function *> &FuncsToRemove) {
1476   OutlinableRegion *CurrentOS = CurrentGroup.Regions[0];
1477 
1478   // Move first extracted function's instructions into new function.
1479   LLVM_DEBUG(dbgs() << "Move instructions from "
1480                     << *CurrentOS->ExtractedFunction << " to instruction "
1481                     << *CurrentGroup.OutlinedFunction << "\n");
1482   moveFunctionData(*CurrentOS->ExtractedFunction,
1483                    *CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs);
1484 
1485   // Transfer the attributes from the function to the new function.
1486   for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs())
1487     CurrentGroup.OutlinedFunction->addFnAttr(A);
1488 
1489   // Create a new set of output blocks for the first extracted function.
1490   DenseMap<Value *, BasicBlock *> NewBBs;
1491   createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs,
1492                              CurrentGroup.OutlinedFunction, "output_block_0");
1493   CurrentOS->OutputBlockNum = 0;
1494 
1495   replaceArgumentUses(*CurrentOS, NewBBs, true);
1496   replaceConstants(*CurrentOS);
1497 
1498   // We first identify if any output blocks are empty, if they are we remove
1499   // them. We then create a branch instruction to the basic block to the return
1500   // block for the function for each non empty output block.
1501   if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) {
1502     OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
1503     for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) {
1504       DenseMap<Value *, BasicBlock *>::iterator VBBIt =
1505           CurrentGroup.EndBBs.find(VToBB.first);
1506       BasicBlock *EndBB = VBBIt->second;
1507       BranchInst::Create(EndBB, VToBB.second);
1508       OutputStoreBBs.back().insert(VToBB);
1509     }
1510   }
1511 
1512   // Replace the call to the extracted function with the outlined function.
1513   CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
1514 
1515   // We only delete the extracted functions at the end since we may need to
1516   // reference instructions contained in them for mapping purposes.
1517   FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
1518 }
1519 
1520 void IROutliner::deduplicateExtractedSections(
1521     Module &M, OutlinableGroup &CurrentGroup,
1522     std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) {
1523   createFunction(M, CurrentGroup, OutlinedFunctionNum);
1524 
1525   std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs;
1526 
1527   OutlinableRegion *CurrentOS;
1528 
1529   fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove);
1530 
1531   std::vector<Value *> SortedKeys;
1532   for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) {
1533     CurrentOS = CurrentGroup.Regions[Idx];
1534     AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction,
1535                                                *CurrentOS->ExtractedFunction);
1536 
1537     // Create a set of BasicBlocks, one for each return block, to hold the
1538     // needed store instructions.
1539     DenseMap<Value *, BasicBlock *> NewBBs;
1540     createAndInsertBasicBlocks(
1541         CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction,
1542         "output_block_" + Twine(static_cast<unsigned>(Idx)));
1543 
1544     replaceArgumentUses(*CurrentOS, NewBBs);
1545     alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs,
1546                                 CurrentGroup.EndBBs, OutputMappings,
1547                                 OutputStoreBBs);
1548 
1549     CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
1550     FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
1551   }
1552 
1553   // Create a switch statement to handle the different output schemes.
1554   createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs);
1555 
1556   OutlinedFunctionNum++;
1557 }
1558 
1559 /// Checks that the next instruction in the InstructionDataList matches the
1560 /// next instruction in the module.  If they do not, there could be the
1561 /// possibility that extra code has been inserted, and we must ignore it.
1562 ///
1563 /// \param ID - The IRInstructionData to check the next instruction of.
1564 /// \returns true if the InstructionDataList and actual instruction match.
1565 static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) {
1566   // We check if there is a discrepancy between the InstructionDataList
1567   // and the actual next instruction in the module.  If there is, it means
1568   // that an extra instruction was added, likely by the CodeExtractor.
1569 
1570   // Since we do not have any similarity data about this particular
1571   // instruction, we cannot confidently outline it, and must discard this
1572   // candidate.
1573   IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator());
1574   Instruction *NextIDLInst = NextIDIt->Inst;
1575   Instruction *NextModuleInst = nullptr;
1576   if (!ID.Inst->isTerminator())
1577     NextModuleInst = ID.Inst->getNextNonDebugInstruction();
1578   else if (NextIDLInst != nullptr)
1579     NextModuleInst =
1580         &*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin();
1581 
1582   if (NextIDLInst && NextIDLInst != NextModuleInst)
1583     return false;
1584 
1585   return true;
1586 }
1587 
1588 bool IROutliner::isCompatibleWithAlreadyOutlinedCode(
1589     const OutlinableRegion &Region) {
1590   IRSimilarityCandidate *IRSC = Region.Candidate;
1591   unsigned StartIdx = IRSC->getStartIdx();
1592   unsigned EndIdx = IRSC->getEndIdx();
1593 
1594   // A check to make sure that we are not about to attempt to outline something
1595   // that has already been outlined.
1596   for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
1597     if (Outlined.contains(Idx))
1598       return false;
1599 
1600   // We check if the recorded instruction matches the actual next instruction,
1601   // if it does not, we fix it in the InstructionDataList.
1602   if (!Region.Candidate->backInstruction()->isTerminator()) {
1603     Instruction *NewEndInst =
1604         Region.Candidate->backInstruction()->getNextNonDebugInstruction();
1605     assert(NewEndInst && "Next instruction is a nullptr?");
1606     if (Region.Candidate->end()->Inst != NewEndInst) {
1607       IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
1608       IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate())
1609           IRInstructionData(*NewEndInst,
1610                             InstructionClassifier.visit(*NewEndInst), *IDL);
1611 
1612       // Insert the first IRInstructionData of the new region after the
1613       // last IRInstructionData of the IRSimilarityCandidate.
1614       IDL->insert(Region.Candidate->end(), *NewEndIRID);
1615     }
1616   }
1617 
1618   return none_of(*IRSC, [this](IRInstructionData &ID) {
1619     if (!nextIRInstructionDataMatchesNextInst(ID))
1620       return true;
1621 
1622     return !this->InstructionClassifier.visit(ID.Inst);
1623   });
1624 }
1625 
1626 void IROutliner::pruneIncompatibleRegions(
1627     std::vector<IRSimilarityCandidate> &CandidateVec,
1628     OutlinableGroup &CurrentGroup) {
1629   bool PreviouslyOutlined;
1630 
1631   // Sort from beginning to end, so the IRSimilarityCandidates are in order.
1632   stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS,
1633                                const IRSimilarityCandidate &RHS) {
1634     return LHS.getStartIdx() < RHS.getStartIdx();
1635   });
1636 
1637   IRSimilarityCandidate &FirstCandidate = CandidateVec[0];
1638   // Since outlining a call and a branch instruction will be the same as only
1639   // outlinining a call instruction, we ignore it as a space saving.
1640   if (FirstCandidate.getLength() == 2) {
1641     if (isa<CallInst>(FirstCandidate.front()->Inst) &&
1642         isa<BranchInst>(FirstCandidate.back()->Inst))
1643         return;
1644   }
1645 
1646   unsigned CurrentEndIdx = 0;
1647   for (IRSimilarityCandidate &IRSC : CandidateVec) {
1648     PreviouslyOutlined = false;
1649     unsigned StartIdx = IRSC.getStartIdx();
1650     unsigned EndIdx = IRSC.getEndIdx();
1651 
1652     for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
1653       if (Outlined.contains(Idx)) {
1654         PreviouslyOutlined = true;
1655         break;
1656       }
1657 
1658     if (PreviouslyOutlined)
1659       continue;
1660 
1661     // Check over the instructions, and if the basic block has its address
1662     // taken for use somewhere else, we do not outline that block.
1663     bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){
1664       return ID.Inst->getParent()->hasAddressTaken();
1665     });
1666 
1667     if (BBHasAddressTaken)
1668       continue;
1669 
1670     if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() &&
1671         !OutlineFromLinkODRs)
1672       continue;
1673 
1674     // Greedily prune out any regions that will overlap with already chosen
1675     // regions.
1676     if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx)
1677       continue;
1678 
1679     bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) {
1680       if (!nextIRInstructionDataMatchesNextInst(ID))
1681         return true;
1682 
1683       return !this->InstructionClassifier.visit(ID.Inst);
1684     });
1685 
1686     if (BadInst)
1687       continue;
1688 
1689     OutlinableRegion *OS = new (RegionAllocator.Allocate())
1690         OutlinableRegion(IRSC, CurrentGroup);
1691     CurrentGroup.Regions.push_back(OS);
1692 
1693     CurrentEndIdx = EndIdx;
1694   }
1695 }
1696 
1697 InstructionCost
1698 IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) {
1699   InstructionCost RegionBenefit = 0;
1700   for (OutlinableRegion *Region : CurrentGroup.Regions) {
1701     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
1702     // We add the number of instructions in the region to the benefit as an
1703     // estimate as to how much will be removed.
1704     RegionBenefit += Region->getBenefit(TTI);
1705     LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit
1706                       << " saved instructions to overfall benefit.\n");
1707   }
1708 
1709   return RegionBenefit;
1710 }
1711 
1712 InstructionCost
1713 IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) {
1714   InstructionCost OverallCost = 0;
1715   for (OutlinableRegion *Region : CurrentGroup.Regions) {
1716     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
1717 
1718     // Each output incurs a load after the call, so we add that to the cost.
1719     for (unsigned OutputGVN : Region->GVNStores) {
1720       Optional<Value *> OV = Region->Candidate->fromGVN(OutputGVN);
1721       assert(OV.hasValue() && "Could not find value for GVN?");
1722       Value *V = OV.getValue();
1723       InstructionCost LoadCost =
1724           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
1725                               TargetTransformInfo::TCK_CodeSize);
1726 
1727       LLVM_DEBUG(dbgs() << "Adding: " << LoadCost
1728                         << " instructions to cost for output of type "
1729                         << *V->getType() << "\n");
1730       OverallCost += LoadCost;
1731     }
1732   }
1733 
1734   return OverallCost;
1735 }
1736 
1737 /// Find the extra instructions needed to handle any output values for the
1738 /// region.
1739 ///
1740 /// \param [in] M - The Module to outline from.
1741 /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze.
1742 /// \param [in] TTI - The TargetTransformInfo used to collect information for
1743 /// new instruction costs.
1744 /// \returns the additional cost to handle the outputs.
1745 static InstructionCost findCostForOutputBlocks(Module &M,
1746                                                OutlinableGroup &CurrentGroup,
1747                                                TargetTransformInfo &TTI) {
1748   InstructionCost OutputCost = 0;
1749   unsigned NumOutputBranches = 0;
1750 
1751   IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate;
1752   DenseSet<BasicBlock *> CandidateBlocks;
1753   Candidate.getBasicBlocks(CandidateBlocks);
1754 
1755   // Count the number of different output branches that point to blocks outside
1756   // of the region.
1757   DenseSet<BasicBlock *> FoundBlocks;
1758   for (IRInstructionData &ID : Candidate) {
1759     if (!isa<BranchInst>(ID.Inst))
1760       continue;
1761 
1762     for (Value *V : ID.OperVals) {
1763       BasicBlock *BB = static_cast<BasicBlock *>(V);
1764       DenseSet<BasicBlock *>::iterator CBIt = CandidateBlocks.find(BB);
1765       if (CBIt != CandidateBlocks.end() || FoundBlocks.contains(BB))
1766         continue;
1767       FoundBlocks.insert(BB);
1768       NumOutputBranches++;
1769     }
1770   }
1771 
1772   CurrentGroup.BranchesToOutside = NumOutputBranches;
1773 
1774   for (const ArrayRef<unsigned> &OutputUse :
1775        CurrentGroup.OutputGVNCombinations) {
1776     for (unsigned GVN : OutputUse) {
1777       Optional<Value *> OV = Candidate.fromGVN(GVN);
1778       assert(OV.hasValue() && "Could not find value for GVN?");
1779       Value *V = OV.getValue();
1780       InstructionCost StoreCost =
1781           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
1782                               TargetTransformInfo::TCK_CodeSize);
1783 
1784       // An instruction cost is added for each store set that needs to occur for
1785       // various output combinations inside the function, plus a branch to
1786       // return to the exit block.
1787       LLVM_DEBUG(dbgs() << "Adding: " << StoreCost
1788                         << " instructions to cost for output of type "
1789                         << *V->getType() << "\n");
1790       OutputCost += StoreCost * NumOutputBranches;
1791     }
1792 
1793     InstructionCost BranchCost =
1794         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
1795     LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for"
1796                       << " a branch instruction\n");
1797     OutputCost += BranchCost * NumOutputBranches;
1798   }
1799 
1800   // If there is more than one output scheme, we must have a comparison and
1801   // branch for each different item in the switch statement.
1802   if (CurrentGroup.OutputGVNCombinations.size() > 1) {
1803     InstructionCost ComparisonCost = TTI.getCmpSelInstrCost(
1804         Instruction::ICmp, Type::getInt32Ty(M.getContext()),
1805         Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE,
1806         TargetTransformInfo::TCK_CodeSize);
1807     InstructionCost BranchCost =
1808         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
1809 
1810     unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size();
1811     InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks;
1812 
1813     LLVM_DEBUG(dbgs() << "Adding: " << TotalCost
1814                       << " instructions for each switch case for each different"
1815                       << " output path in a function\n");
1816     OutputCost += TotalCost * NumOutputBranches;
1817   }
1818 
1819   return OutputCost;
1820 }
1821 
1822 void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) {
1823   InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup);
1824   CurrentGroup.Benefit += RegionBenefit;
1825   LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n");
1826 
1827   InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup);
1828   CurrentGroup.Cost += OutputReloadCost;
1829   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1830 
1831   InstructionCost AverageRegionBenefit =
1832       RegionBenefit / CurrentGroup.Regions.size();
1833   unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size();
1834   unsigned NumRegions = CurrentGroup.Regions.size();
1835   TargetTransformInfo &TTI =
1836       getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction());
1837 
1838   // We add one region to the cost once, to account for the instructions added
1839   // inside of the newly created function.
1840   LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit
1841                     << " instructions to cost for body of new function.\n");
1842   CurrentGroup.Cost += AverageRegionBenefit;
1843   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1844 
1845   // For each argument, we must add an instruction for loading the argument
1846   // out of the register and into a value inside of the newly outlined function.
1847   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
1848                     << " instructions to cost for each argument in the new"
1849                     << " function.\n");
1850   CurrentGroup.Cost +=
1851       OverallArgumentNum * TargetTransformInfo::TCC_Basic;
1852   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1853 
1854   // Each argument needs to either be loaded into a register or onto the stack.
1855   // Some arguments will only be loaded into the stack once the argument
1856   // registers are filled.
1857   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
1858                     << " instructions to cost for each argument in the new"
1859                     << " function " << NumRegions << " times for the "
1860                     << "needed argument handling at the call site.\n");
1861   CurrentGroup.Cost +=
1862       2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions;
1863   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1864 
1865   CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI);
1866   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
1867 }
1868 
1869 void IROutliner::updateOutputMapping(OutlinableRegion &Region,
1870                                      ArrayRef<Value *> Outputs,
1871                                      LoadInst *LI) {
1872   // For and load instructions following the call
1873   Value *Operand = LI->getPointerOperand();
1874   Optional<unsigned> OutputIdx = None;
1875   // Find if the operand it is an output register.
1876   for (unsigned ArgIdx = Region.NumExtractedInputs;
1877        ArgIdx < Region.Call->arg_size(); ArgIdx++) {
1878     if (Operand == Region.Call->getArgOperand(ArgIdx)) {
1879       OutputIdx = ArgIdx - Region.NumExtractedInputs;
1880       break;
1881     }
1882   }
1883 
1884   // If we found an output register, place a mapping of the new value
1885   // to the original in the mapping.
1886   if (!OutputIdx.hasValue())
1887     return;
1888 
1889   if (OutputMappings.find(Outputs[OutputIdx.getValue()]) ==
1890       OutputMappings.end()) {
1891     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "
1892                       << *Outputs[OutputIdx.getValue()] << "\n");
1893     OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.getValue()]));
1894   } else {
1895     Value *Orig = OutputMappings.find(Outputs[OutputIdx.getValue()])->second;
1896     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "
1897                       << *Outputs[OutputIdx.getValue()] << "\n");
1898     OutputMappings.insert(std::make_pair(LI, Orig));
1899   }
1900 }
1901 
1902 bool IROutliner::extractSection(OutlinableRegion &Region) {
1903   SetVector<Value *> ArgInputs, Outputs, SinkCands;
1904   assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!");
1905   BasicBlock *InitialStart = Region.StartBB;
1906   Function *OrigF = Region.StartBB->getParent();
1907   CodeExtractorAnalysisCache CEAC(*OrigF);
1908   Region.ExtractedFunction =
1909       Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs);
1910 
1911   // If the extraction was successful, find the BasicBlock, and reassign the
1912   // OutlinableRegion blocks
1913   if (!Region.ExtractedFunction) {
1914     LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB
1915                       << "\n");
1916     Region.reattachCandidate();
1917     return false;
1918   }
1919 
1920   // Get the block containing the called branch, and reassign the blocks as
1921   // necessary.  If the original block still exists, it is because we ended on
1922   // a branch instruction, and so we move the contents into the block before
1923   // and assign the previous block correctly.
1924   User *InstAsUser = Region.ExtractedFunction->user_back();
1925   BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent();
1926   Region.PrevBB = RewrittenBB->getSinglePredecessor();
1927   assert(Region.PrevBB && "PrevBB is nullptr?");
1928   if (Region.PrevBB == InitialStart) {
1929     BasicBlock *NewPrev = InitialStart->getSinglePredecessor();
1930     Instruction *BI = NewPrev->getTerminator();
1931     BI->eraseFromParent();
1932     moveBBContents(*InitialStart, *NewPrev);
1933     Region.PrevBB = NewPrev;
1934     InitialStart->eraseFromParent();
1935   }
1936 
1937   Region.StartBB = RewrittenBB;
1938   Region.EndBB = RewrittenBB;
1939 
1940   // The sequences of outlinable regions has now changed.  We must fix the
1941   // IRInstructionDataList for consistency.  Although they may not be illegal
1942   // instructions, they should not be compared with anything else as they
1943   // should not be outlined in this round.  So marking these as illegal is
1944   // allowed.
1945   IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
1946   Instruction *BeginRewritten = &*RewrittenBB->begin();
1947   Instruction *EndRewritten = &*RewrittenBB->begin();
1948   Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData(
1949       *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL);
1950   Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData(
1951       *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL);
1952 
1953   // Insert the first IRInstructionData of the new region in front of the
1954   // first IRInstructionData of the IRSimilarityCandidate.
1955   IDL->insert(Region.Candidate->begin(), *Region.NewFront);
1956   // Insert the first IRInstructionData of the new region after the
1957   // last IRInstructionData of the IRSimilarityCandidate.
1958   IDL->insert(Region.Candidate->end(), *Region.NewBack);
1959   // Remove the IRInstructionData from the IRSimilarityCandidate.
1960   IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end()));
1961 
1962   assert(RewrittenBB != nullptr &&
1963          "Could not find a predecessor after extraction!");
1964 
1965   // Iterate over the new set of instructions to find the new call
1966   // instruction.
1967   for (Instruction &I : *RewrittenBB)
1968     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
1969       if (Region.ExtractedFunction == CI->getCalledFunction())
1970         Region.Call = CI;
1971     } else if (LoadInst *LI = dyn_cast<LoadInst>(&I))
1972       updateOutputMapping(Region, Outputs.getArrayRef(), LI);
1973   Region.reattachCandidate();
1974   return true;
1975 }
1976 
1977 unsigned IROutliner::doOutline(Module &M) {
1978   // Find the possible similarity sections.
1979   InstructionClassifier.EnableBranches = !DisableBranches;
1980   IRSimilarityIdentifier &Identifier = getIRSI(M);
1981   SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity();
1982 
1983   // Sort them by size of extracted sections
1984   unsigned OutlinedFunctionNum = 0;
1985   // If we only have one SimilarityGroup in SimilarityCandidates, we do not have
1986   // to sort them by the potential number of instructions to be outlined
1987   if (SimilarityCandidates.size() > 1)
1988     llvm::stable_sort(SimilarityCandidates,
1989                       [](const std::vector<IRSimilarityCandidate> &LHS,
1990                          const std::vector<IRSimilarityCandidate> &RHS) {
1991                         return LHS[0].getLength() * LHS.size() >
1992                                RHS[0].getLength() * RHS.size();
1993                       });
1994   // Creating OutlinableGroups for each SimilarityCandidate to be used in
1995   // each of the following for loops to avoid making an allocator.
1996   std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size());
1997 
1998   DenseSet<unsigned> NotSame;
1999   std::vector<OutlinableGroup *> NegativeCostGroups;
2000   std::vector<OutlinableRegion *> OutlinedRegions;
2001   // Iterate over the possible sets of similarity.
2002   unsigned PotentialGroupIdx = 0;
2003   for (SimilarityGroup &CandidateVec : SimilarityCandidates) {
2004     OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++];
2005 
2006     // Remove entries that were previously outlined
2007     pruneIncompatibleRegions(CandidateVec, CurrentGroup);
2008 
2009     // We pruned the number of regions to 0 to 1, meaning that it's not worth
2010     // trying to outlined since there is no compatible similar instance of this
2011     // code.
2012     if (CurrentGroup.Regions.size() < 2)
2013       continue;
2014 
2015     // Determine if there are any values that are the same constant throughout
2016     // each section in the set.
2017     NotSame.clear();
2018     CurrentGroup.findSameConstants(NotSame);
2019 
2020     if (CurrentGroup.IgnoreGroup)
2021       continue;
2022 
2023     // Create a CodeExtractor for each outlinable region. Identify inputs and
2024     // outputs for each section using the code extractor and create the argument
2025     // types for the Aggregate Outlining Function.
2026     OutlinedRegions.clear();
2027     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2028       // Break the outlinable region out of its parent BasicBlock into its own
2029       // BasicBlocks (see function implementation).
2030       OS->splitCandidate();
2031 
2032       // There's a chance that when the region is split, extra instructions are
2033       // added to the region. This makes the region no longer viable
2034       // to be split, so we ignore it for outlining.
2035       if (!OS->CandidateSplit)
2036         continue;
2037 
2038       SmallVector<BasicBlock *> BE;
2039       DenseSet<BasicBlock *> BBSet;
2040       OS->Candidate->getBasicBlocks(BBSet, BE);
2041       OS->CE = new (ExtractorAllocator.Allocate())
2042           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
2043                         false, "outlined");
2044       findAddInputsOutputs(M, *OS, NotSame);
2045       if (!OS->IgnoreRegion)
2046         OutlinedRegions.push_back(OS);
2047 
2048       // We recombine the blocks together now that we have gathered all the
2049       // needed information.
2050       OS->reattachCandidate();
2051     }
2052 
2053     CurrentGroup.Regions = std::move(OutlinedRegions);
2054 
2055     if (CurrentGroup.Regions.empty())
2056       continue;
2057 
2058     CurrentGroup.collectGVNStoreSets(M);
2059 
2060     if (CostModel)
2061       findCostBenefit(M, CurrentGroup);
2062 
2063     // If we are adhering to the cost model, skip those groups where the cost
2064     // outweighs the benefits.
2065     if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) {
2066       OptimizationRemarkEmitter &ORE =
2067           getORE(*CurrentGroup.Regions[0]->Candidate->getFunction());
2068       ORE.emit([&]() {
2069         IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2070         OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize",
2071                                    C->frontInstruction());
2072         R << "did not outline "
2073           << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2074           << " regions due to estimated increase of "
2075           << ore::NV("InstructionIncrease",
2076                      CurrentGroup.Cost - CurrentGroup.Benefit)
2077           << " instructions at locations ";
2078         interleave(
2079             CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2080             [&R](OutlinableRegion *Region) {
2081               R << ore::NV(
2082                   "DebugLoc",
2083                   Region->Candidate->frontInstruction()->getDebugLoc());
2084             },
2085             [&R]() { R << " "; });
2086         return R;
2087       });
2088       continue;
2089     }
2090 
2091     NegativeCostGroups.push_back(&CurrentGroup);
2092   }
2093 
2094   ExtractorAllocator.DestroyAll();
2095 
2096   if (NegativeCostGroups.size() > 1)
2097     stable_sort(NegativeCostGroups,
2098                 [](const OutlinableGroup *LHS, const OutlinableGroup *RHS) {
2099                   return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost;
2100                 });
2101 
2102   std::vector<Function *> FuncsToRemove;
2103   for (OutlinableGroup *CG : NegativeCostGroups) {
2104     OutlinableGroup &CurrentGroup = *CG;
2105 
2106     OutlinedRegions.clear();
2107     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2108       // We check whether our region is compatible with what has already been
2109       // outlined, and whether we need to ignore this item.
2110       if (!isCompatibleWithAlreadyOutlinedCode(*Region))
2111         continue;
2112       OutlinedRegions.push_back(Region);
2113     }
2114 
2115     if (OutlinedRegions.size() < 2)
2116       continue;
2117 
2118     // Reestimate the cost and benefit of the OutlinableGroup. Continue only if
2119     // we are still outlining enough regions to make up for the added cost.
2120     CurrentGroup.Regions = std::move(OutlinedRegions);
2121     if (CostModel) {
2122       CurrentGroup.Benefit = 0;
2123       CurrentGroup.Cost = 0;
2124       findCostBenefit(M, CurrentGroup);
2125       if (CurrentGroup.Cost >= CurrentGroup.Benefit)
2126         continue;
2127     }
2128     OutlinedRegions.clear();
2129     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2130       Region->splitCandidate();
2131       if (!Region->CandidateSplit)
2132         continue;
2133       OutlinedRegions.push_back(Region);
2134     }
2135 
2136     CurrentGroup.Regions = std::move(OutlinedRegions);
2137     if (CurrentGroup.Regions.size() < 2) {
2138       for (OutlinableRegion *R : CurrentGroup.Regions)
2139         R->reattachCandidate();
2140       continue;
2141     }
2142 
2143     LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost
2144                       << " and benefit " << CurrentGroup.Benefit << "\n");
2145 
2146     // Create functions out of all the sections, and mark them as outlined.
2147     OutlinedRegions.clear();
2148     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2149       SmallVector<BasicBlock *> BE;
2150       DenseSet<BasicBlock *> BBSet;
2151       OS->Candidate->getBasicBlocks(BBSet, BE);
2152       OS->CE = new (ExtractorAllocator.Allocate())
2153           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
2154                         false, "outlined");
2155       bool FunctionOutlined = extractSection(*OS);
2156       if (FunctionOutlined) {
2157         unsigned StartIdx = OS->Candidate->getStartIdx();
2158         unsigned EndIdx = OS->Candidate->getEndIdx();
2159         for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2160           Outlined.insert(Idx);
2161 
2162         OutlinedRegions.push_back(OS);
2163       }
2164     }
2165 
2166     LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size()
2167                       << " with benefit " << CurrentGroup.Benefit
2168                       << " and cost " << CurrentGroup.Cost << "\n");
2169 
2170     CurrentGroup.Regions = std::move(OutlinedRegions);
2171 
2172     if (CurrentGroup.Regions.empty())
2173       continue;
2174 
2175     OptimizationRemarkEmitter &ORE =
2176         getORE(*CurrentGroup.Regions[0]->Call->getFunction());
2177     ORE.emit([&]() {
2178       IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2179       OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst);
2180       R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2181         << " regions with decrease of "
2182         << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost)
2183         << " instructions at locations ";
2184       interleave(
2185           CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2186           [&R](OutlinableRegion *Region) {
2187             R << ore::NV("DebugLoc",
2188                          Region->Candidate->frontInstruction()->getDebugLoc());
2189           },
2190           [&R]() { R << " "; });
2191       return R;
2192     });
2193 
2194     deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove,
2195                                  OutlinedFunctionNum);
2196   }
2197 
2198   for (Function *F : FuncsToRemove)
2199     F->eraseFromParent();
2200 
2201   return OutlinedFunctionNum;
2202 }
2203 
2204 bool IROutliner::run(Module &M) {
2205   CostModel = !NoCostModel;
2206   OutlineFromLinkODRs = EnableLinkOnceODRIROutlining;
2207 
2208   return doOutline(M) > 0;
2209 }
2210 
2211 // Pass Manager Boilerplate
2212 class IROutlinerLegacyPass : public ModulePass {
2213 public:
2214   static char ID;
2215   IROutlinerLegacyPass() : ModulePass(ID) {
2216     initializeIROutlinerLegacyPassPass(*PassRegistry::getPassRegistry());
2217   }
2218 
2219   void getAnalysisUsage(AnalysisUsage &AU) const override {
2220     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2221     AU.addRequired<TargetTransformInfoWrapperPass>();
2222     AU.addRequired<IRSimilarityIdentifierWrapperPass>();
2223   }
2224 
2225   bool runOnModule(Module &M) override;
2226 };
2227 
2228 bool IROutlinerLegacyPass::runOnModule(Module &M) {
2229   if (skipModule(M))
2230     return false;
2231 
2232   std::unique_ptr<OptimizationRemarkEmitter> ORE;
2233   auto GORE = [&ORE](Function &F) -> OptimizationRemarkEmitter & {
2234     ORE.reset(new OptimizationRemarkEmitter(&F));
2235     return *ORE.get();
2236   };
2237 
2238   auto GTTI = [this](Function &F) -> TargetTransformInfo & {
2239     return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2240   };
2241 
2242   auto GIRSI = [this](Module &) -> IRSimilarityIdentifier & {
2243     return this->getAnalysis<IRSimilarityIdentifierWrapperPass>().getIRSI();
2244   };
2245 
2246   return IROutliner(GTTI, GIRSI, GORE).run(M);
2247 }
2248 
2249 PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) {
2250   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2251 
2252   std::function<TargetTransformInfo &(Function &)> GTTI =
2253       [&FAM](Function &F) -> TargetTransformInfo & {
2254     return FAM.getResult<TargetIRAnalysis>(F);
2255   };
2256 
2257   std::function<IRSimilarityIdentifier &(Module &)> GIRSI =
2258       [&AM](Module &M) -> IRSimilarityIdentifier & {
2259     return AM.getResult<IRSimilarityAnalysis>(M);
2260   };
2261 
2262   std::unique_ptr<OptimizationRemarkEmitter> ORE;
2263   std::function<OptimizationRemarkEmitter &(Function &)> GORE =
2264       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
2265     ORE.reset(new OptimizationRemarkEmitter(&F));
2266     return *ORE.get();
2267   };
2268 
2269   if (IROutliner(GTTI, GIRSI, GORE).run(M))
2270     return PreservedAnalyses::none();
2271   return PreservedAnalyses::all();
2272 }
2273 
2274 char IROutlinerLegacyPass::ID = 0;
2275 INITIALIZE_PASS_BEGIN(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
2276                       false)
2277 INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass)
2278 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
2279 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2280 INITIALIZE_PASS_END(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
2281                     false)
2282 
2283 ModulePass *llvm::createIROutlinerPass() { return new IROutlinerLegacyPass(); }
2284