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