xref: /freebsd/contrib/llvm-project/llvm/lib/Transforms/IPO/IROutliner.cpp (revision 1165fc9a526630487a1feb63daef65c5aee1a583)
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 namespace llvm {
40 extern cl::opt<bool> DisableBranches;
41 
42 // A command flag to be used for debugging to indirect calls from similarity
43 // matching and outlining.
44 extern cl::opt<bool> DisableIndirectCalls;
45 
46 // A command flag to be used for debugging to exclude intrinsics from similarity
47 // matching and outlining.
48 extern cl::opt<bool> DisableIntrinsics;
49 
50 } // namespace llvm
51 
52 // Set to true if the user wants the ir outliner to run on linkonceodr linkage
53 // functions. This is false by default because the linker can dedupe linkonceodr
54 // functions. Since the outliner is confined to a single module (modulo LTO),
55 // this is off by default. It should, however, be the default behavior in
56 // LTO.
57 static cl::opt<bool> EnableLinkOnceODRIROutlining(
58     "enable-linkonceodr-ir-outlining", cl::Hidden,
59     cl::desc("Enable the IR outliner on linkonceodr functions"),
60     cl::init(false));
61 
62 // This is a debug option to test small pieces of code to ensure that outlining
63 // works correctly.
64 static cl::opt<bool> NoCostModel(
65     "ir-outlining-no-cost", cl::init(false), cl::ReallyHidden,
66     cl::desc("Debug option to outline greedily, without restriction that "
67              "calculated benefit outweighs cost"));
68 
69 /// The OutlinableGroup holds all the overarching information for outlining
70 /// a set of regions that are structurally similar to one another, such as the
71 /// types of the overall function, the output blocks, the sets of stores needed
72 /// and a list of the different regions. This information is used in the
73 /// deduplication of extracted regions with the same structure.
74 struct OutlinableGroup {
75   /// The sections that could be outlined
76   std::vector<OutlinableRegion *> Regions;
77 
78   /// The argument types for the function created as the overall function to
79   /// replace the extracted function for each region.
80   std::vector<Type *> ArgumentTypes;
81   /// The FunctionType for the overall function.
82   FunctionType *OutlinedFunctionType = nullptr;
83   /// The Function for the collective overall function.
84   Function *OutlinedFunction = nullptr;
85 
86   /// Flag for whether we should not consider this group of OutlinableRegions
87   /// for extraction.
88   bool IgnoreGroup = false;
89 
90   /// The return blocks for the overall function.
91   DenseMap<Value *, BasicBlock *> EndBBs;
92 
93   /// The PHIBlocks with their corresponding return block based on the return
94   /// value as the key.
95   DenseMap<Value *, BasicBlock *> PHIBlocks;
96 
97   /// A set containing the different GVN store sets needed. Each array contains
98   /// a sorted list of the different values that need to be stored into output
99   /// registers.
100   DenseSet<ArrayRef<unsigned>> OutputGVNCombinations;
101 
102   /// Flag for whether the \ref ArgumentTypes have been defined after the
103   /// extraction of the first region.
104   bool InputTypesSet = false;
105 
106   /// The number of input values in \ref ArgumentTypes.  Anything after this
107   /// index in ArgumentTypes is an output argument.
108   unsigned NumAggregateInputs = 0;
109 
110   /// The mapping of the canonical numbering of the values in outlined sections
111   /// to specific arguments.
112   DenseMap<unsigned, unsigned> CanonicalNumberToAggArg;
113 
114   /// The number of branches in the region target a basic block that is outside
115   /// of the region.
116   unsigned BranchesToOutside = 0;
117 
118   /// Tracker counting backwards from the highest unsigned value possible to
119   /// avoid conflicting with the GVNs of assigned values.  We start at -3 since
120   /// -2 and -1 are assigned by the DenseMap.
121   unsigned PHINodeGVNTracker = -3;
122 
123   DenseMap<unsigned,
124            std::pair<std::pair<unsigned, unsigned>, SmallVector<unsigned, 2>>>
125       PHINodeGVNToGVNs;
126   DenseMap<hash_code, unsigned> GVNsToPHINodeGVN;
127 
128   /// The number of instructions that will be outlined by extracting \ref
129   /// Regions.
130   InstructionCost Benefit = 0;
131   /// The number of added instructions needed for the outlining of the \ref
132   /// Regions.
133   InstructionCost Cost = 0;
134 
135   /// The argument that needs to be marked with the swifterr attribute.  If not
136   /// needed, there is no value.
137   Optional<unsigned> SwiftErrorArgument;
138 
139   /// For the \ref Regions, we look at every Value.  If it is a constant,
140   /// we check whether it is the same in Region.
141   ///
142   /// \param [in,out] NotSame contains the global value numbers where the
143   /// constant is not always the same, and must be passed in as an argument.
144   void findSameConstants(DenseSet<unsigned> &NotSame);
145 
146   /// For the regions, look at each set of GVN stores needed and account for
147   /// each combination.  Add an argument to the argument types if there is
148   /// more than one combination.
149   ///
150   /// \param [in] M - The module we are outlining from.
151   void collectGVNStoreSets(Module &M);
152 };
153 
154 /// Move the contents of \p SourceBB to before the last instruction of \p
155 /// TargetBB.
156 /// \param SourceBB - the BasicBlock to pull Instructions from.
157 /// \param TargetBB - the BasicBlock to put Instruction into.
158 static void moveBBContents(BasicBlock &SourceBB, BasicBlock &TargetBB) {
159   for (Instruction &I : llvm::make_early_inc_range(SourceBB))
160     I.moveBefore(TargetBB, TargetBB.end());
161 }
162 
163 /// A function to sort the keys of \p Map, which must be a mapping of constant
164 /// values to basic blocks and return it in \p SortedKeys
165 ///
166 /// \param SortedKeys - The vector the keys will be return in and sorted.
167 /// \param Map - The DenseMap containing keys to sort.
168 static void getSortedConstantKeys(std::vector<Value *> &SortedKeys,
169                                   DenseMap<Value *, BasicBlock *> &Map) {
170   for (auto &VtoBB : Map)
171     SortedKeys.push_back(VtoBB.first);
172 
173   stable_sort(SortedKeys, [](const Value *LHS, const Value *RHS) {
174     const ConstantInt *LHSC = dyn_cast<ConstantInt>(LHS);
175     const ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS);
176     assert(RHSC && "Not a constant integer in return value?");
177     assert(LHSC && "Not a constant integer in return value?");
178 
179     return LHSC->getLimitedValue() < RHSC->getLimitedValue();
180   });
181 }
182 
183 Value *OutlinableRegion::findCorrespondingValueIn(const OutlinableRegion &Other,
184                                                   Value *V) {
185   Optional<unsigned> GVN = Candidate->getGVN(V);
186   assert(GVN.hasValue() && "No GVN for incoming value");
187   Optional<unsigned> CanonNum = Candidate->getCanonicalNum(*GVN);
188   Optional<unsigned> FirstGVN = Other.Candidate->fromCanonicalNum(*CanonNum);
189   Optional<Value *> FoundValueOpt = Other.Candidate->fromGVN(*FirstGVN);
190   return FoundValueOpt.getValueOr(nullptr);
191 }
192 
193 /// Rewrite the BranchInsts in the incoming blocks to \p PHIBlock that are found
194 /// in \p Included to branch to BasicBlock \p Replace if they currently branch
195 /// to the BasicBlock \p Find.  This is used to fix up the incoming basic blocks
196 /// when PHINodes are included in outlined regions.
197 ///
198 /// \param PHIBlock - The BasicBlock containing the PHINodes that need to be
199 /// checked.
200 /// \param Find - The successor block to be replaced.
201 /// \param Replace - The new succesor block to branch to.
202 /// \param Included - The set of blocks about to be outlined.
203 static void replaceTargetsFromPHINode(BasicBlock *PHIBlock, BasicBlock *Find,
204                                       BasicBlock *Replace,
205                                       DenseSet<BasicBlock *> &Included) {
206   for (PHINode &PN : PHIBlock->phis()) {
207     for (unsigned Idx = 0, PNEnd = PN.getNumIncomingValues(); Idx != PNEnd;
208          ++Idx) {
209       // Check if the incoming block is included in the set of blocks being
210       // outlined.
211       BasicBlock *Incoming = PN.getIncomingBlock(Idx);
212       if (!Included.contains(Incoming))
213         continue;
214 
215       BranchInst *BI = dyn_cast<BranchInst>(Incoming->getTerminator());
216       assert(BI && "Not a branch instruction?");
217       // Look over the branching instructions into this block to see if we
218       // used to branch to Find in this outlined block.
219       for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ != End;
220            Succ++) {
221         // If we have found the block to replace, we do so here.
222         if (BI->getSuccessor(Succ) != Find)
223           continue;
224         BI->setSuccessor(Succ, Replace);
225       }
226     }
227   }
228 }
229 
230 
231 void OutlinableRegion::splitCandidate() {
232   assert(!CandidateSplit && "Candidate already split!");
233 
234   Instruction *BackInst = Candidate->backInstruction();
235 
236   Instruction *EndInst = nullptr;
237   // Check whether the last instruction is a terminator, if it is, we do
238   // not split on the following instruction. We leave the block as it is.  We
239   // also check that this is not the last instruction in the Module, otherwise
240   // the check for whether the current following instruction matches the
241   // previously recorded instruction will be incorrect.
242   if (!BackInst->isTerminator() ||
243       BackInst->getParent() != &BackInst->getFunction()->back()) {
244     EndInst = Candidate->end()->Inst;
245     assert(EndInst && "Expected an end instruction?");
246   }
247 
248   // We check if the current instruction following the last instruction in the
249   // region is the same as the recorded instruction following the last
250   // instruction. If they do not match, there could be problems in rewriting
251   // the program after outlining, so we ignore it.
252   if (!BackInst->isTerminator() &&
253       EndInst != BackInst->getNextNonDebugInstruction())
254     return;
255 
256   Instruction *StartInst = (*Candidate->begin()).Inst;
257   assert(StartInst && "Expected a start instruction?");
258   StartBB = StartInst->getParent();
259   PrevBB = StartBB;
260 
261   DenseSet<BasicBlock *> BBSet;
262   Candidate->getBasicBlocks(BBSet);
263 
264   // We iterate over the instructions in the region, if we find a PHINode, we
265   // check if there are predecessors outside of the region, if there are,
266   // we ignore this region since we are unable to handle the severing of the
267   // phi node right now.
268   BasicBlock::iterator It = StartInst->getIterator();
269   while (PHINode *PN = dyn_cast<PHINode>(&*It)) {
270     unsigned NumPredsOutsideRegion = 0;
271     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
272       if (!BBSet.contains(PN->getIncomingBlock(i)))
273         ++NumPredsOutsideRegion;
274 
275     if (NumPredsOutsideRegion > 1)
276       return;
277 
278     It++;
279   }
280 
281   // If the region starts with a PHINode, but is not the initial instruction of
282   // the BasicBlock, we ignore this region for now.
283   if (isa<PHINode>(StartInst) && StartInst != &*StartBB->begin())
284     return;
285 
286   // If the region ends with a PHINode, but does not contain all of the phi node
287   // instructions of the region, we ignore it for now.
288   if (isa<PHINode>(BackInst)) {
289     EndBB = BackInst->getParent();
290     if (BackInst != &*std::prev(EndBB->getFirstInsertionPt()))
291       return;
292   }
293 
294   // The basic block gets split like so:
295   // block:                 block:
296   //   inst1                  inst1
297   //   inst2                  inst2
298   //   region1               br block_to_outline
299   //   region2              block_to_outline:
300   //   region3          ->    region1
301   //   region4                region2
302   //   inst3                  region3
303   //   inst4                  region4
304   //                          br block_after_outline
305   //                        block_after_outline:
306   //                          inst3
307   //                          inst4
308 
309   std::string OriginalName = PrevBB->getName().str();
310 
311   StartBB = PrevBB->splitBasicBlock(StartInst, OriginalName + "_to_outline");
312   PrevBB->replaceSuccessorsPhiUsesWith(PrevBB, StartBB);
313 
314   CandidateSplit = true;
315   if (!BackInst->isTerminator()) {
316     EndBB = EndInst->getParent();
317     FollowBB = EndBB->splitBasicBlock(EndInst, OriginalName + "_after_outline");
318     EndBB->replaceSuccessorsPhiUsesWith(EndBB, FollowBB);
319     FollowBB->replaceSuccessorsPhiUsesWith(PrevBB, FollowBB);
320   } else {
321     EndBB = BackInst->getParent();
322     EndsInBranch = true;
323     FollowBB = nullptr;
324   }
325 
326   // Refind the basic block set.
327   BBSet.clear();
328   Candidate->getBasicBlocks(BBSet);
329   // For the phi nodes in the new starting basic block of the region, we
330   // reassign the targets of the basic blocks branching instructions.
331   replaceTargetsFromPHINode(StartBB, PrevBB, StartBB, BBSet);
332   if (FollowBB)
333     replaceTargetsFromPHINode(FollowBB, EndBB, FollowBB, BBSet);
334 }
335 
336 void OutlinableRegion::reattachCandidate() {
337   assert(CandidateSplit && "Candidate is not split!");
338 
339   // The basic block gets reattached like so:
340   // block:                        block:
341   //   inst1                         inst1
342   //   inst2                         inst2
343   //   br block_to_outline           region1
344   // block_to_outline:        ->     region2
345   //   region1                       region3
346   //   region2                       region4
347   //   region3                       inst3
348   //   region4                       inst4
349   //   br block_after_outline
350   // block_after_outline:
351   //   inst3
352   //   inst4
353   assert(StartBB != nullptr && "StartBB for Candidate is not defined!");
354 
355   assert(PrevBB->getTerminator() && "Terminator removed from PrevBB!");
356   PrevBB->getTerminator()->eraseFromParent();
357 
358   // If we reattaching after outlining, we iterate over the phi nodes to
359   // the initial block, and reassign the branch instructions of the incoming
360   // blocks to the block we are remerging into.
361   if (!ExtractedFunction) {
362     DenseSet<BasicBlock *> BBSet;
363     Candidate->getBasicBlocks(BBSet);
364 
365     replaceTargetsFromPHINode(StartBB, StartBB, PrevBB, BBSet);
366     if (!EndsInBranch)
367       replaceTargetsFromPHINode(FollowBB, FollowBB, EndBB, BBSet);
368   }
369 
370   moveBBContents(*StartBB, *PrevBB);
371 
372   BasicBlock *PlacementBB = PrevBB;
373   if (StartBB != EndBB)
374     PlacementBB = EndBB;
375   if (!EndsInBranch && PlacementBB->getUniqueSuccessor() != nullptr) {
376     assert(FollowBB != nullptr && "FollowBB for Candidate is not defined!");
377     assert(PlacementBB->getTerminator() && "Terminator removed from EndBB!");
378     PlacementBB->getTerminator()->eraseFromParent();
379     moveBBContents(*FollowBB, *PlacementBB);
380     PlacementBB->replaceSuccessorsPhiUsesWith(FollowBB, PlacementBB);
381     FollowBB->eraseFromParent();
382   }
383 
384   PrevBB->replaceSuccessorsPhiUsesWith(StartBB, PrevBB);
385   StartBB->eraseFromParent();
386 
387   // Make sure to save changes back to the StartBB.
388   StartBB = PrevBB;
389   EndBB = nullptr;
390   PrevBB = nullptr;
391   FollowBB = nullptr;
392 
393   CandidateSplit = false;
394 }
395 
396 /// Find whether \p V matches the Constants previously found for the \p GVN.
397 ///
398 /// \param V - The value to check for consistency.
399 /// \param GVN - The global value number assigned to \p V.
400 /// \param GVNToConstant - The mapping of global value number to Constants.
401 /// \returns true if the Value matches the Constant mapped to by V and false if
402 /// it \p V is a Constant but does not match.
403 /// \returns None if \p V is not a Constant.
404 static Optional<bool>
405 constantMatches(Value *V, unsigned GVN,
406                 DenseMap<unsigned, Constant *> &GVNToConstant) {
407   // See if we have a constants
408   Constant *CST = dyn_cast<Constant>(V);
409   if (!CST)
410     return None;
411 
412   // Holds a mapping from a global value number to a Constant.
413   DenseMap<unsigned, Constant *>::iterator GVNToConstantIt;
414   bool Inserted;
415 
416 
417   // If we have a constant, try to make a new entry in the GVNToConstant.
418   std::tie(GVNToConstantIt, Inserted) =
419       GVNToConstant.insert(std::make_pair(GVN, CST));
420   // If it was found and is not equal, it is not the same. We do not
421   // handle this case yet, and exit early.
422   if (Inserted || (GVNToConstantIt->second == CST))
423     return true;
424 
425   return false;
426 }
427 
428 InstructionCost OutlinableRegion::getBenefit(TargetTransformInfo &TTI) {
429   InstructionCost Benefit = 0;
430 
431   // Estimate the benefit of outlining a specific sections of the program.  We
432   // delegate mostly this task to the TargetTransformInfo so that if the target
433   // has specific changes, we can have a more accurate estimate.
434 
435   // However, getInstructionCost delegates the code size calculation for
436   // arithmetic instructions to getArithmeticInstrCost in
437   // include/Analysis/TargetTransformImpl.h, where it always estimates that the
438   // code size for a division and remainder instruction to be equal to 4, and
439   // everything else to 1.  This is not an accurate representation of the
440   // division instruction for targets that have a native division instruction.
441   // To be overly conservative, we only add 1 to the number of instructions for
442   // each division instruction.
443   for (IRInstructionData &ID : *Candidate) {
444     Instruction *I = ID.Inst;
445     switch (I->getOpcode()) {
446     case Instruction::FDiv:
447     case Instruction::FRem:
448     case Instruction::SDiv:
449     case Instruction::SRem:
450     case Instruction::UDiv:
451     case Instruction::URem:
452       Benefit += 1;
453       break;
454     default:
455       Benefit += TTI.getInstructionCost(I, TargetTransformInfo::TCK_CodeSize);
456       break;
457     }
458   }
459 
460   return Benefit;
461 }
462 
463 /// Check the \p OutputMappings structure for value \p Input, if it exists
464 /// it has been used as an output for outlining, and has been renamed, and we
465 /// return the new value, otherwise, we return the same value.
466 ///
467 /// \param OutputMappings [in] - The mapping of values to their renamed value
468 /// after being used as an output for an outlined region.
469 /// \param Input [in] - The value to find the remapped value of, if it exists.
470 /// \return The remapped value if it has been renamed, and the same value if has
471 /// not.
472 static Value *findOutputMapping(const DenseMap<Value *, Value *> OutputMappings,
473                                 Value *Input) {
474   DenseMap<Value *, Value *>::const_iterator OutputMapping =
475       OutputMappings.find(Input);
476   if (OutputMapping != OutputMappings.end())
477     return OutputMapping->second;
478   return Input;
479 }
480 
481 /// Find whether \p Region matches the global value numbering to Constant
482 /// mapping found so far.
483 ///
484 /// \param Region - The OutlinableRegion we are checking for constants
485 /// \param GVNToConstant - The mapping of global value number to Constants.
486 /// \param NotSame - The set of global value numbers that do not have the same
487 /// constant in each region.
488 /// \returns true if all Constants are the same in every use of a Constant in \p
489 /// Region and false if not
490 static bool
491 collectRegionsConstants(OutlinableRegion &Region,
492                         DenseMap<unsigned, Constant *> &GVNToConstant,
493                         DenseSet<unsigned> &NotSame) {
494   bool ConstantsTheSame = true;
495 
496   IRSimilarityCandidate &C = *Region.Candidate;
497   for (IRInstructionData &ID : C) {
498 
499     // Iterate over the operands in an instruction. If the global value number,
500     // assigned by the IRSimilarityCandidate, has been seen before, we check if
501     // the the number has been found to be not the same value in each instance.
502     for (Value *V : ID.OperVals) {
503       Optional<unsigned> GVNOpt = C.getGVN(V);
504       assert(GVNOpt.hasValue() && "Expected a GVN for operand?");
505       unsigned GVN = GVNOpt.getValue();
506 
507       // Check if this global value has been found to not be the same already.
508       if (NotSame.contains(GVN)) {
509         if (isa<Constant>(V))
510           ConstantsTheSame = false;
511         continue;
512       }
513 
514       // If it has been the same so far, we check the value for if the
515       // associated Constant value match the previous instances of the same
516       // global value number.  If the global value does not map to a Constant,
517       // it is considered to not be the same value.
518       Optional<bool> ConstantMatches = constantMatches(V, GVN, GVNToConstant);
519       if (ConstantMatches.hasValue()) {
520         if (ConstantMatches.getValue())
521           continue;
522         else
523           ConstantsTheSame = false;
524       }
525 
526       // While this value is a register, it might not have been previously,
527       // make sure we don't already have a constant mapped to this global value
528       // number.
529       if (GVNToConstant.find(GVN) != GVNToConstant.end())
530         ConstantsTheSame = false;
531 
532       NotSame.insert(GVN);
533     }
534   }
535 
536   return ConstantsTheSame;
537 }
538 
539 void OutlinableGroup::findSameConstants(DenseSet<unsigned> &NotSame) {
540   DenseMap<unsigned, Constant *> GVNToConstant;
541 
542   for (OutlinableRegion *Region : Regions)
543     collectRegionsConstants(*Region, GVNToConstant, NotSame);
544 }
545 
546 void OutlinableGroup::collectGVNStoreSets(Module &M) {
547   for (OutlinableRegion *OS : Regions)
548     OutputGVNCombinations.insert(OS->GVNStores);
549 
550   // We are adding an extracted argument to decide between which output path
551   // to use in the basic block.  It is used in a switch statement and only
552   // needs to be an integer.
553   if (OutputGVNCombinations.size() > 1)
554     ArgumentTypes.push_back(Type::getInt32Ty(M.getContext()));
555 }
556 
557 /// Get the subprogram if it exists for one of the outlined regions.
558 ///
559 /// \param [in] Group - The set of regions to find a subprogram for.
560 /// \returns the subprogram if it exists, or nullptr.
561 static DISubprogram *getSubprogramOrNull(OutlinableGroup &Group) {
562   for (OutlinableRegion *OS : Group.Regions)
563     if (Function *F = OS->Call->getFunction())
564       if (DISubprogram *SP = F->getSubprogram())
565         return SP;
566 
567   return nullptr;
568 }
569 
570 Function *IROutliner::createFunction(Module &M, OutlinableGroup &Group,
571                                      unsigned FunctionNameSuffix) {
572   assert(!Group.OutlinedFunction && "Function is already defined!");
573 
574   Type *RetTy = Type::getVoidTy(M.getContext());
575   // All extracted functions _should_ have the same return type at this point
576   // since the similarity identifier ensures that all branches outside of the
577   // region occur in the same place.
578 
579   // NOTE: Should we ever move to the model that uses a switch at every point
580   // needed, meaning that we could branch within the region or out, it is
581   // possible that we will need to switch to using the most general case all of
582   // the time.
583   for (OutlinableRegion *R : Group.Regions) {
584     Type *ExtractedFuncType = R->ExtractedFunction->getReturnType();
585     if ((RetTy->isVoidTy() && !ExtractedFuncType->isVoidTy()) ||
586         (RetTy->isIntegerTy(1) && ExtractedFuncType->isIntegerTy(16)))
587       RetTy = ExtractedFuncType;
588   }
589 
590   Group.OutlinedFunctionType = FunctionType::get(
591       RetTy, Group.ArgumentTypes, false);
592 
593   // These functions will only be called from within the same module, so
594   // we can set an internal linkage.
595   Group.OutlinedFunction = Function::Create(
596       Group.OutlinedFunctionType, GlobalValue::InternalLinkage,
597       "outlined_ir_func_" + std::to_string(FunctionNameSuffix), M);
598 
599   // Transfer the swifterr attribute to the correct function parameter.
600   if (Group.SwiftErrorArgument.hasValue())
601     Group.OutlinedFunction->addParamAttr(Group.SwiftErrorArgument.getValue(),
602                                          Attribute::SwiftError);
603 
604   Group.OutlinedFunction->addFnAttr(Attribute::OptimizeForSize);
605   Group.OutlinedFunction->addFnAttr(Attribute::MinSize);
606 
607   // If there's a DISubprogram associated with this outlined function, then
608   // emit debug info for the outlined function.
609   if (DISubprogram *SP = getSubprogramOrNull(Group)) {
610     Function *F = Group.OutlinedFunction;
611     // We have a DISubprogram. Get its DICompileUnit.
612     DICompileUnit *CU = SP->getUnit();
613     DIBuilder DB(M, true, CU);
614     DIFile *Unit = SP->getFile();
615     Mangler Mg;
616     // Get the mangled name of the function for the linkage name.
617     std::string Dummy;
618     llvm::raw_string_ostream MangledNameStream(Dummy);
619     Mg.getNameWithPrefix(MangledNameStream, F, false);
620 
621     DISubprogram *OutlinedSP = DB.createFunction(
622         Unit /* Context */, F->getName(), MangledNameStream.str(),
623         Unit /* File */,
624         0 /* Line 0 is reserved for compiler-generated code. */,
625         DB.createSubroutineType(DB.getOrCreateTypeArray(None)), /* void type */
626         0, /* Line 0 is reserved for compiler-generated code. */
627         DINode::DIFlags::FlagArtificial /* Compiler-generated code. */,
628         /* Outlined code is optimized code by definition. */
629         DISubprogram::SPFlagDefinition | DISubprogram::SPFlagOptimized);
630 
631     // Don't add any new variables to the subprogram.
632     DB.finalizeSubprogram(OutlinedSP);
633 
634     // Attach subprogram to the function.
635     F->setSubprogram(OutlinedSP);
636     // We're done with the DIBuilder.
637     DB.finalize();
638   }
639 
640   return Group.OutlinedFunction;
641 }
642 
643 /// Move each BasicBlock in \p Old to \p New.
644 ///
645 /// \param [in] Old - The function to move the basic blocks from.
646 /// \param [in] New - The function to move the basic blocks to.
647 /// \param [out] NewEnds - The return blocks of the new overall function.
648 static void moveFunctionData(Function &Old, Function &New,
649                              DenseMap<Value *, BasicBlock *> &NewEnds) {
650   for (BasicBlock &CurrBB : llvm::make_early_inc_range(Old)) {
651     CurrBB.removeFromParent();
652     CurrBB.insertInto(&New);
653     Instruction *I = CurrBB.getTerminator();
654 
655     // For each block we find a return instruction is, it is a potential exit
656     // path for the function.  We keep track of each block based on the return
657     // value here.
658     if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
659       NewEnds.insert(std::make_pair(RI->getReturnValue(), &CurrBB));
660 
661     std::vector<Instruction *> DebugInsts;
662 
663     for (Instruction &Val : CurrBB) {
664       // We must handle the scoping of called functions differently than
665       // other outlined instructions.
666       if (!isa<CallInst>(&Val)) {
667         // Remove the debug information for outlined functions.
668         Val.setDebugLoc(DebugLoc());
669         continue;
670       }
671 
672       // From this point we are only handling call instructions.
673       CallInst *CI = cast<CallInst>(&Val);
674 
675       // We add any debug statements here, to be removed after.  Since the
676       // instructions originate from many different locations in the program,
677       // it will cause incorrect reporting from a debugger if we keep the
678       // same debug instructions.
679       if (isa<DbgInfoIntrinsic>(CI)) {
680         DebugInsts.push_back(&Val);
681         continue;
682       }
683 
684       // Edit the scope of called functions inside of outlined functions.
685       if (DISubprogram *SP = New.getSubprogram()) {
686         DILocation *DI = DILocation::get(New.getContext(), 0, 0, SP);
687         Val.setDebugLoc(DI);
688       }
689     }
690 
691     for (Instruction *I : DebugInsts)
692       I->eraseFromParent();
693   }
694 
695   assert(NewEnds.size() > 0 && "No return instruction for new function?");
696 }
697 
698 /// Find the the constants that will need to be lifted into arguments
699 /// as they are not the same in each instance of the region.
700 ///
701 /// \param [in] C - The IRSimilarityCandidate containing the region we are
702 /// analyzing.
703 /// \param [in] NotSame - The set of global value numbers that do not have a
704 /// single Constant across all OutlinableRegions similar to \p C.
705 /// \param [out] Inputs - The list containing the global value numbers of the
706 /// arguments needed for the region of code.
707 static void findConstants(IRSimilarityCandidate &C, DenseSet<unsigned> &NotSame,
708                           std::vector<unsigned> &Inputs) {
709   DenseSet<unsigned> Seen;
710   // Iterate over the instructions, and find what constants will need to be
711   // extracted into arguments.
712   for (IRInstructionDataList::iterator IDIt = C.begin(), EndIDIt = C.end();
713        IDIt != EndIDIt; IDIt++) {
714     for (Value *V : (*IDIt).OperVals) {
715       // Since these are stored before any outlining, they will be in the
716       // global value numbering.
717       unsigned GVN = C.getGVN(V).getValue();
718       if (isa<Constant>(V))
719         if (NotSame.contains(GVN) && !Seen.contains(GVN)) {
720           Inputs.push_back(GVN);
721           Seen.insert(GVN);
722         }
723     }
724   }
725 }
726 
727 /// Find the GVN for the inputs that have been found by the CodeExtractor.
728 ///
729 /// \param [in] C - The IRSimilarityCandidate containing the region we are
730 /// analyzing.
731 /// \param [in] CurrentInputs - The set of inputs found by the
732 /// CodeExtractor.
733 /// \param [in] OutputMappings - The mapping of values that have been replaced
734 /// by a new output value.
735 /// \param [out] EndInputNumbers - The global value numbers for the extracted
736 /// arguments.
737 static void mapInputsToGVNs(IRSimilarityCandidate &C,
738                             SetVector<Value *> &CurrentInputs,
739                             const DenseMap<Value *, Value *> &OutputMappings,
740                             std::vector<unsigned> &EndInputNumbers) {
741   // Get the Global Value Number for each input.  We check if the Value has been
742   // replaced by a different value at output, and use the original value before
743   // replacement.
744   for (Value *Input : CurrentInputs) {
745     assert(Input && "Have a nullptr as an input");
746     if (OutputMappings.find(Input) != OutputMappings.end())
747       Input = OutputMappings.find(Input)->second;
748     assert(C.getGVN(Input).hasValue() &&
749            "Could not find a numbering for the given input");
750     EndInputNumbers.push_back(C.getGVN(Input).getValue());
751   }
752 }
753 
754 /// Find the original value for the \p ArgInput values if any one of them was
755 /// replaced during a previous extraction.
756 ///
757 /// \param [in] ArgInputs - The inputs to be extracted by the code extractor.
758 /// \param [in] OutputMappings - The mapping of values that have been replaced
759 /// by a new output value.
760 /// \param [out] RemappedArgInputs - The remapped values according to
761 /// \p OutputMappings that will be extracted.
762 static void
763 remapExtractedInputs(const ArrayRef<Value *> ArgInputs,
764                      const DenseMap<Value *, Value *> &OutputMappings,
765                      SetVector<Value *> &RemappedArgInputs) {
766   // Get the global value number for each input that will be extracted as an
767   // argument by the code extractor, remapping if needed for reloaded values.
768   for (Value *Input : ArgInputs) {
769     if (OutputMappings.find(Input) != OutputMappings.end())
770       Input = OutputMappings.find(Input)->second;
771     RemappedArgInputs.insert(Input);
772   }
773 }
774 
775 /// Find the input GVNs and the output values for a region of Instructions.
776 /// Using the code extractor, we collect the inputs to the extracted function.
777 ///
778 /// The \p Region can be identified as needing to be ignored in this function.
779 /// It should be checked whether it should be ignored after a call to this
780 /// function.
781 ///
782 /// \param [in,out] Region - The region of code to be analyzed.
783 /// \param [out] InputGVNs - The global value numbers for the extracted
784 /// arguments.
785 /// \param [in] NotSame - The global value numbers in the region that do not
786 /// have the same constant value in the regions structurally similar to
787 /// \p Region.
788 /// \param [in] OutputMappings - The mapping of values that have been replaced
789 /// by a new output value after extraction.
790 /// \param [out] ArgInputs - The values of the inputs to the extracted function.
791 /// \param [out] Outputs - The set of values extracted by the CodeExtractor
792 /// as outputs.
793 static void getCodeExtractorArguments(
794     OutlinableRegion &Region, std::vector<unsigned> &InputGVNs,
795     DenseSet<unsigned> &NotSame, DenseMap<Value *, Value *> &OutputMappings,
796     SetVector<Value *> &ArgInputs, SetVector<Value *> &Outputs) {
797   IRSimilarityCandidate &C = *Region.Candidate;
798 
799   // OverallInputs are the inputs to the region found by the CodeExtractor,
800   // SinkCands and HoistCands are used by the CodeExtractor to find sunken
801   // allocas of values whose lifetimes are contained completely within the
802   // outlined region. PremappedInputs are the arguments found by the
803   // CodeExtractor, removing conditions such as sunken allocas, but that
804   // may need to be remapped due to the extracted output values replacing
805   // the original values. We use DummyOutputs for this first run of finding
806   // inputs and outputs since the outputs could change during findAllocas,
807   // the correct set of extracted outputs will be in the final Outputs ValueSet.
808   SetVector<Value *> OverallInputs, PremappedInputs, SinkCands, HoistCands,
809       DummyOutputs;
810 
811   // Use the code extractor to get the inputs and outputs, without sunken
812   // allocas or removing llvm.assumes.
813   CodeExtractor *CE = Region.CE;
814   CE->findInputsOutputs(OverallInputs, DummyOutputs, SinkCands);
815   assert(Region.StartBB && "Region must have a start BasicBlock!");
816   Function *OrigF = Region.StartBB->getParent();
817   CodeExtractorAnalysisCache CEAC(*OrigF);
818   BasicBlock *Dummy = nullptr;
819 
820   // The region may be ineligible due to VarArgs in the parent function. In this
821   // case we ignore the region.
822   if (!CE->isEligible()) {
823     Region.IgnoreRegion = true;
824     return;
825   }
826 
827   // Find if any values are going to be sunk into the function when extracted
828   CE->findAllocas(CEAC, SinkCands, HoistCands, Dummy);
829   CE->findInputsOutputs(PremappedInputs, Outputs, SinkCands);
830 
831   // TODO: Support regions with sunken allocas: values whose lifetimes are
832   // contained completely within the outlined region.  These are not guaranteed
833   // to be the same in every region, so we must elevate them all to arguments
834   // when they appear.  If these values are not equal, it means there is some
835   // Input in OverallInputs that was removed for ArgInputs.
836   if (OverallInputs.size() != PremappedInputs.size()) {
837     Region.IgnoreRegion = true;
838     return;
839   }
840 
841   findConstants(C, NotSame, InputGVNs);
842 
843   mapInputsToGVNs(C, OverallInputs, OutputMappings, InputGVNs);
844 
845   remapExtractedInputs(PremappedInputs.getArrayRef(), OutputMappings,
846                        ArgInputs);
847 
848   // Sort the GVNs, since we now have constants included in the \ref InputGVNs
849   // we need to make sure they are in a deterministic order.
850   stable_sort(InputGVNs);
851 }
852 
853 /// Look over the inputs and map each input argument to an argument in the
854 /// overall function for the OutlinableRegions.  This creates a way to replace
855 /// the arguments of the extracted function with the arguments of the new
856 /// overall function.
857 ///
858 /// \param [in,out] Region - The region of code to be analyzed.
859 /// \param [in] InputGVNs - The global value numbering of the input values
860 /// collected.
861 /// \param [in] ArgInputs - The values of the arguments to the extracted
862 /// function.
863 static void
864 findExtractedInputToOverallInputMapping(OutlinableRegion &Region,
865                                         std::vector<unsigned> &InputGVNs,
866                                         SetVector<Value *> &ArgInputs) {
867 
868   IRSimilarityCandidate &C = *Region.Candidate;
869   OutlinableGroup &Group = *Region.Parent;
870 
871   // This counts the argument number in the overall function.
872   unsigned TypeIndex = 0;
873 
874   // This counts the argument number in the extracted function.
875   unsigned OriginalIndex = 0;
876 
877   // Find the mapping of the extracted arguments to the arguments for the
878   // overall function. Since there may be extra arguments in the overall
879   // function to account for the extracted constants, we have two different
880   // counters as we find extracted arguments, and as we come across overall
881   // arguments.
882 
883   // Additionally, in our first pass, for the first extracted function,
884   // we find argument locations for the canonical value numbering.  This
885   // numbering overrides any discovered location for the extracted code.
886   for (unsigned InputVal : InputGVNs) {
887     Optional<unsigned> CanonicalNumberOpt = C.getCanonicalNum(InputVal);
888     assert(CanonicalNumberOpt.hasValue() && "Canonical number not found?");
889     unsigned CanonicalNumber = CanonicalNumberOpt.getValue();
890 
891     Optional<Value *> InputOpt = C.fromGVN(InputVal);
892     assert(InputOpt.hasValue() && "Global value number not found?");
893     Value *Input = InputOpt.getValue();
894 
895     DenseMap<unsigned, unsigned>::iterator AggArgIt =
896         Group.CanonicalNumberToAggArg.find(CanonicalNumber);
897 
898     if (!Group.InputTypesSet) {
899       Group.ArgumentTypes.push_back(Input->getType());
900       // If the input value has a swifterr attribute, make sure to mark the
901       // argument in the overall function.
902       if (Input->isSwiftError()) {
903         assert(
904             !Group.SwiftErrorArgument.hasValue() &&
905             "Argument already marked with swifterr for this OutlinableGroup!");
906         Group.SwiftErrorArgument = TypeIndex;
907       }
908     }
909 
910     // Check if we have a constant. If we do add it to the overall argument
911     // number to Constant map for the region, and continue to the next input.
912     if (Constant *CST = dyn_cast<Constant>(Input)) {
913       if (AggArgIt != Group.CanonicalNumberToAggArg.end())
914         Region.AggArgToConstant.insert(std::make_pair(AggArgIt->second, CST));
915       else {
916         Group.CanonicalNumberToAggArg.insert(
917             std::make_pair(CanonicalNumber, TypeIndex));
918         Region.AggArgToConstant.insert(std::make_pair(TypeIndex, CST));
919       }
920       TypeIndex++;
921       continue;
922     }
923 
924     // It is not a constant, we create the mapping from extracted argument list
925     // to the overall argument list, using the canonical location, if it exists.
926     assert(ArgInputs.count(Input) && "Input cannot be found!");
927 
928     if (AggArgIt != Group.CanonicalNumberToAggArg.end()) {
929       if (OriginalIndex != AggArgIt->second)
930         Region.ChangedArgOrder = true;
931       Region.ExtractedArgToAgg.insert(
932           std::make_pair(OriginalIndex, AggArgIt->second));
933       Region.AggArgToExtracted.insert(
934           std::make_pair(AggArgIt->second, OriginalIndex));
935     } else {
936       Group.CanonicalNumberToAggArg.insert(
937           std::make_pair(CanonicalNumber, TypeIndex));
938       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, TypeIndex));
939       Region.AggArgToExtracted.insert(std::make_pair(TypeIndex, OriginalIndex));
940     }
941     OriginalIndex++;
942     TypeIndex++;
943   }
944 
945   // If the function type definitions for the OutlinableGroup holding the region
946   // have not been set, set the length of the inputs here.  We should have the
947   // same inputs for all of the different regions contained in the
948   // OutlinableGroup since they are all structurally similar to one another.
949   if (!Group.InputTypesSet) {
950     Group.NumAggregateInputs = TypeIndex;
951     Group.InputTypesSet = true;
952   }
953 
954   Region.NumExtractedInputs = OriginalIndex;
955 }
956 
957 /// Check if the \p V has any uses outside of the region other than \p PN.
958 ///
959 /// \param V [in] - The value to check.
960 /// \param PHILoc [in] - The location in the PHINode of \p V.
961 /// \param PN [in] - The PHINode using \p V.
962 /// \param Exits [in] - The potential blocks we exit to from the outlined
963 /// region.
964 /// \param BlocksInRegion [in] - The basic blocks contained in the region.
965 /// \returns true if \p V has any use soutside its region other than \p PN.
966 static bool outputHasNonPHI(Value *V, unsigned PHILoc, PHINode &PN,
967                             SmallPtrSet<BasicBlock *, 1> &Exits,
968                             DenseSet<BasicBlock *> &BlocksInRegion) {
969   // We check to see if the value is used by the PHINode from some other
970   // predecessor not included in the region.  If it is, we make sure
971   // to keep it as an output.
972   SmallVector<unsigned, 2> IncomingNumbers(PN.getNumIncomingValues());
973   std::iota(IncomingNumbers.begin(), IncomingNumbers.end(), 0);
974   if (any_of(IncomingNumbers, [PHILoc, &PN, V, &BlocksInRegion](unsigned Idx) {
975         return (Idx != PHILoc && V == PN.getIncomingValue(Idx) &&
976                 !BlocksInRegion.contains(PN.getIncomingBlock(Idx)));
977       }))
978     return true;
979 
980   // Check if the value is used by any other instructions outside the region.
981   return any_of(V->users(), [&Exits, &BlocksInRegion](User *U) {
982     Instruction *I = dyn_cast<Instruction>(U);
983     if (!I)
984       return false;
985 
986     // If the use of the item is inside the region, we skip it.  Uses
987     // inside the region give us useful information about how the item could be
988     // used as an output.
989     BasicBlock *Parent = I->getParent();
990     if (BlocksInRegion.contains(Parent))
991       return false;
992 
993     // If it's not a PHINode then we definitely know the use matters.  This
994     // output value will not completely combined with another item in a PHINode
995     // as it is directly reference by another non-phi instruction
996     if (!isa<PHINode>(I))
997       return true;
998 
999     // If we have a PHINode outside one of the exit locations, then it
1000     // can be considered an outside use as well.  If there is a PHINode
1001     // contained in the Exit where this values use matters, it will be
1002     // caught when we analyze that PHINode.
1003     if (!Exits.contains(Parent))
1004       return true;
1005 
1006     return false;
1007   });
1008 }
1009 
1010 /// Test whether \p CurrentExitFromRegion contains any PhiNodes that should be
1011 /// considered outputs. A PHINodes is an output when more than one incoming
1012 /// value has been marked by the CodeExtractor as an output.
1013 ///
1014 /// \param CurrentExitFromRegion [in] - The block to analyze.
1015 /// \param PotentialExitsFromRegion [in] - The potential exit blocks from the
1016 /// region.
1017 /// \param RegionBlocks [in] - The basic blocks in the region.
1018 /// \param Outputs [in, out] - The existing outputs for the region, we may add
1019 /// PHINodes to this as we find that they replace output values.
1020 /// \param OutputsReplacedByPHINode [out] - A set containing outputs that are
1021 /// totally replaced  by a PHINode.
1022 /// \param OutputsWithNonPhiUses [out] - A set containing outputs that are used
1023 /// in PHINodes, but have other uses, and should still be considered outputs.
1024 static void analyzeExitPHIsForOutputUses(
1025     BasicBlock *CurrentExitFromRegion,
1026     SmallPtrSet<BasicBlock *, 1> &PotentialExitsFromRegion,
1027     DenseSet<BasicBlock *> &RegionBlocks, SetVector<Value *> &Outputs,
1028     DenseSet<Value *> &OutputsReplacedByPHINode,
1029     DenseSet<Value *> &OutputsWithNonPhiUses) {
1030   for (PHINode &PN : CurrentExitFromRegion->phis()) {
1031     // Find all incoming values from the outlining region.
1032     SmallVector<unsigned, 2> IncomingVals;
1033     for (unsigned I = 0, E = PN.getNumIncomingValues(); I < E; ++I)
1034       if (RegionBlocks.contains(PN.getIncomingBlock(I)))
1035         IncomingVals.push_back(I);
1036 
1037     // Do not process PHI if there are no predecessors from region.
1038     unsigned NumIncomingVals = IncomingVals.size();
1039     if (NumIncomingVals == 0)
1040       continue;
1041 
1042     // If there is one predecessor, we mark it as a value that needs to be kept
1043     // as an output.
1044     if (NumIncomingVals == 1) {
1045       Value *V = PN.getIncomingValue(*IncomingVals.begin());
1046       OutputsWithNonPhiUses.insert(V);
1047       OutputsReplacedByPHINode.erase(V);
1048       continue;
1049     }
1050 
1051     // This PHINode will be used as an output value, so we add it to our list.
1052     Outputs.insert(&PN);
1053 
1054     // Not all of the incoming values should be ignored as other inputs and
1055     // outputs may have uses in outlined region.  If they have other uses
1056     // outside of the single PHINode we should not skip over it.
1057     for (unsigned Idx : IncomingVals) {
1058       Value *V = PN.getIncomingValue(Idx);
1059       if (outputHasNonPHI(V, Idx, PN, PotentialExitsFromRegion, RegionBlocks)) {
1060         OutputsWithNonPhiUses.insert(V);
1061         OutputsReplacedByPHINode.erase(V);
1062         continue;
1063       }
1064       if (!OutputsWithNonPhiUses.contains(V))
1065         OutputsReplacedByPHINode.insert(V);
1066     }
1067   }
1068 }
1069 
1070 // Represents the type for the unsigned number denoting the output number for
1071 // phi node, along with the canonical number for the exit block.
1072 using ArgLocWithBBCanon = std::pair<unsigned, unsigned>;
1073 // The list of canonical numbers for the incoming values to a PHINode.
1074 using CanonList = SmallVector<unsigned, 2>;
1075 // The pair type representing the set of canonical values being combined in the
1076 // PHINode, along with the location data for the PHINode.
1077 using PHINodeData = std::pair<ArgLocWithBBCanon, CanonList>;
1078 
1079 /// Encode \p PND as an integer for easy lookup based on the argument location,
1080 /// the parent BasicBlock canonical numbering, and the canonical numbering of
1081 /// the values stored in the PHINode.
1082 ///
1083 /// \param PND - The data to hash.
1084 /// \returns The hash code of \p PND.
1085 static hash_code encodePHINodeData(PHINodeData &PND) {
1086   return llvm::hash_combine(
1087       llvm::hash_value(PND.first.first), llvm::hash_value(PND.first.second),
1088       llvm::hash_combine_range(PND.second.begin(), PND.second.end()));
1089 }
1090 
1091 /// Create a special GVN for PHINodes that will be used outside of
1092 /// the region.  We create a hash code based on the Canonical number of the
1093 /// parent BasicBlock, the canonical numbering of the values stored in the
1094 /// PHINode and the aggregate argument location.  This is used to find whether
1095 /// this PHINode type has been given a canonical numbering already.  If not, we
1096 /// assign it a value and store it for later use.  The value is returned to
1097 /// identify different output schemes for the set of regions.
1098 ///
1099 /// \param Region - The region that \p PN is an output for.
1100 /// \param PN - The PHINode we are analyzing.
1101 /// \param AggArgIdx - The argument \p PN will be stored into.
1102 /// \returns An optional holding the assigned canonical number, or None if
1103 /// there is some attribute of the PHINode blocking it from being used.
1104 static Optional<unsigned> getGVNForPHINode(OutlinableRegion &Region,
1105                                            PHINode *PN, unsigned AggArgIdx) {
1106   OutlinableGroup &Group = *Region.Parent;
1107   IRSimilarityCandidate &Cand = *Region.Candidate;
1108   BasicBlock *PHIBB = PN->getParent();
1109   CanonList PHIGVNs;
1110   for (Value *Incoming : PN->incoming_values()) {
1111     // If we cannot find a GVN, this means that the input to the PHINode is
1112     // not included in the region we are trying to analyze, meaning, that if
1113     // it was outlined, we would be adding an extra input.  We ignore this
1114     // case for now, and so ignore the region.
1115     Optional<unsigned> OGVN = Cand.getGVN(Incoming);
1116     if (!OGVN.hasValue()) {
1117       Region.IgnoreRegion = true;
1118       return None;
1119     }
1120 
1121     // Collect the canonical numbers of the values in the PHINode.
1122     unsigned GVN = OGVN.getValue();
1123     OGVN = Cand.getCanonicalNum(GVN);
1124     assert(OGVN.hasValue() && "No GVN found for incoming value?");
1125     PHIGVNs.push_back(*OGVN);
1126   }
1127 
1128   // Now that we have the GVNs for the incoming values, we are going to combine
1129   // them with the GVN of the incoming bock, and the output location of the
1130   // PHINode to generate a hash value representing this instance of the PHINode.
1131   DenseMap<hash_code, unsigned>::iterator GVNToPHIIt;
1132   DenseMap<unsigned, PHINodeData>::iterator PHIToGVNIt;
1133   Optional<unsigned> BBGVN = Cand.getGVN(PHIBB);
1134   assert(BBGVN.hasValue() && "Could not find GVN for the incoming block!");
1135 
1136   BBGVN = Cand.getCanonicalNum(BBGVN.getValue());
1137   assert(BBGVN.hasValue() &&
1138          "Could not find canonical number for the incoming block!");
1139   // Create a pair of the exit block canonical value, and the aggregate
1140   // argument location, connected to the canonical numbers stored in the
1141   // PHINode.
1142   PHINodeData TemporaryPair =
1143       std::make_pair(std::make_pair(BBGVN.getValue(), AggArgIdx), PHIGVNs);
1144   hash_code PHINodeDataHash = encodePHINodeData(TemporaryPair);
1145 
1146   // Look for and create a new entry in our connection between canonical
1147   // numbers for PHINodes, and the set of objects we just created.
1148   GVNToPHIIt = Group.GVNsToPHINodeGVN.find(PHINodeDataHash);
1149   if (GVNToPHIIt == Group.GVNsToPHINodeGVN.end()) {
1150     bool Inserted = false;
1151     std::tie(PHIToGVNIt, Inserted) = Group.PHINodeGVNToGVNs.insert(
1152         std::make_pair(Group.PHINodeGVNTracker, TemporaryPair));
1153     std::tie(GVNToPHIIt, Inserted) = Group.GVNsToPHINodeGVN.insert(
1154         std::make_pair(PHINodeDataHash, Group.PHINodeGVNTracker--));
1155   }
1156 
1157   return GVNToPHIIt->second;
1158 }
1159 
1160 /// Create a mapping of the output arguments for the \p Region to the output
1161 /// arguments of the overall outlined function.
1162 ///
1163 /// \param [in,out] Region - The region of code to be analyzed.
1164 /// \param [in] Outputs - The values found by the code extractor.
1165 static void
1166 findExtractedOutputToOverallOutputMapping(OutlinableRegion &Region,
1167                                           SetVector<Value *> &Outputs) {
1168   OutlinableGroup &Group = *Region.Parent;
1169   IRSimilarityCandidate &C = *Region.Candidate;
1170 
1171   SmallVector<BasicBlock *> BE;
1172   DenseSet<BasicBlock *> BlocksInRegion;
1173   C.getBasicBlocks(BlocksInRegion, BE);
1174 
1175   // Find the exits to the region.
1176   SmallPtrSet<BasicBlock *, 1> Exits;
1177   for (BasicBlock *Block : BE)
1178     for (BasicBlock *Succ : successors(Block))
1179       if (!BlocksInRegion.contains(Succ))
1180         Exits.insert(Succ);
1181 
1182   // After determining which blocks exit to PHINodes, we add these PHINodes to
1183   // the set of outputs to be processed.  We also check the incoming values of
1184   // the PHINodes for whether they should no longer be considered outputs.
1185   DenseSet<Value *> OutputsReplacedByPHINode;
1186   DenseSet<Value *> OutputsWithNonPhiUses;
1187   for (BasicBlock *ExitBB : Exits)
1188     analyzeExitPHIsForOutputUses(ExitBB, Exits, BlocksInRegion, Outputs,
1189                                  OutputsReplacedByPHINode,
1190                                  OutputsWithNonPhiUses);
1191 
1192   // This counts the argument number in the extracted function.
1193   unsigned OriginalIndex = Region.NumExtractedInputs;
1194 
1195   // This counts the argument number in the overall function.
1196   unsigned TypeIndex = Group.NumAggregateInputs;
1197   bool TypeFound;
1198   DenseSet<unsigned> AggArgsUsed;
1199 
1200   // Iterate over the output types and identify if there is an aggregate pointer
1201   // type whose base type matches the current output type. If there is, we mark
1202   // that we will use this output register for this value. If not we add another
1203   // type to the overall argument type list. We also store the GVNs used for
1204   // stores to identify which values will need to be moved into an special
1205   // block that holds the stores to the output registers.
1206   for (Value *Output : Outputs) {
1207     TypeFound = false;
1208     // We can do this since it is a result value, and will have a number
1209     // that is necessarily the same. BUT if in the future, the instructions
1210     // do not have to be in same order, but are functionally the same, we will
1211     // have to use a different scheme, as one-to-one correspondence is not
1212     // guaranteed.
1213     unsigned ArgumentSize = Group.ArgumentTypes.size();
1214 
1215     // If the output is combined in a PHINode, we make sure to skip over it.
1216     if (OutputsReplacedByPHINode.contains(Output))
1217       continue;
1218 
1219     unsigned AggArgIdx = 0;
1220     for (unsigned Jdx = TypeIndex; Jdx < ArgumentSize; Jdx++) {
1221       if (Group.ArgumentTypes[Jdx] != PointerType::getUnqual(Output->getType()))
1222         continue;
1223 
1224       if (AggArgsUsed.contains(Jdx))
1225         continue;
1226 
1227       TypeFound = true;
1228       AggArgsUsed.insert(Jdx);
1229       Region.ExtractedArgToAgg.insert(std::make_pair(OriginalIndex, Jdx));
1230       Region.AggArgToExtracted.insert(std::make_pair(Jdx, OriginalIndex));
1231       AggArgIdx = Jdx;
1232       break;
1233     }
1234 
1235     // We were unable to find an unused type in the output type set that matches
1236     // the output, so we add a pointer type to the argument types of the overall
1237     // function to handle this output and create a mapping to it.
1238     if (!TypeFound) {
1239       Group.ArgumentTypes.push_back(PointerType::getUnqual(Output->getType()));
1240       // Mark the new pointer type as the last value in the aggregate argument
1241       // list.
1242       unsigned ArgTypeIdx = Group.ArgumentTypes.size() - 1;
1243       AggArgsUsed.insert(ArgTypeIdx);
1244       Region.ExtractedArgToAgg.insert(
1245           std::make_pair(OriginalIndex, ArgTypeIdx));
1246       Region.AggArgToExtracted.insert(
1247           std::make_pair(ArgTypeIdx, OriginalIndex));
1248       AggArgIdx = ArgTypeIdx;
1249     }
1250 
1251     // TODO: Adapt to the extra input from the PHINode.
1252     PHINode *PN = dyn_cast<PHINode>(Output);
1253 
1254     Optional<unsigned> GVN;
1255     if (PN && !BlocksInRegion.contains(PN->getParent())) {
1256       // Values outside the region can be combined into PHINode when we
1257       // have multiple exits. We collect both of these into a list to identify
1258       // which values are being used in the PHINode. Each list identifies a
1259       // different PHINode, and a different output. We store the PHINode as it's
1260       // own canonical value.  These canonical values are also dependent on the
1261       // output argument it is saved to.
1262 
1263       // If two PHINodes have the same canonical values, but different aggregate
1264       // argument locations, then they will have distinct Canonical Values.
1265       GVN = getGVNForPHINode(Region, PN, AggArgIdx);
1266       if (!GVN.hasValue())
1267         return;
1268     } else {
1269       // If we do not have a PHINode we use the global value numbering for the
1270       // output value, to find the canonical number to add to the set of stored
1271       // values.
1272       GVN = C.getGVN(Output);
1273       GVN = C.getCanonicalNum(*GVN);
1274     }
1275 
1276     // Each region has a potentially unique set of outputs.  We save which
1277     // values are output in a list of canonical values so we can differentiate
1278     // among the different store schemes.
1279     Region.GVNStores.push_back(*GVN);
1280 
1281     OriginalIndex++;
1282     TypeIndex++;
1283   }
1284 
1285   // We sort the stored values to make sure that we are not affected by analysis
1286   // order when determining what combination of items were stored.
1287   stable_sort(Region.GVNStores);
1288 }
1289 
1290 void IROutliner::findAddInputsOutputs(Module &M, OutlinableRegion &Region,
1291                                       DenseSet<unsigned> &NotSame) {
1292   std::vector<unsigned> Inputs;
1293   SetVector<Value *> ArgInputs, Outputs;
1294 
1295   getCodeExtractorArguments(Region, Inputs, NotSame, OutputMappings, ArgInputs,
1296                             Outputs);
1297 
1298   if (Region.IgnoreRegion)
1299     return;
1300 
1301   // Map the inputs found by the CodeExtractor to the arguments found for
1302   // the overall function.
1303   findExtractedInputToOverallInputMapping(Region, Inputs, ArgInputs);
1304 
1305   // Map the outputs found by the CodeExtractor to the arguments found for
1306   // the overall function.
1307   findExtractedOutputToOverallOutputMapping(Region, Outputs);
1308 }
1309 
1310 /// Replace the extracted function in the Region with a call to the overall
1311 /// function constructed from the deduplicated similar regions, replacing and
1312 /// remapping the values passed to the extracted function as arguments to the
1313 /// new arguments of the overall function.
1314 ///
1315 /// \param [in] M - The module to outline from.
1316 /// \param [in] Region - The regions of extracted code to be replaced with a new
1317 /// function.
1318 /// \returns a call instruction with the replaced function.
1319 CallInst *replaceCalledFunction(Module &M, OutlinableRegion &Region) {
1320   std::vector<Value *> NewCallArgs;
1321   DenseMap<unsigned, unsigned>::iterator ArgPair;
1322 
1323   OutlinableGroup &Group = *Region.Parent;
1324   CallInst *Call = Region.Call;
1325   assert(Call && "Call to replace is nullptr?");
1326   Function *AggFunc = Group.OutlinedFunction;
1327   assert(AggFunc && "Function to replace with is nullptr?");
1328 
1329   // If the arguments are the same size, there are not values that need to be
1330   // made into an argument, the argument ordering has not been change, or
1331   // different output registers to handle.  We can simply replace the called
1332   // function in this case.
1333   if (!Region.ChangedArgOrder && AggFunc->arg_size() == Call->arg_size()) {
1334     LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
1335                       << *AggFunc << " with same number of arguments\n");
1336     Call->setCalledFunction(AggFunc);
1337     return Call;
1338   }
1339 
1340   // We have a different number of arguments than the new function, so
1341   // we need to use our previously mappings off extracted argument to overall
1342   // function argument, and constants to overall function argument to create the
1343   // new argument list.
1344   for (unsigned AggArgIdx = 0; AggArgIdx < AggFunc->arg_size(); AggArgIdx++) {
1345 
1346     if (AggArgIdx == AggFunc->arg_size() - 1 &&
1347         Group.OutputGVNCombinations.size() > 1) {
1348       // If we are on the last argument, and we need to differentiate between
1349       // output blocks, add an integer to the argument list to determine
1350       // what block to take
1351       LLVM_DEBUG(dbgs() << "Set switch block argument to "
1352                         << Region.OutputBlockNum << "\n");
1353       NewCallArgs.push_back(ConstantInt::get(Type::getInt32Ty(M.getContext()),
1354                                              Region.OutputBlockNum));
1355       continue;
1356     }
1357 
1358     ArgPair = Region.AggArgToExtracted.find(AggArgIdx);
1359     if (ArgPair != Region.AggArgToExtracted.end()) {
1360       Value *ArgumentValue = Call->getArgOperand(ArgPair->second);
1361       // If we found the mapping from the extracted function to the overall
1362       // function, we simply add it to the argument list.  We use the same
1363       // value, it just needs to honor the new order of arguments.
1364       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1365                         << *ArgumentValue << "\n");
1366       NewCallArgs.push_back(ArgumentValue);
1367       continue;
1368     }
1369 
1370     // If it is a constant, we simply add it to the argument list as a value.
1371     if (Region.AggArgToConstant.find(AggArgIdx) !=
1372         Region.AggArgToConstant.end()) {
1373       Constant *CST = Region.AggArgToConstant.find(AggArgIdx)->second;
1374       LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to value "
1375                         << *CST << "\n");
1376       NewCallArgs.push_back(CST);
1377       continue;
1378     }
1379 
1380     // Add a nullptr value if the argument is not found in the extracted
1381     // function.  If we cannot find a value, it means it is not in use
1382     // for the region, so we should not pass anything to it.
1383     LLVM_DEBUG(dbgs() << "Setting argument " << AggArgIdx << " to nullptr\n");
1384     NewCallArgs.push_back(ConstantPointerNull::get(
1385         static_cast<PointerType *>(AggFunc->getArg(AggArgIdx)->getType())));
1386   }
1387 
1388   LLVM_DEBUG(dbgs() << "Replace call to " << *Call << " with call to "
1389                     << *AggFunc << " with new set of arguments\n");
1390   // Create the new call instruction and erase the old one.
1391   Call = CallInst::Create(AggFunc->getFunctionType(), AggFunc, NewCallArgs, "",
1392                           Call);
1393 
1394   // It is possible that the call to the outlined function is either the first
1395   // instruction is in the new block, the last instruction, or both.  If either
1396   // of these is the case, we need to make sure that we replace the instruction
1397   // in the IRInstructionData struct with the new call.
1398   CallInst *OldCall = Region.Call;
1399   if (Region.NewFront->Inst == OldCall)
1400     Region.NewFront->Inst = Call;
1401   if (Region.NewBack->Inst == OldCall)
1402     Region.NewBack->Inst = Call;
1403 
1404   // Transfer any debug information.
1405   Call->setDebugLoc(Region.Call->getDebugLoc());
1406   // Since our output may determine which branch we go to, we make sure to
1407   // propogate this new call value through the module.
1408   OldCall->replaceAllUsesWith(Call);
1409 
1410   // Remove the old instruction.
1411   OldCall->eraseFromParent();
1412   Region.Call = Call;
1413 
1414   // Make sure that the argument in the new function has the SwiftError
1415   // argument.
1416   if (Group.SwiftErrorArgument.hasValue())
1417     Call->addParamAttr(Group.SwiftErrorArgument.getValue(),
1418                        Attribute::SwiftError);
1419 
1420   return Call;
1421 }
1422 
1423 /// Find or create a BasicBlock in the outlined function containing PhiBlocks
1424 /// for \p RetVal.
1425 ///
1426 /// \param Group - The OutlinableGroup containing the information about the
1427 /// overall outlined function.
1428 /// \param RetVal - The return value or exit option that we are currently
1429 /// evaluating.
1430 /// \returns The found or newly created BasicBlock to contain the needed
1431 /// PHINodes to be used as outputs.
1432 static BasicBlock *findOrCreatePHIBlock(OutlinableGroup &Group, Value *RetVal) {
1433   DenseMap<Value *, BasicBlock *>::iterator PhiBlockForRetVal,
1434       ReturnBlockForRetVal;
1435   PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
1436   ReturnBlockForRetVal = Group.EndBBs.find(RetVal);
1437   assert(ReturnBlockForRetVal != Group.EndBBs.end() &&
1438          "Could not find output value!");
1439   BasicBlock *ReturnBB = ReturnBlockForRetVal->second;
1440 
1441   // Find if a PHIBlock exists for this return value already.  If it is
1442   // the first time we are analyzing this, we will not, so we record it.
1443   PhiBlockForRetVal = Group.PHIBlocks.find(RetVal);
1444   if (PhiBlockForRetVal != Group.PHIBlocks.end())
1445     return PhiBlockForRetVal->second;
1446 
1447   // If we did not find a block, we create one, and insert it into the
1448   // overall function and record it.
1449   bool Inserted = false;
1450   BasicBlock *PHIBlock = BasicBlock::Create(ReturnBB->getContext(), "phi_block",
1451                                             ReturnBB->getParent());
1452   std::tie(PhiBlockForRetVal, Inserted) =
1453       Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
1454 
1455   // We find the predecessors of the return block in the newly created outlined
1456   // function in order to point them to the new PHIBlock rather than the already
1457   // existing return block.
1458   SmallVector<BranchInst *, 2> BranchesToChange;
1459   for (BasicBlock *Pred : predecessors(ReturnBB))
1460     BranchesToChange.push_back(cast<BranchInst>(Pred->getTerminator()));
1461 
1462   // Now we mark the branch instructions found, and change the references of the
1463   // return block to the newly created PHIBlock.
1464   for (BranchInst *BI : BranchesToChange)
1465     for (unsigned Succ = 0, End = BI->getNumSuccessors(); Succ < End; Succ++) {
1466       if (BI->getSuccessor(Succ) != ReturnBB)
1467         continue;
1468       BI->setSuccessor(Succ, PHIBlock);
1469     }
1470 
1471   BranchInst::Create(ReturnBB, PHIBlock);
1472 
1473   return PhiBlockForRetVal->second;
1474 }
1475 
1476 /// For the function call now representing the \p Region, find the passed value
1477 /// to that call that represents Argument \p A at the call location if the
1478 /// call has already been replaced with a call to the  overall, aggregate
1479 /// function.
1480 ///
1481 /// \param A - The Argument to get the passed value for.
1482 /// \param Region - The extracted Region corresponding to the outlined function.
1483 /// \returns The Value representing \p A at the call site.
1484 static Value *
1485 getPassedArgumentInAlreadyOutlinedFunction(const Argument *A,
1486                                            const OutlinableRegion &Region) {
1487   // If we don't need to adjust the argument number at all (since the call
1488   // has already been replaced by a call to the overall outlined function)
1489   // we can just get the specified argument.
1490   return Region.Call->getArgOperand(A->getArgNo());
1491 }
1492 
1493 /// For the function call now representing the \p Region, find the passed value
1494 /// to that call that represents Argument \p A at the call location if the
1495 /// call has only been replaced by the call to the aggregate function.
1496 ///
1497 /// \param A - The Argument to get the passed value for.
1498 /// \param Region - The extracted Region corresponding to the outlined function.
1499 /// \returns The Value representing \p A at the call site.
1500 static Value *
1501 getPassedArgumentAndAdjustArgumentLocation(const Argument *A,
1502                                            const OutlinableRegion &Region) {
1503   unsigned ArgNum = A->getArgNo();
1504 
1505   // If it is a constant, we can look at our mapping from when we created
1506   // the outputs to figure out what the constant value is.
1507   if (Region.AggArgToConstant.count(ArgNum))
1508     return Region.AggArgToConstant.find(ArgNum)->second;
1509 
1510   // If it is not a constant, and we are not looking at the overall function, we
1511   // need to adjust which argument we are looking at.
1512   ArgNum = Region.AggArgToExtracted.find(ArgNum)->second;
1513   return Region.Call->getArgOperand(ArgNum);
1514 }
1515 
1516 /// Find the canonical numbering for the incoming Values into the PHINode \p PN.
1517 ///
1518 /// \param PN [in] - The PHINode that we are finding the canonical numbers for.
1519 /// \param Region [in] - The OutlinableRegion containing \p PN.
1520 /// \param OutputMappings [in] - The mapping of output values from outlined
1521 /// region to their original values.
1522 /// \param CanonNums [out] - The canonical numbering for the incoming values to
1523 /// \p PN.
1524 /// \param ReplacedWithOutlinedCall - A flag to use the extracted function call
1525 /// of \p Region rather than the overall function's call.
1526 static void
1527 findCanonNumsForPHI(PHINode *PN, OutlinableRegion &Region,
1528                     const DenseMap<Value *, Value *> &OutputMappings,
1529                     DenseSet<unsigned> &CanonNums,
1530                     bool ReplacedWithOutlinedCall = true) {
1531   // Iterate over the incoming values.
1532   for (unsigned Idx = 0, EIdx = PN->getNumIncomingValues(); Idx < EIdx; Idx++) {
1533     Value *IVal = PN->getIncomingValue(Idx);
1534     // If we have an argument as incoming value, we need to grab the passed
1535     // value from the call itself.
1536     if (Argument *A = dyn_cast<Argument>(IVal)) {
1537       if (ReplacedWithOutlinedCall)
1538         IVal = getPassedArgumentInAlreadyOutlinedFunction(A, Region);
1539       else
1540         IVal = getPassedArgumentAndAdjustArgumentLocation(A, Region);
1541     }
1542 
1543     // Get the original value if it has been replaced by an output value.
1544     IVal = findOutputMapping(OutputMappings, IVal);
1545 
1546     // Find and add the canonical number for the incoming value.
1547     Optional<unsigned> GVN = Region.Candidate->getGVN(IVal);
1548     assert(GVN.hasValue() && "No GVN for incoming value");
1549     Optional<unsigned> CanonNum = Region.Candidate->getCanonicalNum(*GVN);
1550     assert(CanonNum.hasValue() && "No Canonical Number for GVN");
1551     CanonNums.insert(*CanonNum);
1552   }
1553 }
1554 
1555 /// Find, or add PHINode \p PN to the combined PHINode Block \p OverallPHIBlock
1556 /// in order to condense the number of instructions added to the outlined
1557 /// function.
1558 ///
1559 /// \param PN [in] - The PHINode that we are finding the canonical numbers for.
1560 /// \param Region [in] - The OutlinableRegion containing \p PN.
1561 /// \param OverallPhiBlock [in] - The overall PHIBlock we are trying to find
1562 /// \p PN in.
1563 /// \param OutputMappings [in] - The mapping of output values from outlined
1564 /// region to their original values.
1565 /// \return the newly found or created PHINode in \p OverallPhiBlock.
1566 static PHINode*
1567 findOrCreatePHIInBlock(PHINode &PN, OutlinableRegion &Region,
1568                        BasicBlock *OverallPhiBlock,
1569                        const DenseMap<Value *, Value *> &OutputMappings) {
1570   OutlinableGroup &Group = *Region.Parent;
1571 
1572   DenseSet<unsigned> PNCanonNums;
1573   // We have to use the extracted function since we have merged this region into
1574   // the overall function yet.  We make sure to reassign the argument numbering
1575   // since it is possible that the argument ordering is different between the
1576   // functions.
1577   findCanonNumsForPHI(&PN, Region, OutputMappings, PNCanonNums,
1578                       /* ReplacedWithOutlinedCall = */ false);
1579 
1580   OutlinableRegion *FirstRegion = Group.Regions[0];
1581   DenseSet<unsigned> CurrentCanonNums;
1582   // Find the Canonical Numbering for each PHINode, if it matches, we replace
1583   // the uses of the PHINode we are searching for, with the found PHINode.
1584   for (PHINode &CurrPN : OverallPhiBlock->phis()) {
1585     CurrentCanonNums.clear();
1586     findCanonNumsForPHI(&CurrPN, *FirstRegion, OutputMappings, CurrentCanonNums,
1587                         /* ReplacedWithOutlinedCall = */ true);
1588 
1589     if (all_of(PNCanonNums, [&CurrentCanonNums](unsigned CanonNum) {
1590           return CurrentCanonNums.contains(CanonNum);
1591         }))
1592       return &CurrPN;
1593   }
1594 
1595   // If we've made it here, it means we weren't able to replace the PHINode, so
1596   // we must insert it ourselves.
1597   PHINode *NewPN = cast<PHINode>(PN.clone());
1598   NewPN->insertBefore(&*OverallPhiBlock->begin());
1599   for (unsigned Idx = 0, Edx = NewPN->getNumIncomingValues(); Idx < Edx;
1600        Idx++) {
1601     Value *IncomingVal = NewPN->getIncomingValue(Idx);
1602     BasicBlock *IncomingBlock = NewPN->getIncomingBlock(Idx);
1603 
1604     // Find corresponding basic block in the overall function for the incoming
1605     // block.
1606     Instruction *FirstNonPHI = IncomingBlock->getFirstNonPHI();
1607     assert(FirstNonPHI && "Incoming block is empty?");
1608     Value *CorrespondingVal =
1609         Region.findCorrespondingValueIn(*FirstRegion, FirstNonPHI);
1610     assert(CorrespondingVal && "Value is nullptr?");
1611     BasicBlock *BlockToUse = cast<Instruction>(CorrespondingVal)->getParent();
1612     NewPN->setIncomingBlock(Idx, BlockToUse);
1613 
1614     // If we have an argument we make sure we replace using the argument from
1615     // the correct function.
1616     if (Argument *A = dyn_cast<Argument>(IncomingVal)) {
1617       Value *Val = Group.OutlinedFunction->getArg(A->getArgNo());
1618       NewPN->setIncomingValue(Idx, Val);
1619       continue;
1620     }
1621 
1622     // Find the corresponding value in the overall function.
1623     IncomingVal = findOutputMapping(OutputMappings, IncomingVal);
1624     Value *Val = Region.findCorrespondingValueIn(*FirstRegion, IncomingVal);
1625     assert(Val && "Value is nullptr?");
1626     NewPN->setIncomingValue(Idx, Val);
1627   }
1628   return NewPN;
1629 }
1630 
1631 // Within an extracted function, replace the argument uses of the extracted
1632 // region with the arguments of the function for an OutlinableGroup.
1633 //
1634 /// \param [in] Region - The region of extracted code to be changed.
1635 /// \param [in,out] OutputBBs - The BasicBlock for the output stores for this
1636 /// region.
1637 /// \param [in] FirstFunction - A flag to indicate whether we are using this
1638 /// function to define the overall outlined function for all the regions, or
1639 /// if we are operating on one of the following regions.
1640 static void
1641 replaceArgumentUses(OutlinableRegion &Region,
1642                     DenseMap<Value *, BasicBlock *> &OutputBBs,
1643                     const DenseMap<Value *, Value *> &OutputMappings,
1644                     bool FirstFunction = false) {
1645   OutlinableGroup &Group = *Region.Parent;
1646   assert(Region.ExtractedFunction && "Region has no extracted function?");
1647 
1648   Function *DominatingFunction = Region.ExtractedFunction;
1649   if (FirstFunction)
1650     DominatingFunction = Group.OutlinedFunction;
1651   DominatorTree DT(*DominatingFunction);
1652 
1653   for (unsigned ArgIdx = 0; ArgIdx < Region.ExtractedFunction->arg_size();
1654        ArgIdx++) {
1655     assert(Region.ExtractedArgToAgg.find(ArgIdx) !=
1656                Region.ExtractedArgToAgg.end() &&
1657            "No mapping from extracted to outlined?");
1658     unsigned AggArgIdx = Region.ExtractedArgToAgg.find(ArgIdx)->second;
1659     Argument *AggArg = Group.OutlinedFunction->getArg(AggArgIdx);
1660     Argument *Arg = Region.ExtractedFunction->getArg(ArgIdx);
1661     // The argument is an input, so we can simply replace it with the overall
1662     // argument value
1663     if (ArgIdx < Region.NumExtractedInputs) {
1664       LLVM_DEBUG(dbgs() << "Replacing uses of input " << *Arg << " in function "
1665                         << *Region.ExtractedFunction << " with " << *AggArg
1666                         << " in function " << *Group.OutlinedFunction << "\n");
1667       Arg->replaceAllUsesWith(AggArg);
1668       continue;
1669     }
1670 
1671     // If we are replacing an output, we place the store value in its own
1672     // block inside the overall function before replacing the use of the output
1673     // in the function.
1674     assert(Arg->hasOneUse() && "Output argument can only have one use");
1675     User *InstAsUser = Arg->user_back();
1676     assert(InstAsUser && "User is nullptr!");
1677 
1678     Instruction *I = cast<Instruction>(InstAsUser);
1679     BasicBlock *BB = I->getParent();
1680     SmallVector<BasicBlock *, 4> Descendants;
1681     DT.getDescendants(BB, Descendants);
1682     bool EdgeAdded = false;
1683     if (Descendants.size() == 0) {
1684       EdgeAdded = true;
1685       DT.insertEdge(&DominatingFunction->getEntryBlock(), BB);
1686       DT.getDescendants(BB, Descendants);
1687     }
1688 
1689     // Iterate over the following blocks, looking for return instructions,
1690     // if we find one, find the corresponding output block for the return value
1691     // and move our store instruction there.
1692     for (BasicBlock *DescendBB : Descendants) {
1693       ReturnInst *RI = dyn_cast<ReturnInst>(DescendBB->getTerminator());
1694       if (!RI)
1695         continue;
1696       Value *RetVal = RI->getReturnValue();
1697       auto VBBIt = OutputBBs.find(RetVal);
1698       assert(VBBIt != OutputBBs.end() && "Could not find output value!");
1699 
1700       // If this is storing a PHINode, we must make sure it is included in the
1701       // overall function.
1702       StoreInst *SI = cast<StoreInst>(I);
1703 
1704       Value *ValueOperand = SI->getValueOperand();
1705 
1706       StoreInst *NewI = cast<StoreInst>(I->clone());
1707       NewI->setDebugLoc(DebugLoc());
1708       BasicBlock *OutputBB = VBBIt->second;
1709       OutputBB->getInstList().push_back(NewI);
1710       LLVM_DEBUG(dbgs() << "Move store for instruction " << *I << " to "
1711                         << *OutputBB << "\n");
1712 
1713       // If this is storing a PHINode, we must make sure it is included in the
1714       // overall function.
1715       if (!isa<PHINode>(ValueOperand) ||
1716           Region.Candidate->getGVN(ValueOperand).hasValue()) {
1717         if (FirstFunction)
1718           continue;
1719         Value *CorrVal =
1720             Region.findCorrespondingValueIn(*Group.Regions[0], ValueOperand);
1721         assert(CorrVal && "Value is nullptr?");
1722         NewI->setOperand(0, CorrVal);
1723         continue;
1724       }
1725       PHINode *PN = cast<PHINode>(SI->getValueOperand());
1726       // If it has a value, it was not split by the code extractor, which
1727       // is what we are looking for.
1728       if (Region.Candidate->getGVN(PN).hasValue())
1729         continue;
1730 
1731       // We record the parent block for the PHINode in the Region so that
1732       // we can exclude it from checks later on.
1733       Region.PHIBlocks.insert(std::make_pair(RetVal, PN->getParent()));
1734 
1735       // If this is the first function, we do not need to worry about mergiing
1736       // this with any other block in the overall outlined function, so we can
1737       // just continue.
1738       if (FirstFunction) {
1739         BasicBlock *PHIBlock = PN->getParent();
1740         Group.PHIBlocks.insert(std::make_pair(RetVal, PHIBlock));
1741         continue;
1742       }
1743 
1744       // We look for the aggregate block that contains the PHINodes leading into
1745       // this exit path. If we can't find one, we create one.
1746       BasicBlock *OverallPhiBlock = findOrCreatePHIBlock(Group, RetVal);
1747 
1748       // For our PHINode, we find the combined canonical numbering, and
1749       // attempt to find a matching PHINode in the overall PHIBlock.  If we
1750       // cannot, we copy the PHINode and move it into this new block.
1751       PHINode *NewPN =
1752           findOrCreatePHIInBlock(*PN, Region, OverallPhiBlock, OutputMappings);
1753       NewI->setOperand(0, NewPN);
1754     }
1755 
1756     // If we added an edge for basic blocks without a predecessor, we remove it
1757     // here.
1758     if (EdgeAdded)
1759       DT.deleteEdge(&DominatingFunction->getEntryBlock(), BB);
1760     I->eraseFromParent();
1761 
1762     LLVM_DEBUG(dbgs() << "Replacing uses of output " << *Arg << " in function "
1763                       << *Region.ExtractedFunction << " with " << *AggArg
1764                       << " in function " << *Group.OutlinedFunction << "\n");
1765     Arg->replaceAllUsesWith(AggArg);
1766   }
1767 }
1768 
1769 /// Within an extracted function, replace the constants that need to be lifted
1770 /// into arguments with the actual argument.
1771 ///
1772 /// \param Region [in] - The region of extracted code to be changed.
1773 void replaceConstants(OutlinableRegion &Region) {
1774   OutlinableGroup &Group = *Region.Parent;
1775   // Iterate over the constants that need to be elevated into arguments
1776   for (std::pair<unsigned, Constant *> &Const : Region.AggArgToConstant) {
1777     unsigned AggArgIdx = Const.first;
1778     Function *OutlinedFunction = Group.OutlinedFunction;
1779     assert(OutlinedFunction && "Overall Function is not defined?");
1780     Constant *CST = Const.second;
1781     Argument *Arg = Group.OutlinedFunction->getArg(AggArgIdx);
1782     // Identify the argument it will be elevated to, and replace instances of
1783     // that constant in the function.
1784 
1785     // TODO: If in the future constants do not have one global value number,
1786     // i.e. a constant 1 could be mapped to several values, this check will
1787     // have to be more strict.  It cannot be using only replaceUsesWithIf.
1788 
1789     LLVM_DEBUG(dbgs() << "Replacing uses of constant " << *CST
1790                       << " in function " << *OutlinedFunction << " with "
1791                       << *Arg << "\n");
1792     CST->replaceUsesWithIf(Arg, [OutlinedFunction](Use &U) {
1793       if (Instruction *I = dyn_cast<Instruction>(U.getUser()))
1794         return I->getFunction() == OutlinedFunction;
1795       return false;
1796     });
1797   }
1798 }
1799 
1800 /// It is possible that there is a basic block that already performs the same
1801 /// stores. This returns a duplicate block, if it exists
1802 ///
1803 /// \param OutputBBs [in] the blocks we are looking for a duplicate of.
1804 /// \param OutputStoreBBs [in] The existing output blocks.
1805 /// \returns an optional value with the number output block if there is a match.
1806 Optional<unsigned> findDuplicateOutputBlock(
1807     DenseMap<Value *, BasicBlock *> &OutputBBs,
1808     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1809 
1810   bool Mismatch = false;
1811   unsigned MatchingNum = 0;
1812   // We compare the new set output blocks to the other sets of output blocks.
1813   // If they are the same number, and have identical instructions, they are
1814   // considered to be the same.
1815   for (DenseMap<Value *, BasicBlock *> &CompBBs : OutputStoreBBs) {
1816     Mismatch = false;
1817     for (std::pair<Value *, BasicBlock *> &VToB : CompBBs) {
1818       DenseMap<Value *, BasicBlock *>::iterator OutputBBIt =
1819           OutputBBs.find(VToB.first);
1820       if (OutputBBIt == OutputBBs.end()) {
1821         Mismatch = true;
1822         break;
1823       }
1824 
1825       BasicBlock *CompBB = VToB.second;
1826       BasicBlock *OutputBB = OutputBBIt->second;
1827       if (CompBB->size() - 1 != OutputBB->size()) {
1828         Mismatch = true;
1829         break;
1830       }
1831 
1832       BasicBlock::iterator NIt = OutputBB->begin();
1833       for (Instruction &I : *CompBB) {
1834         if (isa<BranchInst>(&I))
1835           continue;
1836 
1837         if (!I.isIdenticalTo(&(*NIt))) {
1838           Mismatch = true;
1839           break;
1840         }
1841 
1842         NIt++;
1843       }
1844     }
1845 
1846     if (!Mismatch)
1847       return MatchingNum;
1848 
1849     MatchingNum++;
1850   }
1851 
1852   return None;
1853 }
1854 
1855 /// Remove empty output blocks from the outlined region.
1856 ///
1857 /// \param BlocksToPrune - Mapping of return values output blocks for the \p
1858 /// Region.
1859 /// \param Region - The OutlinableRegion we are analyzing.
1860 static bool
1861 analyzeAndPruneOutputBlocks(DenseMap<Value *, BasicBlock *> &BlocksToPrune,
1862                             OutlinableRegion &Region) {
1863   bool AllRemoved = true;
1864   Value *RetValueForBB;
1865   BasicBlock *NewBB;
1866   SmallVector<Value *, 4> ToRemove;
1867   // Iterate over the output blocks created in the outlined section.
1868   for (std::pair<Value *, BasicBlock *> &VtoBB : BlocksToPrune) {
1869     RetValueForBB = VtoBB.first;
1870     NewBB = VtoBB.second;
1871 
1872     // If there are no instructions, we remove it from the module, and also
1873     // mark the value for removal from the return value to output block mapping.
1874     if (NewBB->size() == 0) {
1875       NewBB->eraseFromParent();
1876       ToRemove.push_back(RetValueForBB);
1877       continue;
1878     }
1879 
1880     // Mark that we could not remove all the blocks since they were not all
1881     // empty.
1882     AllRemoved = false;
1883   }
1884 
1885   // Remove the return value from the mapping.
1886   for (Value *V : ToRemove)
1887     BlocksToPrune.erase(V);
1888 
1889   // Mark the region as having the no output scheme.
1890   if (AllRemoved)
1891     Region.OutputBlockNum = -1;
1892 
1893   return AllRemoved;
1894 }
1895 
1896 /// For the outlined section, move needed the StoreInsts for the output
1897 /// registers into their own block. Then, determine if there is a duplicate
1898 /// output block already created.
1899 ///
1900 /// \param [in] OG - The OutlinableGroup of regions to be outlined.
1901 /// \param [in] Region - The OutlinableRegion that is being analyzed.
1902 /// \param [in,out] OutputBBs - the blocks that stores for this region will be
1903 /// placed in.
1904 /// \param [in] EndBBs - the final blocks of the extracted function.
1905 /// \param [in] OutputMappings - OutputMappings the mapping of values that have
1906 /// been replaced by a new output value.
1907 /// \param [in,out] OutputStoreBBs - The existing output blocks.
1908 static void alignOutputBlockWithAggFunc(
1909     OutlinableGroup &OG, OutlinableRegion &Region,
1910     DenseMap<Value *, BasicBlock *> &OutputBBs,
1911     DenseMap<Value *, BasicBlock *> &EndBBs,
1912     const DenseMap<Value *, Value *> &OutputMappings,
1913     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1914   // If none of the output blocks have any instructions, this means that we do
1915   // not have to determine if it matches any of the other output schemes, and we
1916   // don't have to do anything else.
1917   if (analyzeAndPruneOutputBlocks(OutputBBs, Region))
1918     return;
1919 
1920   // Determine is there is a duplicate set of blocks.
1921   Optional<unsigned> MatchingBB =
1922       findDuplicateOutputBlock(OutputBBs, OutputStoreBBs);
1923 
1924   // If there is, we remove the new output blocks.  If it does not,
1925   // we add it to our list of sets of output blocks.
1926   if (MatchingBB.hasValue()) {
1927     LLVM_DEBUG(dbgs() << "Set output block for region in function"
1928                       << Region.ExtractedFunction << " to "
1929                       << MatchingBB.getValue());
1930 
1931     Region.OutputBlockNum = MatchingBB.getValue();
1932     for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs)
1933       VtoBB.second->eraseFromParent();
1934     return;
1935   }
1936 
1937   Region.OutputBlockNum = OutputStoreBBs.size();
1938 
1939   Value *RetValueForBB;
1940   BasicBlock *NewBB;
1941   OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
1942   for (std::pair<Value *, BasicBlock *> &VtoBB : OutputBBs) {
1943     RetValueForBB = VtoBB.first;
1944     NewBB = VtoBB.second;
1945     DenseMap<Value *, BasicBlock *>::iterator VBBIt =
1946         EndBBs.find(RetValueForBB);
1947     LLVM_DEBUG(dbgs() << "Create output block for region in"
1948                       << Region.ExtractedFunction << " to "
1949                       << *NewBB);
1950     BranchInst::Create(VBBIt->second, NewBB);
1951     OutputStoreBBs.back().insert(std::make_pair(RetValueForBB, NewBB));
1952   }
1953 }
1954 
1955 /// Takes in a mapping, \p OldMap of ConstantValues to BasicBlocks, sorts keys,
1956 /// before creating a basic block for each \p NewMap, and inserting into the new
1957 /// block. Each BasicBlock is named with the scheme "<basename>_<key_idx>".
1958 ///
1959 /// \param OldMap [in] - The mapping to base the new mapping off of.
1960 /// \param NewMap [out] - The output mapping using the keys of \p OldMap.
1961 /// \param ParentFunc [in] - The function to put the new basic block in.
1962 /// \param BaseName [in] - The start of the BasicBlock names to be appended to
1963 /// by an index value.
1964 static void createAndInsertBasicBlocks(DenseMap<Value *, BasicBlock *> &OldMap,
1965                                        DenseMap<Value *, BasicBlock *> &NewMap,
1966                                        Function *ParentFunc, Twine BaseName) {
1967   unsigned Idx = 0;
1968   std::vector<Value *> SortedKeys;
1969 
1970   getSortedConstantKeys(SortedKeys, OldMap);
1971 
1972   for (Value *RetVal : SortedKeys) {
1973     BasicBlock *NewBB = BasicBlock::Create(
1974         ParentFunc->getContext(),
1975         Twine(BaseName) + Twine("_") + Twine(static_cast<unsigned>(Idx++)),
1976         ParentFunc);
1977     NewMap.insert(std::make_pair(RetVal, NewBB));
1978   }
1979 }
1980 
1981 /// Create the switch statement for outlined function to differentiate between
1982 /// all the output blocks.
1983 ///
1984 /// For the outlined section, determine if an outlined block already exists that
1985 /// matches the needed stores for the extracted section.
1986 /// \param [in] M - The module we are outlining from.
1987 /// \param [in] OG - The group of regions to be outlined.
1988 /// \param [in] EndBBs - The final blocks of the extracted function.
1989 /// \param [in,out] OutputStoreBBs - The existing output blocks.
1990 void createSwitchStatement(
1991     Module &M, OutlinableGroup &OG, DenseMap<Value *, BasicBlock *> &EndBBs,
1992     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs) {
1993   // We only need the switch statement if there is more than one store
1994   // combination, or there is more than one set of output blocks.  The first
1995   // will occur when we store different sets of values for two different
1996   // regions.  The second will occur when we have two outputs that are combined
1997   // in a PHINode outside of the region in one outlined instance, and are used
1998   // seaparately in another. This will create the same set of OutputGVNs, but
1999   // will generate two different output schemes.
2000   if (OG.OutputGVNCombinations.size() > 1) {
2001     Function *AggFunc = OG.OutlinedFunction;
2002     // Create a final block for each different return block.
2003     DenseMap<Value *, BasicBlock *> ReturnBBs;
2004     createAndInsertBasicBlocks(OG.EndBBs, ReturnBBs, AggFunc, "final_block");
2005 
2006     for (std::pair<Value *, BasicBlock *> &RetBlockPair : ReturnBBs) {
2007       std::pair<Value *, BasicBlock *> &OutputBlock =
2008           *OG.EndBBs.find(RetBlockPair.first);
2009       BasicBlock *ReturnBlock = RetBlockPair.second;
2010       BasicBlock *EndBB = OutputBlock.second;
2011       Instruction *Term = EndBB->getTerminator();
2012       // Move the return value to the final block instead of the original exit
2013       // stub.
2014       Term->moveBefore(*ReturnBlock, ReturnBlock->end());
2015       // Put the switch statement in the old end basic block for the function
2016       // with a fall through to the new return block.
2017       LLVM_DEBUG(dbgs() << "Create switch statement in " << *AggFunc << " for "
2018                         << OutputStoreBBs.size() << "\n");
2019       SwitchInst *SwitchI =
2020           SwitchInst::Create(AggFunc->getArg(AggFunc->arg_size() - 1),
2021                              ReturnBlock, OutputStoreBBs.size(), EndBB);
2022 
2023       unsigned Idx = 0;
2024       for (DenseMap<Value *, BasicBlock *> &OutputStoreBB : OutputStoreBBs) {
2025         DenseMap<Value *, BasicBlock *>::iterator OSBBIt =
2026             OutputStoreBB.find(OutputBlock.first);
2027 
2028         if (OSBBIt == OutputStoreBB.end())
2029           continue;
2030 
2031         BasicBlock *BB = OSBBIt->second;
2032         SwitchI->addCase(
2033             ConstantInt::get(Type::getInt32Ty(M.getContext()), Idx), BB);
2034         Term = BB->getTerminator();
2035         Term->setSuccessor(0, ReturnBlock);
2036         Idx++;
2037       }
2038     }
2039     return;
2040   }
2041 
2042   assert(OutputStoreBBs.size() < 2 && "Different store sets not handled!");
2043 
2044   // If there needs to be stores, move them from the output blocks to their
2045   // corresponding ending block.  We do not check that the OutputGVNCombinations
2046   // is equal to 1 here since that could just been the case where there are 0
2047   // outputs. Instead, we check whether there is more than one set of output
2048   // blocks since this is the only case where we would have to move the
2049   // stores, and erase the extraneous blocks.
2050   if (OutputStoreBBs.size() == 1) {
2051     LLVM_DEBUG(dbgs() << "Move store instructions to the end block in "
2052                       << *OG.OutlinedFunction << "\n");
2053     DenseMap<Value *, BasicBlock *> OutputBlocks = OutputStoreBBs[0];
2054     for (std::pair<Value *, BasicBlock *> &VBPair : OutputBlocks) {
2055       DenseMap<Value *, BasicBlock *>::iterator EndBBIt =
2056           EndBBs.find(VBPair.first);
2057       assert(EndBBIt != EndBBs.end() && "Could not find end block");
2058       BasicBlock *EndBB = EndBBIt->second;
2059       BasicBlock *OutputBB = VBPair.second;
2060       Instruction *Term = OutputBB->getTerminator();
2061       Term->eraseFromParent();
2062       Term = EndBB->getTerminator();
2063       moveBBContents(*OutputBB, *EndBB);
2064       Term->moveBefore(*EndBB, EndBB->end());
2065       OutputBB->eraseFromParent();
2066     }
2067   }
2068 }
2069 
2070 /// Fill the new function that will serve as the replacement function for all of
2071 /// the extracted regions of a certain structure from the first region in the
2072 /// list of regions.  Replace this first region's extracted function with the
2073 /// new overall function.
2074 ///
2075 /// \param [in] M - The module we are outlining from.
2076 /// \param [in] CurrentGroup - The group of regions to be outlined.
2077 /// \param [in,out] OutputStoreBBs - The output blocks for each different
2078 /// set of stores needed for the different functions.
2079 /// \param [in,out] FuncsToRemove - Extracted functions to erase from module
2080 /// once outlining is complete.
2081 /// \param [in] OutputMappings - Extracted functions to erase from module
2082 /// once outlining is complete.
2083 static void fillOverallFunction(
2084     Module &M, OutlinableGroup &CurrentGroup,
2085     std::vector<DenseMap<Value *, BasicBlock *>> &OutputStoreBBs,
2086     std::vector<Function *> &FuncsToRemove,
2087     const DenseMap<Value *, Value *> &OutputMappings) {
2088   OutlinableRegion *CurrentOS = CurrentGroup.Regions[0];
2089 
2090   // Move first extracted function's instructions into new function.
2091   LLVM_DEBUG(dbgs() << "Move instructions from "
2092                     << *CurrentOS->ExtractedFunction << " to instruction "
2093                     << *CurrentGroup.OutlinedFunction << "\n");
2094   moveFunctionData(*CurrentOS->ExtractedFunction,
2095                    *CurrentGroup.OutlinedFunction, CurrentGroup.EndBBs);
2096 
2097   // Transfer the attributes from the function to the new function.
2098   for (Attribute A : CurrentOS->ExtractedFunction->getAttributes().getFnAttrs())
2099     CurrentGroup.OutlinedFunction->addFnAttr(A);
2100 
2101   // Create a new set of output blocks for the first extracted function.
2102   DenseMap<Value *, BasicBlock *> NewBBs;
2103   createAndInsertBasicBlocks(CurrentGroup.EndBBs, NewBBs,
2104                              CurrentGroup.OutlinedFunction, "output_block_0");
2105   CurrentOS->OutputBlockNum = 0;
2106 
2107   replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings, true);
2108   replaceConstants(*CurrentOS);
2109 
2110   // We first identify if any output blocks are empty, if they are we remove
2111   // them. We then create a branch instruction to the basic block to the return
2112   // block for the function for each non empty output block.
2113   if (!analyzeAndPruneOutputBlocks(NewBBs, *CurrentOS)) {
2114     OutputStoreBBs.push_back(DenseMap<Value *, BasicBlock *>());
2115     for (std::pair<Value *, BasicBlock *> &VToBB : NewBBs) {
2116       DenseMap<Value *, BasicBlock *>::iterator VBBIt =
2117           CurrentGroup.EndBBs.find(VToBB.first);
2118       BasicBlock *EndBB = VBBIt->second;
2119       BranchInst::Create(EndBB, VToBB.second);
2120       OutputStoreBBs.back().insert(VToBB);
2121     }
2122   }
2123 
2124   // Replace the call to the extracted function with the outlined function.
2125   CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
2126 
2127   // We only delete the extracted functions at the end since we may need to
2128   // reference instructions contained in them for mapping purposes.
2129   FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
2130 }
2131 
2132 void IROutliner::deduplicateExtractedSections(
2133     Module &M, OutlinableGroup &CurrentGroup,
2134     std::vector<Function *> &FuncsToRemove, unsigned &OutlinedFunctionNum) {
2135   createFunction(M, CurrentGroup, OutlinedFunctionNum);
2136 
2137   std::vector<DenseMap<Value *, BasicBlock *>> OutputStoreBBs;
2138 
2139   OutlinableRegion *CurrentOS;
2140 
2141   fillOverallFunction(M, CurrentGroup, OutputStoreBBs, FuncsToRemove,
2142                       OutputMappings);
2143 
2144   std::vector<Value *> SortedKeys;
2145   for (unsigned Idx = 1; Idx < CurrentGroup.Regions.size(); Idx++) {
2146     CurrentOS = CurrentGroup.Regions[Idx];
2147     AttributeFuncs::mergeAttributesForOutlining(*CurrentGroup.OutlinedFunction,
2148                                                *CurrentOS->ExtractedFunction);
2149 
2150     // Create a set of BasicBlocks, one for each return block, to hold the
2151     // needed store instructions.
2152     DenseMap<Value *, BasicBlock *> NewBBs;
2153     createAndInsertBasicBlocks(
2154         CurrentGroup.EndBBs, NewBBs, CurrentGroup.OutlinedFunction,
2155         "output_block_" + Twine(static_cast<unsigned>(Idx)));
2156     replaceArgumentUses(*CurrentOS, NewBBs, OutputMappings);
2157     alignOutputBlockWithAggFunc(CurrentGroup, *CurrentOS, NewBBs,
2158                                 CurrentGroup.EndBBs, OutputMappings,
2159                                 OutputStoreBBs);
2160 
2161     CurrentOS->Call = replaceCalledFunction(M, *CurrentOS);
2162     FuncsToRemove.push_back(CurrentOS->ExtractedFunction);
2163   }
2164 
2165   // Create a switch statement to handle the different output schemes.
2166   createSwitchStatement(M, CurrentGroup, CurrentGroup.EndBBs, OutputStoreBBs);
2167 
2168   OutlinedFunctionNum++;
2169 }
2170 
2171 /// Checks that the next instruction in the InstructionDataList matches the
2172 /// next instruction in the module.  If they do not, there could be the
2173 /// possibility that extra code has been inserted, and we must ignore it.
2174 ///
2175 /// \param ID - The IRInstructionData to check the next instruction of.
2176 /// \returns true if the InstructionDataList and actual instruction match.
2177 static bool nextIRInstructionDataMatchesNextInst(IRInstructionData &ID) {
2178   // We check if there is a discrepancy between the InstructionDataList
2179   // and the actual next instruction in the module.  If there is, it means
2180   // that an extra instruction was added, likely by the CodeExtractor.
2181 
2182   // Since we do not have any similarity data about this particular
2183   // instruction, we cannot confidently outline it, and must discard this
2184   // candidate.
2185   IRInstructionDataList::iterator NextIDIt = std::next(ID.getIterator());
2186   Instruction *NextIDLInst = NextIDIt->Inst;
2187   Instruction *NextModuleInst = nullptr;
2188   if (!ID.Inst->isTerminator())
2189     NextModuleInst = ID.Inst->getNextNonDebugInstruction();
2190   else if (NextIDLInst != nullptr)
2191     NextModuleInst =
2192         &*NextIDIt->Inst->getParent()->instructionsWithoutDebug().begin();
2193 
2194   if (NextIDLInst && NextIDLInst != NextModuleInst)
2195     return false;
2196 
2197   return true;
2198 }
2199 
2200 bool IROutliner::isCompatibleWithAlreadyOutlinedCode(
2201     const OutlinableRegion &Region) {
2202   IRSimilarityCandidate *IRSC = Region.Candidate;
2203   unsigned StartIdx = IRSC->getStartIdx();
2204   unsigned EndIdx = IRSC->getEndIdx();
2205 
2206   // A check to make sure that we are not about to attempt to outline something
2207   // that has already been outlined.
2208   for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2209     if (Outlined.contains(Idx))
2210       return false;
2211 
2212   // We check if the recorded instruction matches the actual next instruction,
2213   // if it does not, we fix it in the InstructionDataList.
2214   if (!Region.Candidate->backInstruction()->isTerminator()) {
2215     Instruction *NewEndInst =
2216         Region.Candidate->backInstruction()->getNextNonDebugInstruction();
2217     assert(NewEndInst && "Next instruction is a nullptr?");
2218     if (Region.Candidate->end()->Inst != NewEndInst) {
2219       IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
2220       IRInstructionData *NewEndIRID = new (InstDataAllocator.Allocate())
2221           IRInstructionData(*NewEndInst,
2222                             InstructionClassifier.visit(*NewEndInst), *IDL);
2223 
2224       // Insert the first IRInstructionData of the new region after the
2225       // last IRInstructionData of the IRSimilarityCandidate.
2226       IDL->insert(Region.Candidate->end(), *NewEndIRID);
2227     }
2228   }
2229 
2230   return none_of(*IRSC, [this](IRInstructionData &ID) {
2231     if (!nextIRInstructionDataMatchesNextInst(ID))
2232       return true;
2233 
2234     return !this->InstructionClassifier.visit(ID.Inst);
2235   });
2236 }
2237 
2238 void IROutliner::pruneIncompatibleRegions(
2239     std::vector<IRSimilarityCandidate> &CandidateVec,
2240     OutlinableGroup &CurrentGroup) {
2241   bool PreviouslyOutlined;
2242 
2243   // Sort from beginning to end, so the IRSimilarityCandidates are in order.
2244   stable_sort(CandidateVec, [](const IRSimilarityCandidate &LHS,
2245                                const IRSimilarityCandidate &RHS) {
2246     return LHS.getStartIdx() < RHS.getStartIdx();
2247   });
2248 
2249   IRSimilarityCandidate &FirstCandidate = CandidateVec[0];
2250   // Since outlining a call and a branch instruction will be the same as only
2251   // outlinining a call instruction, we ignore it as a space saving.
2252   if (FirstCandidate.getLength() == 2) {
2253     if (isa<CallInst>(FirstCandidate.front()->Inst) &&
2254         isa<BranchInst>(FirstCandidate.back()->Inst))
2255       return;
2256   }
2257 
2258   unsigned CurrentEndIdx = 0;
2259   for (IRSimilarityCandidate &IRSC : CandidateVec) {
2260     PreviouslyOutlined = false;
2261     unsigned StartIdx = IRSC.getStartIdx();
2262     unsigned EndIdx = IRSC.getEndIdx();
2263 
2264     for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2265       if (Outlined.contains(Idx)) {
2266         PreviouslyOutlined = true;
2267         break;
2268       }
2269 
2270     if (PreviouslyOutlined)
2271       continue;
2272 
2273     // Check over the instructions, and if the basic block has its address
2274     // taken for use somewhere else, we do not outline that block.
2275     bool BBHasAddressTaken = any_of(IRSC, [](IRInstructionData &ID){
2276       return ID.Inst->getParent()->hasAddressTaken();
2277     });
2278 
2279     if (BBHasAddressTaken)
2280       continue;
2281 
2282     if (IRSC.front()->Inst->getFunction()->hasLinkOnceODRLinkage() &&
2283         !OutlineFromLinkODRs)
2284       continue;
2285 
2286     // Greedily prune out any regions that will overlap with already chosen
2287     // regions.
2288     if (CurrentEndIdx != 0 && StartIdx <= CurrentEndIdx)
2289       continue;
2290 
2291     bool BadInst = any_of(IRSC, [this](IRInstructionData &ID) {
2292       if (!nextIRInstructionDataMatchesNextInst(ID))
2293         return true;
2294 
2295       return !this->InstructionClassifier.visit(ID.Inst);
2296     });
2297 
2298     if (BadInst)
2299       continue;
2300 
2301     OutlinableRegion *OS = new (RegionAllocator.Allocate())
2302         OutlinableRegion(IRSC, CurrentGroup);
2303     CurrentGroup.Regions.push_back(OS);
2304 
2305     CurrentEndIdx = EndIdx;
2306   }
2307 }
2308 
2309 InstructionCost
2310 IROutliner::findBenefitFromAllRegions(OutlinableGroup &CurrentGroup) {
2311   InstructionCost RegionBenefit = 0;
2312   for (OutlinableRegion *Region : CurrentGroup.Regions) {
2313     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
2314     // We add the number of instructions in the region to the benefit as an
2315     // estimate as to how much will be removed.
2316     RegionBenefit += Region->getBenefit(TTI);
2317     LLVM_DEBUG(dbgs() << "Adding: " << RegionBenefit
2318                       << " saved instructions to overfall benefit.\n");
2319   }
2320 
2321   return RegionBenefit;
2322 }
2323 
2324 /// For the \p OutputCanon number passed in find the value represented by this
2325 /// canonical number. If it is from a PHINode, we pick the first incoming
2326 /// value and return that Value instead.
2327 ///
2328 /// \param Region - The OutlinableRegion to get the Value from.
2329 /// \param OutputCanon - The canonical number to find the Value from.
2330 /// \returns The Value represented by a canonical number \p OutputCanon in \p
2331 /// Region.
2332 static Value *findOutputValueInRegion(OutlinableRegion &Region,
2333                                       unsigned OutputCanon) {
2334   OutlinableGroup &CurrentGroup = *Region.Parent;
2335   // If the value is greater than the value in the tracker, we have a
2336   // PHINode and will instead use one of the incoming values to find the
2337   // type.
2338   if (OutputCanon > CurrentGroup.PHINodeGVNTracker) {
2339     auto It = CurrentGroup.PHINodeGVNToGVNs.find(OutputCanon);
2340     assert(It != CurrentGroup.PHINodeGVNToGVNs.end() &&
2341            "Could not find GVN set for PHINode number!");
2342     assert(It->second.second.size() > 0 && "PHINode does not have any values!");
2343     OutputCanon = *It->second.second.begin();
2344   }
2345   Optional<unsigned> OGVN = Region.Candidate->fromCanonicalNum(OutputCanon);
2346   assert(OGVN.hasValue() && "Could not find GVN for Canonical Number?");
2347   Optional<Value *> OV = Region.Candidate->fromGVN(*OGVN);
2348   assert(OV.hasValue() && "Could not find value for GVN?");
2349   return *OV;
2350 }
2351 
2352 InstructionCost
2353 IROutliner::findCostOutputReloads(OutlinableGroup &CurrentGroup) {
2354   InstructionCost OverallCost = 0;
2355   for (OutlinableRegion *Region : CurrentGroup.Regions) {
2356     TargetTransformInfo &TTI = getTTI(*Region->StartBB->getParent());
2357 
2358     // Each output incurs a load after the call, so we add that to the cost.
2359     for (unsigned OutputCanon : Region->GVNStores) {
2360       Value *V = findOutputValueInRegion(*Region, OutputCanon);
2361       InstructionCost LoadCost =
2362           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
2363                               TargetTransformInfo::TCK_CodeSize);
2364 
2365       LLVM_DEBUG(dbgs() << "Adding: " << LoadCost
2366                         << " instructions to cost for output of type "
2367                         << *V->getType() << "\n");
2368       OverallCost += LoadCost;
2369     }
2370   }
2371 
2372   return OverallCost;
2373 }
2374 
2375 /// Find the extra instructions needed to handle any output values for the
2376 /// region.
2377 ///
2378 /// \param [in] M - The Module to outline from.
2379 /// \param [in] CurrentGroup - The collection of OutlinableRegions to analyze.
2380 /// \param [in] TTI - The TargetTransformInfo used to collect information for
2381 /// new instruction costs.
2382 /// \returns the additional cost to handle the outputs.
2383 static InstructionCost findCostForOutputBlocks(Module &M,
2384                                                OutlinableGroup &CurrentGroup,
2385                                                TargetTransformInfo &TTI) {
2386   InstructionCost OutputCost = 0;
2387   unsigned NumOutputBranches = 0;
2388 
2389   OutlinableRegion &FirstRegion = *CurrentGroup.Regions[0];
2390   IRSimilarityCandidate &Candidate = *CurrentGroup.Regions[0]->Candidate;
2391   DenseSet<BasicBlock *> CandidateBlocks;
2392   Candidate.getBasicBlocks(CandidateBlocks);
2393 
2394   // Count the number of different output branches that point to blocks outside
2395   // of the region.
2396   DenseSet<BasicBlock *> FoundBlocks;
2397   for (IRInstructionData &ID : Candidate) {
2398     if (!isa<BranchInst>(ID.Inst))
2399       continue;
2400 
2401     for (Value *V : ID.OperVals) {
2402       BasicBlock *BB = static_cast<BasicBlock *>(V);
2403       DenseSet<BasicBlock *>::iterator CBIt = CandidateBlocks.find(BB);
2404       if (CBIt != CandidateBlocks.end() || FoundBlocks.contains(BB))
2405         continue;
2406       FoundBlocks.insert(BB);
2407       NumOutputBranches++;
2408     }
2409   }
2410 
2411   CurrentGroup.BranchesToOutside = NumOutputBranches;
2412 
2413   for (const ArrayRef<unsigned> &OutputUse :
2414        CurrentGroup.OutputGVNCombinations) {
2415     for (unsigned OutputCanon : OutputUse) {
2416       Value *V = findOutputValueInRegion(FirstRegion, OutputCanon);
2417       InstructionCost StoreCost =
2418           TTI.getMemoryOpCost(Instruction::Load, V->getType(), Align(1), 0,
2419                               TargetTransformInfo::TCK_CodeSize);
2420 
2421       // An instruction cost is added for each store set that needs to occur for
2422       // various output combinations inside the function, plus a branch to
2423       // return to the exit block.
2424       LLVM_DEBUG(dbgs() << "Adding: " << StoreCost
2425                         << " instructions to cost for output of type "
2426                         << *V->getType() << "\n");
2427       OutputCost += StoreCost * NumOutputBranches;
2428     }
2429 
2430     InstructionCost BranchCost =
2431         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
2432     LLVM_DEBUG(dbgs() << "Adding " << BranchCost << " to the current cost for"
2433                       << " a branch instruction\n");
2434     OutputCost += BranchCost * NumOutputBranches;
2435   }
2436 
2437   // If there is more than one output scheme, we must have a comparison and
2438   // branch for each different item in the switch statement.
2439   if (CurrentGroup.OutputGVNCombinations.size() > 1) {
2440     InstructionCost ComparisonCost = TTI.getCmpSelInstrCost(
2441         Instruction::ICmp, Type::getInt32Ty(M.getContext()),
2442         Type::getInt32Ty(M.getContext()), CmpInst::BAD_ICMP_PREDICATE,
2443         TargetTransformInfo::TCK_CodeSize);
2444     InstructionCost BranchCost =
2445         TTI.getCFInstrCost(Instruction::Br, TargetTransformInfo::TCK_CodeSize);
2446 
2447     unsigned DifferentBlocks = CurrentGroup.OutputGVNCombinations.size();
2448     InstructionCost TotalCost = ComparisonCost * BranchCost * DifferentBlocks;
2449 
2450     LLVM_DEBUG(dbgs() << "Adding: " << TotalCost
2451                       << " instructions for each switch case for each different"
2452                       << " output path in a function\n");
2453     OutputCost += TotalCost * NumOutputBranches;
2454   }
2455 
2456   return OutputCost;
2457 }
2458 
2459 void IROutliner::findCostBenefit(Module &M, OutlinableGroup &CurrentGroup) {
2460   InstructionCost RegionBenefit = findBenefitFromAllRegions(CurrentGroup);
2461   CurrentGroup.Benefit += RegionBenefit;
2462   LLVM_DEBUG(dbgs() << "Current Benefit: " << CurrentGroup.Benefit << "\n");
2463 
2464   InstructionCost OutputReloadCost = findCostOutputReloads(CurrentGroup);
2465   CurrentGroup.Cost += OutputReloadCost;
2466   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2467 
2468   InstructionCost AverageRegionBenefit =
2469       RegionBenefit / CurrentGroup.Regions.size();
2470   unsigned OverallArgumentNum = CurrentGroup.ArgumentTypes.size();
2471   unsigned NumRegions = CurrentGroup.Regions.size();
2472   TargetTransformInfo &TTI =
2473       getTTI(*CurrentGroup.Regions[0]->Candidate->getFunction());
2474 
2475   // We add one region to the cost once, to account for the instructions added
2476   // inside of the newly created function.
2477   LLVM_DEBUG(dbgs() << "Adding: " << AverageRegionBenefit
2478                     << " instructions to cost for body of new function.\n");
2479   CurrentGroup.Cost += AverageRegionBenefit;
2480   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2481 
2482   // For each argument, we must add an instruction for loading the argument
2483   // out of the register and into a value inside of the newly outlined function.
2484   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
2485                     << " instructions to cost for each argument in the new"
2486                     << " function.\n");
2487   CurrentGroup.Cost +=
2488       OverallArgumentNum * TargetTransformInfo::TCC_Basic;
2489   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2490 
2491   // Each argument needs to either be loaded into a register or onto the stack.
2492   // Some arguments will only be loaded into the stack once the argument
2493   // registers are filled.
2494   LLVM_DEBUG(dbgs() << "Adding: " << OverallArgumentNum
2495                     << " instructions to cost for each argument in the new"
2496                     << " function " << NumRegions << " times for the "
2497                     << "needed argument handling at the call site.\n");
2498   CurrentGroup.Cost +=
2499       2 * OverallArgumentNum * TargetTransformInfo::TCC_Basic * NumRegions;
2500   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2501 
2502   CurrentGroup.Cost += findCostForOutputBlocks(M, CurrentGroup, TTI);
2503   LLVM_DEBUG(dbgs() << "Current Cost: " << CurrentGroup.Cost << "\n");
2504 }
2505 
2506 void IROutliner::updateOutputMapping(OutlinableRegion &Region,
2507                                      ArrayRef<Value *> Outputs,
2508                                      LoadInst *LI) {
2509   // For and load instructions following the call
2510   Value *Operand = LI->getPointerOperand();
2511   Optional<unsigned> OutputIdx = None;
2512   // Find if the operand it is an output register.
2513   for (unsigned ArgIdx = Region.NumExtractedInputs;
2514        ArgIdx < Region.Call->arg_size(); ArgIdx++) {
2515     if (Operand == Region.Call->getArgOperand(ArgIdx)) {
2516       OutputIdx = ArgIdx - Region.NumExtractedInputs;
2517       break;
2518     }
2519   }
2520 
2521   // If we found an output register, place a mapping of the new value
2522   // to the original in the mapping.
2523   if (!OutputIdx.hasValue())
2524     return;
2525 
2526   if (OutputMappings.find(Outputs[OutputIdx.getValue()]) ==
2527       OutputMappings.end()) {
2528     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *LI << " to "
2529                       << *Outputs[OutputIdx.getValue()] << "\n");
2530     OutputMappings.insert(std::make_pair(LI, Outputs[OutputIdx.getValue()]));
2531   } else {
2532     Value *Orig = OutputMappings.find(Outputs[OutputIdx.getValue()])->second;
2533     LLVM_DEBUG(dbgs() << "Mapping extracted output " << *Orig << " to "
2534                       << *Outputs[OutputIdx.getValue()] << "\n");
2535     OutputMappings.insert(std::make_pair(LI, Orig));
2536   }
2537 }
2538 
2539 bool IROutliner::extractSection(OutlinableRegion &Region) {
2540   SetVector<Value *> ArgInputs, Outputs, SinkCands;
2541   assert(Region.StartBB && "StartBB for the OutlinableRegion is nullptr!");
2542   BasicBlock *InitialStart = Region.StartBB;
2543   Function *OrigF = Region.StartBB->getParent();
2544   CodeExtractorAnalysisCache CEAC(*OrigF);
2545   Region.ExtractedFunction =
2546       Region.CE->extractCodeRegion(CEAC, ArgInputs, Outputs);
2547 
2548   // If the extraction was successful, find the BasicBlock, and reassign the
2549   // OutlinableRegion blocks
2550   if (!Region.ExtractedFunction) {
2551     LLVM_DEBUG(dbgs() << "CodeExtractor failed to outline " << Region.StartBB
2552                       << "\n");
2553     Region.reattachCandidate();
2554     return false;
2555   }
2556 
2557   // Get the block containing the called branch, and reassign the blocks as
2558   // necessary.  If the original block still exists, it is because we ended on
2559   // a branch instruction, and so we move the contents into the block before
2560   // and assign the previous block correctly.
2561   User *InstAsUser = Region.ExtractedFunction->user_back();
2562   BasicBlock *RewrittenBB = cast<Instruction>(InstAsUser)->getParent();
2563   Region.PrevBB = RewrittenBB->getSinglePredecessor();
2564   assert(Region.PrevBB && "PrevBB is nullptr?");
2565   if (Region.PrevBB == InitialStart) {
2566     BasicBlock *NewPrev = InitialStart->getSinglePredecessor();
2567     Instruction *BI = NewPrev->getTerminator();
2568     BI->eraseFromParent();
2569     moveBBContents(*InitialStart, *NewPrev);
2570     Region.PrevBB = NewPrev;
2571     InitialStart->eraseFromParent();
2572   }
2573 
2574   Region.StartBB = RewrittenBB;
2575   Region.EndBB = RewrittenBB;
2576 
2577   // The sequences of outlinable regions has now changed.  We must fix the
2578   // IRInstructionDataList for consistency.  Although they may not be illegal
2579   // instructions, they should not be compared with anything else as they
2580   // should not be outlined in this round.  So marking these as illegal is
2581   // allowed.
2582   IRInstructionDataList *IDL = Region.Candidate->front()->IDL;
2583   Instruction *BeginRewritten = &*RewrittenBB->begin();
2584   Instruction *EndRewritten = &*RewrittenBB->begin();
2585   Region.NewFront = new (InstDataAllocator.Allocate()) IRInstructionData(
2586       *BeginRewritten, InstructionClassifier.visit(*BeginRewritten), *IDL);
2587   Region.NewBack = new (InstDataAllocator.Allocate()) IRInstructionData(
2588       *EndRewritten, InstructionClassifier.visit(*EndRewritten), *IDL);
2589 
2590   // Insert the first IRInstructionData of the new region in front of the
2591   // first IRInstructionData of the IRSimilarityCandidate.
2592   IDL->insert(Region.Candidate->begin(), *Region.NewFront);
2593   // Insert the first IRInstructionData of the new region after the
2594   // last IRInstructionData of the IRSimilarityCandidate.
2595   IDL->insert(Region.Candidate->end(), *Region.NewBack);
2596   // Remove the IRInstructionData from the IRSimilarityCandidate.
2597   IDL->erase(Region.Candidate->begin(), std::prev(Region.Candidate->end()));
2598 
2599   assert(RewrittenBB != nullptr &&
2600          "Could not find a predecessor after extraction!");
2601 
2602   // Iterate over the new set of instructions to find the new call
2603   // instruction.
2604   for (Instruction &I : *RewrittenBB)
2605     if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2606       if (Region.ExtractedFunction == CI->getCalledFunction())
2607         Region.Call = CI;
2608     } else if (LoadInst *LI = dyn_cast<LoadInst>(&I))
2609       updateOutputMapping(Region, Outputs.getArrayRef(), LI);
2610   Region.reattachCandidate();
2611   return true;
2612 }
2613 
2614 unsigned IROutliner::doOutline(Module &M) {
2615   // Find the possible similarity sections.
2616   InstructionClassifier.EnableBranches = !DisableBranches;
2617   InstructionClassifier.EnableIndirectCalls = !DisableIndirectCalls;
2618   InstructionClassifier.EnableIntrinsics = !DisableIntrinsics;
2619 
2620   IRSimilarityIdentifier &Identifier = getIRSI(M);
2621   SimilarityGroupList &SimilarityCandidates = *Identifier.getSimilarity();
2622 
2623   // Sort them by size of extracted sections
2624   unsigned OutlinedFunctionNum = 0;
2625   // If we only have one SimilarityGroup in SimilarityCandidates, we do not have
2626   // to sort them by the potential number of instructions to be outlined
2627   if (SimilarityCandidates.size() > 1)
2628     llvm::stable_sort(SimilarityCandidates,
2629                       [](const std::vector<IRSimilarityCandidate> &LHS,
2630                          const std::vector<IRSimilarityCandidate> &RHS) {
2631                         return LHS[0].getLength() * LHS.size() >
2632                                RHS[0].getLength() * RHS.size();
2633                       });
2634   // Creating OutlinableGroups for each SimilarityCandidate to be used in
2635   // each of the following for loops to avoid making an allocator.
2636   std::vector<OutlinableGroup> PotentialGroups(SimilarityCandidates.size());
2637 
2638   DenseSet<unsigned> NotSame;
2639   std::vector<OutlinableGroup *> NegativeCostGroups;
2640   std::vector<OutlinableRegion *> OutlinedRegions;
2641   // Iterate over the possible sets of similarity.
2642   unsigned PotentialGroupIdx = 0;
2643   for (SimilarityGroup &CandidateVec : SimilarityCandidates) {
2644     OutlinableGroup &CurrentGroup = PotentialGroups[PotentialGroupIdx++];
2645 
2646     // Remove entries that were previously outlined
2647     pruneIncompatibleRegions(CandidateVec, CurrentGroup);
2648 
2649     // We pruned the number of regions to 0 to 1, meaning that it's not worth
2650     // trying to outlined since there is no compatible similar instance of this
2651     // code.
2652     if (CurrentGroup.Regions.size() < 2)
2653       continue;
2654 
2655     // Determine if there are any values that are the same constant throughout
2656     // each section in the set.
2657     NotSame.clear();
2658     CurrentGroup.findSameConstants(NotSame);
2659 
2660     if (CurrentGroup.IgnoreGroup)
2661       continue;
2662 
2663     // Create a CodeExtractor for each outlinable region. Identify inputs and
2664     // outputs for each section using the code extractor and create the argument
2665     // types for the Aggregate Outlining Function.
2666     OutlinedRegions.clear();
2667     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2668       // Break the outlinable region out of its parent BasicBlock into its own
2669       // BasicBlocks (see function implementation).
2670       OS->splitCandidate();
2671 
2672       // There's a chance that when the region is split, extra instructions are
2673       // added to the region. This makes the region no longer viable
2674       // to be split, so we ignore it for outlining.
2675       if (!OS->CandidateSplit)
2676         continue;
2677 
2678       SmallVector<BasicBlock *> BE;
2679       DenseSet<BasicBlock *> BlocksInRegion;
2680       OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
2681       OS->CE = new (ExtractorAllocator.Allocate())
2682           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
2683                         false, "outlined");
2684       findAddInputsOutputs(M, *OS, NotSame);
2685       if (!OS->IgnoreRegion)
2686         OutlinedRegions.push_back(OS);
2687 
2688       // We recombine the blocks together now that we have gathered all the
2689       // needed information.
2690       OS->reattachCandidate();
2691     }
2692 
2693     CurrentGroup.Regions = std::move(OutlinedRegions);
2694 
2695     if (CurrentGroup.Regions.empty())
2696       continue;
2697 
2698     CurrentGroup.collectGVNStoreSets(M);
2699 
2700     if (CostModel)
2701       findCostBenefit(M, CurrentGroup);
2702 
2703     // If we are adhering to the cost model, skip those groups where the cost
2704     // outweighs the benefits.
2705     if (CurrentGroup.Cost >= CurrentGroup.Benefit && CostModel) {
2706       OptimizationRemarkEmitter &ORE =
2707           getORE(*CurrentGroup.Regions[0]->Candidate->getFunction());
2708       ORE.emit([&]() {
2709         IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2710         OptimizationRemarkMissed R(DEBUG_TYPE, "WouldNotDecreaseSize",
2711                                    C->frontInstruction());
2712         R << "did not outline "
2713           << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2714           << " regions due to estimated increase of "
2715           << ore::NV("InstructionIncrease",
2716                      CurrentGroup.Cost - CurrentGroup.Benefit)
2717           << " instructions at locations ";
2718         interleave(
2719             CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2720             [&R](OutlinableRegion *Region) {
2721               R << ore::NV(
2722                   "DebugLoc",
2723                   Region->Candidate->frontInstruction()->getDebugLoc());
2724             },
2725             [&R]() { R << " "; });
2726         return R;
2727       });
2728       continue;
2729     }
2730 
2731     NegativeCostGroups.push_back(&CurrentGroup);
2732   }
2733 
2734   ExtractorAllocator.DestroyAll();
2735 
2736   if (NegativeCostGroups.size() > 1)
2737     stable_sort(NegativeCostGroups,
2738                 [](const OutlinableGroup *LHS, const OutlinableGroup *RHS) {
2739                   return LHS->Benefit - LHS->Cost > RHS->Benefit - RHS->Cost;
2740                 });
2741 
2742   std::vector<Function *> FuncsToRemove;
2743   for (OutlinableGroup *CG : NegativeCostGroups) {
2744     OutlinableGroup &CurrentGroup = *CG;
2745 
2746     OutlinedRegions.clear();
2747     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2748       // We check whether our region is compatible with what has already been
2749       // outlined, and whether we need to ignore this item.
2750       if (!isCompatibleWithAlreadyOutlinedCode(*Region))
2751         continue;
2752       OutlinedRegions.push_back(Region);
2753     }
2754 
2755     if (OutlinedRegions.size() < 2)
2756       continue;
2757 
2758     // Reestimate the cost and benefit of the OutlinableGroup. Continue only if
2759     // we are still outlining enough regions to make up for the added cost.
2760     CurrentGroup.Regions = std::move(OutlinedRegions);
2761     if (CostModel) {
2762       CurrentGroup.Benefit = 0;
2763       CurrentGroup.Cost = 0;
2764       findCostBenefit(M, CurrentGroup);
2765       if (CurrentGroup.Cost >= CurrentGroup.Benefit)
2766         continue;
2767     }
2768     OutlinedRegions.clear();
2769     for (OutlinableRegion *Region : CurrentGroup.Regions) {
2770       Region->splitCandidate();
2771       if (!Region->CandidateSplit)
2772         continue;
2773       OutlinedRegions.push_back(Region);
2774     }
2775 
2776     CurrentGroup.Regions = std::move(OutlinedRegions);
2777     if (CurrentGroup.Regions.size() < 2) {
2778       for (OutlinableRegion *R : CurrentGroup.Regions)
2779         R->reattachCandidate();
2780       continue;
2781     }
2782 
2783     LLVM_DEBUG(dbgs() << "Outlining regions with cost " << CurrentGroup.Cost
2784                       << " and benefit " << CurrentGroup.Benefit << "\n");
2785 
2786     // Create functions out of all the sections, and mark them as outlined.
2787     OutlinedRegions.clear();
2788     for (OutlinableRegion *OS : CurrentGroup.Regions) {
2789       SmallVector<BasicBlock *> BE;
2790       DenseSet<BasicBlock *> BlocksInRegion;
2791       OS->Candidate->getBasicBlocks(BlocksInRegion, BE);
2792       OS->CE = new (ExtractorAllocator.Allocate())
2793           CodeExtractor(BE, nullptr, false, nullptr, nullptr, nullptr, false,
2794                         false, "outlined");
2795       bool FunctionOutlined = extractSection(*OS);
2796       if (FunctionOutlined) {
2797         unsigned StartIdx = OS->Candidate->getStartIdx();
2798         unsigned EndIdx = OS->Candidate->getEndIdx();
2799         for (unsigned Idx = StartIdx; Idx <= EndIdx; Idx++)
2800           Outlined.insert(Idx);
2801 
2802         OutlinedRegions.push_back(OS);
2803       }
2804     }
2805 
2806     LLVM_DEBUG(dbgs() << "Outlined " << OutlinedRegions.size()
2807                       << " with benefit " << CurrentGroup.Benefit
2808                       << " and cost " << CurrentGroup.Cost << "\n");
2809 
2810     CurrentGroup.Regions = std::move(OutlinedRegions);
2811 
2812     if (CurrentGroup.Regions.empty())
2813       continue;
2814 
2815     OptimizationRemarkEmitter &ORE =
2816         getORE(*CurrentGroup.Regions[0]->Call->getFunction());
2817     ORE.emit([&]() {
2818       IRSimilarityCandidate *C = CurrentGroup.Regions[0]->Candidate;
2819       OptimizationRemark R(DEBUG_TYPE, "Outlined", C->front()->Inst);
2820       R << "outlined " << ore::NV(std::to_string(CurrentGroup.Regions.size()))
2821         << " regions with decrease of "
2822         << ore::NV("Benefit", CurrentGroup.Benefit - CurrentGroup.Cost)
2823         << " instructions at locations ";
2824       interleave(
2825           CurrentGroup.Regions.begin(), CurrentGroup.Regions.end(),
2826           [&R](OutlinableRegion *Region) {
2827             R << ore::NV("DebugLoc",
2828                          Region->Candidate->frontInstruction()->getDebugLoc());
2829           },
2830           [&R]() { R << " "; });
2831       return R;
2832     });
2833 
2834     deduplicateExtractedSections(M, CurrentGroup, FuncsToRemove,
2835                                  OutlinedFunctionNum);
2836   }
2837 
2838   for (Function *F : FuncsToRemove)
2839     F->eraseFromParent();
2840 
2841   return OutlinedFunctionNum;
2842 }
2843 
2844 bool IROutliner::run(Module &M) {
2845   CostModel = !NoCostModel;
2846   OutlineFromLinkODRs = EnableLinkOnceODRIROutlining;
2847 
2848   return doOutline(M) > 0;
2849 }
2850 
2851 // Pass Manager Boilerplate
2852 namespace {
2853 class IROutlinerLegacyPass : public ModulePass {
2854 public:
2855   static char ID;
2856   IROutlinerLegacyPass() : ModulePass(ID) {
2857     initializeIROutlinerLegacyPassPass(*PassRegistry::getPassRegistry());
2858   }
2859 
2860   void getAnalysisUsage(AnalysisUsage &AU) const override {
2861     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2862     AU.addRequired<TargetTransformInfoWrapperPass>();
2863     AU.addRequired<IRSimilarityIdentifierWrapperPass>();
2864   }
2865 
2866   bool runOnModule(Module &M) override;
2867 };
2868 } // namespace
2869 
2870 bool IROutlinerLegacyPass::runOnModule(Module &M) {
2871   if (skipModule(M))
2872     return false;
2873 
2874   std::unique_ptr<OptimizationRemarkEmitter> ORE;
2875   auto GORE = [&ORE](Function &F) -> OptimizationRemarkEmitter & {
2876     ORE.reset(new OptimizationRemarkEmitter(&F));
2877     return *ORE.get();
2878   };
2879 
2880   auto GTTI = [this](Function &F) -> TargetTransformInfo & {
2881     return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2882   };
2883 
2884   auto GIRSI = [this](Module &) -> IRSimilarityIdentifier & {
2885     return this->getAnalysis<IRSimilarityIdentifierWrapperPass>().getIRSI();
2886   };
2887 
2888   return IROutliner(GTTI, GIRSI, GORE).run(M);
2889 }
2890 
2891 PreservedAnalyses IROutlinerPass::run(Module &M, ModuleAnalysisManager &AM) {
2892   auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
2893 
2894   std::function<TargetTransformInfo &(Function &)> GTTI =
2895       [&FAM](Function &F) -> TargetTransformInfo & {
2896     return FAM.getResult<TargetIRAnalysis>(F);
2897   };
2898 
2899   std::function<IRSimilarityIdentifier &(Module &)> GIRSI =
2900       [&AM](Module &M) -> IRSimilarityIdentifier & {
2901     return AM.getResult<IRSimilarityAnalysis>(M);
2902   };
2903 
2904   std::unique_ptr<OptimizationRemarkEmitter> ORE;
2905   std::function<OptimizationRemarkEmitter &(Function &)> GORE =
2906       [&ORE](Function &F) -> OptimizationRemarkEmitter & {
2907     ORE.reset(new OptimizationRemarkEmitter(&F));
2908     return *ORE.get();
2909   };
2910 
2911   if (IROutliner(GTTI, GIRSI, GORE).run(M))
2912     return PreservedAnalyses::none();
2913   return PreservedAnalyses::all();
2914 }
2915 
2916 char IROutlinerLegacyPass::ID = 0;
2917 INITIALIZE_PASS_BEGIN(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
2918                       false)
2919 INITIALIZE_PASS_DEPENDENCY(IRSimilarityIdentifierWrapperPass)
2920 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
2921 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
2922 INITIALIZE_PASS_END(IROutlinerLegacyPass, "iroutliner", "IR Outliner", false,
2923                     false)
2924 
2925 ModulePass *llvm::createIROutlinerPass() { return new IROutlinerLegacyPass(); }
2926