Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1 | //===- CodeExtractor.cpp - Pull code region into a new function -----------===// |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 2 | // |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
Chris Lattner | f3ebc3f | 2007-12-29 20:36:04 +0000 | [diff] [blame] | 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 7 | // |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements the interface to tear out a code region, such as an |
| 11 | // individual loop or a parallel section, into a new function, replacing it with |
| 12 | // a call to the new function. |
| 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 16 | #include "llvm/Transforms/Utils/CodeExtractor.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/ArrayRef.h" |
| 18 | #include "llvm/ADT/DenseMap.h" |
| 19 | #include "llvm/ADT/Optional.h" |
Jakub Staszak | f23980a | 2013-02-09 01:04:28 +0000 | [diff] [blame] | 20 | #include "llvm/ADT/STLExtras.h" |
Chandler Carruth | 8a8cd2b | 2014-01-07 11:48:04 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/SetVector.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 22 | #include "llvm/ADT/SmallPtrSet.h" |
| 23 | #include "llvm/ADT/SmallVector.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 25 | #include "llvm/Analysis/BlockFrequencyInfoImpl.h" |
| 26 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/LoopInfo.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Argument.h" |
| 29 | #include "llvm/IR/Attributes.h" |
| 30 | #include "llvm/IR/BasicBlock.h" |
| 31 | #include "llvm/IR/CFG.h" |
| 32 | #include "llvm/IR/Constant.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Constants.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 34 | #include "llvm/IR/DataLayout.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 35 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 36 | #include "llvm/IR/Dominators.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Function.h" |
| 38 | #include "llvm/IR/GlobalValue.h" |
| 39 | #include "llvm/IR/InstrTypes.h" |
| 40 | #include "llvm/IR/Instruction.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 41 | #include "llvm/IR/Instructions.h" |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 42 | #include "llvm/IR/IntrinsicInst.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 43 | #include "llvm/IR/Intrinsics.h" |
| 44 | #include "llvm/IR/LLVMContext.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 45 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 46 | #include "llvm/IR/Module.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 47 | #include "llvm/IR/Type.h" |
| 48 | #include "llvm/IR/User.h" |
| 49 | #include "llvm/IR/Value.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 50 | #include "llvm/IR/Verifier.h" |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 51 | #include "llvm/Pass.h" |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 52 | #include "llvm/Support/BlockFrequency.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 53 | #include "llvm/Support/BranchProbability.h" |
| 54 | #include "llvm/Support/Casting.h" |
Reid Spencer | 7c16caa | 2004-09-01 22:55:40 +0000 | [diff] [blame] | 55 | #include "llvm/Support/CommandLine.h" |
| 56 | #include "llvm/Support/Debug.h" |
Torok Edwin | ccb29cd | 2009-07-11 13:10:19 +0000 | [diff] [blame] | 57 | #include "llvm/Support/ErrorHandling.h" |
Chris Lattner | b25de3f | 2009-08-23 04:37:46 +0000 | [diff] [blame] | 58 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 59 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Vedant Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 60 | #include "llvm/Transforms/Utils/Local.h" |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 61 | #include <cassert> |
| 62 | #include <cstdint> |
| 63 | #include <iterator> |
| 64 | #include <map> |
Chris Lattner | 9c431f6 | 2004-03-14 22:34:55 +0000 | [diff] [blame] | 65 | #include <set> |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 66 | #include <utility> |
| 67 | #include <vector> |
| 68 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 69 | using namespace llvm; |
Easwaran Raman | e5b8de2 | 2018-01-17 22:24:23 +0000 | [diff] [blame] | 70 | using ProfileCount = Function::ProfileCount; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 71 | |
Chandler Carruth | e96dd89 | 2014-04-21 22:55:11 +0000 | [diff] [blame] | 72 | #define DEBUG_TYPE "code-extractor" |
| 73 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 74 | // Provide a command-line option to aggregate function arguments into a struct |
Misha Brukman | 234b44a | 2008-12-13 05:21:37 +0000 | [diff] [blame] | 75 | // for functions produced by the code extractor. This is useful when converting |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 76 | // extracted functions to pthread-based code, as only one argument (void*) can |
| 77 | // be passed in to pthread_create(). |
| 78 | static cl::opt<bool> |
| 79 | AggregateArgsOpt("aggregate-extracted-args", cl::Hidden, |
| 80 | cl::desc("Aggregate arguments to code-extracted functions")); |
| 81 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 82 | /// Test whether a block is valid for extraction. |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 83 | static bool isBlockValidForExtraction(const BasicBlock &BB, |
| 84 | const SetVector<BasicBlock *> &Result, |
| 85 | bool AllowVarArgs, bool AllowAlloca) { |
Serge Guelton | 7bc405a | 2017-06-27 18:57:53 +0000 | [diff] [blame] | 86 | // taking the address of a basic block moved to another function is illegal |
| 87 | if (BB.hasAddressTaken()) |
| 88 | return false; |
| 89 | |
| 90 | // don't hoist code that uses another basicblock address, as it's likely to |
| 91 | // lead to unexpected behavior, like cross-function jumps |
| 92 | SmallPtrSet<User const *, 16> Visited; |
| 93 | SmallVector<User const *, 16> ToVisit; |
| 94 | |
| 95 | for (Instruction const &Inst : BB) |
| 96 | ToVisit.push_back(&Inst); |
| 97 | |
| 98 | while (!ToVisit.empty()) { |
| 99 | User const *Curr = ToVisit.pop_back_val(); |
| 100 | if (!Visited.insert(Curr).second) |
| 101 | continue; |
| 102 | if (isa<BlockAddress const>(Curr)) |
| 103 | return false; // even a reference to self is likely to be not compatible |
| 104 | |
| 105 | if (isa<Instruction>(Curr) && cast<Instruction>(Curr)->getParent() != &BB) |
| 106 | continue; |
| 107 | |
| 108 | for (auto const &U : Curr->operands()) { |
| 109 | if (auto *UU = dyn_cast<User>(U)) |
| 110 | ToVisit.push_back(UU); |
| 111 | } |
| 112 | } |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 113 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 114 | // If explicitly requested, allow vastart and alloca. For invoke instructions |
| 115 | // verify that extraction is valid. |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 116 | for (BasicBlock::const_iterator I = BB.begin(), E = BB.end(); I != E; ++I) { |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 117 | if (isa<AllocaInst>(I)) { |
| 118 | if (!AllowAlloca) |
| 119 | return false; |
| 120 | continue; |
| 121 | } |
| 122 | |
| 123 | if (const auto *II = dyn_cast<InvokeInst>(I)) { |
| 124 | // Unwind destination (either a landingpad, catchswitch, or cleanuppad) |
| 125 | // must be a part of the subgraph which is being extracted. |
| 126 | if (auto *UBB = II->getUnwindDest()) |
| 127 | if (!Result.count(UBB)) |
| 128 | return false; |
| 129 | continue; |
| 130 | } |
| 131 | |
| 132 | // All catch handlers of a catchswitch instruction as well as the unwind |
| 133 | // destination must be in the subgraph. |
| 134 | if (const auto *CSI = dyn_cast<CatchSwitchInst>(I)) { |
| 135 | if (auto *UBB = CSI->getUnwindDest()) |
| 136 | if (!Result.count(UBB)) |
| 137 | return false; |
| 138 | for (auto *HBB : CSI->handlers()) |
| 139 | if (!Result.count(const_cast<BasicBlock*>(HBB))) |
| 140 | return false; |
| 141 | continue; |
| 142 | } |
| 143 | |
| 144 | // Make sure that entire catch handler is within subgraph. It is sufficient |
| 145 | // to check that catch return's block is in the list. |
| 146 | if (const auto *CPI = dyn_cast<CatchPadInst>(I)) { |
| 147 | for (const auto *U : CPI->users()) |
| 148 | if (const auto *CRI = dyn_cast<CatchReturnInst>(U)) |
| 149 | if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) |
| 150 | return false; |
| 151 | continue; |
| 152 | } |
| 153 | |
| 154 | // And do similar checks for cleanup handler - the entire handler must be |
| 155 | // in subgraph which is going to be extracted. For cleanup return should |
| 156 | // additionally check that the unwind destination is also in the subgraph. |
| 157 | if (const auto *CPI = dyn_cast<CleanupPadInst>(I)) { |
| 158 | for (const auto *U : CPI->users()) |
| 159 | if (const auto *CRI = dyn_cast<CleanupReturnInst>(U)) |
| 160 | if (!Result.count(const_cast<BasicBlock*>(CRI->getParent()))) |
| 161 | return false; |
| 162 | continue; |
| 163 | } |
| 164 | if (const auto *CRI = dyn_cast<CleanupReturnInst>(I)) { |
| 165 | if (auto *UBB = CRI->getUnwindDest()) |
| 166 | if (!Result.count(UBB)) |
| 167 | return false; |
| 168 | continue; |
| 169 | } |
| 170 | |
Vedant Kumar | 1e209e2 | 2018-11-06 19:06:08 +0000 | [diff] [blame] | 171 | if (const CallInst *CI = dyn_cast<CallInst>(I)) { |
| 172 | if (const Function *F = CI->getCalledFunction()) { |
| 173 | auto IID = F->getIntrinsicID(); |
| 174 | if (IID == Intrinsic::vastart) { |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 175 | if (AllowVarArgs) |
| 176 | continue; |
| 177 | else |
| 178 | return false; |
| 179 | } |
Vedant Kumar | 1e209e2 | 2018-11-06 19:06:08 +0000 | [diff] [blame] | 180 | |
| 181 | // Currently, we miscompile outlined copies of eh_typid_for. There are |
| 182 | // proposals for fixing this in llvm.org/PR39545. |
| 183 | if (IID == Intrinsic::eh_typeid_for) |
| 184 | return false; |
| 185 | } |
| 186 | } |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 187 | } |
| 188 | |
| 189 | return true; |
| 190 | } |
| 191 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 192 | /// Build a set of blocks to extract if the input blocks are viable. |
Davide Italiano | 059574c | 2017-04-21 00:21:09 +0000 | [diff] [blame] | 193 | static SetVector<BasicBlock *> |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 194 | buildExtractionBlockSet(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 195 | bool AllowVarArgs, bool AllowAlloca) { |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 196 | assert(!BBs.empty() && "The set of blocks to extract must be non-empty"); |
Davide Italiano | 059574c | 2017-04-21 00:21:09 +0000 | [diff] [blame] | 197 | SetVector<BasicBlock *> Result; |
Chandler Carruth | 2f5d019 | 2012-05-04 10:26:45 +0000 | [diff] [blame] | 198 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 199 | // Loop over the blocks, adding them to our set-vector, and aborting with an |
| 200 | // empty set if we encounter invalid blocks. |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 201 | for (BasicBlock *BB : BBs) { |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 202 | // If this block is dead, don't process it. |
| 203 | if (DT && !DT->isReachableFromEntry(BB)) |
| 204 | continue; |
| 205 | |
| 206 | if (!Result.insert(BB)) |
| 207 | llvm_unreachable("Repeated basic blocks in extraction input"); |
Davide Italiano | fa15de3 | 2017-04-21 04:25:00 +0000 | [diff] [blame] | 208 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 209 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 210 | for (auto *BB : Result) { |
| 211 | if (!isBlockValidForExtraction(*BB, Result, AllowVarArgs, AllowAlloca)) |
| 212 | return {}; |
| 213 | |
| 214 | // Make sure that the first block is not a landing pad. |
| 215 | if (BB == Result.front()) { |
| 216 | if (BB->isEHPad()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 217 | LLVM_DEBUG(dbgs() << "The first block cannot be an unwind block\n"); |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 218 | return {}; |
| 219 | } |
| 220 | continue; |
| 221 | } |
| 222 | |
| 223 | // All blocks other than the first must not have predecessors outside of |
| 224 | // the subgraph which is being extracted. |
| 225 | for (auto *PBB : predecessors(BB)) |
| 226 | if (!Result.count(PBB)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 227 | LLVM_DEBUG( |
| 228 | dbgs() << "No blocks in this region may have entries from " |
| 229 | "outside the region except for the first block!\n"); |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 230 | return {}; |
| 231 | } |
| 232 | } |
Chandler Carruth | 2f5d019 | 2012-05-04 10:26:45 +0000 | [diff] [blame] | 233 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 234 | return Result; |
| 235 | } |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 236 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 237 | CodeExtractor::CodeExtractor(ArrayRef<BasicBlock *> BBs, DominatorTree *DT, |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 238 | bool AggregateArgs, BlockFrequencyInfo *BFI, |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 239 | BranchProbabilityInfo *BPI, bool AllowVarArgs, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 240 | bool AllowAlloca, std::string Suffix) |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 241 | : DT(DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 242 | BPI(BPI), AllowVarArgs(AllowVarArgs), |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 243 | Blocks(buildExtractionBlockSet(BBs, DT, AllowVarArgs, AllowAlloca)), |
| 244 | Suffix(Suffix) {} |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 245 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 246 | CodeExtractor::CodeExtractor(DominatorTree &DT, Loop &L, bool AggregateArgs, |
| 247 | BlockFrequencyInfo *BFI, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 248 | BranchProbabilityInfo *BPI, std::string Suffix) |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 249 | : DT(&DT), AggregateArgs(AggregateArgs || AggregateArgsOpt), BFI(BFI), |
Florian Hahn | 7114755 | 2017-11-13 11:08:47 +0000 | [diff] [blame] | 250 | BPI(BPI), AllowVarArgs(false), |
| 251 | Blocks(buildExtractionBlockSet(L.getBlocks(), &DT, |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 252 | /* AllowVarArgs */ false, |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 253 | /* AllowAlloca */ false)), |
| 254 | Suffix(Suffix) {} |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 255 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 256 | /// definedInRegion - Return true if the specified value is defined in the |
| 257 | /// extracted region. |
| 258 | static bool definedInRegion(const SetVector<BasicBlock *> &Blocks, Value *V) { |
| 259 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 260 | if (Blocks.count(I->getParent())) |
| 261 | return true; |
| 262 | return false; |
| 263 | } |
| 264 | |
| 265 | /// definedInCaller - Return true if the specified value is defined in the |
| 266 | /// function being code extracted, but not in the region being extracted. |
| 267 | /// These values must be passed in as live-ins to the function. |
| 268 | static bool definedInCaller(const SetVector<BasicBlock *> &Blocks, Value *V) { |
| 269 | if (isa<Argument>(V)) return true; |
| 270 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 271 | if (!Blocks.count(I->getParent())) |
| 272 | return true; |
| 273 | return false; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 274 | } |
| 275 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 276 | static BasicBlock *getCommonExitBlock(const SetVector<BasicBlock *> &Blocks) { |
| 277 | BasicBlock *CommonExitBlock = nullptr; |
| 278 | auto hasNonCommonExitSucc = [&](BasicBlock *Block) { |
| 279 | for (auto *Succ : successors(Block)) { |
| 280 | // Internal edges, ok. |
| 281 | if (Blocks.count(Succ)) |
| 282 | continue; |
| 283 | if (!CommonExitBlock) { |
| 284 | CommonExitBlock = Succ; |
| 285 | continue; |
| 286 | } |
| 287 | if (CommonExitBlock == Succ) |
| 288 | continue; |
| 289 | |
| 290 | return true; |
| 291 | } |
| 292 | return false; |
| 293 | }; |
| 294 | |
| 295 | if (any_of(Blocks, hasNonCommonExitSucc)) |
| 296 | return nullptr; |
| 297 | |
| 298 | return CommonExitBlock; |
| 299 | } |
| 300 | |
| 301 | bool CodeExtractor::isLegalToShrinkwrapLifetimeMarkers( |
| 302 | Instruction *Addr) const { |
| 303 | AllocaInst *AI = cast<AllocaInst>(Addr->stripInBoundsConstantOffsets()); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 304 | Function *Func = (*Blocks.begin())->getParent(); |
| 305 | for (BasicBlock &BB : *Func) { |
| 306 | if (Blocks.count(&BB)) |
| 307 | continue; |
| 308 | for (Instruction &II : BB) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 309 | if (isa<DbgInfoIntrinsic>(II)) |
| 310 | continue; |
| 311 | |
| 312 | unsigned Opcode = II.getOpcode(); |
| 313 | Value *MemAddr = nullptr; |
| 314 | switch (Opcode) { |
| 315 | case Instruction::Store: |
| 316 | case Instruction::Load: { |
| 317 | if (Opcode == Instruction::Store) { |
| 318 | StoreInst *SI = cast<StoreInst>(&II); |
| 319 | MemAddr = SI->getPointerOperand(); |
| 320 | } else { |
| 321 | LoadInst *LI = cast<LoadInst>(&II); |
| 322 | MemAddr = LI->getPointerOperand(); |
| 323 | } |
| 324 | // Global variable can not be aliased with locals. |
| 325 | if (dyn_cast<Constant>(MemAddr)) |
| 326 | break; |
| 327 | Value *Base = MemAddr->stripInBoundsConstantOffsets(); |
| 328 | if (!dyn_cast<AllocaInst>(Base) || Base == AI) |
| 329 | return false; |
| 330 | break; |
| 331 | } |
| 332 | default: { |
| 333 | IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(&II); |
| 334 | if (IntrInst) { |
| 335 | if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start || |
| 336 | IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) |
| 337 | break; |
| 338 | return false; |
| 339 | } |
| 340 | // Treat all the other cases conservatively if it has side effects. |
| 341 | if (II.mayHaveSideEffects()) |
| 342 | return false; |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | return true; |
| 349 | } |
| 350 | |
| 351 | BasicBlock * |
| 352 | CodeExtractor::findOrCreateBlockForHoisting(BasicBlock *CommonExitBlock) { |
| 353 | BasicBlock *SinglePredFromOutlineRegion = nullptr; |
| 354 | assert(!Blocks.count(CommonExitBlock) && |
| 355 | "Expect a block outside the region!"); |
| 356 | for (auto *Pred : predecessors(CommonExitBlock)) { |
| 357 | if (!Blocks.count(Pred)) |
| 358 | continue; |
| 359 | if (!SinglePredFromOutlineRegion) { |
| 360 | SinglePredFromOutlineRegion = Pred; |
| 361 | } else if (SinglePredFromOutlineRegion != Pred) { |
| 362 | SinglePredFromOutlineRegion = nullptr; |
| 363 | break; |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | if (SinglePredFromOutlineRegion) |
| 368 | return SinglePredFromOutlineRegion; |
| 369 | |
| 370 | #ifndef NDEBUG |
| 371 | auto getFirstPHI = [](BasicBlock *BB) { |
| 372 | BasicBlock::iterator I = BB->begin(); |
| 373 | PHINode *FirstPhi = nullptr; |
| 374 | while (I != BB->end()) { |
| 375 | PHINode *Phi = dyn_cast<PHINode>(I); |
| 376 | if (!Phi) |
| 377 | break; |
| 378 | if (!FirstPhi) { |
| 379 | FirstPhi = Phi; |
| 380 | break; |
| 381 | } |
| 382 | } |
| 383 | return FirstPhi; |
| 384 | }; |
| 385 | // If there are any phi nodes, the single pred either exists or has already |
| 386 | // be created before code extraction. |
| 387 | assert(!getFirstPHI(CommonExitBlock) && "Phi not expected"); |
| 388 | #endif |
| 389 | |
| 390 | BasicBlock *NewExitBlock = CommonExitBlock->splitBasicBlock( |
| 391 | CommonExitBlock->getFirstNonPHI()->getIterator()); |
| 392 | |
Florian Hahn | b93c063 | 2017-11-01 09:48:12 +0000 | [diff] [blame] | 393 | for (auto PI = pred_begin(CommonExitBlock), PE = pred_end(CommonExitBlock); |
| 394 | PI != PE;) { |
| 395 | BasicBlock *Pred = *PI++; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 396 | if (Blocks.count(Pred)) |
| 397 | continue; |
| 398 | Pred->getTerminator()->replaceUsesOfWith(CommonExitBlock, NewExitBlock); |
| 399 | } |
| 400 | // Now add the old exit block to the outline region. |
| 401 | Blocks.insert(CommonExitBlock); |
| 402 | return CommonExitBlock; |
| 403 | } |
| 404 | |
| 405 | void CodeExtractor::findAllocas(ValueSet &SinkCands, ValueSet &HoistCands, |
| 406 | BasicBlock *&ExitBlock) const { |
| 407 | Function *Func = (*Blocks.begin())->getParent(); |
| 408 | ExitBlock = getCommonExitBlock(Blocks); |
| 409 | |
| 410 | for (BasicBlock &BB : *Func) { |
| 411 | if (Blocks.count(&BB)) |
| 412 | continue; |
| 413 | for (Instruction &II : BB) { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 414 | auto *AI = dyn_cast<AllocaInst>(&II); |
| 415 | if (!AI) |
| 416 | continue; |
| 417 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 418 | // Find the pair of life time markers for address 'Addr' that are either |
| 419 | // defined inside the outline region or can legally be shrinkwrapped into |
| 420 | // the outline region. If there are not other untracked uses of the |
| 421 | // address, return the pair of markers if found; otherwise return a pair |
| 422 | // of nullptr. |
| 423 | auto GetLifeTimeMarkers = |
| 424 | [&](Instruction *Addr, bool &SinkLifeStart, |
| 425 | bool &HoistLifeEnd) -> std::pair<Instruction *, Instruction *> { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 426 | Instruction *LifeStart = nullptr, *LifeEnd = nullptr; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 427 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 428 | for (User *U : Addr->users()) { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 429 | IntrinsicInst *IntrInst = dyn_cast<IntrinsicInst>(U); |
| 430 | if (IntrInst) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 431 | if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_start) { |
| 432 | // Do not handle the case where AI has multiple start markers. |
| 433 | if (LifeStart) |
| 434 | return std::make_pair<Instruction *>(nullptr, nullptr); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 435 | LifeStart = IntrInst; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 436 | } |
| 437 | if (IntrInst->getIntrinsicID() == Intrinsic::lifetime_end) { |
| 438 | if (LifeEnd) |
| 439 | return std::make_pair<Instruction *>(nullptr, nullptr); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 440 | LifeEnd = IntrInst; |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 441 | } |
| 442 | continue; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 443 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 444 | // Find untracked uses of the address, bail. |
| 445 | if (!definedInRegion(Blocks, U)) |
| 446 | return std::make_pair<Instruction *>(nullptr, nullptr); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 447 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 448 | |
| 449 | if (!LifeStart || !LifeEnd) |
| 450 | return std::make_pair<Instruction *>(nullptr, nullptr); |
| 451 | |
| 452 | SinkLifeStart = !definedInRegion(Blocks, LifeStart); |
| 453 | HoistLifeEnd = !definedInRegion(Blocks, LifeEnd); |
| 454 | // Do legality Check. |
| 455 | if ((SinkLifeStart || HoistLifeEnd) && |
| 456 | !isLegalToShrinkwrapLifetimeMarkers(Addr)) |
| 457 | return std::make_pair<Instruction *>(nullptr, nullptr); |
| 458 | |
| 459 | // Check to see if we have a place to do hoisting, if not, bail. |
| 460 | if (HoistLifeEnd && !ExitBlock) |
| 461 | return std::make_pair<Instruction *>(nullptr, nullptr); |
| 462 | |
| 463 | return std::make_pair(LifeStart, LifeEnd); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 464 | }; |
| 465 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 466 | bool SinkLifeStart = false, HoistLifeEnd = false; |
| 467 | auto Markers = GetLifeTimeMarkers(AI, SinkLifeStart, HoistLifeEnd); |
| 468 | |
| 469 | if (Markers.first) { |
| 470 | if (SinkLifeStart) |
| 471 | SinkCands.insert(Markers.first); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 472 | SinkCands.insert(AI); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 473 | if (HoistLifeEnd) |
| 474 | HoistCands.insert(Markers.second); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 475 | continue; |
| 476 | } |
| 477 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 478 | // Follow the bitcast. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 479 | Instruction *MarkerAddr = nullptr; |
| 480 | for (User *U : AI->users()) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 481 | if (U->stripInBoundsConstantOffsets() == AI) { |
| 482 | SinkLifeStart = false; |
| 483 | HoistLifeEnd = false; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 484 | Instruction *Bitcast = cast<Instruction>(U); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 485 | Markers = GetLifeTimeMarkers(Bitcast, SinkLifeStart, HoistLifeEnd); |
| 486 | if (Markers.first) { |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 487 | MarkerAddr = Bitcast; |
| 488 | continue; |
| 489 | } |
| 490 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 491 | |
| 492 | // Found unknown use of AI. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 493 | if (!definedInRegion(Blocks, U)) { |
| 494 | MarkerAddr = nullptr; |
| 495 | break; |
| 496 | } |
| 497 | } |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 498 | |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 499 | if (MarkerAddr) { |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 500 | if (SinkLifeStart) |
| 501 | SinkCands.insert(Markers.first); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 502 | if (!definedInRegion(Blocks, MarkerAddr)) |
| 503 | SinkCands.insert(MarkerAddr); |
| 504 | SinkCands.insert(AI); |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 505 | if (HoistLifeEnd) |
| 506 | HoistCands.insert(Markers.second); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 507 | } |
| 508 | } |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | void CodeExtractor::findInputsOutputs(ValueSet &Inputs, ValueSet &Outputs, |
| 513 | const ValueSet &SinkCands) const { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 514 | for (BasicBlock *BB : Blocks) { |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 515 | // If a used value is defined outside the region, it's an input. If an |
| 516 | // instruction is used outside the region, it's an output. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 517 | for (Instruction &II : *BB) { |
| 518 | for (User::op_iterator OI = II.op_begin(), OE = II.op_end(); OI != OE; |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 519 | ++OI) { |
| 520 | Value *V = *OI; |
| 521 | if (!SinkCands.count(V) && definedInCaller(Blocks, V)) |
| 522 | Inputs.insert(V); |
| 523 | } |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 524 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 525 | for (User *U : II.users()) |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 526 | if (!definedInRegion(Blocks, U)) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 527 | Outputs.insert(&II); |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 528 | break; |
| 529 | } |
| 530 | } |
| 531 | } |
| 532 | } |
| 533 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 534 | /// severSplitPHINodes - If a PHI node has multiple inputs from outside of the |
| 535 | /// region, we need to split the entry block of the region so that the PHI node |
| 536 | /// is easier to deal with. |
| 537 | void CodeExtractor::severSplitPHINodes(BasicBlock *&Header) { |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 538 | unsigned NumPredsFromRegion = 0; |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 539 | unsigned NumPredsOutsideRegion = 0; |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 540 | |
Dan Gohman | dcb291f | 2007-03-22 16:38:57 +0000 | [diff] [blame] | 541 | if (Header != &Header->getParent()->getEntryBlock()) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 542 | PHINode *PN = dyn_cast<PHINode>(Header->begin()); |
| 543 | if (!PN) return; // No PHI nodes. |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 544 | |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 545 | // If the header node contains any PHI nodes, check to see if there is more |
| 546 | // than one entry from outside the region. If so, we need to sever the |
| 547 | // header block into two. |
| 548 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 549 | if (Blocks.count(PN->getIncomingBlock(i))) |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 550 | ++NumPredsFromRegion; |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 551 | else |
| 552 | ++NumPredsOutsideRegion; |
| 553 | |
| 554 | // If there is one (or fewer) predecessor from outside the region, we don't |
| 555 | // need to do anything special. |
| 556 | if (NumPredsOutsideRegion <= 1) return; |
| 557 | } |
| 558 | |
| 559 | // Otherwise, we need to split the header block into two pieces: one |
| 560 | // containing PHI nodes merging values from outside of the region, and a |
| 561 | // second that contains all of the code for the block and merges back any |
| 562 | // incoming values from inside of the region. |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 563 | BasicBlock *NewBB = SplitBlock(Header, Header->getFirstNonPHI(), DT); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 564 | |
| 565 | // We only want to code extract the second block now, and it becomes the new |
| 566 | // header of the region. |
| 567 | BasicBlock *OldPred = Header; |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 568 | Blocks.remove(OldPred); |
| 569 | Blocks.insert(NewBB); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 570 | Header = NewBB; |
| 571 | |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 572 | // Okay, now we need to adjust the PHI nodes and any branches from within the |
| 573 | // region to go to the new header block instead of the old header block. |
Jay Foad | e0938d8 | 2011-03-30 11:19:20 +0000 | [diff] [blame] | 574 | if (NumPredsFromRegion) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 575 | PHINode *PN = cast<PHINode>(OldPred->begin()); |
| 576 | // Loop over all of the predecessors of OldPred that are in the region, |
| 577 | // changing them to branch to NewBB instead. |
| 578 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 579 | if (Blocks.count(PN->getIncomingBlock(i))) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 580 | Instruction *TI = PN->getIncomingBlock(i)->getTerminator(); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 581 | TI->replaceUsesOfWith(OldPred, NewBB); |
| 582 | } |
| 583 | |
Chris Lattner | 0ab5e2c | 2011-04-15 05:18:47 +0000 | [diff] [blame] | 584 | // Okay, everything within the region is now branching to the right block, we |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 585 | // just have to update the PHI nodes now, inserting PHI nodes into NewBB. |
Xinliang David Li | 99e3ca1 | 2017-04-20 21:40:22 +0000 | [diff] [blame] | 586 | BasicBlock::iterator AfterPHIs; |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 587 | for (AfterPHIs = OldPred->begin(); isa<PHINode>(AfterPHIs); ++AfterPHIs) { |
| 588 | PHINode *PN = cast<PHINode>(AfterPHIs); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 589 | // Create a new PHI node in the new region, which has an incoming value |
| 590 | // from OldPred of PN. |
Jay Foad | 5213134 | 2011-03-30 11:28:46 +0000 | [diff] [blame] | 591 | PHINode *NewPN = PHINode::Create(PN->getType(), 1 + NumPredsFromRegion, |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 592 | PN->getName() + ".ce", &NewBB->front()); |
Xinliang David Li | f12a0fa | 2017-04-25 04:51:19 +0000 | [diff] [blame] | 593 | PN->replaceAllUsesWith(NewPN); |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 594 | NewPN->addIncoming(PN, OldPred); |
| 595 | |
| 596 | // Loop over all of the incoming value in PN, moving them to NewPN if they |
| 597 | // are from the extracted region. |
| 598 | for (unsigned i = 0; i != PN->getNumIncomingValues(); ++i) { |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 599 | if (Blocks.count(PN->getIncomingBlock(i))) { |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 600 | NewPN->addIncoming(PN->getIncomingValue(i), PN->getIncomingBlock(i)); |
| 601 | PN->removeIncomingValue(i); |
| 602 | --i; |
| 603 | } |
| 604 | } |
| 605 | } |
| 606 | } |
Chris Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 607 | } |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 608 | |
Chris Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 609 | void CodeExtractor::splitReturnBlocks() { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 610 | for (BasicBlock *Block : Blocks) |
| 611 | if (ReturnInst *RI = dyn_cast<ReturnInst>(Block->getTerminator())) { |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 612 | BasicBlock *New = |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 613 | Block->splitBasicBlock(RI->getIterator(), Block->getName() + ".ret"); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 614 | if (DT) { |
Gabor Greif | 2f5f696 | 2010-09-10 22:25:58 +0000 | [diff] [blame] | 615 | // Old dominates New. New node dominates all other nodes dominated |
| 616 | // by Old. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 617 | DomTreeNode *OldNode = DT->getNode(Block); |
| 618 | SmallVector<DomTreeNode *, 8> Children(OldNode->begin(), |
| 619 | OldNode->end()); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 620 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 621 | DomTreeNode *NewNode = DT->addNewBlock(New, Block); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 622 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 623 | for (DomTreeNode *I : Children) |
| 624 | DT->changeImmediateDominator(I, NewNode); |
Owen Anderson | b4aa5b1 | 2009-08-24 23:32:14 +0000 | [diff] [blame] | 625 | } |
| 626 | } |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 627 | } |
| 628 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 629 | /// constructFunction - make a function based on inputs and outputs, as follows: |
| 630 | /// f(in0, ..., inN, out0, ..., outN) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 631 | Function *CodeExtractor::constructFunction(const ValueSet &inputs, |
| 632 | const ValueSet &outputs, |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 633 | BasicBlock *header, |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 634 | BasicBlock *newRootNode, |
| 635 | BasicBlock *newHeader, |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 636 | Function *oldFunction, |
| 637 | Module *M) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 638 | LLVM_DEBUG(dbgs() << "inputs: " << inputs.size() << "\n"); |
| 639 | LLVM_DEBUG(dbgs() << "outputs: " << outputs.size() << "\n"); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 640 | |
| 641 | // This function returns unsigned, outputs will go back by reference. |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 642 | switch (NumExitBlocks) { |
| 643 | case 0: |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 644 | case 1: RetTy = Type::getVoidTy(header->getContext()); break; |
| 645 | case 2: RetTy = Type::getInt1Ty(header->getContext()); break; |
| 646 | default: RetTy = Type::getInt16Ty(header->getContext()); break; |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 647 | } |
| 648 | |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 649 | std::vector<Type *> paramTy; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 650 | |
| 651 | // Add the types of the input values to the function's argument list |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 652 | for (Value *value : inputs) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 653 | LLVM_DEBUG(dbgs() << "value used in func: " << *value << "\n"); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 654 | paramTy.push_back(value->getType()); |
| 655 | } |
| 656 | |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 657 | // Add the types of the output values to the function's argument list. |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 658 | for (Value *output : outputs) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 659 | LLVM_DEBUG(dbgs() << "instr used in func: " << *output << "\n"); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 660 | if (AggregateArgs) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 661 | paramTy.push_back(output->getType()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 662 | else |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 663 | paramTy.push_back(PointerType::getUnqual(output->getType())); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 664 | } |
| 665 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 666 | LLVM_DEBUG({ |
Benjamin Kramer | 706e4883 | 2016-06-26 13:39:33 +0000 | [diff] [blame] | 667 | dbgs() << "Function type: " << *RetTy << " f("; |
| 668 | for (Type *i : paramTy) |
| 669 | dbgs() << *i << ", "; |
| 670 | dbgs() << ")\n"; |
| 671 | }); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 672 | |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 673 | StructType *StructTy; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 674 | if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 675 | StructTy = StructType::get(M->getContext(), paramTy); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 676 | paramTy.clear(); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 677 | paramTy.push_back(PointerType::getUnqual(StructTy)); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 678 | } |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 679 | FunctionType *funcType = |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 680 | FunctionType::get(RetTy, paramTy, |
| 681 | AllowVarArgs && oldFunction->isVarArg()); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 682 | |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 683 | std::string SuffixToUse = |
| 684 | Suffix.empty() |
| 685 | ? (header->getName().empty() ? "extracted" : header->getName().str()) |
| 686 | : Suffix; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 687 | // Create the new function |
Alexander Richardson | 6bcf2ba | 2018-08-23 09:25:17 +0000 | [diff] [blame] | 688 | Function *newFunction = Function::Create( |
| 689 | funcType, GlobalValue::InternalLinkage, oldFunction->getAddressSpace(), |
Teresa Johnson | c8dba68 | 2018-10-24 18:53:47 +0000 | [diff] [blame] | 690 | oldFunction->getName() + "." + SuffixToUse, M); |
Chris Lattner | 4caf5eb | 2008-12-18 05:52:56 +0000 | [diff] [blame] | 691 | // If the old function is no-throw, so is the new one. |
| 692 | if (oldFunction->doesNotThrow()) |
Bill Wendling | f319e99 | 2012-10-10 03:12:49 +0000 | [diff] [blame] | 693 | newFunction->setDoesNotThrow(); |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 694 | |
| 695 | // Inherit the uwtable attribute if we need to. |
| 696 | if (oldFunction->hasUWTable()) |
| 697 | newFunction->setHasUWTable(); |
| 698 | |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 699 | // Inherit all of the target dependent attributes and white-listed |
| 700 | // target independent attributes. |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 701 | // (e.g. If the extracted region contains a call to an x86.sse |
| 702 | // instruction we need to make sure that the extracted region has the |
| 703 | // "target-features" attribute allowing it to be lowered. |
| 704 | // FIXME: This should be changed to check to see if a specific |
| 705 | // attribute can not be inherited. |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 706 | for (const auto &Attr : oldFunction->getAttributes().getFnAttributes()) { |
| 707 | if (Attr.isStringAttribute()) { |
| 708 | if (Attr.getKindAsString() == "thunk") |
| 709 | continue; |
| 710 | } else |
| 711 | switch (Attr.getKindAsEnum()) { |
| 712 | // Those attributes cannot be propagated safely. Explicitly list them |
| 713 | // here so we get a warning if new attributes are added. This list also |
| 714 | // includes non-function attributes. |
| 715 | case Attribute::Alignment: |
| 716 | case Attribute::AllocSize: |
| 717 | case Attribute::ArgMemOnly: |
| 718 | case Attribute::Builtin: |
| 719 | case Attribute::ByVal: |
| 720 | case Attribute::Convergent: |
| 721 | case Attribute::Dereferenceable: |
| 722 | case Attribute::DereferenceableOrNull: |
| 723 | case Attribute::InAlloca: |
| 724 | case Attribute::InReg: |
| 725 | case Attribute::InaccessibleMemOnly: |
| 726 | case Attribute::InaccessibleMemOrArgMemOnly: |
| 727 | case Attribute::JumpTable: |
| 728 | case Attribute::Naked: |
| 729 | case Attribute::Nest: |
| 730 | case Attribute::NoAlias: |
| 731 | case Attribute::NoBuiltin: |
| 732 | case Attribute::NoCapture: |
| 733 | case Attribute::NoReturn: |
| 734 | case Attribute::None: |
| 735 | case Attribute::NonNull: |
| 736 | case Attribute::ReadNone: |
| 737 | case Attribute::ReadOnly: |
| 738 | case Attribute::Returned: |
| 739 | case Attribute::ReturnsTwice: |
| 740 | case Attribute::SExt: |
| 741 | case Attribute::Speculatable: |
| 742 | case Attribute::StackAlignment: |
| 743 | case Attribute::StructRet: |
| 744 | case Attribute::SwiftError: |
| 745 | case Attribute::SwiftSelf: |
| 746 | case Attribute::WriteOnly: |
| 747 | case Attribute::ZExt: |
| 748 | case Attribute::EndAttrKinds: |
| 749 | continue; |
| 750 | // Those attributes should be safe to propagate to the extracted function. |
| 751 | case Attribute::AlwaysInline: |
| 752 | case Attribute::Cold: |
| 753 | case Attribute::NoRecurse: |
| 754 | case Attribute::InlineHint: |
| 755 | case Attribute::MinSize: |
| 756 | case Attribute::NoDuplicate: |
| 757 | case Attribute::NoImplicitFloat: |
| 758 | case Attribute::NoInline: |
| 759 | case Attribute::NonLazyBind: |
| 760 | case Attribute::NoRedZone: |
| 761 | case Attribute::NoUnwind: |
Matt Morehouse | 236cdaf | 2018-03-22 17:07:51 +0000 | [diff] [blame] | 762 | case Attribute::OptForFuzzing: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 763 | case Attribute::OptimizeNone: |
| 764 | case Attribute::OptimizeForSize: |
| 765 | case Attribute::SafeStack: |
Vlad Tsyrklevich | d17f61e | 2018-04-03 20:10:40 +0000 | [diff] [blame] | 766 | case Attribute::ShadowCallStack: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 767 | case Attribute::SanitizeAddress: |
| 768 | case Attribute::SanitizeMemory: |
| 769 | case Attribute::SanitizeThread: |
| 770 | case Attribute::SanitizeHWAddress: |
Chandler Carruth | 664aa86 | 2018-09-04 12:38:00 +0000 | [diff] [blame] | 771 | case Attribute::SpeculativeLoadHardening: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 772 | case Attribute::StackProtect: |
| 773 | case Attribute::StackProtectReq: |
| 774 | case Attribute::StackProtectStrong: |
| 775 | case Attribute::StrictFP: |
| 776 | case Attribute::UWTable: |
Oren Ben Simhon | fdd72fd | 2018-03-17 13:29:46 +0000 | [diff] [blame] | 777 | case Attribute::NoCfCheck: |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 778 | break; |
| 779 | } |
Sean Silva | a0a802a | 2016-08-01 03:15:32 +0000 | [diff] [blame] | 780 | |
Florian Hahn | 55be37e | 2018-01-07 11:22:25 +0000 | [diff] [blame] | 781 | newFunction->addFnAttr(Attr); |
| 782 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 783 | newFunction->getBasicBlockList().push_back(newRootNode); |
| 784 | |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 785 | // Create an iterator to name all of the arguments we inserted. |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 786 | Function::arg_iterator AI = newFunction->arg_begin(); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 787 | |
| 788 | // Rewrite all users of the inputs in the extracted region to use the |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 789 | // arguments (or appropriate addressing into struct) instead. |
| 790 | for (unsigned i = 0, e = inputs.size(); i != e; ++i) { |
| 791 | Value *RewriteVal; |
| 792 | if (AggregateArgs) { |
David Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 793 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 794 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(header->getContext())); |
| 795 | Idx[1] = ConstantInt::get(Type::getInt32Ty(header->getContext()), i); |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 796 | Instruction *TI = newFunction->begin()->getTerminator(); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 797 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 798 | StructTy, &*AI, Idx, "gep_" + inputs[i]->getName(), TI); |
Daniel Dunbar | 12368685 | 2009-07-24 08:24:36 +0000 | [diff] [blame] | 799 | RewriteVal = new LoadInst(GEP, "loadgep_" + inputs[i]->getName(), TI); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 800 | } else |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 801 | RewriteVal = &*AI++; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 802 | |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 803 | std::vector<User *> Users(inputs[i]->user_begin(), inputs[i]->user_end()); |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 804 | for (User *use : Users) |
| 805 | if (Instruction *inst = dyn_cast<Instruction>(use)) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 806 | if (Blocks.count(inst->getParent())) |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 807 | inst->replaceUsesOfWith(inputs[i], RewriteVal); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 808 | } |
| 809 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 810 | // Set names for input and output arguments. |
| 811 | if (!AggregateArgs) { |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 812 | AI = newFunction->arg_begin(); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 813 | for (unsigned i = 0, e = inputs.size(); i != e; ++i, ++AI) |
Owen Anderson | 7629b71 | 2008-04-14 17:38:21 +0000 | [diff] [blame] | 814 | AI->setName(inputs[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 815 | for (unsigned i = 0, e = outputs.size(); i != e; ++i, ++AI) |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 816 | AI->setName(outputs[i]->getName()+".out"); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 817 | } |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 818 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 819 | // Rewrite branches to basic blocks outside of the loop to new dummy blocks |
| 820 | // within the new function. This must be done before we lose track of which |
| 821 | // blocks were originally in the code region. |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 822 | std::vector<User *> Users(header->user_begin(), header->user_end()); |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 823 | for (unsigned i = 0, e = Users.size(); i != e; ++i) |
| 824 | // The BasicBlock which contains the branch is not in the region |
| 825 | // modify the branch target to a new block |
Chandler Carruth | 8b7a812 | 2018-10-18 00:38:54 +0000 | [diff] [blame] | 826 | if (Instruction *I = dyn_cast<Instruction>(Users[i])) |
| 827 | if (I->isTerminator() && !Blocks.count(I->getParent()) && |
| 828 | I->getParent()->getParent() == oldFunction) |
| 829 | I->replaceUsesOfWith(header, newHeader); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 830 | |
| 831 | return newFunction; |
| 832 | } |
| 833 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 834 | /// emitCallAndSwitchStatement - This method sets up the caller side by adding |
| 835 | /// the call instruction, splitting any PHI nodes in the header block as |
| 836 | /// necessary. |
| 837 | void CodeExtractor:: |
| 838 | emitCallAndSwitchStatement(Function *newFunction, BasicBlock *codeReplacer, |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 839 | ValueSet &inputs, ValueSet &outputs) { |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 840 | // Emit a call to the new function, passing in: *pointer to struct (if |
| 841 | // aggregating parameters), or plan inputs and allocated memory for outputs |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 842 | std::vector<Value *> params, StructValues, ReloadOutputs, Reloads; |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 843 | |
| 844 | Module *M = newFunction->getParent(); |
| 845 | LLVMContext &Context = M->getContext(); |
| 846 | const DataLayout &DL = M->getDataLayout(); |
Chris Lattner | d8017a3 | 2004-03-18 04:12:05 +0000 | [diff] [blame] | 847 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 848 | // Add inputs as params, or to be filled into the struct |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 849 | for (Value *input : inputs) |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 850 | if (AggregateArgs) |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 851 | StructValues.push_back(input); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 852 | else |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 853 | params.push_back(input); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 854 | |
| 855 | // Create allocas for the outputs |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 856 | for (Value *output : outputs) { |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 857 | if (AggregateArgs) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 858 | StructValues.push_back(output); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 859 | } else { |
| 860 | AllocaInst *alloca = |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 861 | new AllocaInst(output->getType(), DL.getAllocaAddrSpace(), |
| 862 | nullptr, output->getName() + ".loc", |
| 863 | &codeReplacer->getParent()->front().front()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 864 | ReloadOutputs.push_back(alloca); |
| 865 | params.push_back(alloca); |
| 866 | } |
| 867 | } |
| 868 | |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 869 | StructType *StructArgTy = nullptr; |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 870 | AllocaInst *Struct = nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 871 | if (AggregateArgs && (inputs.size() + outputs.size() > 0)) { |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 872 | std::vector<Type *> ArgTypes; |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 873 | for (ValueSet::iterator v = StructValues.begin(), |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 874 | ve = StructValues.end(); v != ve; ++v) |
| 875 | ArgTypes.push_back((*v)->getType()); |
| 876 | |
| 877 | // Allocate a struct at the beginning of this function |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 878 | StructArgTy = StructType::get(newFunction->getContext(), ArgTypes); |
Matt Arsenault | 3c1fc76 | 2017-04-10 22:27:50 +0000 | [diff] [blame] | 879 | Struct = new AllocaInst(StructArgTy, DL.getAllocaAddrSpace(), nullptr, |
| 880 | "structArg", |
Duncan P. N. Exon Smith | 5b4c837 | 2015-10-13 02:39:05 +0000 | [diff] [blame] | 881 | &codeReplacer->getParent()->front().front()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 882 | params.push_back(Struct); |
| 883 | |
| 884 | for (unsigned i = 0, e = inputs.size(); i != e; ++i) { |
David Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 885 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 886 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); |
| 887 | Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), i); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 888 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 889 | StructArgTy, Struct, Idx, "gep_" + StructValues[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 890 | codeReplacer->getInstList().push_back(GEP); |
| 891 | StoreInst *SI = new StoreInst(StructValues[i], GEP); |
| 892 | codeReplacer->getInstList().push_back(SI); |
| 893 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 894 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 895 | |
| 896 | // Emit the call to the function |
Jay Foad | 5bd375a | 2011-07-15 08:37:34 +0000 | [diff] [blame] | 897 | CallInst *call = CallInst::Create(newFunction, params, |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 898 | NumExitBlocks > 1 ? "targetBlock" : ""); |
Florian Hahn | e5089e2 | 2017-12-08 21:49:03 +0000 | [diff] [blame] | 899 | // Add debug location to the new call, if the original function has debug |
| 900 | // info. In that case, the terminator of the entry block of the extracted |
| 901 | // function contains the first debug location of the extracted function, |
| 902 | // set in extractCodeRegion. |
| 903 | if (codeReplacer->getParent()->getSubprogram()) { |
| 904 | if (auto DL = newFunction->getEntryBlock().getTerminator()->getDebugLoc()) |
| 905 | call->setDebugLoc(DL); |
| 906 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 907 | codeReplacer->getInstList().push_back(call); |
| 908 | |
Chris Lattner | 531f9e9 | 2005-03-15 04:54:21 +0000 | [diff] [blame] | 909 | Function::arg_iterator OutputArgBegin = newFunction->arg_begin(); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 910 | unsigned FirstOut = inputs.size(); |
| 911 | if (!AggregateArgs) |
| 912 | std::advance(OutputArgBegin, inputs.size()); |
| 913 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 914 | // Reload the outputs passed in by reference. |
| 915 | Function::arg_iterator OAI = OutputArgBegin; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 916 | for (unsigned i = 0, e = outputs.size(); i != e; ++i) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 917 | Value *Output = nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 918 | if (AggregateArgs) { |
David Greene | c656cbb | 2007-09-04 15:46:09 +0000 | [diff] [blame] | 919 | Value *Idx[2]; |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 920 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); |
| 921 | Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); |
David Blaikie | 741c8f8 | 2015-03-14 01:53:18 +0000 | [diff] [blame] | 922 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 923 | StructArgTy, Struct, Idx, "gep_reload_" + outputs[i]->getName()); |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 924 | codeReplacer->getInstList().push_back(GEP); |
| 925 | Output = GEP; |
| 926 | } else { |
| 927 | Output = ReloadOutputs[i]; |
| 928 | } |
| 929 | LoadInst *load = new LoadInst(Output, outputs[i]->getName()+".reload"); |
Owen Anderson | 34e6148 | 2009-08-25 00:54:39 +0000 | [diff] [blame] | 930 | Reloads.push_back(load); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 931 | codeReplacer->getInstList().push_back(load); |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 932 | std::vector<User *> Users(outputs[i]->user_begin(), outputs[i]->user_end()); |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 933 | for (unsigned u = 0, e = Users.size(); u != e; ++u) { |
| 934 | Instruction *inst = cast<Instruction>(Users[u]); |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 935 | if (!Blocks.count(inst->getParent())) |
Chris Lattner | 37de257 | 2004-03-18 03:49:40 +0000 | [diff] [blame] | 936 | inst->replaceUsesOfWith(outputs[i], load); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 937 | } |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 938 | |
| 939 | // Store to argument right after the definition of output value. |
| 940 | auto *OutI = dyn_cast<Instruction>(outputs[i]); |
| 941 | if (!OutI) |
| 942 | continue; |
Florian Hahn | 7cdf52e | 2018-08-21 20:07:46 +0000 | [diff] [blame] | 943 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 944 | // Find proper insertion point. |
Florian Hahn | 7cdf52e | 2018-08-21 20:07:46 +0000 | [diff] [blame] | 945 | Instruction *InsertPt; |
| 946 | // In case OutI is an invoke, we insert the store at the beginning in the |
| 947 | // 'normal destination' BB. Otherwise we insert the store right after OutI. |
| 948 | if (auto *InvokeI = dyn_cast<InvokeInst>(OutI)) |
| 949 | InsertPt = InvokeI->getNormalDest()->getFirstNonPHI(); |
| 950 | else |
| 951 | InsertPt = OutI->getNextNode(); |
| 952 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 953 | // Let's assume that there is no other guy interleave non-PHI in PHIs. |
| 954 | if (isa<PHINode>(InsertPt)) |
| 955 | InsertPt = InsertPt->getParent()->getFirstNonPHI(); |
| 956 | |
| 957 | assert(OAI != newFunction->arg_end() && |
| 958 | "Number of output arguments should match " |
| 959 | "the amount of defined values"); |
| 960 | if (AggregateArgs) { |
| 961 | Value *Idx[2]; |
| 962 | Idx[0] = Constant::getNullValue(Type::getInt32Ty(Context)); |
| 963 | Idx[1] = ConstantInt::get(Type::getInt32Ty(Context), FirstOut + i); |
| 964 | GetElementPtrInst *GEP = GetElementPtrInst::Create( |
| 965 | StructArgTy, &*OAI, Idx, "gep_" + outputs[i]->getName(), InsertPt); |
| 966 | new StoreInst(outputs[i], GEP, InsertPt); |
| 967 | // Since there should be only one struct argument aggregating |
| 968 | // all the output values, we shouldn't increment OAI, which always |
| 969 | // points to the struct argument, in this case. |
| 970 | } else { |
| 971 | new StoreInst(outputs[i], &*OAI, InsertPt); |
| 972 | ++OAI; |
| 973 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 974 | } |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 975 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 976 | // Now we can emit a switch statement using the call as a value. |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 977 | SwitchInst *TheSwitch = |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 978 | SwitchInst::Create(Constant::getNullValue(Type::getInt16Ty(Context)), |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 979 | codeReplacer, 0, codeReplacer); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 980 | |
| 981 | // Since there may be multiple exits from the original region, make the new |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 982 | // function return an unsigned, switch on that number. This loop iterates |
| 983 | // over all of the blocks in the extracted region, updating any terminator |
| 984 | // instructions in the to-be-extracted region that branch to blocks that are |
| 985 | // not in the region to be extracted. |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 986 | std::map<BasicBlock *, BasicBlock *> ExitBlockMap; |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 987 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 988 | unsigned switchVal = 0; |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 989 | for (BasicBlock *Block : Blocks) { |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 990 | Instruction *TI = Block->getTerminator(); |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 991 | for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 992 | if (!Blocks.count(TI->getSuccessor(i))) { |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 993 | BasicBlock *OldTarget = TI->getSuccessor(i); |
| 994 | // add a new basic block which returns the appropriate value |
| 995 | BasicBlock *&NewTarget = ExitBlockMap[OldTarget]; |
| 996 | if (!NewTarget) { |
| 997 | // If we don't already have an exit stub for this non-extracted |
| 998 | // destination, create one now! |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 999 | NewTarget = BasicBlock::Create(Context, |
| 1000 | OldTarget->getName() + ".exitStub", |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1001 | newFunction); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1002 | unsigned SuccNum = switchVal++; |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1003 | |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1004 | Value *brVal = nullptr; |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1005 | switch (NumExitBlocks) { |
| 1006 | case 0: |
| 1007 | case 1: break; // No value needed. |
| 1008 | case 2: // Conditional branch, return a bool |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1009 | brVal = ConstantInt::get(Type::getInt1Ty(Context), !SuccNum); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1010 | break; |
| 1011 | default: |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1012 | brVal = ConstantInt::get(Type::getInt16Ty(Context), SuccNum); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1013 | break; |
| 1014 | } |
| 1015 | |
Jakub Kuderski | cbe9fae | 2017-10-06 03:37:06 +0000 | [diff] [blame] | 1016 | ReturnInst::Create(Context, brVal, NewTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1017 | |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1018 | // Update the switch instruction. |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1019 | TheSwitch->addCase(ConstantInt::get(Type::getInt16Ty(Context), |
| 1020 | SuccNum), |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1021 | OldTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1022 | } |
Chris Lattner | b4d8bf3 | 2004-03-14 23:05:49 +0000 | [diff] [blame] | 1023 | |
| 1024 | // rewrite the original branch instruction with this new target |
| 1025 | TI->setSuccessor(i, NewTarget); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1026 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1027 | } |
Chris Lattner | 5b2072e | 2004-03-14 23:43:24 +0000 | [diff] [blame] | 1028 | |
Chris Lattner | 3d1ca67 | 2004-05-12 03:22:33 +0000 | [diff] [blame] | 1029 | // Now that we've done the deed, simplify the switch instruction. |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 1030 | Type *OldFnRetTy = TheSwitch->getParent()->getParent()->getReturnType(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1031 | switch (NumExitBlocks) { |
| 1032 | case 0: |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1033 | // There are no successors (the block containing the switch itself), which |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1034 | // means that previously this was the last part of the function, and hence |
| 1035 | // this should be rewritten as a `ret' |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1036 | |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1037 | // Check if the function should return a value |
Benjamin Kramer | ccce8ba | 2010-01-05 13:12:22 +0000 | [diff] [blame] | 1038 | if (OldFnRetTy->isVoidTy()) { |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1039 | ReturnInst::Create(Context, nullptr, TheSwitch); // Return void |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1040 | } else if (OldFnRetTy == TheSwitch->getCondition()->getType()) { |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1041 | // return what we have |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1042 | ReturnInst::Create(Context, TheSwitch->getCondition(), TheSwitch); |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1043 | } else { |
| 1044 | // Otherwise we must have code extracted an unwind or something, just |
| 1045 | // return whatever we want. |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1046 | ReturnInst::Create(Context, |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1047 | Constant::getNullValue(OldFnRetTy), TheSwitch); |
Chris Lattner | 7f1c7ed | 2004-08-12 03:17:02 +0000 | [diff] [blame] | 1048 | } |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1049 | |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1050 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1051 | break; |
| 1052 | case 1: |
| 1053 | // Only a single destination, change the switch into an unconditional |
| 1054 | // branch. |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1055 | BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch); |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1056 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1057 | break; |
| 1058 | case 2: |
Gabor Greif | e9ecc68 | 2008-04-06 20:25:17 +0000 | [diff] [blame] | 1059 | BranchInst::Create(TheSwitch->getSuccessor(1), TheSwitch->getSuccessor(2), |
| 1060 | call, TheSwitch); |
Dan Gohman | 158ff2c | 2008-06-21 22:08:46 +0000 | [diff] [blame] | 1061 | TheSwitch->eraseFromParent(); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1062 | break; |
| 1063 | default: |
| 1064 | // Otherwise, make the default destination of the switch instruction be one |
| 1065 | // of the other successors. |
Stepan Dyatkovskiy | 513aaa5 | 2012-02-01 07:49:51 +0000 | [diff] [blame] | 1066 | TheSwitch->setCondition(call); |
| 1067 | TheSwitch->setDefaultDest(TheSwitch->getSuccessor(NumExitBlocks)); |
Stepan Dyatkovskiy | 5b648af | 2012-03-08 07:06:20 +0000 | [diff] [blame] | 1068 | // Remove redundant case |
Bob Wilson | e407736 | 2013-09-09 19:14:35 +0000 | [diff] [blame] | 1069 | TheSwitch->removeCase(SwitchInst::CaseIt(TheSwitch, NumExitBlocks-1)); |
Chris Lattner | ffc4926 | 2004-05-12 04:14:24 +0000 | [diff] [blame] | 1070 | break; |
Chris Lattner | 5b2072e | 2004-03-14 23:43:24 +0000 | [diff] [blame] | 1071 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1072 | } |
| 1073 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1074 | void CodeExtractor::moveCodeToFunction(Function *newFunction) { |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1075 | Function *oldFunc = (*Blocks.begin())->getParent(); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1076 | Function::BasicBlockListType &oldBlocks = oldFunc->getBasicBlockList(); |
| 1077 | Function::BasicBlockListType &newBlocks = newFunction->getBasicBlockList(); |
| 1078 | |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1079 | for (BasicBlock *Block : Blocks) { |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1080 | // Delete the basic block from the old function, and the list of blocks |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1081 | oldBlocks.remove(Block); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1082 | |
| 1083 | // Insert this basic block into the new function |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1084 | newBlocks.push_back(Block); |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1085 | } |
| 1086 | } |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1087 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1088 | void CodeExtractor::calculateNewCallTerminatorWeights( |
| 1089 | BasicBlock *CodeReplacer, |
| 1090 | DenseMap<BasicBlock *, BlockFrequency> &ExitWeights, |
| 1091 | BranchProbabilityInfo *BPI) { |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1092 | using Distribution = BlockFrequencyInfoImplBase::Distribution; |
| 1093 | using BlockNode = BlockFrequencyInfoImplBase::BlockNode; |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1094 | |
| 1095 | // Update the branch weights for the exit block. |
Chandler Carruth | edb12a8 | 2018-10-15 10:04:59 +0000 | [diff] [blame] | 1096 | Instruction *TI = CodeReplacer->getTerminator(); |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1097 | SmallVector<unsigned, 8> BranchWeights(TI->getNumSuccessors(), 0); |
| 1098 | |
| 1099 | // Block Frequency distribution with dummy node. |
| 1100 | Distribution BranchDist; |
| 1101 | |
| 1102 | // Add each of the frequencies of the successors. |
| 1103 | for (unsigned i = 0, e = TI->getNumSuccessors(); i < e; ++i) { |
| 1104 | BlockNode ExitNode(i); |
| 1105 | uint64_t ExitFreq = ExitWeights[TI->getSuccessor(i)].getFrequency(); |
| 1106 | if (ExitFreq != 0) |
| 1107 | BranchDist.addExit(ExitNode, ExitFreq); |
| 1108 | else |
| 1109 | BPI->setEdgeProbability(CodeReplacer, i, BranchProbability::getZero()); |
| 1110 | } |
| 1111 | |
| 1112 | // Check for no total weight. |
| 1113 | if (BranchDist.Total == 0) |
| 1114 | return; |
| 1115 | |
| 1116 | // Normalize the distribution so that they can fit in unsigned. |
| 1117 | BranchDist.normalize(); |
| 1118 | |
| 1119 | // Create normalized branch weights and set the metadata. |
| 1120 | for (unsigned I = 0, E = BranchDist.Weights.size(); I < E; ++I) { |
| 1121 | const auto &Weight = BranchDist.Weights[I]; |
| 1122 | |
| 1123 | // Get the weight and update the current BFI. |
| 1124 | BranchWeights[Weight.TargetNode.Index] = Weight.Amount; |
| 1125 | BranchProbability BP(Weight.Amount, BranchDist.Total); |
| 1126 | BPI->setEdgeProbability(CodeReplacer, Weight.TargetNode.Index, BP); |
| 1127 | } |
| 1128 | TI->setMetadata( |
| 1129 | LLVMContext::MD_prof, |
| 1130 | MDBuilder(TI->getContext()).createBranchWeights(BranchWeights)); |
| 1131 | } |
| 1132 | |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1133 | Function *CodeExtractor::extractCodeRegion() { |
| 1134 | if (!isEligible()) |
Craig Topper | f40110f | 2014-04-25 05:29:35 +0000 | [diff] [blame] | 1135 | return nullptr; |
Misha Brukman | 3596f0a | 2004-04-23 23:54:17 +0000 | [diff] [blame] | 1136 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1137 | // Assumption: this is a single-entry code region, and the header is the first |
Chris Lattner | 73ab1fa | 2004-03-15 01:18:23 +0000 | [diff] [blame] | 1138 | // block in the region. |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1139 | BasicBlock *header = *Blocks.begin(); |
Florian Hahn | 0e9dec6 | 2017-11-13 10:35:52 +0000 | [diff] [blame] | 1140 | Function *oldFunction = header->getParent(); |
| 1141 | |
| 1142 | // For functions with varargs, check that varargs handling is only done in the |
| 1143 | // outlined function, i.e vastart and vaend are only used in outlined blocks. |
| 1144 | if (AllowVarArgs && oldFunction->getFunctionType()->isVarArg()) { |
| 1145 | auto containsVarArgIntrinsic = [](Instruction &I) { |
| 1146 | if (const CallInst *CI = dyn_cast<CallInst>(&I)) |
| 1147 | if (const Function *F = CI->getCalledFunction()) |
| 1148 | return F->getIntrinsicID() == Intrinsic::vastart || |
| 1149 | F->getIntrinsicID() == Intrinsic::vaend; |
| 1150 | return false; |
| 1151 | }; |
| 1152 | |
| 1153 | for (auto &BB : *oldFunction) { |
| 1154 | if (Blocks.count(&BB)) |
| 1155 | continue; |
| 1156 | if (llvm::any_of(BB, containsVarArgIntrinsic)) |
| 1157 | return nullptr; |
| 1158 | } |
| 1159 | } |
| 1160 | ValueSet inputs, outputs, SinkingCands, HoistingCands; |
| 1161 | BasicBlock *CommonExit = nullptr; |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1162 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1163 | // Calculate the entry frequency of the new function before we change the root |
| 1164 | // block. |
| 1165 | BlockFrequency EntryFreq; |
| 1166 | if (BFI) { |
| 1167 | assert(BPI && "Both BPI and BFI are required to preserve profile info"); |
| 1168 | for (BasicBlock *Pred : predecessors(header)) { |
| 1169 | if (Blocks.count(Pred)) |
| 1170 | continue; |
| 1171 | EntryFreq += |
| 1172 | BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, header); |
| 1173 | } |
| 1174 | } |
| 1175 | |
Chris Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 1176 | // If we have to split PHI nodes or the entry block, do so now. |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 1177 | severSplitPHINodes(header); |
| 1178 | |
Chris Lattner | 13d2ddf | 2004-05-12 16:07:41 +0000 | [diff] [blame] | 1179 | // If we have any return instructions in the region, split those blocks so |
| 1180 | // that the return is not in the region. |
| 1181 | splitReturnBlocks(); |
| 1182 | |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1183 | // This takes place of the original loop |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1184 | BasicBlock *codeReplacer = BasicBlock::Create(header->getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1185 | "codeRepl", oldFunction, |
Gabor Greif | 697e94c | 2008-05-15 10:04:30 +0000 | [diff] [blame] | 1186 | header); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1187 | |
| 1188 | // The new function needs a root node because other nodes can branch to the |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1189 | // head of the region, but the entry node of a function cannot have preds. |
Fangrui Song | f78650a | 2018-07-30 19:41:25 +0000 | [diff] [blame] | 1190 | BasicBlock *newFuncRoot = BasicBlock::Create(header->getContext(), |
Owen Anderson | 55f1c09 | 2009-08-13 21:58:54 +0000 | [diff] [blame] | 1191 | "newFuncRoot"); |
Florian Hahn | e5089e2 | 2017-12-08 21:49:03 +0000 | [diff] [blame] | 1192 | auto *BranchI = BranchInst::Create(header); |
| 1193 | // If the original function has debug info, we have to add a debug location |
| 1194 | // to the new branch instruction from the artificial entry block. |
| 1195 | // We use the debug location of the first instruction in the extracted |
| 1196 | // blocks, as there is no other equivalent line in the source code. |
| 1197 | if (oldFunction->getSubprogram()) { |
| 1198 | any_of(Blocks, [&BranchI](const BasicBlock *BB) { |
| 1199 | return any_of(*BB, [&BranchI](const Instruction &I) { |
| 1200 | if (!I.getDebugLoc()) |
| 1201 | return false; |
| 1202 | BranchI->setDebugLoc(I.getDebugLoc()); |
| 1203 | return true; |
| 1204 | }); |
| 1205 | }); |
| 1206 | } |
| 1207 | newFuncRoot->getInstList().push_back(BranchI); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1208 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 1209 | findAllocas(SinkingCands, HoistingCands, CommonExit); |
| 1210 | assert(HoistingCands.empty() || CommonExit); |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 1211 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1212 | // Find inputs to, outputs from the code region. |
Xinliang David Li | 74480ad | 2017-05-30 21:22:18 +0000 | [diff] [blame] | 1213 | findInputsOutputs(inputs, outputs, SinkingCands); |
| 1214 | |
| 1215 | // Now sink all instructions which only have non-phi uses inside the region |
| 1216 | for (auto *II : SinkingCands) |
| 1217 | cast<Instruction>(II)->moveBefore(*newFuncRoot, |
| 1218 | newFuncRoot->getFirstInsertionPt()); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1219 | |
Xinliang David Li | 7ed6cd3 | 2017-06-11 20:46:05 +0000 | [diff] [blame] | 1220 | if (!HoistingCands.empty()) { |
| 1221 | auto *HoistToBlock = findOrCreateBlockForHoisting(CommonExit); |
| 1222 | Instruction *TI = HoistToBlock->getTerminator(); |
| 1223 | for (auto *II : HoistingCands) |
| 1224 | cast<Instruction>(II)->moveBefore(TI); |
| 1225 | } |
| 1226 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1227 | // Calculate the exit blocks for the extracted region and the total exit |
Eugene Zelenko | 286d589 | 2017-10-11 21:41:43 +0000 | [diff] [blame] | 1228 | // weights for each of those blocks. |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1229 | DenseMap<BasicBlock *, BlockFrequency> ExitWeights; |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 1230 | SmallPtrSet<BasicBlock *, 1> ExitBlocks; |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1231 | for (BasicBlock *Block : Blocks) { |
Benjamin Kramer | 135f735 | 2016-06-26 12:28:59 +0000 | [diff] [blame] | 1232 | for (succ_iterator SI = succ_begin(Block), SE = succ_end(Block); SI != SE; |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1233 | ++SI) { |
| 1234 | if (!Blocks.count(*SI)) { |
| 1235 | // Update the branch weight for this successor. |
| 1236 | if (BFI) { |
| 1237 | BlockFrequency &BF = ExitWeights[*SI]; |
| 1238 | BF += BFI->getBlockFreq(Block) * BPI->getEdgeProbability(Block, *SI); |
| 1239 | } |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1240 | ExitBlocks.insert(*SI); |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1241 | } |
| 1242 | } |
| 1243 | } |
Chandler Carruth | 14316fc | 2012-05-04 11:20:27 +0000 | [diff] [blame] | 1244 | NumExitBlocks = ExitBlocks.size(); |
| 1245 | |
Chris Lattner | 3b2917b | 2004-05-12 06:01:40 +0000 | [diff] [blame] | 1246 | // Construct new function based on inputs/outputs & add allocas for all defs. |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 1247 | Function *newFunction = constructFunction(inputs, outputs, header, |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1248 | newFuncRoot, |
Chris Lattner | 73ab1fa | 2004-03-15 01:18:23 +0000 | [diff] [blame] | 1249 | codeReplacer, oldFunction, |
| 1250 | oldFunction->getParent()); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1251 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1252 | // Update the entry count of the function. |
| 1253 | if (BFI) { |
Easwaran Raman | e5b8de2 | 2018-01-17 22:24:23 +0000 | [diff] [blame] | 1254 | auto Count = BFI->getProfileCountFromFreq(EntryFreq.getFrequency()); |
| 1255 | if (Count.hasValue()) |
| 1256 | newFunction->setEntryCount( |
| 1257 | ProfileCount(Count.getValue(), Function::PCT_Real)); // FIXME |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1258 | BFI->setBlockFreq(codeReplacer, EntryFreq.getFrequency()); |
| 1259 | } |
| 1260 | |
Chris Lattner | 9c431f6 | 2004-03-14 22:34:55 +0000 | [diff] [blame] | 1261 | emitCallAndSwitchStatement(newFunction, codeReplacer, inputs, outputs); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1262 | |
Chris Lattner | 9c431f6 | 2004-03-14 22:34:55 +0000 | [diff] [blame] | 1263 | moveCodeToFunction(newFunction); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1264 | |
Sergey Dmitriev | 69c9cd2 | 2018-05-11 22:49:49 +0000 | [diff] [blame] | 1265 | // Propagate personality info to the new function if there is one. |
| 1266 | if (oldFunction->hasPersonalityFn()) |
| 1267 | newFunction->setPersonalityFn(oldFunction->getPersonalityFn()); |
| 1268 | |
Sean Silva | f801575 | 2016-08-02 02:15:45 +0000 | [diff] [blame] | 1269 | // Update the branch weights for the exit block. |
| 1270 | if (BFI && NumExitBlocks > 1) |
| 1271 | calculateNewCallTerminatorWeights(codeReplacer, ExitWeights, BPI); |
| 1272 | |
Chris Lattner | 795c993 | 2004-05-12 15:29:13 +0000 | [diff] [blame] | 1273 | // Loop over all of the PHI nodes in the header block, and change any |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 1274 | // references to the old incoming edge to be the new incoming edge. |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 1275 | for (BasicBlock::iterator I = header->begin(); isa<PHINode>(I); ++I) { |
| 1276 | PHINode *PN = cast<PHINode>(I); |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 1277 | for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) |
Chandler Carruth | 0fde001 | 2012-05-04 10:18:49 +0000 | [diff] [blame] | 1278 | if (!Blocks.count(PN->getIncomingBlock(i))) |
Chris Lattner | 320d59f | 2004-03-18 05:28:49 +0000 | [diff] [blame] | 1279 | PN->setIncomingBlock(i, newFuncRoot); |
Reid Spencer | 6614946 | 2004-09-15 17:06:42 +0000 | [diff] [blame] | 1280 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1281 | |
Chris Lattner | acd7598 | 2004-03-18 05:38:31 +0000 | [diff] [blame] | 1282 | // Look at all successors of the codeReplacer block. If any of these blocks |
| 1283 | // had PHI nodes in them, we need to update the "from" block to be the code |
| 1284 | // replacer, not the original block in the extracted region. |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1285 | for (BasicBlock *SuccBB : successors(codeReplacer)) { |
| 1286 | for (PHINode &PN : SuccBB->phis()) { |
| 1287 | Value *IncomingCodeReplacerVal = nullptr; |
| 1288 | SmallVector<unsigned, 2> IncomingValsToRemove; |
| 1289 | for (unsigned I = 0, E = PN.getNumIncomingValues(); I != E; ++I) { |
| 1290 | BasicBlock *IncomingBB = PN.getIncomingBlock(I); |
| 1291 | |
| 1292 | // Ignore incoming values from outside of the extracted region. |
| 1293 | if (!Blocks.count(IncomingBB)) |
| 1294 | continue; |
| 1295 | |
| 1296 | // Ensure that there is only one incoming value from codeReplacer. |
| 1297 | if (!IncomingCodeReplacerVal) { |
| 1298 | PN.setIncomingBlock(I, codeReplacer); |
| 1299 | IncomingCodeReplacerVal = PN.getIncomingValue(I); |
| 1300 | } else { |
| 1301 | assert(IncomingCodeReplacerVal == PN.getIncomingValue(I) && |
| 1302 | "PHI has two incompatbile incoming values from codeRepl"); |
| 1303 | IncomingValsToRemove.push_back(I); |
Anton Korobeynikov | 1bfd121 | 2008-02-20 11:26:25 +0000 | [diff] [blame] | 1304 | } |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1305 | } |
| 1306 | |
| 1307 | for (unsigned I : reverse(IncomingValsToRemove)) |
| 1308 | PN.removeIncomingValue(I, /*DeletePHIIfEmpty=*/false); |
Chris Lattner | 5627382 | 2004-08-13 03:27:07 +0000 | [diff] [blame] | 1309 | } |
Vedant Kumar | c299006 | 2018-10-24 22:15:41 +0000 | [diff] [blame] | 1310 | } |
Misha Brukman | b1c9317 | 2005-04-21 23:48:37 +0000 | [diff] [blame] | 1311 | |
Vedant Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1312 | // Erase debug info intrinsics. Variable updates within the new function are |
| 1313 | // invisible to debuggers. This could be improved by defining a DISubprogram |
| 1314 | // for the new function. |
| 1315 | for (BasicBlock &BB : *newFunction) { |
| 1316 | auto BlockIt = BB.begin(); |
Vedant Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 1317 | // Remove debug info intrinsics from the new function. |
Vedant Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1318 | while (BlockIt != BB.end()) { |
| 1319 | Instruction *Inst = &*BlockIt; |
| 1320 | ++BlockIt; |
| 1321 | if (isa<DbgInfoIntrinsic>(Inst)) |
| 1322 | Inst->eraseFromParent(); |
| 1323 | } |
Vedant Kumar | 09b7aa4 | 2018-11-06 19:05:53 +0000 | [diff] [blame] | 1324 | // Remove debug info intrinsics which refer to values in the new function |
| 1325 | // from the old function. |
| 1326 | SmallVector<DbgVariableIntrinsic *, 4> DbgUsers; |
| 1327 | for (Instruction &I : BB) |
| 1328 | findDbgUsers(DbgUsers, &I); |
| 1329 | for (DbgVariableIntrinsic *DVI : DbgUsers) |
| 1330 | DVI->eraseFromParent(); |
Vedant Kumar | 15718a6 | 2018-10-15 19:22:20 +0000 | [diff] [blame] | 1331 | } |
| 1332 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1333 | LLVM_DEBUG(if (verifyFunction(*newFunction)) |
| 1334 | report_fatal_error("verifyFunction failed!")); |
Misha Brukman | caa1a5a | 2004-02-28 03:26:20 +0000 | [diff] [blame] | 1335 | return newFunction; |
| 1336 | } |