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