Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1 | //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===// |
| 2 | // |
| 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. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This pass munges the code in the input function to better prepare it for |
Gordon Henriksen | 829046b | 2008-05-08 17:46:35 +0000 | [diff] [blame] | 11 | // SelectionDAG-based code generation. This works around limitations in it's |
| 12 | // basic-block-at-a-time approach. It should eventually be removed. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 13 | // |
| 14 | //===----------------------------------------------------------------------===// |
| 15 | |
Quentin Colombet | a349084 | 2014-02-22 00:07:45 +0000 | [diff] [blame] | 16 | #include "llvm/CodeGen/Passes.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 17 | #include "llvm/ADT/DenseMap.h" |
| 18 | #include "llvm/ADT/SmallSet.h" |
| 19 | #include "llvm/ADT/Statistic.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/InstructionSimplify.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 22 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 23 | #include "llvm/IR/Constants.h" |
| 24 | #include "llvm/IR/DataLayout.h" |
| 25 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 26 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 27 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 28 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 29 | #include "llvm/IR/IRBuilder.h" |
| 30 | #include "llvm/IR/InlineAsm.h" |
| 31 | #include "llvm/IR/Instructions.h" |
| 32 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame^] | 33 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 34 | #include "llvm/IR/PatternMatch.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 35 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 36 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 37 | #include "llvm/Pass.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 38 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 39 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 40 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 41 | #include "llvm/Target/TargetLibraryInfo.h" |
| 42 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 43 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 44 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 45 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 47 | #include "llvm/Transforms/Utils/Local.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 48 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 49 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 50 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 51 | #define DEBUG_TYPE "codegenprepare" |
| 52 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 53 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 54 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 55 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 56 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 57 | "sunken Cmps"); |
| 58 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 59 | "of sunken Casts"); |
| 60 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 61 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 62 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 63 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
| 64 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 65 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 66 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 67 | STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 68 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 69 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 70 | static cl::opt<bool> DisableBranchOpts( |
| 71 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 72 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 73 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 74 | static cl::opt<bool> DisableSelectToBranch( |
| 75 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 76 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 77 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 78 | static cl::opt<bool> AddrSinkUsingGEPs( |
| 79 | "addr-sink-using-gep", cl::Hidden, cl::init(false), |
| 80 | cl::desc("Address sinking in CGP using GEPs.")); |
| 81 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 82 | static cl::opt<bool> EnableAndCmpSinking( |
| 83 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 84 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 85 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 86 | static cl::opt<bool> DisableStoreExtract( |
| 87 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 88 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 89 | |
| 90 | static cl::opt<bool> StressStoreExtract( |
| 91 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 92 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 93 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 94 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 95 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 96 | struct TypeIsSExt { |
| 97 | Type *Ty; |
| 98 | bool IsSExt; |
| 99 | TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {} |
| 100 | }; |
| 101 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 102 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 103 | class CodeGenPrepare : public FunctionPass { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 104 | /// TLI - Keep a pointer of a TargetLowering to consult for determining |
| 105 | /// transformation profitability. |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 106 | const TargetMachine *TM; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 107 | const TargetLowering *TLI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 108 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 109 | const TargetLibraryInfo *TLInfo; |
Cameron Zwarich | 84986b2 | 2011-01-08 17:01:52 +0000 | [diff] [blame] | 110 | DominatorTree *DT; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 111 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 112 | /// CurInstIterator - As we scan instructions optimizing them, this is the |
| 113 | /// next instruction to optimize. Xforms that can invalidate this should |
| 114 | /// update it. |
| 115 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 116 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 117 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 118 | /// This allows us to avoid inserting duplicate code for blocks with |
| 119 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 120 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 121 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 122 | /// Keeps track of all truncates inserted for the current function. |
| 123 | SetOfInstrs InsertedTruncsSet; |
| 124 | /// Keeps track of the type of the related instruction before their |
| 125 | /// promotion for the current function. |
| 126 | InstrToOrigTy PromotedInsts; |
| 127 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 128 | /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 129 | /// be updated. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 130 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 131 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 132 | /// OptSize - True if optimizing for size. |
| 133 | bool OptSize; |
| 134 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 135 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 136 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 137 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 138 | : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 139 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 140 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 141 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 142 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 143 | const char *getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 144 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 145 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 146 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 147 | AU.addRequired<TargetLibraryInfo>(); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 148 | AU.addRequired<TargetTransformInfo>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 149 | } |
| 150 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 151 | private: |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 152 | bool EliminateFallThrough(Function &F); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 153 | bool EliminateMostlyEmptyBlocks(Function &F); |
| 154 | bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 155 | void EliminateMostlyEmptyBlock(BasicBlock *BB); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 156 | bool OptimizeBlock(BasicBlock &BB); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 157 | bool OptimizeInst(Instruction *I); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 158 | bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy); |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 159 | bool OptimizeInlineAsmInst(CallInst *CS); |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 160 | bool OptimizeCallInst(CallInst *CI); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 161 | bool MoveExtToFormExtLoad(Instruction *I); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 162 | bool OptimizeExtUses(Instruction *I); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 163 | bool OptimizeSelectInst(SelectInst *SI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 164 | bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 165 | bool OptimizeExtractElementInst(Instruction *Inst); |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 166 | bool DupRetToEnableTailCallOpts(BasicBlock *BB); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 167 | bool PlaceDbgValues(Function &F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 168 | bool sinkAndCmp(Function &F); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame^] | 169 | bool splitBranchCondition(Function &F); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 170 | }; |
| 171 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 172 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 173 | char CodeGenPrepare::ID = 0; |
Jiangning Liu | d623c52 | 2014-06-11 07:04:37 +0000 | [diff] [blame] | 174 | INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare", |
| 175 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 176 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 177 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 178 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 179 | } |
| 180 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 181 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 182 | if (skipOptnoneFunction(F)) |
| 183 | return false; |
| 184 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 185 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 186 | // Clear per function information. |
| 187 | InsertedTruncsSet.clear(); |
| 188 | PromotedInsts.clear(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 189 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 190 | ModifiedDT = false; |
Eric Christopher | d913448 | 2014-08-04 21:25:23 +0000 | [diff] [blame] | 191 | if (TM) |
| 192 | TLI = TM->getSubtargetImpl()->getTargetLowering(); |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 193 | TLInfo = &getAnalysis<TargetLibraryInfo>(); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 194 | TTI = &getAnalysis<TargetTransformInfo>(); |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 195 | DominatorTreeWrapperPass *DTWP = |
| 196 | getAnalysisIfAvailable<DominatorTreeWrapperPass>(); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 197 | DT = DTWP ? &DTWP->getDomTree() : nullptr; |
Bill Wendling | 698e84f | 2012-12-30 10:32:01 +0000 | [diff] [blame] | 198 | OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex, |
| 199 | Attribute::OptimizeForSize); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 200 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 201 | /// This optimization identifies DIV instructions that can be |
| 202 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 203 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 204 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 205 | TLI->getBypassSlowDivWidths(); |
Evan Cheng | 71be12b | 2012-09-14 21:25:34 +0000 | [diff] [blame] | 206 | for (Function::iterator I = F.begin(); I != F.end(); I++) |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 207 | EverMadeChange |= bypassSlowDivision(F, I, BypassWidths); |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 208 | } |
| 209 | |
| 210 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 211 | // unconditional branch. |
| 212 | EverMadeChange |= EliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 213 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 214 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 215 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 216 | // find a node corresponding to the value. |
| 217 | EverMadeChange |= PlaceDbgValues(F); |
| 218 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 219 | // If there is a mask, compare against zero, and branch that can be combined |
| 220 | // into a single target instruction, push the mask and compare into branch |
| 221 | // users. Do this before OptimizeBlock -> OptimizeInst -> |
| 222 | // OptimizeCmpExpression, which perturbs the pattern being searched for. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame^] | 223 | if (!DisableBranchOpts) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 224 | EverMadeChange |= sinkAndCmp(F); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame^] | 225 | EverMadeChange |= splitBranchCondition(F); |
| 226 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 227 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 228 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 229 | while (MadeChange) { |
| 230 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 231 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 232 | BasicBlock *BB = I++; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 233 | MadeChange |= OptimizeBlock(*BB); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 234 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 235 | EverMadeChange |= MadeChange; |
| 236 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 237 | |
| 238 | SunkAddrs.clear(); |
| 239 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 240 | if (!DisableBranchOpts) { |
| 241 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 242 | SmallPtrSet<BasicBlock*, 8> WorkList; |
| 243 | for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) { |
| 244 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
Frits van Bommel | ad96455 | 2011-05-22 16:24:18 +0000 | [diff] [blame] | 245 | MadeChange |= ConstantFoldTerminator(BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 246 | if (!MadeChange) continue; |
| 247 | |
| 248 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 249 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 250 | if (pred_begin(*II) == pred_end(*II)) |
| 251 | WorkList.insert(*II); |
| 252 | } |
| 253 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 254 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 255 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 256 | while (!WorkList.empty()) { |
| 257 | BasicBlock *BB = *WorkList.begin(); |
| 258 | WorkList.erase(BB); |
| 259 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 260 | |
| 261 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 262 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 263 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 264 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 265 | if (pred_begin(*II) == pred_end(*II)) |
| 266 | WorkList.insert(*II); |
| 267 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 268 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 269 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 270 | // a single edge. |
| 271 | if (EverMadeChange || MadeChange) |
| 272 | MadeChange |= EliminateFallThrough(F); |
| 273 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 274 | if (MadeChange) |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 275 | ModifiedDT = true; |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 276 | EverMadeChange |= MadeChange; |
| 277 | } |
| 278 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 279 | if (ModifiedDT && DT) |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 280 | DT->recalculate(F); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 281 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 282 | return EverMadeChange; |
| 283 | } |
| 284 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 285 | /// EliminateFallThrough - Merge basic blocks which are connected |
| 286 | /// by a single edge, where one of the basic blocks has a single successor |
| 287 | /// pointing to the other basic block, which has a single predecessor. |
| 288 | bool CodeGenPrepare::EliminateFallThrough(Function &F) { |
| 289 | bool Changed = false; |
| 290 | // Scan all of the blocks in the function, except for the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 291 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 292 | BasicBlock *BB = I++; |
| 293 | // If the destination block has a single pred, then this is a trivial |
| 294 | // edge, just collapse it. |
| 295 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 296 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 297 | // Don't merge if BB's address is taken. |
| 298 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 299 | |
| 300 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 301 | if (Term && !Term->isConditional()) { |
| 302 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 303 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 304 | // Remember if SinglePred was the entry block of the function. |
| 305 | // If so, we will need to move BB back to the entry position. |
| 306 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
| 307 | MergeBasicBlockIntoOnlyPred(BB, this); |
| 308 | |
| 309 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 310 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 311 | |
| 312 | // We have erased a block. Update the iterator. |
| 313 | I = BB; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 314 | } |
| 315 | } |
| 316 | return Changed; |
| 317 | } |
| 318 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 319 | /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes, |
| 320 | /// debug info directives, and an unconditional branch. Passes before isel |
| 321 | /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for |
| 322 | /// isel. Start by eliminating these blocks so we can split them the way we |
| 323 | /// want them. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 324 | bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) { |
| 325 | bool MadeChange = false; |
| 326 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 327 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 328 | BasicBlock *BB = I++; |
| 329 | |
| 330 | // If this block doesn't end with an uncond branch, ignore it. |
| 331 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 332 | if (!BI || !BI->isUnconditional()) |
| 333 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 334 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 335 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 336 | // node, then other stuff is happening here. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 337 | BasicBlock::iterator BBI = BI; |
| 338 | if (BBI != BB->begin()) { |
| 339 | --BBI; |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 340 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 341 | if (BBI == BB->begin()) |
| 342 | break; |
| 343 | --BBI; |
| 344 | } |
| 345 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 346 | continue; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 347 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 348 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 349 | // Do not break infinite loops. |
| 350 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 351 | if (DestBB == BB) |
| 352 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 353 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 354 | if (!CanMergeBlocks(BB, DestBB)) |
| 355 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 356 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 357 | EliminateMostlyEmptyBlock(BB); |
| 358 | MadeChange = true; |
| 359 | } |
| 360 | return MadeChange; |
| 361 | } |
| 362 | |
| 363 | /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a |
| 364 | /// single uncond branch between them, and BB contains no other non-phi |
| 365 | /// instructions. |
| 366 | bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB, |
| 367 | const BasicBlock *DestBB) const { |
| 368 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 369 | // the successor. If there are more complex condition (e.g. preheaders), |
| 370 | // don't mess around with them. |
| 371 | BasicBlock::const_iterator BBI = BB->begin(); |
| 372 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 373 | for (const User *U : PN->users()) { |
| 374 | const Instruction *UI = cast<Instruction>(U); |
| 375 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 376 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 377 | // If User is inside DestBB block and it is a PHINode then check |
| 378 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 379 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 380 | if (UI->getParent() == DestBB) { |
| 381 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 382 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 383 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 384 | if (Insn && Insn->getParent() == BB && |
| 385 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 386 | return false; |
| 387 | } |
| 388 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 389 | } |
| 390 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 391 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 392 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 393 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 394 | // can't merge the block. |
| 395 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 396 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 397 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 398 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 399 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 400 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 401 | // It is faster to get preds from a PHI than with pred_iterator. |
| 402 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 403 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 404 | } else { |
| 405 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 406 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 407 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 408 | // Walk the preds of DestBB. |
| 409 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 410 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 411 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 412 | BBI = DestBB->begin(); |
| 413 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 414 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 415 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 416 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 417 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 418 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 419 | if (V2PN->getParent() == BB) |
| 420 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 421 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 422 | // If there is a conflict, bail out. |
| 423 | if (V1 != V2) return false; |
| 424 | } |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | return true; |
| 429 | } |
| 430 | |
| 431 | |
| 432 | /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and |
| 433 | /// an unconditional branch in it. |
| 434 | void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) { |
| 435 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 436 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 437 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 438 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 439 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 440 | // If the destination block has a single pred, then this is a trivial edge, |
| 441 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 442 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 443 | if (SinglePred != DestBB) { |
| 444 | // Remember if SinglePred was the entry block of the function. If so, we |
| 445 | // will need to move BB back to the entry position. |
| 446 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 447 | MergeBasicBlockIntoOnlyPred(DestBB, this); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 448 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 449 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 450 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 451 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 452 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 453 | return; |
| 454 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 455 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 456 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 457 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 458 | // to handle the new incoming edges it is about to have. |
| 459 | PHINode *PN; |
| 460 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 461 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 462 | // Remove the incoming value for BB, and remember it. |
| 463 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 464 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 465 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 466 | // value that dominates BB. |
| 467 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 468 | if (InValPhi && InValPhi->getParent() == BB) { |
| 469 | // Add all of the input values of the input PHI as inputs of this phi. |
| 470 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 471 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 472 | InValPhi->getIncomingBlock(i)); |
| 473 | } else { |
| 474 | // Otherwise, add one instance of the dominating value for each edge that |
| 475 | // we will be adding. |
| 476 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 477 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 478 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 479 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 480 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 481 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 482 | } |
| 483 | } |
| 484 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 485 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 486 | // The PHIs are now updated, change everything that refers to BB to use |
| 487 | // DestBB and remove BB. |
| 488 | BB->replaceAllUsesWith(DestBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 489 | if (DT && !ModifiedDT) { |
Cameron Zwarich | 84986b2 | 2011-01-08 17:01:52 +0000 | [diff] [blame] | 490 | BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock(); |
| 491 | BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock(); |
| 492 | BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom); |
| 493 | DT->changeImmediateDominator(DestBB, NewIDom); |
| 494 | DT->eraseNode(BB); |
| 495 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 496 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 497 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 498 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 499 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 500 | } |
| 501 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 502 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 503 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 504 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 505 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 506 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 507 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 508 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 509 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 510 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 511 | UI != E; ) { |
| 512 | Use &TheUse = UI.getUse(); |
| 513 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 514 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 515 | // Figure out which BB this cast is used in. For PHI's this is the |
| 516 | // appropriate predecessor block. |
| 517 | BasicBlock *UserBB = User->getParent(); |
| 518 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 519 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 520 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 521 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 522 | // Preincrement use iterator so we don't invalidate it. |
| 523 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 524 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 525 | // If this user is in the same block as the cast, don't change the cast. |
| 526 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 527 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 528 | // If we have already inserted a cast into this block, use it. |
| 529 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 530 | |
| 531 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 532 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 533 | InsertedCast = |
| 534 | CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 535 | InsertPt); |
| 536 | MadeChange = true; |
| 537 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 538 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 539 | // Replace a use of the cast with a use of the new cast. |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 540 | TheUse = InsertedCast; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 541 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 542 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 543 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 544 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 545 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 546 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 547 | MadeChange = true; |
| 548 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 549 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 550 | return MadeChange; |
| 551 | } |
| 552 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 553 | /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop |
| 554 | /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC), |
| 555 | /// sink it into user blocks to reduce the number of virtual |
| 556 | /// registers that must be created and coalesced. |
| 557 | /// |
| 558 | /// Return true if any changes are made. |
| 559 | /// |
| 560 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){ |
| 561 | // If this is a noop copy, |
| 562 | EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType()); |
| 563 | EVT DstVT = TLI.getValueType(CI->getType()); |
| 564 | |
| 565 | // This is an fp<->int conversion? |
| 566 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 567 | return false; |
| 568 | |
| 569 | // If this is an extension, it will be a zero or sign extension, which |
| 570 | // isn't a noop. |
| 571 | if (SrcVT.bitsLT(DstVT)) return false; |
| 572 | |
| 573 | // If these values will be promoted, find out what they will be promoted |
| 574 | // to. This helps us consider truncates on PPC as noop copies when they |
| 575 | // are. |
| 576 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 577 | TargetLowering::TypePromoteInteger) |
| 578 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 579 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 580 | TargetLowering::TypePromoteInteger) |
| 581 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 582 | |
| 583 | // If, after promotion, these are the same types, this is a noop copy. |
| 584 | if (SrcVT != DstVT) |
| 585 | return false; |
| 586 | |
| 587 | return SinkCast(CI); |
| 588 | } |
| 589 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 590 | /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 591 | /// the number of virtual registers that must be created and coalesced. This is |
Chris Lattner | 2740694 | 2007-08-02 16:53:43 +0000 | [diff] [blame] | 592 | /// a clear win except on targets with multiple condition code registers |
| 593 | /// (PowerPC), where it might lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 594 | /// |
| 595 | /// Return true if any changes are made. |
Chris Lattner | 6416a6b | 2008-11-24 22:44:16 +0000 | [diff] [blame] | 596 | static bool OptimizeCmpExpression(CmpInst *CI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 597 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 598 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 599 | /// InsertedCmp - Only insert a cmp in each block once. |
| 600 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 601 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 602 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 603 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 604 | UI != E; ) { |
| 605 | Use &TheUse = UI.getUse(); |
| 606 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 607 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 608 | // Preincrement use iterator so we don't invalidate it. |
| 609 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 610 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 611 | // Don't bother for PHI nodes. |
| 612 | if (isa<PHINode>(User)) |
| 613 | continue; |
| 614 | |
| 615 | // Figure out which BB this cmp is used in. |
| 616 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 617 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 618 | // If this user is in the same block as the cmp, don't change the cmp. |
| 619 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 620 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 621 | // If we have already inserted a cmp into this block, use it. |
| 622 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 623 | |
| 624 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 625 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 626 | InsertedCmp = |
Dan Gohman | ad1f0a1 | 2009-08-25 23:17:54 +0000 | [diff] [blame] | 627 | CmpInst::Create(CI->getOpcode(), |
Owen Anderson | 1e5f00e | 2009-07-09 23:48:35 +0000 | [diff] [blame] | 628 | CI->getPredicate(), CI->getOperand(0), |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 629 | CI->getOperand(1), "", InsertPt); |
| 630 | MadeChange = true; |
| 631 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 632 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 633 | // Replace a use of the cmp with a use of the new cmp. |
| 634 | TheUse = InsertedCmp; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 635 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 636 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 637 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 638 | // If we removed all uses, nuke the cmp. |
| 639 | if (CI->use_empty()) |
| 640 | CI->eraseFromParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 641 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 642 | return MadeChange; |
| 643 | } |
| 644 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 645 | /// isExtractBitsCandidateUse - Check if the candidates could |
| 646 | /// be combined with shift instruction, which includes: |
| 647 | /// 1. Truncate instruction |
| 648 | /// 2. And instruction and the imm is a mask of the low bits: |
| 649 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 650 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 651 | if (!isa<TruncInst>(User)) { |
| 652 | if (User->getOpcode() != Instruction::And || |
| 653 | !isa<ConstantInt>(User->getOperand(1))) |
| 654 | return false; |
| 655 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 656 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 657 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 658 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 659 | return false; |
| 660 | } |
| 661 | return true; |
| 662 | } |
| 663 | |
| 664 | /// SinkShiftAndTruncate - sink both shift and truncate instruction |
| 665 | /// to the use of truncate's BB. |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 666 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 667 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 668 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
| 669 | const TargetLowering &TLI) { |
| 670 | BasicBlock *UserBB = User->getParent(); |
| 671 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 672 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 673 | bool MadeChange = false; |
| 674 | |
| 675 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 676 | TruncE = TruncI->user_end(); |
| 677 | TruncUI != TruncE;) { |
| 678 | |
| 679 | Use &TruncTheUse = TruncUI.getUse(); |
| 680 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 681 | // Preincrement use iterator so we don't invalidate it. |
| 682 | |
| 683 | ++TruncUI; |
| 684 | |
| 685 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 686 | if (!ISDOpcode) |
| 687 | continue; |
| 688 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 689 | // If the use is actually a legal node, there will not be an |
| 690 | // implicit truncate. |
| 691 | // FIXME: always querying the result type is just an |
| 692 | // approximation; some nodes' legality is determined by the |
| 693 | // operand or other means. There's no good way to find out though. |
Ahmed Bougacha | 0788d49 | 2014-11-12 22:16:55 +0000 | [diff] [blame] | 694 | if (TLI.isOperationLegalOrCustom( |
| 695 | ISDOpcode, TLI.getValueType(TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 696 | continue; |
| 697 | |
| 698 | // Don't bother for PHI nodes. |
| 699 | if (isa<PHINode>(TruncUser)) |
| 700 | continue; |
| 701 | |
| 702 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 703 | |
| 704 | if (UserBB == TruncUserBB) |
| 705 | continue; |
| 706 | |
| 707 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 708 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 709 | |
| 710 | if (!InsertedShift && !InsertedTrunc) { |
| 711 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
| 712 | // Sink the shift |
| 713 | if (ShiftI->getOpcode() == Instruction::AShr) |
| 714 | InsertedShift = |
| 715 | BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 716 | else |
| 717 | InsertedShift = |
| 718 | BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 719 | |
| 720 | // Sink the trunc |
| 721 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 722 | TruncInsertPt++; |
| 723 | |
| 724 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
| 725 | TruncI->getType(), "", TruncInsertPt); |
| 726 | |
| 727 | MadeChange = true; |
| 728 | |
| 729 | TruncTheUse = InsertedTrunc; |
| 730 | } |
| 731 | } |
| 732 | return MadeChange; |
| 733 | } |
| 734 | |
| 735 | /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if |
| 736 | /// the uses could potentially be combined with this shift instruction and |
| 737 | /// generate BitExtract instruction. It will only be applied if the architecture |
| 738 | /// supports BitExtract instruction. Here is an example: |
| 739 | /// BB1: |
| 740 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 741 | /// BB2: |
| 742 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 743 | /// ==> |
| 744 | /// |
| 745 | /// BB2: |
| 746 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 747 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 748 | /// |
| 749 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 750 | /// instruction. |
| 751 | /// Return true if any changes are made. |
| 752 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
| 753 | const TargetLowering &TLI) { |
| 754 | BasicBlock *DefBB = ShiftI->getParent(); |
| 755 | |
| 756 | /// Only insert instructions in each block once. |
| 757 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 758 | |
| 759 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType())); |
| 760 | |
| 761 | bool MadeChange = false; |
| 762 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 763 | UI != E;) { |
| 764 | Use &TheUse = UI.getUse(); |
| 765 | Instruction *User = cast<Instruction>(*UI); |
| 766 | // Preincrement use iterator so we don't invalidate it. |
| 767 | ++UI; |
| 768 | |
| 769 | // Don't bother for PHI nodes. |
| 770 | if (isa<PHINode>(User)) |
| 771 | continue; |
| 772 | |
| 773 | if (!isExtractBitsCandidateUse(User)) |
| 774 | continue; |
| 775 | |
| 776 | BasicBlock *UserBB = User->getParent(); |
| 777 | |
| 778 | if (UserBB == DefBB) { |
| 779 | // If the shift and truncate instruction are in the same BB. The use of |
| 780 | // the truncate(TruncUse) may still introduce another truncate if not |
| 781 | // legal. In this case, we would like to sink both shift and truncate |
| 782 | // instruction to the BB of TruncUse. |
| 783 | // for example: |
| 784 | // BB1: |
| 785 | // i64 shift.result = lshr i64 opnd, imm |
| 786 | // trunc.result = trunc shift.result to i16 |
| 787 | // |
| 788 | // BB2: |
| 789 | // ----> We will have an implicit truncate here if the architecture does |
| 790 | // not have i16 compare. |
| 791 | // cmp i16 trunc.result, opnd2 |
| 792 | // |
| 793 | if (isa<TruncInst>(User) && shiftIsLegal |
| 794 | // If the type of the truncate is legal, no trucate will be |
| 795 | // introduced in other basic blocks. |
| 796 | && (!TLI.isTypeLegal(TLI.getValueType(User->getType())))) |
| 797 | MadeChange = |
| 798 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI); |
| 799 | |
| 800 | continue; |
| 801 | } |
| 802 | // If we have already inserted a shift into this block, use it. |
| 803 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 804 | |
| 805 | if (!InsertedShift) { |
| 806 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
| 807 | |
| 808 | if (ShiftI->getOpcode() == Instruction::AShr) |
| 809 | InsertedShift = |
| 810 | BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 811 | else |
| 812 | InsertedShift = |
| 813 | BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt); |
| 814 | |
| 815 | MadeChange = true; |
| 816 | } |
| 817 | |
| 818 | // Replace a use of the shift with a use of the new shift. |
| 819 | TheUse = InsertedShift; |
| 820 | } |
| 821 | |
| 822 | // If we removed all uses, nuke the shift. |
| 823 | if (ShiftI->use_empty()) |
| 824 | ShiftI->eraseFromParent(); |
| 825 | |
| 826 | return MadeChange; |
| 827 | } |
| 828 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 829 | namespace { |
| 830 | class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls { |
| 831 | protected: |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 832 | void replaceCall(Value *With) override { |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 833 | CI->replaceAllUsesWith(With); |
| 834 | CI->eraseFromParent(); |
| 835 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 836 | bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override { |
Gabor Greif | 6d67395 | 2010-07-16 09:38:02 +0000 | [diff] [blame] | 837 | if (ConstantInt *SizeCI = |
| 838 | dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) |
| 839 | return SizeCI->isAllOnesValue(); |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 840 | return false; |
| 841 | } |
| 842 | }; |
| 843 | } // end anonymous namespace |
| 844 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 845 | bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 846 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 847 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 848 | // Lower inline assembly if we can. |
| 849 | // If we found an inline asm expession, and if the target knows how to |
| 850 | // lower it to normal LLVM code, do so now. |
| 851 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 852 | if (TLI->ExpandInlineAsm(CI)) { |
| 853 | // Avoid invalidating the iterator. |
| 854 | CurInstIterator = BB->begin(); |
| 855 | // Avoid processing instructions out of order, which could cause |
| 856 | // reuse before a value is defined. |
| 857 | SunkAddrs.clear(); |
| 858 | return true; |
| 859 | } |
| 860 | // Sink address computing for memory operands into the block. |
| 861 | if (OptimizeInlineAsmInst(CI)) |
| 862 | return true; |
| 863 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 864 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 865 | // Lower all uses of llvm.objectsize.* |
| 866 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
| 867 | if (II && II->getIntrinsicID() == Intrinsic::objectsize) { |
Gabor Greif | 4a39b84 | 2010-06-24 00:44:01 +0000 | [diff] [blame] | 868 | bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1); |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 869 | Type *ReturnTy = CI->getType(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 870 | Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL); |
| 871 | |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 872 | // Substituting this can cause recursive simplifications, which can |
| 873 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 874 | // happens. |
| 875 | WeakVH IterHandle(CurInstIterator); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 876 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 877 | replaceAndRecursivelySimplify(CI, RetVal, |
| 878 | TLI ? TLI->getDataLayout() : nullptr, |
| 879 | TLInfo, ModifiedDT ? nullptr : DT); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 880 | |
| 881 | // If the iterator instruction was recursively deleted, start over at the |
| 882 | // start of the block. |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 883 | if (IterHandle != CurInstIterator) { |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 884 | CurInstIterator = BB->begin(); |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 885 | SunkAddrs.clear(); |
| 886 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 887 | return true; |
| 888 | } |
| 889 | |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 890 | if (II && TLI) { |
| 891 | SmallVector<Value*, 2> PtrOps; |
| 892 | Type *AccessTy; |
| 893 | if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy)) |
| 894 | while (!PtrOps.empty()) |
| 895 | if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy)) |
| 896 | return true; |
| 897 | } |
| 898 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 899 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 900 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 901 | |
Micah Villmow | cdfe20b | 2012-10-08 16:38:25 +0000 | [diff] [blame] | 902 | // We'll need DataLayout from here on out. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 903 | const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 904 | if (!TD) return false; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 905 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 906 | // Lower all default uses of _chk calls. This is very similar |
| 907 | // to what InstCombineCalls does, but here we are only lowering calls |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 908 | // that have the default "don't know" as the objectsize. Anything else |
| 909 | // should be left alone. |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 910 | CodeGenPrepareFortifiedLibCalls Simplifier; |
Nuno Lopes | 89702e9 | 2012-07-25 16:46:31 +0000 | [diff] [blame] | 911 | return Simplifier.fold(CI, TD, TLInfo); |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 912 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 913 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 914 | /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return |
| 915 | /// instructions to the predecessor to enable tail call optimizations. The |
| 916 | /// case it is currently looking for is: |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 917 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 918 | /// bb0: |
| 919 | /// %tmp0 = tail call i32 @f0() |
| 920 | /// br label %return |
| 921 | /// bb1: |
| 922 | /// %tmp1 = tail call i32 @f1() |
| 923 | /// br label %return |
| 924 | /// bb2: |
| 925 | /// %tmp2 = tail call i32 @f2() |
| 926 | /// br label %return |
| 927 | /// return: |
| 928 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 929 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 930 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 931 | /// |
| 932 | /// => |
| 933 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 934 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 935 | /// bb0: |
| 936 | /// %tmp0 = tail call i32 @f0() |
| 937 | /// ret i32 %tmp0 |
| 938 | /// bb1: |
| 939 | /// %tmp1 = tail call i32 @f1() |
| 940 | /// ret i32 %tmp1 |
| 941 | /// bb2: |
| 942 | /// %tmp2 = tail call i32 @f2() |
| 943 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 944 | /// @endcode |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 945 | bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 946 | if (!TLI) |
| 947 | return false; |
| 948 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 949 | ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 950 | if (!RI) |
| 951 | return false; |
| 952 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 953 | PHINode *PN = nullptr; |
| 954 | BitCastInst *BCI = nullptr; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 955 | Value *V = RI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 956 | if (V) { |
| 957 | BCI = dyn_cast<BitCastInst>(V); |
| 958 | if (BCI) |
| 959 | V = BCI->getOperand(0); |
| 960 | |
| 961 | PN = dyn_cast<PHINode>(V); |
| 962 | if (!PN) |
| 963 | return false; |
| 964 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 965 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 966 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 967 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 968 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 969 | // It's not safe to eliminate the sign / zero extension of the return value. |
| 970 | // See llvm::isInTailCallPosition(). |
| 971 | const Function *F = BB->getParent(); |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 972 | AttributeSet CallerAttrs = F->getAttributes(); |
| 973 | if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || |
| 974 | CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 975 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 976 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 977 | // Make sure there are no instructions between the PHI and return, or that the |
| 978 | // return is the first instruction in the block. |
| 979 | if (PN) { |
| 980 | BasicBlock::iterator BI = BB->begin(); |
| 981 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 982 | if (&*BI == BCI) |
| 983 | // Also skip over the bitcast. |
| 984 | ++BI; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 985 | if (&*BI != RI) |
| 986 | return false; |
| 987 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 988 | BasicBlock::iterator BI = BB->begin(); |
| 989 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
| 990 | if (&*BI != RI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 991 | return false; |
| 992 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 993 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 994 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 995 | /// call. |
| 996 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 997 | if (PN) { |
| 998 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 999 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 1000 | // Make sure the phi value is indeed produced by the tail call. |
| 1001 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
| 1002 | TLI->mayBeEmittedAsTailCall(CI)) |
| 1003 | TailCalls.push_back(CI); |
| 1004 | } |
| 1005 | } else { |
| 1006 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1007 | for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) { |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 1008 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1009 | continue; |
| 1010 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1011 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1012 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 1013 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1014 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 1015 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1016 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1017 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1018 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Cameron Zwarich | 2edfe77 | 2011-03-24 15:54:11 +0000 | [diff] [blame] | 1019 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1020 | TailCalls.push_back(CI); |
| 1021 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1022 | } |
| 1023 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1024 | bool Changed = false; |
| 1025 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 1026 | CallInst *CI = TailCalls[i]; |
| 1027 | CallSite CS(CI); |
| 1028 | |
| 1029 | // Conservatively require the attributes of the call to match those of the |
| 1030 | // return. Ignore noalias because it doesn't affect the call sequence. |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1031 | AttributeSet CalleeAttrs = CS.getAttributes(); |
| 1032 | if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1033 | removeAttribute(Attribute::NoAlias) != |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1034 | AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1035 | removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1036 | continue; |
| 1037 | |
| 1038 | // Make sure the call instruction is followed by an unconditional branch to |
| 1039 | // the return block. |
| 1040 | BasicBlock *CallBB = CI->getParent(); |
| 1041 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 1042 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 1043 | continue; |
| 1044 | |
| 1045 | // Duplicate the return into CallBB. |
| 1046 | (void)FoldReturnIntoUncondBranch(RI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 1047 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1048 | ++NumRetsDup; |
| 1049 | } |
| 1050 | |
| 1051 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 1052 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1053 | BB->eraseFromParent(); |
| 1054 | |
| 1055 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1056 | } |
| 1057 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1058 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1059 | // Memory Optimization |
| 1060 | //===----------------------------------------------------------------------===// |
| 1061 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1062 | namespace { |
| 1063 | |
| 1064 | /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode |
| 1065 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 1066 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1067 | Value *BaseReg; |
| 1068 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1069 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1070 | void print(raw_ostream &OS) const; |
| 1071 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1072 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1073 | bool operator==(const ExtAddrMode& O) const { |
| 1074 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 1075 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 1076 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 1077 | } |
| 1078 | }; |
| 1079 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 1080 | #ifndef NDEBUG |
| 1081 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 1082 | AM.print(OS); |
| 1083 | return OS; |
| 1084 | } |
| 1085 | #endif |
| 1086 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1087 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 1088 | bool NeedPlus = false; |
| 1089 | OS << "["; |
| 1090 | if (BaseGV) { |
| 1091 | OS << (NeedPlus ? " + " : "") |
| 1092 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1093 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1094 | NeedPlus = true; |
| 1095 | } |
| 1096 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 1097 | if (BaseOffs) { |
| 1098 | OS << (NeedPlus ? " + " : "") |
| 1099 | << BaseOffs; |
| 1100 | NeedPlus = true; |
| 1101 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1102 | |
| 1103 | if (BaseReg) { |
| 1104 | OS << (NeedPlus ? " + " : "") |
| 1105 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1106 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1107 | NeedPlus = true; |
| 1108 | } |
| 1109 | if (Scale) { |
| 1110 | OS << (NeedPlus ? " + " : "") |
| 1111 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1112 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1113 | } |
| 1114 | |
| 1115 | OS << ']'; |
| 1116 | } |
| 1117 | |
| 1118 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 1119 | void ExtAddrMode::dump() const { |
| 1120 | print(dbgs()); |
| 1121 | dbgs() << '\n'; |
| 1122 | } |
| 1123 | #endif |
| 1124 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1125 | /// \brief This class provides transaction based operation on the IR. |
| 1126 | /// Every change made through this class is recorded in the internal state and |
| 1127 | /// can be undone (rollback) until commit is called. |
| 1128 | class TypePromotionTransaction { |
| 1129 | |
| 1130 | /// \brief This represents the common interface of the individual transaction. |
| 1131 | /// Each class implements the logic for doing one specific modification on |
| 1132 | /// the IR via the TypePromotionTransaction. |
| 1133 | class TypePromotionAction { |
| 1134 | protected: |
| 1135 | /// The Instruction modified. |
| 1136 | Instruction *Inst; |
| 1137 | |
| 1138 | public: |
| 1139 | /// \brief Constructor of the action. |
| 1140 | /// The constructor performs the related action on the IR. |
| 1141 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 1142 | |
| 1143 | virtual ~TypePromotionAction() {} |
| 1144 | |
| 1145 | /// \brief Undo the modification done by this action. |
| 1146 | /// When this method is called, the IR must be in the same state as it was |
| 1147 | /// before this action was applied. |
| 1148 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 1149 | /// state as it was directly after this action was applied. |
| 1150 | virtual void undo() = 0; |
| 1151 | |
| 1152 | /// \brief Advocate every change made by this action. |
| 1153 | /// When the results on the IR of the action are to be kept, it is important |
| 1154 | /// to call this function, otherwise hidden information may be kept forever. |
| 1155 | virtual void commit() { |
| 1156 | // Nothing to be done, this action is not doing anything. |
| 1157 | } |
| 1158 | }; |
| 1159 | |
| 1160 | /// \brief Utility to remember the position of an instruction. |
| 1161 | class InsertionHandler { |
| 1162 | /// Position of an instruction. |
| 1163 | /// Either an instruction: |
| 1164 | /// - Is the first in a basic block: BB is used. |
| 1165 | /// - Has a previous instructon: PrevInst is used. |
| 1166 | union { |
| 1167 | Instruction *PrevInst; |
| 1168 | BasicBlock *BB; |
| 1169 | } Point; |
| 1170 | /// Remember whether or not the instruction had a previous instruction. |
| 1171 | bool HasPrevInstruction; |
| 1172 | |
| 1173 | public: |
| 1174 | /// \brief Record the position of \p Inst. |
| 1175 | InsertionHandler(Instruction *Inst) { |
| 1176 | BasicBlock::iterator It = Inst; |
| 1177 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 1178 | if (HasPrevInstruction) |
| 1179 | Point.PrevInst = --It; |
| 1180 | else |
| 1181 | Point.BB = Inst->getParent(); |
| 1182 | } |
| 1183 | |
| 1184 | /// \brief Insert \p Inst at the recorded position. |
| 1185 | void insert(Instruction *Inst) { |
| 1186 | if (HasPrevInstruction) { |
| 1187 | if (Inst->getParent()) |
| 1188 | Inst->removeFromParent(); |
| 1189 | Inst->insertAfter(Point.PrevInst); |
| 1190 | } else { |
| 1191 | Instruction *Position = Point.BB->getFirstInsertionPt(); |
| 1192 | if (Inst->getParent()) |
| 1193 | Inst->moveBefore(Position); |
| 1194 | else |
| 1195 | Inst->insertBefore(Position); |
| 1196 | } |
| 1197 | } |
| 1198 | }; |
| 1199 | |
| 1200 | /// \brief Move an instruction before another. |
| 1201 | class InstructionMoveBefore : public TypePromotionAction { |
| 1202 | /// Original position of the instruction. |
| 1203 | InsertionHandler Position; |
| 1204 | |
| 1205 | public: |
| 1206 | /// \brief Move \p Inst before \p Before. |
| 1207 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 1208 | : TypePromotionAction(Inst), Position(Inst) { |
| 1209 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 1210 | Inst->moveBefore(Before); |
| 1211 | } |
| 1212 | |
| 1213 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1214 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1215 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 1216 | Position.insert(Inst); |
| 1217 | } |
| 1218 | }; |
| 1219 | |
| 1220 | /// \brief Set the operand of an instruction with a new value. |
| 1221 | class OperandSetter : public TypePromotionAction { |
| 1222 | /// Original operand of the instruction. |
| 1223 | Value *Origin; |
| 1224 | /// Index of the modified instruction. |
| 1225 | unsigned Idx; |
| 1226 | |
| 1227 | public: |
| 1228 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 1229 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 1230 | : TypePromotionAction(Inst), Idx(Idx) { |
| 1231 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 1232 | << "for:" << *Inst << "\n" |
| 1233 | << "with:" << *NewVal << "\n"); |
| 1234 | Origin = Inst->getOperand(Idx); |
| 1235 | Inst->setOperand(Idx, NewVal); |
| 1236 | } |
| 1237 | |
| 1238 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1239 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1240 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 1241 | << "for: " << *Inst << "\n" |
| 1242 | << "with: " << *Origin << "\n"); |
| 1243 | Inst->setOperand(Idx, Origin); |
| 1244 | } |
| 1245 | }; |
| 1246 | |
| 1247 | /// \brief Hide the operands of an instruction. |
| 1248 | /// Do as if this instruction was not using any of its operands. |
| 1249 | class OperandsHider : public TypePromotionAction { |
| 1250 | /// The list of original operands. |
| 1251 | SmallVector<Value *, 4> OriginalValues; |
| 1252 | |
| 1253 | public: |
| 1254 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 1255 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 1256 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 1257 | unsigned NumOpnds = Inst->getNumOperands(); |
| 1258 | OriginalValues.reserve(NumOpnds); |
| 1259 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 1260 | // Save the current operand. |
| 1261 | Value *Val = Inst->getOperand(It); |
| 1262 | OriginalValues.push_back(Val); |
| 1263 | // Set a dummy one. |
| 1264 | // We could use OperandSetter here, but that would implied an overhead |
| 1265 | // that we are not willing to pay. |
| 1266 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 1267 | } |
| 1268 | } |
| 1269 | |
| 1270 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1271 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1272 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 1273 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 1274 | Inst->setOperand(It, OriginalValues[It]); |
| 1275 | } |
| 1276 | }; |
| 1277 | |
| 1278 | /// \brief Build a truncate instruction. |
| 1279 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1280 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1281 | public: |
| 1282 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 1283 | /// result. |
| 1284 | /// trunc Opnd to Ty. |
| 1285 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 1286 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1287 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 1288 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1289 | } |
| 1290 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1291 | /// \brief Get the built value. |
| 1292 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1293 | |
| 1294 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1295 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1296 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 1297 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 1298 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1299 | } |
| 1300 | }; |
| 1301 | |
| 1302 | /// \brief Build a sign extension instruction. |
| 1303 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1304 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1305 | public: |
| 1306 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 1307 | /// result. |
| 1308 | /// sext Opnd to Ty. |
| 1309 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1310 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1311 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1312 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 1313 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1314 | } |
| 1315 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1316 | /// \brief Get the built value. |
| 1317 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1318 | |
| 1319 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1320 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1321 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 1322 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 1323 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1324 | } |
| 1325 | }; |
| 1326 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1327 | /// \brief Build a zero extension instruction. |
| 1328 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1329 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1330 | public: |
| 1331 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 1332 | /// result. |
| 1333 | /// zext Opnd to Ty. |
| 1334 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1335 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1336 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1337 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 1338 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1339 | } |
| 1340 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1341 | /// \brief Get the built value. |
| 1342 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1343 | |
| 1344 | /// \brief Remove the built instruction. |
| 1345 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1346 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 1347 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 1348 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1349 | } |
| 1350 | }; |
| 1351 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1352 | /// \brief Mutate an instruction to another type. |
| 1353 | class TypeMutator : public TypePromotionAction { |
| 1354 | /// Record the original type. |
| 1355 | Type *OrigTy; |
| 1356 | |
| 1357 | public: |
| 1358 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 1359 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 1360 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 1361 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 1362 | << "\n"); |
| 1363 | Inst->mutateType(NewTy); |
| 1364 | } |
| 1365 | |
| 1366 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1367 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1368 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 1369 | << "\n"); |
| 1370 | Inst->mutateType(OrigTy); |
| 1371 | } |
| 1372 | }; |
| 1373 | |
| 1374 | /// \brief Replace the uses of an instruction by another instruction. |
| 1375 | class UsesReplacer : public TypePromotionAction { |
| 1376 | /// Helper structure to keep track of the replaced uses. |
| 1377 | struct InstructionAndIdx { |
| 1378 | /// The instruction using the instruction. |
| 1379 | Instruction *Inst; |
| 1380 | /// The index where this instruction is used for Inst. |
| 1381 | unsigned Idx; |
| 1382 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 1383 | : Inst(Inst), Idx(Idx) {} |
| 1384 | }; |
| 1385 | |
| 1386 | /// Keep track of the original uses (pair Instruction, Index). |
| 1387 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 1388 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 1389 | |
| 1390 | public: |
| 1391 | /// \brief Replace all the use of \p Inst by \p New. |
| 1392 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 1393 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 1394 | << "\n"); |
| 1395 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1396 | for (Use &U : Inst->uses()) { |
| 1397 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 1398 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1399 | } |
| 1400 | // Now, we can replace the uses. |
| 1401 | Inst->replaceAllUsesWith(New); |
| 1402 | } |
| 1403 | |
| 1404 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1405 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1406 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 1407 | for (use_iterator UseIt = OriginalUses.begin(), |
| 1408 | EndIt = OriginalUses.end(); |
| 1409 | UseIt != EndIt; ++UseIt) { |
| 1410 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 1411 | } |
| 1412 | } |
| 1413 | }; |
| 1414 | |
| 1415 | /// \brief Remove an instruction from the IR. |
| 1416 | class InstructionRemover : public TypePromotionAction { |
| 1417 | /// Original position of the instruction. |
| 1418 | InsertionHandler Inserter; |
| 1419 | /// Helper structure to hide all the link to the instruction. In other |
| 1420 | /// words, this helps to do as if the instruction was removed. |
| 1421 | OperandsHider Hider; |
| 1422 | /// Keep track of the uses replaced, if any. |
| 1423 | UsesReplacer *Replacer; |
| 1424 | |
| 1425 | public: |
| 1426 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 1427 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1428 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 1429 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1430 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1431 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1432 | if (New) |
| 1433 | Replacer = new UsesReplacer(Inst, New); |
| 1434 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 1435 | Inst->removeFromParent(); |
| 1436 | } |
| 1437 | |
| 1438 | ~InstructionRemover() { delete Replacer; } |
| 1439 | |
| 1440 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1441 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1442 | |
| 1443 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 1444 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 1445 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1446 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 1447 | Inserter.insert(Inst); |
| 1448 | if (Replacer) |
| 1449 | Replacer->undo(); |
| 1450 | Hider.undo(); |
| 1451 | } |
| 1452 | }; |
| 1453 | |
| 1454 | public: |
| 1455 | /// Restoration point. |
| 1456 | /// The restoration point is a pointer to an action instead of an iterator |
| 1457 | /// because the iterator may be invalidated but not the pointer. |
| 1458 | typedef const TypePromotionAction *ConstRestorationPt; |
| 1459 | /// Advocate every changes made in that transaction. |
| 1460 | void commit(); |
| 1461 | /// Undo all the changes made after the given point. |
| 1462 | void rollback(ConstRestorationPt Point); |
| 1463 | /// Get the current restoration point. |
| 1464 | ConstRestorationPt getRestorationPoint() const; |
| 1465 | |
| 1466 | /// \name API for IR modification with state keeping to support rollback. |
| 1467 | /// @{ |
| 1468 | /// Same as Instruction::setOperand. |
| 1469 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 1470 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1471 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1472 | /// Same as Value::replaceAllUsesWith. |
| 1473 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 1474 | /// Same as Value::mutateType. |
| 1475 | void mutateType(Instruction *Inst, Type *NewTy); |
| 1476 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1477 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1478 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1479 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1480 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1481 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1482 | /// Same as Instruction::moveBefore. |
| 1483 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 1484 | /// @} |
| 1485 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1486 | private: |
| 1487 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1488 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 1489 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1490 | }; |
| 1491 | |
| 1492 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 1493 | Value *NewVal) { |
| 1494 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1495 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1496 | } |
| 1497 | |
| 1498 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 1499 | Value *NewVal) { |
| 1500 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1501 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1502 | } |
| 1503 | |
| 1504 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 1505 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1506 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1507 | } |
| 1508 | |
| 1509 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1510 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1511 | } |
| 1512 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1513 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 1514 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1515 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1516 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1517 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1518 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1519 | } |
| 1520 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1521 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 1522 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1523 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1524 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1525 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1526 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1527 | } |
| 1528 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1529 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 1530 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1531 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1532 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1533 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1534 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1535 | } |
| 1536 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1537 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 1538 | Instruction *Before) { |
| 1539 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1540 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1541 | } |
| 1542 | |
| 1543 | TypePromotionTransaction::ConstRestorationPt |
| 1544 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1545 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1546 | } |
| 1547 | |
| 1548 | void TypePromotionTransaction::commit() { |
| 1549 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1550 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1551 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1552 | Actions.clear(); |
| 1553 | } |
| 1554 | |
| 1555 | void TypePromotionTransaction::rollback( |
| 1556 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 1557 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 1558 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1559 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1560 | } |
| 1561 | } |
| 1562 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1563 | /// \brief A helper class for matching addressing modes. |
| 1564 | /// |
| 1565 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 1566 | class AddressingModeMatcher { |
| 1567 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
| 1568 | const TargetLowering &TLI; |
| 1569 | |
| 1570 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 1571 | /// the memory instruction that we're computing this address for. |
| 1572 | Type *AccessTy; |
| 1573 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1574 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1575 | /// AddrMode - This is the addressing mode that we're building up. This is |
| 1576 | /// part of the return value of this addressing mode matching stuff. |
| 1577 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1578 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1579 | /// The truncate instruction inserted by other CodeGenPrepare optimizations. |
| 1580 | const SetOfInstrs &InsertedTruncs; |
| 1581 | /// A map from the instructions to their type before promotion. |
| 1582 | InstrToOrigTy &PromotedInsts; |
| 1583 | /// The ongoing transaction where every action should be registered. |
| 1584 | TypePromotionTransaction &TPT; |
| 1585 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1586 | /// IgnoreProfitability - This is set to true when we should not do |
| 1587 | /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode |
| 1588 | /// always returns true. |
| 1589 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1590 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1591 | AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI, |
| 1592 | const TargetLowering &T, Type *AT, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1593 | Instruction *MI, ExtAddrMode &AM, |
| 1594 | const SetOfInstrs &InsertedTruncs, |
| 1595 | InstrToOrigTy &PromotedInsts, |
| 1596 | TypePromotionTransaction &TPT) |
| 1597 | : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM), |
| 1598 | InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1599 | IgnoreProfitability = false; |
| 1600 | } |
| 1601 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1602 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1603 | /// Match - Find the maximal addressing mode that a load/store of V can fold, |
| 1604 | /// give an access type of AccessTy. This returns a list of involved |
| 1605 | /// instructions in AddrModeInsts. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1606 | /// \p InsertedTruncs The truncate instruction inserted by other |
| 1607 | /// CodeGenPrepare |
| 1608 | /// optimizations. |
| 1609 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1610 | /// \p The ongoing transaction where every action should be registered. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1611 | static ExtAddrMode Match(Value *V, Type *AccessTy, |
| 1612 | Instruction *MemoryInst, |
| 1613 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1614 | const TargetLowering &TLI, |
| 1615 | const SetOfInstrs &InsertedTruncs, |
| 1616 | InstrToOrigTy &PromotedInsts, |
| 1617 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1618 | ExtAddrMode Result; |
| 1619 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1620 | bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy, |
| 1621 | MemoryInst, Result, InsertedTruncs, |
| 1622 | PromotedInsts, TPT).MatchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1623 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 1624 | return Result; |
| 1625 | } |
| 1626 | private: |
| 1627 | bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 1628 | bool MatchAddr(Value *V, unsigned Depth); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1629 | bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1630 | bool *MovedAway = nullptr); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1631 | bool IsProfitableToFoldIntoAddressingMode(Instruction *I, |
| 1632 | ExtAddrMode &AMBefore, |
| 1633 | ExtAddrMode &AMAfter); |
| 1634 | bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 1635 | bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion, |
| 1636 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1637 | }; |
| 1638 | |
| 1639 | /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode. |
| 1640 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 1641 | /// false if not. |
| 1642 | bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale, |
| 1643 | unsigned Depth) { |
| 1644 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 1645 | // mode. Just process that directly. |
| 1646 | if (Scale == 1) |
| 1647 | return MatchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1648 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1649 | // If the scale is 0, it takes nothing to add this. |
| 1650 | if (Scale == 0) |
| 1651 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1652 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1653 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 1654 | // need an available scale field. |
| 1655 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 1656 | return false; |
| 1657 | |
| 1658 | ExtAddrMode TestAddrMode = AddrMode; |
| 1659 | |
| 1660 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 1661 | // [A+B + A*7] -> [B+A*8]. |
| 1662 | TestAddrMode.Scale += Scale; |
| 1663 | TestAddrMode.ScaledReg = ScaleReg; |
| 1664 | |
| 1665 | // If the new address isn't legal, bail out. |
| 1666 | if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) |
| 1667 | return false; |
| 1668 | |
| 1669 | // It was legal, so commit it. |
| 1670 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1671 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1672 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 1673 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 1674 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1675 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1676 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 1677 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 1678 | TestAddrMode.ScaledReg = AddLHS; |
| 1679 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1680 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1681 | // If this addressing mode is legal, commit it and remember that we folded |
| 1682 | // this instruction. |
| 1683 | if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) { |
| 1684 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 1685 | AddrMode = TestAddrMode; |
| 1686 | return true; |
| 1687 | } |
| 1688 | } |
| 1689 | |
| 1690 | // Otherwise, not (x+c)*scale, just return what we have. |
| 1691 | return true; |
| 1692 | } |
| 1693 | |
| 1694 | /// MightBeFoldableInst - This is a little filter, which returns true if an |
| 1695 | /// addressing computation involving I might be folded into a load/store |
| 1696 | /// accessing it. This doesn't need to be perfect, but needs to accept at least |
| 1697 | /// the set of instructions that MatchOperationAddr can. |
| 1698 | static bool MightBeFoldableInst(Instruction *I) { |
| 1699 | switch (I->getOpcode()) { |
| 1700 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 1701 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1702 | // Don't touch identity bitcasts. |
| 1703 | if (I->getType() == I->getOperand(0)->getType()) |
| 1704 | return false; |
| 1705 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 1706 | case Instruction::PtrToInt: |
| 1707 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 1708 | return true; |
| 1709 | case Instruction::IntToPtr: |
| 1710 | // We know the input is intptr_t, so this is foldable. |
| 1711 | return true; |
| 1712 | case Instruction::Add: |
| 1713 | return true; |
| 1714 | case Instruction::Mul: |
| 1715 | case Instruction::Shl: |
| 1716 | // Can only handle X*C and X << C. |
| 1717 | return isa<ConstantInt>(I->getOperand(1)); |
| 1718 | case Instruction::GetElementPtr: |
| 1719 | return true; |
| 1720 | default: |
| 1721 | return false; |
| 1722 | } |
| 1723 | } |
| 1724 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1725 | /// \brief Hepler class to perform type promotion. |
| 1726 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1727 | /// \brief Utility function to check whether or not a sign or zero extension |
| 1728 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 1729 | /// either using the operands of \p Inst or promoting \p Inst. |
| 1730 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1731 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1732 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1733 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1734 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1735 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1736 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1737 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1738 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 1739 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1740 | |
| 1741 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 1742 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1743 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1744 | if (isa<SelectInst>(Inst) && OpIdx == 0) |
| 1745 | return false; |
| 1746 | return true; |
| 1747 | } |
| 1748 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1749 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1750 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1751 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1752 | /// \p CreatedInsts[out] contains how many non-free instructions have been |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1753 | /// created to promote the operand of Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1754 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1755 | /// \return The promoted value which is used instead of Ext. |
| 1756 | static Value *promoteOperandForTruncAndAnyExt(Instruction *Ext, |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1757 | TypePromotionTransaction &TPT, |
| 1758 | InstrToOrigTy &PromotedInsts, |
| 1759 | unsigned &CreatedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1760 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1761 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1762 | /// operand is promotable and is not a supported trunc or sext. |
| 1763 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 1764 | /// \p CreatedInsts[out] contains how many non-free instructions have been |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1765 | /// created to promote the operand of Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1766 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1767 | /// \return The promoted value which is used instead of Ext. |
| 1768 | static Value *promoteOperandForOther(Instruction *Ext, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1769 | TypePromotionTransaction &TPT, |
| 1770 | InstrToOrigTy &PromotedInsts, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1771 | unsigned &CreatedInsts, bool IsSExt); |
| 1772 | |
| 1773 | /// \see promoteOperandForOther. |
| 1774 | static Value *signExtendOperandForOther(Instruction *Ext, |
| 1775 | TypePromotionTransaction &TPT, |
| 1776 | InstrToOrigTy &PromotedInsts, |
| 1777 | unsigned &CreatedInsts) { |
| 1778 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, true); |
| 1779 | } |
| 1780 | |
| 1781 | /// \see promoteOperandForOther. |
| 1782 | static Value *zeroExtendOperandForOther(Instruction *Ext, |
| 1783 | TypePromotionTransaction &TPT, |
| 1784 | InstrToOrigTy &PromotedInsts, |
| 1785 | unsigned &CreatedInsts) { |
| 1786 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, false); |
| 1787 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1788 | |
| 1789 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1790 | /// Type for the utility function that promotes the operand of Ext. |
| 1791 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1792 | InstrToOrigTy &PromotedInsts, |
| 1793 | unsigned &CreatedInsts); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1794 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 1795 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1796 | /// \return NULL if no promotable action is possible with the current |
| 1797 | /// sign extension. |
| 1798 | /// \p InsertedTruncs keeps track of all the truncate instructions inserted by |
| 1799 | /// the others CodeGenPrepare optimizations. This information is important |
| 1800 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 1801 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 1802 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1803 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1804 | const TargetLowering &TLI, |
| 1805 | const InstrToOrigTy &PromotedInsts); |
| 1806 | }; |
| 1807 | |
| 1808 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1809 | Type *ConsideredExtType, |
| 1810 | const InstrToOrigTy &PromotedInsts, |
| 1811 | bool IsSExt) { |
| 1812 | // We can always get through zext. |
| 1813 | if (isa<ZExtInst>(Inst)) |
| 1814 | return true; |
| 1815 | |
| 1816 | // sext(sext) is ok too. |
| 1817 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1818 | return true; |
| 1819 | |
| 1820 | // We can get through binary operator, if it is legal. In other words, the |
| 1821 | // binary operator must have a nuw or nsw flag. |
| 1822 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 1823 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1824 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 1825 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1826 | return true; |
| 1827 | |
| 1828 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1829 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1830 | if (!isa<TruncInst>(Inst)) |
| 1831 | return false; |
| 1832 | |
| 1833 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1834 | // Check if we can use this operand in the extension. |
| 1835 | // If the type is larger than the result type of the extension, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1836 | // we cannot. |
| 1837 | if (OpndVal->getType()->getIntegerBitWidth() > |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1838 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1839 | return false; |
| 1840 | |
| 1841 | // If the operand of the truncate is not an instruction, we will not have |
| 1842 | // any information on the dropped bits. |
| 1843 | // (Actually we could for constant but it is not worth the extra logic). |
| 1844 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 1845 | if (!Opnd) |
| 1846 | return false; |
| 1847 | |
| 1848 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1849 | // I.e., check that trunc just drops extended bits of the same kind of |
| 1850 | // the extension. |
| 1851 | // #1 get the type of the operand and check the kind of the extended bits. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1852 | const Type *OpndType; |
| 1853 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1854 | if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt) |
| 1855 | OpndType = It->second.Ty; |
| 1856 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 1857 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1858 | else |
| 1859 | return false; |
| 1860 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1861 | // #2 check that the truncate just drop extended bits. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1862 | if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth()) |
| 1863 | return true; |
| 1864 | |
| 1865 | return false; |
| 1866 | } |
| 1867 | |
| 1868 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1869 | Instruction *Ext, const SetOfInstrs &InsertedTruncs, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1870 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1871 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 1872 | "Unexpected instruction type"); |
| 1873 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 1874 | Type *ExtTy = Ext->getType(); |
| 1875 | bool IsSExt = isa<SExtInst>(Ext); |
| 1876 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1877 | // get through. |
| 1878 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1879 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1880 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1881 | |
| 1882 | // Do not promote if the operand has been added by codegenprepare. |
| 1883 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 1884 | // redone, thus causing potential infinite loop. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1885 | if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1886 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1887 | |
| 1888 | // SExt or Trunc instructions. |
| 1889 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1890 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 1891 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1892 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1893 | |
| 1894 | // Regular instruction. |
| 1895 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1896 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1897 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1898 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1899 | } |
| 1900 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1901 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1902 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
| 1903 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) { |
| 1904 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 1905 | // get through it and this method should not be called. |
| 1906 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1907 | Value *ExtVal = SExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1908 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1909 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1910 | // => zext(opnd). |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1911 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1912 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 1913 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 1914 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1915 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1916 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1917 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 1918 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 1919 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 1920 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1921 | CreatedInsts = 0; |
| 1922 | |
| 1923 | // Remove dead code. |
| 1924 | if (SExtOpnd->use_empty()) |
| 1925 | TPT.eraseInstruction(SExtOpnd); |
| 1926 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 1927 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1928 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
| 1929 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) |
| 1930 | return ExtVal; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1931 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 1932 | // At this point we have: ext ty opnd to ty. |
| 1933 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 1934 | Value *NextVal = ExtInst->getOperand(0); |
| 1935 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1936 | return NextVal; |
| 1937 | } |
| 1938 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1939 | Value *TypePromotionHelper::promoteOperandForOther( |
| 1940 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 1941 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts, bool IsSExt) { |
| 1942 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1943 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1944 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1945 | CreatedInsts = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1946 | if (!ExtOpnd->hasOneUse()) { |
| 1947 | // ExtOpnd will be promoted. |
| 1948 | // All its uses, but Ext, will need to use a truncated value of the |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1949 | // promoted version. |
| 1950 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1951 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1952 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 1953 | ITrunc->removeFromParent(); |
| 1954 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1955 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 1956 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1957 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1958 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
| 1959 | // Restore the operand of Ext (which has been replace by the previous call |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1960 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1961 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1962 | } |
| 1963 | |
| 1964 | // Get through the Instruction: |
| 1965 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1966 | // 2. Replace the uses of Ext by Inst. |
| 1967 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1968 | |
| 1969 | // Remember the original type of the instruction before promotion. |
| 1970 | // This is useful to know that the high bits are sign extended bits. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1971 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 1972 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1973 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1974 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1975 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1976 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1977 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1978 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1979 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1980 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 1981 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1982 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1983 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 1984 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 1985 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1986 | DEBUG(dbgs() << "No need to propagate\n"); |
| 1987 | continue; |
| 1988 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1989 | // Check if we can statically extend the operand. |
| 1990 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1991 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 1992 | DEBUG(dbgs() << "Statically extend\n"); |
| 1993 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 1994 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 1995 | : Cst->getValue().zext(BitWidth); |
| 1996 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1997 | continue; |
| 1998 | } |
| 1999 | // UndefValue are typed, so we have to statically sign extend them. |
| 2000 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2001 | DEBUG(dbgs() << "Statically extend\n"); |
| 2002 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2003 | continue; |
| 2004 | } |
| 2005 | |
| 2006 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2007 | // Check if Ext was reused to extend an operand. |
| 2008 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2009 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2010 | DEBUG(dbgs() << "More operands to ext\n"); |
| 2011 | ExtForOpnd = |
| 2012 | cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 2013 | : TPT.createZExt(Ext, Opnd, Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2014 | ++CreatedInsts; |
| 2015 | } |
| 2016 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2017 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2018 | |
| 2019 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2020 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 2021 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2022 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2023 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2024 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2025 | if (ExtForOpnd == Ext) { |
| 2026 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 2027 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2028 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2029 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2030 | } |
| 2031 | |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2032 | /// IsPromotionProfitable - Check whether or not promoting an instruction |
| 2033 | /// to a wider type was profitable. |
| 2034 | /// \p MatchedSize gives the number of instructions that have been matched |
| 2035 | /// in the addressing mode after the promotion was applied. |
| 2036 | /// \p SizeWithPromotion gives the number of created instructions for |
| 2037 | /// the promotion plus the number of instructions that have been |
| 2038 | /// matched in the addressing mode before the promotion. |
| 2039 | /// \p PromotedOperand is the value that has been promoted. |
| 2040 | /// \return True if the promotion is profitable, false otherwise. |
| 2041 | bool |
| 2042 | AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize, |
| 2043 | unsigned SizeWithPromotion, |
| 2044 | Value *PromotedOperand) const { |
| 2045 | // We folded less instructions than what we created to promote the operand. |
| 2046 | // This is not profitable. |
| 2047 | if (MatchedSize < SizeWithPromotion) |
| 2048 | return false; |
| 2049 | if (MatchedSize > SizeWithPromotion) |
| 2050 | return true; |
| 2051 | // The promotion is neutral but it may help folding the sign extension in |
| 2052 | // loads for instance. |
| 2053 | // Check that we did not create an illegal instruction. |
| 2054 | Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand); |
| 2055 | if (!PromotedInst) |
| 2056 | return false; |
Quentin Colombet | 1627a41 | 2014-02-22 01:06:41 +0000 | [diff] [blame] | 2057 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 2058 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 2059 | if (!ISDOpcode) |
| 2060 | return true; |
| 2061 | // Otherwise, check if the promoted instruction is legal or not. |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 2062 | return TLI.isOperationLegalOrCustom( |
| 2063 | ISDOpcode, TLI.getValueType(PromotedInst->getType())); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2064 | } |
| 2065 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2066 | /// MatchOperationAddr - Given an instruction or constant expr, see if we can |
| 2067 | /// fold the operation into the addressing mode. If so, update the addressing |
| 2068 | /// mode and return true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2069 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 2070 | /// not AddrInst has to be folded into the addressing mode on success. |
| 2071 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 2072 | /// because it has been moved away. |
| 2073 | /// Thus AddrInst must not be added in the matched instructions. |
| 2074 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 2075 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 2076 | /// not be referenced anymore. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2077 | bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2078 | unsigned Depth, |
| 2079 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2080 | // Avoid exponential behavior on extremely deep expression trees. |
| 2081 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2082 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2083 | // By default, all matched instructions stay in place. |
| 2084 | if (MovedAway) |
| 2085 | *MovedAway = false; |
| 2086 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2087 | switch (Opcode) { |
| 2088 | case Instruction::PtrToInt: |
| 2089 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 2090 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2091 | case Instruction::IntToPtr: |
| 2092 | // This inttoptr is a no-op if the integer type is pointer sized. |
| 2093 | if (TLI.getValueType(AddrInst->getOperand(0)->getType()) == |
Matt Arsenault | 37d42ec | 2013-09-06 00:18:43 +0000 | [diff] [blame] | 2094 | TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace())) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2095 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2096 | return false; |
| 2097 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 2098 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2099 | // BitCast is always a noop, and we can handle it as long as it is |
| 2100 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 2101 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 2102 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 2103 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 2104 | // and we don't want to mess around with them. Assume it knows what it |
| 2105 | // is doing. |
| 2106 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
| 2107 | return MatchAddr(AddrInst->getOperand(0), Depth); |
| 2108 | return false; |
| 2109 | case Instruction::Add: { |
| 2110 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 2111 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2112 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2113 | // Start a transaction at this point. |
| 2114 | // The LHS may match but not the RHS. |
| 2115 | // Therefore, we need a higher level restoration point to undo partially |
| 2116 | // matched operation. |
| 2117 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2118 | TPT.getRestorationPoint(); |
| 2119 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2120 | if (MatchAddr(AddrInst->getOperand(1), Depth+1) && |
| 2121 | MatchAddr(AddrInst->getOperand(0), Depth+1)) |
| 2122 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2123 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2124 | // Restore the old addr mode info. |
| 2125 | AddrMode = BackupAddrMode; |
| 2126 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2127 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2128 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2129 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. |
| 2130 | if (MatchAddr(AddrInst->getOperand(0), Depth+1) && |
| 2131 | MatchAddr(AddrInst->getOperand(1), Depth+1)) |
| 2132 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2133 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2134 | // Otherwise we definitely can't merge the ADD in. |
| 2135 | AddrMode = BackupAddrMode; |
| 2136 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2137 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2138 | break; |
| 2139 | } |
| 2140 | //case Instruction::Or: |
| 2141 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 2142 | //break; |
| 2143 | case Instruction::Mul: |
| 2144 | case Instruction::Shl: { |
| 2145 | // Can only handle X*C and X << C. |
| 2146 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 2147 | if (!RHS) |
| 2148 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2149 | int64_t Scale = RHS->getSExtValue(); |
| 2150 | if (Opcode == Instruction::Shl) |
| 2151 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2152 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2153 | return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
| 2154 | } |
| 2155 | case Instruction::GetElementPtr: { |
| 2156 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 2157 | // one variable offset. |
| 2158 | int VariableOperand = -1; |
| 2159 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2160 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2161 | int64_t ConstantOffset = 0; |
| 2162 | const DataLayout *TD = TLI.getDataLayout(); |
| 2163 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 2164 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
| 2165 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
| 2166 | const StructLayout *SL = TD->getStructLayout(STy); |
| 2167 | unsigned Idx = |
| 2168 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 2169 | ConstantOffset += SL->getElementOffset(Idx); |
| 2170 | } else { |
| 2171 | uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType()); |
| 2172 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 2173 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 2174 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 2175 | // We only allow one variable index at the moment. |
| 2176 | if (VariableOperand != -1) |
| 2177 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2178 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2179 | // Remember the variable index. |
| 2180 | VariableOperand = i; |
| 2181 | VariableScale = TypeSize; |
| 2182 | } |
| 2183 | } |
| 2184 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2185 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2186 | // A common case is for the GEP to only do a constant offset. In this case, |
| 2187 | // just add it to the disp field and check validity. |
| 2188 | if (VariableOperand == -1) { |
| 2189 | AddrMode.BaseOffs += ConstantOffset; |
| 2190 | if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){ |
| 2191 | // Check to see if we can fold the base pointer in too. |
| 2192 | if (MatchAddr(AddrInst->getOperand(0), Depth+1)) |
| 2193 | return true; |
| 2194 | } |
| 2195 | AddrMode.BaseOffs -= ConstantOffset; |
| 2196 | return false; |
| 2197 | } |
| 2198 | |
| 2199 | // Save the valid addressing mode in case we can't match. |
| 2200 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2201 | unsigned OldSize = AddrModeInsts.size(); |
| 2202 | |
| 2203 | // See if the scale and offset amount is valid for this target. |
| 2204 | AddrMode.BaseOffs += ConstantOffset; |
| 2205 | |
| 2206 | // Match the base operand of the GEP. |
| 2207 | if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) { |
| 2208 | // If it couldn't be matched, just stuff the value in a register. |
| 2209 | if (AddrMode.HasBaseReg) { |
| 2210 | AddrMode = BackupAddrMode; |
| 2211 | AddrModeInsts.resize(OldSize); |
| 2212 | return false; |
| 2213 | } |
| 2214 | AddrMode.HasBaseReg = true; |
| 2215 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 2216 | } |
| 2217 | |
| 2218 | // Match the remaining variable portion of the GEP. |
| 2219 | if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
| 2220 | Depth)) { |
| 2221 | // If it couldn't be matched, try stuffing the base into a register |
| 2222 | // instead of matching it, and retrying the match of the scale. |
| 2223 | AddrMode = BackupAddrMode; |
| 2224 | AddrModeInsts.resize(OldSize); |
| 2225 | if (AddrMode.HasBaseReg) |
| 2226 | return false; |
| 2227 | AddrMode.HasBaseReg = true; |
| 2228 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 2229 | AddrMode.BaseOffs += ConstantOffset; |
| 2230 | if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), |
| 2231 | VariableScale, Depth)) { |
| 2232 | // If even that didn't work, bail. |
| 2233 | AddrMode = BackupAddrMode; |
| 2234 | AddrModeInsts.resize(OldSize); |
| 2235 | return false; |
| 2236 | } |
| 2237 | } |
| 2238 | |
| 2239 | return true; |
| 2240 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2241 | case Instruction::SExt: |
| 2242 | case Instruction::ZExt: { |
| 2243 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 2244 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 2245 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 2246 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2247 | // Try to move this ext out of the way of the addressing mode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2248 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2249 | TypePromotionHelper::Action TPH = |
| 2250 | TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2251 | if (!TPH) |
| 2252 | return false; |
| 2253 | |
| 2254 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2255 | TPT.getRestorationPoint(); |
| 2256 | unsigned CreatedInsts = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2257 | Value *PromotedOperand = TPH(Ext, TPT, PromotedInsts, CreatedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2258 | // SExt has been moved away. |
| 2259 | // Thus either it will be rematched later in the recursive calls or it is |
| 2260 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 2261 | // E.g., |
| 2262 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2263 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2264 | // addr = gep base, idx |
| 2265 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2266 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2267 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 2268 | // addr = gep base, op <- match |
| 2269 | if (MovedAway) |
| 2270 | *MovedAway = true; |
| 2271 | |
| 2272 | assert(PromotedOperand && |
| 2273 | "TypePromotionHelper should have filtered out those cases"); |
| 2274 | |
| 2275 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2276 | unsigned OldSize = AddrModeInsts.size(); |
| 2277 | |
| 2278 | if (!MatchAddr(PromotedOperand, Depth) || |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2279 | !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts, |
| 2280 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2281 | AddrMode = BackupAddrMode; |
| 2282 | AddrModeInsts.resize(OldSize); |
| 2283 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 2284 | TPT.rollback(LastKnownGood); |
| 2285 | return false; |
| 2286 | } |
| 2287 | return true; |
| 2288 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2289 | } |
| 2290 | return false; |
| 2291 | } |
| 2292 | |
| 2293 | /// MatchAddr - If we can, try to add the value of 'Addr' into the current |
| 2294 | /// addressing mode. If Addr can't be added to AddrMode this returns false and |
| 2295 | /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type |
| 2296 | /// or intptr_t for the target. |
| 2297 | /// |
| 2298 | bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2299 | // Start a transaction at this point that we will rollback if the matching |
| 2300 | // fails. |
| 2301 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2302 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2303 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 2304 | // Fold in immediates if legal for the target. |
| 2305 | AddrMode.BaseOffs += CI->getSExtValue(); |
| 2306 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2307 | return true; |
| 2308 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 2309 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 2310 | // If this is a global variable, try to fold it into the addressing mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2311 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2312 | AddrMode.BaseGV = GV; |
| 2313 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2314 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2315 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2316 | } |
| 2317 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 2318 | ExtAddrMode BackupAddrMode = AddrMode; |
| 2319 | unsigned OldSize = AddrModeInsts.size(); |
| 2320 | |
| 2321 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2322 | bool MovedAway = false; |
| 2323 | if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
| 2324 | // This instruction may have been move away. If so, there is nothing |
| 2325 | // to check here. |
| 2326 | if (MovedAway) |
| 2327 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2328 | // Okay, it's possible to fold this. Check to see if it is actually |
| 2329 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 2330 | // register pressure too much. |
| 2331 | if (I->hasOneUse() || |
| 2332 | IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
| 2333 | AddrModeInsts.push_back(I); |
| 2334 | return true; |
| 2335 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2336 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2337 | // It isn't profitable to do this, roll back. |
| 2338 | //cerr << "NOT FOLDING: " << *I; |
| 2339 | AddrMode = BackupAddrMode; |
| 2340 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2341 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2342 | } |
| 2343 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
| 2344 | if (MatchOperationAddr(CE, CE->getOpcode(), Depth)) |
| 2345 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2346 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2347 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 2348 | // Null pointer gets folded without affecting the addressing mode. |
| 2349 | return true; |
| 2350 | } |
| 2351 | |
| 2352 | // Worse case, the target should support [reg] addressing modes. :) |
| 2353 | if (!AddrMode.HasBaseReg) { |
| 2354 | AddrMode.HasBaseReg = true; |
| 2355 | AddrMode.BaseReg = Addr; |
| 2356 | // Still check for legality in case the target supports [imm] but not [i+r]. |
| 2357 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2358 | return true; |
| 2359 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2360 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2361 | } |
| 2362 | |
| 2363 | // If the base register is already taken, see if we can do [r+r]. |
| 2364 | if (AddrMode.Scale == 0) { |
| 2365 | AddrMode.Scale = 1; |
| 2366 | AddrMode.ScaledReg = Addr; |
| 2367 | if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) |
| 2368 | return true; |
| 2369 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2370 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2371 | } |
| 2372 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2373 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2374 | return false; |
| 2375 | } |
| 2376 | |
| 2377 | /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified |
| 2378 | /// inline asm call are due to memory operands. If so, return true, otherwise |
| 2379 | /// return false. |
| 2380 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
| 2381 | const TargetLowering &TLI) { |
| 2382 | TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI)); |
| 2383 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 2384 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2385 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2386 | // Compute the constraint code and ConstraintType to use. |
| 2387 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); |
| 2388 | |
| 2389 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 2390 | // operand, we can't fold it! |
| 2391 | if (OpInfo.CallOperandVal == OpVal && |
| 2392 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 2393 | !OpInfo.isIndirect)) |
| 2394 | return false; |
| 2395 | } |
| 2396 | |
| 2397 | return true; |
| 2398 | } |
| 2399 | |
| 2400 | /// FindAllMemoryUses - Recursively walk all the uses of I until we find a |
| 2401 | /// memory use. If we find an obviously non-foldable instruction, return true. |
| 2402 | /// Add the ultimately found memory instructions to MemoryUses. |
| 2403 | static bool FindAllMemoryUses(Instruction *I, |
| 2404 | SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses, |
Craig Topper | 71b7b68 | 2014-08-21 05:55:13 +0000 | [diff] [blame] | 2405 | SmallPtrSetImpl<Instruction*> &ConsideredInsts, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2406 | const TargetLowering &TLI) { |
| 2407 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 2408 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2409 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2410 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2411 | // If this is an obviously unfoldable instruction, bail out. |
| 2412 | if (!MightBeFoldableInst(I)) |
| 2413 | return true; |
| 2414 | |
| 2415 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2416 | for (Use &U : I->uses()) { |
| 2417 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2418 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2419 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 2420 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2421 | continue; |
| 2422 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2423 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2424 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 2425 | unsigned opNo = U.getOperandNo(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2426 | if (opNo == 0) return true; // Storing addr, not into addr. |
| 2427 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 2428 | continue; |
| 2429 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2430 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2431 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2432 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 2433 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2434 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2435 | // If this is a memory operand, we're cool, otherwise bail out. |
| 2436 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI)) |
| 2437 | return true; |
| 2438 | continue; |
| 2439 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2440 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2441 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2442 | return true; |
| 2443 | } |
| 2444 | |
| 2445 | return false; |
| 2446 | } |
| 2447 | |
| 2448 | /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at |
| 2449 | /// the use site that we're folding it into. If so, there is no cost to |
| 2450 | /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values |
| 2451 | /// that we know are live at the instruction already. |
| 2452 | bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
| 2453 | Value *KnownLive2) { |
| 2454 | // If Val is either of the known-live values, we know it is live! |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2455 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2456 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2457 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2458 | // All values other than instructions and arguments (e.g. constants) are live. |
| 2459 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2460 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2461 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 2462 | // true because it is just a reference to the stack/frame pointer, which is |
| 2463 | // live for the whole function. |
| 2464 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 2465 | if (AI->isStaticAlloca()) |
| 2466 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2467 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2468 | // Check to see if this value is already used in the memory instruction's |
| 2469 | // block. If so, it's already live into the block at the very least, so we |
| 2470 | // can reasonably fold it. |
| 2471 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 2472 | } |
| 2473 | |
| 2474 | /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing |
| 2475 | /// mode of the machine to fold the specified instruction into a load or store |
| 2476 | /// that ultimately uses it. However, the specified instruction has multiple |
| 2477 | /// uses. Given this, it may actually increase register pressure to fold it |
| 2478 | /// into the load. For example, consider this code: |
| 2479 | /// |
| 2480 | /// X = ... |
| 2481 | /// Y = X+1 |
| 2482 | /// use(Y) -> nonload/store |
| 2483 | /// Z = Y+1 |
| 2484 | /// load Z |
| 2485 | /// |
| 2486 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 2487 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 2488 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 2489 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 2490 | /// number of computations either. |
| 2491 | /// |
| 2492 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 2493 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 2494 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 2495 | bool AddressingModeMatcher:: |
| 2496 | IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
| 2497 | ExtAddrMode &AMAfter) { |
| 2498 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2499 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2500 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 2501 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 2502 | // the set of registers referenced by AMAfter and subtract out those |
| 2503 | // referenced by AMBefore: this is the set of values which folding in this |
| 2504 | // address extends the lifetime of. |
| 2505 | // |
| 2506 | // Note that there are only two potential values being referenced here, |
| 2507 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 2508 | // folded immediates). |
| 2509 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2510 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2511 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 2512 | // lifetime wasn't extended by adding this instruction. |
| 2513 | if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2514 | BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2515 | if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2516 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2517 | |
| 2518 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 2519 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2520 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2521 | return true; |
| 2522 | |
| 2523 | // If all uses of this instruction are ultimately load/store/inlineasm's, |
| 2524 | // check to see if their addressing modes will include this instruction. If |
| 2525 | // so, we can fold it into all uses, so it doesn't matter if it has multiple |
| 2526 | // uses. |
| 2527 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 2528 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
| 2529 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI)) |
| 2530 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2531 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2532 | // Now that we know that all uses of this instruction are part of a chain of |
| 2533 | // computation involving only operations that could theoretically be folded |
| 2534 | // into a memory use, loop over each of these uses and see if they could |
| 2535 | // *actually* fold the instruction. |
| 2536 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 2537 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 2538 | Instruction *User = MemoryUses[i].first; |
| 2539 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2540 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2541 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 2542 | // know what it accesses. |
| 2543 | Value *Address = User->getOperand(OpNo); |
| 2544 | if (!Address->getType()->isPointerTy()) |
| 2545 | return false; |
Matt Arsenault | 8227b9f | 2013-09-06 00:37:24 +0000 | [diff] [blame] | 2546 | Type *AddressAccessTy = Address->getType()->getPointerElementType(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2547 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2548 | // Do a match against the root of this address, ignoring profitability. This |
| 2549 | // will tell us if the addressing mode for the memory operation will |
| 2550 | // *actually* cover the shared instruction. |
| 2551 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 2552 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2553 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2554 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2555 | MemoryInst, Result, InsertedTruncs, |
| 2556 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2557 | Matcher.IgnoreProfitability = true; |
| 2558 | bool Success = Matcher.MatchAddr(Address, 0); |
| 2559 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2560 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 2561 | // The match was to check the profitability, the changes made are not |
| 2562 | // part of the original matcher. Therefore, they should be dropped |
| 2563 | // otherwise the original matcher will not present the right state. |
| 2564 | TPT.rollback(LastKnownGood); |
| 2565 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2566 | // If the match didn't cover I, then it won't be shared by it. |
| 2567 | if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(), |
| 2568 | I) == MatchedAddrModeInsts.end()) |
| 2569 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2570 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2571 | MatchedAddrModeInsts.clear(); |
| 2572 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2573 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2574 | return true; |
| 2575 | } |
| 2576 | |
| 2577 | } // end anonymous namespace |
| 2578 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2579 | /// IsNonLocalValue - Return true if the specified values are defined in a |
| 2580 | /// different basic block than BB. |
| 2581 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 2582 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 2583 | return I->getParent() != BB; |
| 2584 | return false; |
| 2585 | } |
| 2586 | |
Bob Wilson | 53bdae3 | 2009-12-03 21:47:07 +0000 | [diff] [blame] | 2587 | /// OptimizeMemoryInst - Load and Store Instructions often have |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2588 | /// addressing modes that can do significant amounts of computation. As such, |
| 2589 | /// instruction selection will try to get the load or store to do as much |
| 2590 | /// computation as possible for the program. The problem is that isel can only |
| 2591 | /// see within a single block. As such, we sink as much legal addressing mode |
| 2592 | /// stuff into the block as possible. |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2593 | /// |
| 2594 | /// This method is used to optimize both load/store and inline asms with memory |
| 2595 | /// operands. |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 2596 | bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Chris Lattner | 229907c | 2011-07-18 04:54:35 +0000 | [diff] [blame] | 2597 | Type *AccessTy) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2598 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2599 | |
| 2600 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2601 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 2602 | SmallVector<Value*, 8> worklist; |
| 2603 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2604 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2605 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2606 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 2607 | // the addressing mode obtained from the non-PHI roots of the graph |
| 2608 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2609 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2610 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 2611 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2612 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 2613 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2614 | TypePromotionTransaction TPT; |
| 2615 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 2616 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2617 | while (!worklist.empty()) { |
| 2618 | Value *V = worklist.back(); |
| 2619 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2620 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2621 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 2622 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2623 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2624 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2625 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2626 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2627 | // For a PHI node, push all of its incoming values. |
| 2628 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
| 2629 | for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i) |
| 2630 | worklist.push_back(P->getIncomingValue(i)); |
| 2631 | continue; |
| 2632 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2633 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2634 | // For non-PHIs, determine the addressing mode being computed. |
| 2635 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2636 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
| 2637 | V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet, |
| 2638 | PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 2639 | |
| 2640 | // This check is broken into two cases with very similar code to avoid using |
| 2641 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 2642 | // calling getNumUses() unconditionally caused a significant compile-time |
| 2643 | // regression. |
| 2644 | if (!Consensus) { |
| 2645 | Consensus = V; |
| 2646 | AddrMode = NewAddrMode; |
| 2647 | AddrModeInsts = NewAddrModeInsts; |
| 2648 | continue; |
| 2649 | } else if (NewAddrMode == AddrMode) { |
| 2650 | if (!IsNumUsesConsensusValid) { |
| 2651 | NumUsesConsensus = Consensus->getNumUses(); |
| 2652 | IsNumUsesConsensusValid = true; |
| 2653 | } |
| 2654 | |
| 2655 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 2656 | // for all other roots of the PHI traversal. Also, when choosing one |
| 2657 | // such root as representative, select the one with the most uses in order |
| 2658 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 2659 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2660 | unsigned NumUses = V->getNumUses(); |
| 2661 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2662 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 2663 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2664 | AddrModeInsts = NewAddrModeInsts; |
| 2665 | } |
| 2666 | continue; |
| 2667 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2668 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2669 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2670 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2671 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2672 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 2673 | // If the addressing mode couldn't be determined, or if multiple different |
| 2674 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2675 | if (!Consensus) { |
| 2676 | TPT.rollback(LastKnownGood); |
| 2677 | return false; |
| 2678 | } |
| 2679 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2680 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2681 | // Check to see if any of the instructions supersumed by this addr mode are |
| 2682 | // non-local to I's BB. |
| 2683 | bool AnyNonLocal = false; |
| 2684 | for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) { |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 2685 | if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) { |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2686 | AnyNonLocal = true; |
| 2687 | break; |
| 2688 | } |
| 2689 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2690 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2691 | // If all the instructions matched are already in this BB, don't do anything. |
| 2692 | if (!AnyNonLocal) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2693 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2694 | return false; |
| 2695 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2696 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2697 | // Insert this computation right after this user. Since our caller is |
| 2698 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 2699 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2700 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2701 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2702 | // Now that we determined the addressing expression we want to use and know |
| 2703 | // that we have to sink it into this block. Check to see if we have already |
| 2704 | // done this for some other load/store instr in this block. If so, reuse the |
| 2705 | // computation. |
| 2706 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 2707 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2708 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2709 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2710 | if (SunkAddr->getType() != Addr->getType()) |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 2711 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2712 | } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() && |
| 2713 | TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) { |
| 2714 | // By default, we use the GEP-based method when AA is used later. This |
| 2715 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 2716 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2717 | << *MemoryInst << "\n"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2718 | Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2719 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2720 | |
| 2721 | // First, find the pointer. |
| 2722 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 2723 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2724 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2725 | } |
| 2726 | |
| 2727 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 2728 | // We can't add more than one pointer together, nor can we scale a |
| 2729 | // pointer (both of which seem meaningless). |
| 2730 | if (ResultPtr || AddrMode.Scale != 1) |
| 2731 | return false; |
| 2732 | |
| 2733 | ResultPtr = AddrMode.ScaledReg; |
| 2734 | AddrMode.Scale = 0; |
| 2735 | } |
| 2736 | |
| 2737 | if (AddrMode.BaseGV) { |
| 2738 | if (ResultPtr) |
| 2739 | return false; |
| 2740 | |
| 2741 | ResultPtr = AddrMode.BaseGV; |
| 2742 | } |
| 2743 | |
| 2744 | // If the real base value actually came from an inttoptr, then the matcher |
| 2745 | // will look through it and provide only the integer value. In that case, |
| 2746 | // use it here. |
| 2747 | if (!ResultPtr && AddrMode.BaseReg) { |
| 2748 | ResultPtr = |
| 2749 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2750 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2751 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 2752 | ResultPtr = |
| 2753 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 2754 | AddrMode.Scale = 0; |
| 2755 | } |
| 2756 | |
| 2757 | if (!ResultPtr && |
| 2758 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 2759 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 2760 | } else if (!ResultPtr) { |
| 2761 | return false; |
| 2762 | } else { |
| 2763 | Type *I8PtrTy = |
| 2764 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 2765 | |
| 2766 | // Start with the base register. Do this first so that subsequent address |
| 2767 | // matching finds it last, which will prevent it from trying to match it |
| 2768 | // as the scaled value in case it happens to be a mul. That would be |
| 2769 | // problematic if we've sunk a different mul for the scale, because then |
| 2770 | // we'd end up sinking both muls. |
| 2771 | if (AddrMode.BaseReg) { |
| 2772 | Value *V = AddrMode.BaseReg; |
| 2773 | if (V->getType() != IntPtrTy) |
| 2774 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 2775 | |
| 2776 | ResultIndex = V; |
| 2777 | } |
| 2778 | |
| 2779 | // Add the scale value. |
| 2780 | if (AddrMode.Scale) { |
| 2781 | Value *V = AddrMode.ScaledReg; |
| 2782 | if (V->getType() == IntPtrTy) { |
| 2783 | // done. |
| 2784 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 2785 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 2786 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 2787 | } else { |
| 2788 | // It is only safe to sign extend the BaseReg if we know that the math |
| 2789 | // required to create it did not overflow before we extend it. Since |
| 2790 | // the original IR value was tossed in favor of a constant back when |
| 2791 | // the AddrMode was created we need to bail out gracefully if widths |
| 2792 | // do not match instead of extending it. |
| 2793 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 2794 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 2795 | I->eraseFromParent(); |
| 2796 | return false; |
| 2797 | } |
| 2798 | |
| 2799 | if (AddrMode.Scale != 1) |
| 2800 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 2801 | "sunkaddr"); |
| 2802 | if (ResultIndex) |
| 2803 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 2804 | else |
| 2805 | ResultIndex = V; |
| 2806 | } |
| 2807 | |
| 2808 | // Add in the Base Offset if present. |
| 2809 | if (AddrMode.BaseOffs) { |
| 2810 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 2811 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 2812 | // We need to add this separately from the scale above to help with |
| 2813 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 2814 | if (ResultPtr->getType() != I8PtrTy) |
| 2815 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
| 2816 | ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr"); |
| 2817 | } |
| 2818 | |
| 2819 | ResultIndex = V; |
| 2820 | } |
| 2821 | |
| 2822 | if (!ResultIndex) { |
| 2823 | SunkAddr = ResultPtr; |
| 2824 | } else { |
| 2825 | if (ResultPtr->getType() != I8PtrTy) |
| 2826 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
| 2827 | SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr"); |
| 2828 | } |
| 2829 | |
| 2830 | if (SunkAddr->getType() != Addr->getType()) |
| 2831 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
| 2832 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2833 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 2834 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 2835 | << *MemoryInst << "\n"); |
Matt Arsenault | 37d42ec | 2013-09-06 00:18:43 +0000 | [diff] [blame] | 2836 | Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2837 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2838 | |
| 2839 | // Start with the base register. Do this first so that subsequent address |
| 2840 | // matching finds it last, which will prevent it from trying to match it |
| 2841 | // as the scaled value in case it happens to be a mul. That would be |
| 2842 | // problematic if we've sunk a different mul for the scale, because then |
| 2843 | // we'd end up sinking both muls. |
| 2844 | if (AddrMode.BaseReg) { |
| 2845 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 2846 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2847 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2848 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2849 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 2850 | Result = V; |
| 2851 | } |
| 2852 | |
| 2853 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2854 | if (AddrMode.Scale) { |
| 2855 | Value *V = AddrMode.ScaledReg; |
| 2856 | if (V->getType() == IntPtrTy) { |
| 2857 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 2858 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2859 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2860 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 2861 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2862 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2863 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 2864 | // It is only safe to sign extend the BaseReg if we know that the math |
| 2865 | // required to create it did not overflow before we extend it. Since |
| 2866 | // the original IR value was tossed in favor of a constant back when |
| 2867 | // the AddrMode was created we need to bail out gracefully if widths |
| 2868 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 2869 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 2870 | if (I && (Result != AddrMode.BaseReg)) |
| 2871 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 2872 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2873 | } |
| 2874 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2875 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 2876 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2877 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2878 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2879 | else |
| 2880 | Result = V; |
| 2881 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2882 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2883 | // Add in the BaseGV if present. |
| 2884 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2885 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2886 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2887 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2888 | else |
| 2889 | Result = V; |
| 2890 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2891 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2892 | // Add in the Base Offset if present. |
| 2893 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 2894 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2895 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2896 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2897 | else |
| 2898 | Result = V; |
| 2899 | } |
| 2900 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2901 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 2902 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2903 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 2904 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2905 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2906 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2907 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 2908 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2909 | // If we have no uses, recursively delete the value and all dead instructions |
| 2910 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 2911 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2912 | // This can cause recursive deletion, which can invalidate our iterator. |
| 2913 | // Use a WeakVH to hold onto it in case this happens. |
| 2914 | WeakVH IterHandle(CurInstIterator); |
| 2915 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2916 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 2917 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 2918 | |
| 2919 | if (IterHandle != CurInstIterator) { |
| 2920 | // If the iterator instruction was recursively deleted, start over at the |
| 2921 | // start of the block. |
| 2922 | CurInstIterator = BB->begin(); |
| 2923 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2924 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 2925 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 2926 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 2927 | return true; |
| 2928 | } |
| 2929 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2930 | /// OptimizeInlineAsmInst - If there are any memory operands, use |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2931 | /// OptimizeMemoryInst to sink their address computing into the block when |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2932 | /// possible / profitable. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2933 | bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2934 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2935 | |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2936 | TargetLowering::AsmOperandInfoVector |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2937 | TargetConstraints = TLI->ParseConstraints(CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 2938 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 2939 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 2940 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2941 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2942 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 2943 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2944 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 2945 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 2946 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2947 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 2948 | MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType()); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 2949 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 2950 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 2951 | } |
| 2952 | |
| 2953 | return MadeChange; |
| 2954 | } |
| 2955 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2956 | /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same |
| 2957 | /// basic block as the load, unless conditions are unfavorable. This allows |
| 2958 | /// SelectionDAG to fold the extend into the load. |
| 2959 | /// |
| 2960 | bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) { |
| 2961 | // Look for a load being extended. |
| 2962 | LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0)); |
| 2963 | if (!LI) return false; |
| 2964 | |
| 2965 | // If they're already in the same block, there's nothing to do. |
| 2966 | if (LI->getParent() == I->getParent()) |
| 2967 | return false; |
| 2968 | |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 2969 | EVT VT = TLI->getValueType(I->getType()); |
| 2970 | EVT LoadVT = TLI->getValueType(LI->getType()); |
| 2971 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2972 | // If the load has other users and the truncate is not free, this probably |
| 2973 | // isn't worthwhile. |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 2974 | if (!LI->hasOneUse() && TLI && |
| 2975 | (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
Bob Wilson | 4ddcb6a | 2010-09-21 21:54:27 +0000 | [diff] [blame] | 2976 | !TLI->isTruncateFree(I->getType(), LI->getType())) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2977 | return false; |
| 2978 | |
| 2979 | // Check whether the target supports casts folded into loads. |
| 2980 | unsigned LType; |
| 2981 | if (isa<ZExtInst>(I)) |
| 2982 | LType = ISD::ZEXTLOAD; |
| 2983 | else { |
| 2984 | assert(isa<SExtInst>(I) && "Unexpected ext type!"); |
| 2985 | LType = ISD::SEXTLOAD; |
| 2986 | } |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 2987 | if (TLI && !TLI->isLoadExtLegal(LType, LoadVT)) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2988 | return false; |
| 2989 | |
| 2990 | // Move the extend into the same block as the load, so that SelectionDAG |
| 2991 | // can fold it. |
| 2992 | I->removeFromParent(); |
| 2993 | I->insertAfter(LI); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 2994 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 2995 | return true; |
| 2996 | } |
| 2997 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 2998 | bool CodeGenPrepare::OptimizeExtUses(Instruction *I) { |
| 2999 | BasicBlock *DefBB = I->getParent(); |
| 3000 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 3001 | // If the result of a {s|z}ext and its source are both live out, rewrite all |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3002 | // other uses of the source with result of extension. |
| 3003 | Value *Src = I->getOperand(0); |
| 3004 | if (Src->hasOneUse()) |
| 3005 | return false; |
| 3006 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 3007 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 3008 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 3009 | return false; |
| 3010 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 3011 | // Only safe to perform the optimization if the source is also defined in |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 3012 | // this block. |
| 3013 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 3014 | return false; |
| 3015 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3016 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3017 | for (User *U : I->users()) { |
| 3018 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3019 | |
| 3020 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3021 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3022 | if (UserBB == DefBB) continue; |
| 3023 | DefIsLiveOut = true; |
| 3024 | break; |
| 3025 | } |
| 3026 | if (!DefIsLiveOut) |
| 3027 | return false; |
| 3028 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 3029 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3030 | for (User *U : Src->users()) { |
| 3031 | Instruction *UI = cast<Instruction>(U); |
| 3032 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 3033 | if (UserBB == DefBB) continue; |
| 3034 | // Be conservative. We don't want this xform to end up introducing |
| 3035 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3036 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 3037 | return false; |
| 3038 | } |
| 3039 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3040 | // InsertedTruncs - Only insert one trunc in each block once. |
| 3041 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 3042 | |
| 3043 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3044 | for (Use &U : Src->uses()) { |
| 3045 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3046 | |
| 3047 | // Figure out which BB this ext is used in. |
| 3048 | BasicBlock *UserBB = User->getParent(); |
| 3049 | if (UserBB == DefBB) continue; |
| 3050 | |
| 3051 | // Both src and def are live in this block. Rewrite the use. |
| 3052 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 3053 | |
| 3054 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 3055 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3056 | InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3057 | InsertedTruncsSet.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3058 | } |
| 3059 | |
| 3060 | // Replace a use of the {s|z}ext source with a use of the result. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3061 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 3062 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 3063 | MadeChange = true; |
| 3064 | } |
| 3065 | |
| 3066 | return MadeChange; |
| 3067 | } |
| 3068 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3069 | /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be |
| 3070 | /// turned into an explicit branch. |
| 3071 | static bool isFormingBranchFromSelectProfitable(SelectInst *SI) { |
| 3072 | // FIXME: This should use the same heuristics as IfConversion to determine |
| 3073 | // whether a select is better represented as a branch. This requires that |
| 3074 | // branch probability metadata is preserved for the select, which is not the |
| 3075 | // case currently. |
| 3076 | |
| 3077 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 3078 | |
| 3079 | // If the branch is predicted right, an out of order CPU can avoid blocking on |
| 3080 | // the compare. Emit cmovs on compares with a memory operand as branches to |
| 3081 | // avoid stalls on the load from memory. If the compare has more than one use |
| 3082 | // there's probably another cmov or setcc around so it's not worth emitting a |
| 3083 | // branch. |
| 3084 | if (!Cmp) |
| 3085 | return false; |
| 3086 | |
| 3087 | Value *CmpOp0 = Cmp->getOperand(0); |
| 3088 | Value *CmpOp1 = Cmp->getOperand(1); |
| 3089 | |
| 3090 | // We check that the memory operand has one use to avoid uses of the loaded |
| 3091 | // value directly after the compare, making branches unprofitable. |
| 3092 | return Cmp->hasOneUse() && |
| 3093 | ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) || |
| 3094 | (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse())); |
| 3095 | } |
| 3096 | |
| 3097 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3098 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 3099 | /// turn it into a branch. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3100 | bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) { |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3101 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 3102 | |
| 3103 | // Can we convert the 'select' to CF ? |
| 3104 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3105 | return false; |
| 3106 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 3107 | TargetLowering::SelectSupportKind SelectKind; |
| 3108 | if (VectorCond) |
| 3109 | SelectKind = TargetLowering::VectorMaskSelect; |
| 3110 | else if (SI->getType()->isVectorTy()) |
| 3111 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 3112 | else |
| 3113 | SelectKind = TargetLowering::ScalarValSelect; |
| 3114 | |
| 3115 | // Do we have efficient codegen support for this kind of 'selects' ? |
| 3116 | if (TLI->isSelectSupported(SelectKind)) { |
| 3117 | // We have efficient codegen support for the select instruction. |
| 3118 | // Check if it is profitable to keep this 'select'. |
| 3119 | if (!TLI->isPredictableSelectExpensive() || |
| 3120 | !isFormingBranchFromSelectProfitable(SI)) |
| 3121 | return false; |
| 3122 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3123 | |
| 3124 | ModifiedDT = true; |
| 3125 | |
| 3126 | // First, we split the block containing the select into 2 blocks. |
| 3127 | BasicBlock *StartBlock = SI->getParent(); |
| 3128 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI)); |
| 3129 | BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
| 3130 | |
| 3131 | // Create a new block serving as the landing pad for the branch. |
| 3132 | BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid", |
| 3133 | NextBlock->getParent(), NextBlock); |
| 3134 | |
| 3135 | // Move the unconditional branch from the block with the select in it into our |
| 3136 | // landing pad block. |
| 3137 | StartBlock->getTerminator()->eraseFromParent(); |
| 3138 | BranchInst::Create(NextBlock, SmallBlock); |
| 3139 | |
| 3140 | // Insert the real conditional branch based on the original condition. |
| 3141 | BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI); |
| 3142 | |
| 3143 | // The select itself is replaced with a PHI Node. |
| 3144 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin()); |
| 3145 | PN->takeName(SI); |
| 3146 | PN->addIncoming(SI->getTrueValue(), StartBlock); |
| 3147 | PN->addIncoming(SI->getFalseValue(), SmallBlock); |
| 3148 | SI->replaceAllUsesWith(PN); |
| 3149 | SI->eraseFromParent(); |
| 3150 | |
| 3151 | // Instruct OptimizeBlock to skip to the next block. |
| 3152 | CurInstIterator = StartBlock->end(); |
| 3153 | ++NumSelectsExpanded; |
| 3154 | return true; |
| 3155 | } |
| 3156 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 3157 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3158 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 3159 | int SplatElem = -1; |
| 3160 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 3161 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 3162 | return false; |
| 3163 | SplatElem = Mask[i]; |
| 3164 | } |
| 3165 | |
| 3166 | return true; |
| 3167 | } |
| 3168 | |
| 3169 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 3170 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 3171 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 3172 | /// codegen can spot all lanes are identical. |
| 3173 | bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
| 3174 | BasicBlock *DefBB = SVI->getParent(); |
| 3175 | |
| 3176 | // Only do this xform if variable vector shifts are particularly expensive. |
| 3177 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 3178 | return false; |
| 3179 | |
| 3180 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 3181 | // constant splat. |
| 3182 | if (!isBroadcastShuffle(SVI)) |
| 3183 | return false; |
| 3184 | |
| 3185 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 3186 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 3187 | |
| 3188 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3189 | for (User *U : SVI->users()) { |
| 3190 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3191 | |
| 3192 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3193 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3194 | if (UserBB == DefBB) continue; |
| 3195 | |
| 3196 | // For now only apply this when the splat is used by a shift instruction. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3197 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3198 | |
| 3199 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 3200 | // already have a copy. |
| 3201 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 3202 | |
| 3203 | if (!InsertedShuffle) { |
| 3204 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
| 3205 | InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0), |
| 3206 | SVI->getOperand(1), |
| 3207 | SVI->getOperand(2), "", InsertPt); |
| 3208 | } |
| 3209 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3210 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3211 | MadeChange = true; |
| 3212 | } |
| 3213 | |
| 3214 | // If we removed all uses, nuke the shuffle. |
| 3215 | if (SVI->use_empty()) { |
| 3216 | SVI->eraseFromParent(); |
| 3217 | MadeChange = true; |
| 3218 | } |
| 3219 | |
| 3220 | return MadeChange; |
| 3221 | } |
| 3222 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 3223 | namespace { |
| 3224 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 3225 | /// This class is used to move downward extractelement transition. |
| 3226 | /// E.g., |
| 3227 | /// a = vector_op <2 x i32> |
| 3228 | /// b = extractelement <2 x i32> a, i32 0 |
| 3229 | /// c = scalar_op b |
| 3230 | /// store c |
| 3231 | /// |
| 3232 | /// => |
| 3233 | /// a = vector_op <2 x i32> |
| 3234 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 3235 | /// * d = extractelement <2 x i32> c, i32 0 |
| 3236 | /// * store d |
| 3237 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 3238 | /// transition. |
| 3239 | class VectorPromoteHelper { |
| 3240 | /// Used to perform some checks on the legality of vector operations. |
| 3241 | const TargetLowering &TLI; |
| 3242 | |
| 3243 | /// Used to estimated the cost of the promoted chain. |
| 3244 | const TargetTransformInfo &TTI; |
| 3245 | |
| 3246 | /// The transition being moved downwards. |
| 3247 | Instruction *Transition; |
| 3248 | /// The sequence of instructions to be promoted. |
| 3249 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 3250 | /// Cost of combining a store and an extract. |
| 3251 | unsigned StoreExtractCombineCost; |
| 3252 | /// Instruction that will be combined with the transition. |
| 3253 | Instruction *CombineInst; |
| 3254 | |
| 3255 | /// \brief The instruction that represents the current end of the transition. |
| 3256 | /// Since we are faking the promotion until we reach the end of the chain |
| 3257 | /// of computation, we need a way to get the current end of the transition. |
| 3258 | Instruction *getEndOfTransition() const { |
| 3259 | if (InstsToBePromoted.empty()) |
| 3260 | return Transition; |
| 3261 | return InstsToBePromoted.back(); |
| 3262 | } |
| 3263 | |
| 3264 | /// \brief Return the index of the original value in the transition. |
| 3265 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 3266 | /// c, is at index 0. |
| 3267 | unsigned getTransitionOriginalValueIdx() const { |
| 3268 | assert(isa<ExtractElementInst>(Transition) && |
| 3269 | "Other kind of transitions are not supported yet"); |
| 3270 | return 0; |
| 3271 | } |
| 3272 | |
| 3273 | /// \brief Return the index of the index in the transition. |
| 3274 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 3275 | /// is at index 1. |
| 3276 | unsigned getTransitionIdx() const { |
| 3277 | assert(isa<ExtractElementInst>(Transition) && |
| 3278 | "Other kind of transitions are not supported yet"); |
| 3279 | return 1; |
| 3280 | } |
| 3281 | |
| 3282 | /// \brief Get the type of the transition. |
| 3283 | /// This is the type of the original value. |
| 3284 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 3285 | /// transition is <2 x i32>. |
| 3286 | Type *getTransitionType() const { |
| 3287 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 3288 | } |
| 3289 | |
| 3290 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 3291 | /// I.e., we have the following sequence: |
| 3292 | /// Def = Transition <ty1> a to <ty2> |
| 3293 | /// b = ToBePromoted <ty2> Def, ... |
| 3294 | /// => |
| 3295 | /// b = ToBePromoted <ty1> a, ... |
| 3296 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 3297 | void promoteImpl(Instruction *ToBePromoted); |
| 3298 | |
| 3299 | /// \brief Check whether or not it is profitable to promote all the |
| 3300 | /// instructions enqueued to be promoted. |
| 3301 | bool isProfitableToPromote() { |
| 3302 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 3303 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 3304 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 3305 | : -1; |
| 3306 | Type *PromotedType = getTransitionType(); |
| 3307 | |
| 3308 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 3309 | unsigned AS = ST->getPointerAddressSpace(); |
| 3310 | unsigned Align = ST->getAlignment(); |
| 3311 | // Check if this store is supported. |
| 3312 | if (!TLI.allowsMisalignedMemoryAccesses( |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 3313 | TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 3314 | // If this is not supported, there is no way we can combine |
| 3315 | // the extract with the store. |
| 3316 | return false; |
| 3317 | } |
| 3318 | |
| 3319 | // The scalar chain of computation has to pay for the transition |
| 3320 | // scalar to vector. |
| 3321 | // The vector chain has to account for the combining cost. |
| 3322 | uint64_t ScalarCost = |
| 3323 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 3324 | uint64_t VectorCost = StoreExtractCombineCost; |
| 3325 | for (const auto &Inst : InstsToBePromoted) { |
| 3326 | // Compute the cost. |
| 3327 | // By construction, all instructions being promoted are arithmetic ones. |
| 3328 | // Moreover, one argument is a constant that can be viewed as a splat |
| 3329 | // constant. |
| 3330 | Value *Arg0 = Inst->getOperand(0); |
| 3331 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 3332 | isa<ConstantFP>(Arg0); |
| 3333 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 3334 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 3335 | : TargetTransformInfo::OK_AnyValue; |
| 3336 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 3337 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 3338 | : TargetTransformInfo::OK_AnyValue; |
| 3339 | ScalarCost += TTI.getArithmeticInstrCost( |
| 3340 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 3341 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 3342 | Arg0OVK, Arg1OVK); |
| 3343 | } |
| 3344 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 3345 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 3346 | return ScalarCost > VectorCost; |
| 3347 | } |
| 3348 | |
| 3349 | /// \brief Generate a constant vector with \p Val with the same |
| 3350 | /// number of elements as the transition. |
| 3351 | /// \p UseSplat defines whether or not \p Val should be replicated |
| 3352 | /// accross the whole vector. |
| 3353 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 3354 | /// otherwise we generate a vector with as many undef as possible: |
| 3355 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 3356 | /// used at the index of the extract. |
| 3357 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 3358 | unsigned ExtractIdx = UINT_MAX; |
| 3359 | if (!UseSplat) { |
| 3360 | // If we cannot determine where the constant must be, we have to |
| 3361 | // use a splat constant. |
| 3362 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 3363 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 3364 | ExtractIdx = CstVal->getSExtValue(); |
| 3365 | else |
| 3366 | UseSplat = true; |
| 3367 | } |
| 3368 | |
| 3369 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 3370 | if (UseSplat) |
| 3371 | return ConstantVector::getSplat(End, Val); |
| 3372 | |
| 3373 | SmallVector<Constant *, 4> ConstVec; |
| 3374 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 3375 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 3376 | if (Idx == ExtractIdx) |
| 3377 | ConstVec.push_back(Val); |
| 3378 | else |
| 3379 | ConstVec.push_back(UndefVal); |
| 3380 | } |
| 3381 | return ConstantVector::get(ConstVec); |
| 3382 | } |
| 3383 | |
| 3384 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 3385 | /// in \p Use can trigger undefined behavior. |
| 3386 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 3387 | unsigned OperandIdx) { |
| 3388 | // This is not safe to introduce undef when the operand is on |
| 3389 | // the right hand side of a division-like instruction. |
| 3390 | if (OperandIdx != 1) |
| 3391 | return false; |
| 3392 | switch (Use->getOpcode()) { |
| 3393 | default: |
| 3394 | return false; |
| 3395 | case Instruction::SDiv: |
| 3396 | case Instruction::UDiv: |
| 3397 | case Instruction::SRem: |
| 3398 | case Instruction::URem: |
| 3399 | return true; |
| 3400 | case Instruction::FDiv: |
| 3401 | case Instruction::FRem: |
| 3402 | return !Use->hasNoNaNs(); |
| 3403 | } |
| 3404 | llvm_unreachable(nullptr); |
| 3405 | } |
| 3406 | |
| 3407 | public: |
| 3408 | VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI, |
| 3409 | Instruction *Transition, unsigned CombineCost) |
| 3410 | : TLI(TLI), TTI(TTI), Transition(Transition), |
| 3411 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 3412 | assert(Transition && "Do not know how to promote null"); |
| 3413 | } |
| 3414 | |
| 3415 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 3416 | bool canPromote(const Instruction *ToBePromoted) const { |
| 3417 | // We could support CastInst too. |
| 3418 | return isa<BinaryOperator>(ToBePromoted); |
| 3419 | } |
| 3420 | |
| 3421 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 3422 | /// by moving downward the transition through. |
| 3423 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 3424 | // Promote only if all the operands can be statically expanded. |
| 3425 | // Indeed, we do not want to introduce any new kind of transitions. |
| 3426 | for (const Use &U : ToBePromoted->operands()) { |
| 3427 | const Value *Val = U.get(); |
| 3428 | if (Val == getEndOfTransition()) { |
| 3429 | // If the use is a division and the transition is on the rhs, |
| 3430 | // we cannot promote the operation, otherwise we may create a |
| 3431 | // division by zero. |
| 3432 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 3433 | return false; |
| 3434 | continue; |
| 3435 | } |
| 3436 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 3437 | !isa<ConstantFP>(Val)) |
| 3438 | return false; |
| 3439 | } |
| 3440 | // Check that the resulting operation is legal. |
| 3441 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 3442 | if (!ISDOpcode) |
| 3443 | return false; |
| 3444 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 3445 | TLI.isOperationLegalOrCustom( |
| 3446 | ISDOpcode, TLI.getValueType(getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 3447 | } |
| 3448 | |
| 3449 | /// \brief Check whether or not \p Use can be combined |
| 3450 | /// with the transition. |
| 3451 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 3452 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 3453 | |
| 3454 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 3455 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 3456 | InstsToBePromoted.push_back(ToBePromoted); |
| 3457 | } |
| 3458 | |
| 3459 | /// \brief Set the instruction that will be combined with the transition. |
| 3460 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 3461 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 3462 | CombineInst = ToBeCombined; |
| 3463 | } |
| 3464 | |
| 3465 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 3466 | /// is profitable. |
| 3467 | /// \return True if the promotion happened, false otherwise. |
| 3468 | bool promote() { |
| 3469 | // Check if there is something to promote. |
| 3470 | // Right now, if we do not have anything to combine with, |
| 3471 | // we assume the promotion is not profitable. |
| 3472 | if (InstsToBePromoted.empty() || !CombineInst) |
| 3473 | return false; |
| 3474 | |
| 3475 | // Check cost. |
| 3476 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 3477 | return false; |
| 3478 | |
| 3479 | // Promote. |
| 3480 | for (auto &ToBePromoted : InstsToBePromoted) |
| 3481 | promoteImpl(ToBePromoted); |
| 3482 | InstsToBePromoted.clear(); |
| 3483 | return true; |
| 3484 | } |
| 3485 | }; |
| 3486 | } // End of anonymous namespace. |
| 3487 | |
| 3488 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 3489 | // At this point, we know that all the operands of ToBePromoted but Def |
| 3490 | // can be statically promoted. |
| 3491 | // For Def, we need to use its parameter in ToBePromoted: |
| 3492 | // b = ToBePromoted ty1 a |
| 3493 | // Def = Transition ty1 b to ty2 |
| 3494 | // Move the transition down. |
| 3495 | // 1. Replace all uses of the promoted operation by the transition. |
| 3496 | // = ... b => = ... Def. |
| 3497 | assert(ToBePromoted->getType() == Transition->getType() && |
| 3498 | "The type of the result of the transition does not match " |
| 3499 | "the final type"); |
| 3500 | ToBePromoted->replaceAllUsesWith(Transition); |
| 3501 | // 2. Update the type of the uses. |
| 3502 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 3503 | Type *TransitionTy = getTransitionType(); |
| 3504 | ToBePromoted->mutateType(TransitionTy); |
| 3505 | // 3. Update all the operands of the promoted operation with promoted |
| 3506 | // operands. |
| 3507 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 3508 | for (Use &U : ToBePromoted->operands()) { |
| 3509 | Value *Val = U.get(); |
| 3510 | Value *NewVal = nullptr; |
| 3511 | if (Val == Transition) |
| 3512 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 3513 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 3514 | isa<ConstantFP>(Val)) { |
| 3515 | // Use a splat constant if it is not safe to use undef. |
| 3516 | NewVal = getConstantVector( |
| 3517 | cast<Constant>(Val), |
| 3518 | isa<UndefValue>(Val) || |
| 3519 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 3520 | } else |
| 3521 | assert(0 && "Did you modified shouldPromote and forgot to update this?"); |
| 3522 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 3523 | } |
| 3524 | Transition->removeFromParent(); |
| 3525 | Transition->insertAfter(ToBePromoted); |
| 3526 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 3527 | } |
| 3528 | |
| 3529 | /// Some targets can do store(extractelement) with one instruction. |
| 3530 | /// Try to push the extractelement towards the stores when the target |
| 3531 | /// has this feature and this is profitable. |
| 3532 | bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) { |
| 3533 | unsigned CombineCost = UINT_MAX; |
| 3534 | if (DisableStoreExtract || !TLI || |
| 3535 | (!StressStoreExtract && |
| 3536 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 3537 | Inst->getOperand(1), CombineCost))) |
| 3538 | return false; |
| 3539 | |
| 3540 | // At this point we know that Inst is a vector to scalar transition. |
| 3541 | // Try to move it down the def-use chain, until: |
| 3542 | // - We can combine the transition with its single use |
| 3543 | // => we got rid of the transition. |
| 3544 | // - We escape the current basic block |
| 3545 | // => we would need to check that we are moving it at a cheaper place and |
| 3546 | // we do not do that for now. |
| 3547 | BasicBlock *Parent = Inst->getParent(); |
| 3548 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
| 3549 | VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost); |
| 3550 | // If the transition has more than one use, assume this is not going to be |
| 3551 | // beneficial. |
| 3552 | while (Inst->hasOneUse()) { |
| 3553 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 3554 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 3555 | |
| 3556 | if (ToBePromoted->getParent() != Parent) { |
| 3557 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 3558 | << ToBePromoted->getParent()->getName() |
| 3559 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 3560 | return false; |
| 3561 | } |
| 3562 | |
| 3563 | if (VPH.canCombine(ToBePromoted)) { |
| 3564 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 3565 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 3566 | VPH.recordCombineInstruction(ToBePromoted); |
| 3567 | bool Changed = VPH.promote(); |
| 3568 | NumStoreExtractExposed += Changed; |
| 3569 | return Changed; |
| 3570 | } |
| 3571 | |
| 3572 | DEBUG(dbgs() << "Try promoting.\n"); |
| 3573 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 3574 | return false; |
| 3575 | |
| 3576 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 3577 | |
| 3578 | VPH.enqueueForPromotion(ToBePromoted); |
| 3579 | Inst = ToBePromoted; |
| 3580 | } |
| 3581 | return false; |
| 3582 | } |
| 3583 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3584 | bool CodeGenPrepare::OptimizeInst(Instruction *I) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3585 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 3586 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 3587 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 3588 | // trivial PHI, go ahead and zap it here. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3589 | if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr, |
Benjamin Kramer | 30d249a | 2013-09-24 16:37:40 +0000 | [diff] [blame] | 3590 | TLInfo, DT)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3591 | P->replaceAllUsesWith(V); |
| 3592 | P->eraseFromParent(); |
| 3593 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3594 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3595 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3596 | return false; |
| 3597 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3598 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3599 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3600 | // If the source of the cast is a constant, then this should have |
| 3601 | // already been constant folded. The only reason NOT to constant fold |
| 3602 | // it is if something (e.g. LSR) was careful to place the constant |
| 3603 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 3604 | // the address of globals out of a loop). If this is the case, we don't |
| 3605 | // want to forward-subst the cast. |
| 3606 | if (isa<Constant>(CI->getOperand(0))) |
| 3607 | return false; |
| 3608 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3609 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI)) |
| 3610 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3611 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3612 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 3613 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 3614 | /// fit in one register |
| 3615 | if (TLI && TLI->getTypeAction(CI->getContext(), |
| 3616 | TLI->getValueType(CI->getType())) == |
| 3617 | TargetLowering::TypeExpandInteger) { |
| 3618 | return SinkCast(CI); |
| 3619 | } else { |
| 3620 | bool MadeChange = MoveExtToFormExtLoad(I); |
| 3621 | return MadeChange | OptimizeExtUses(I); |
| 3622 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3623 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3624 | return false; |
| 3625 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3626 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3627 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 3628 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
| 3629 | return OptimizeCmpExpression(CI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3630 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3631 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3632 | if (TLI) |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 3633 | return OptimizeMemoryInst(I, I->getOperand(0), LI->getType()); |
| 3634 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3635 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3636 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3637 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3638 | if (TLI) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3639 | return OptimizeMemoryInst(I, SI->getOperand(1), |
| 3640 | SI->getOperand(0)->getType()); |
| 3641 | return false; |
| 3642 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3643 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 3644 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 3645 | |
| 3646 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 3647 | BinOp->getOpcode() == Instruction::LShr)) { |
| 3648 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 3649 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
| 3650 | return OptimizeExtractBits(BinOp, CI, *TLI); |
| 3651 | |
| 3652 | return false; |
| 3653 | } |
| 3654 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3655 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3656 | if (GEPI->hasAllZeroIndices()) { |
| 3657 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 3658 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 3659 | GEPI->getName(), GEPI); |
| 3660 | GEPI->replaceAllUsesWith(NC); |
| 3661 | GEPI->eraseFromParent(); |
| 3662 | ++NumGEPsElim; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3663 | OptimizeInst(NC); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3664 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 3665 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3666 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3667 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3668 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3669 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
| 3670 | return OptimizeCallInst(CI); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3671 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 3672 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
| 3673 | return OptimizeSelectInst(SI); |
| 3674 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 3675 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
| 3676 | return OptimizeShuffleVectorInst(SVI); |
| 3677 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 3678 | if (isa<ExtractElementInst>(I)) |
| 3679 | return OptimizeExtractElementInst(I); |
| 3680 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 3681 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 3682 | } |
| 3683 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 3684 | // In this pass we look for GEP and cast instructions that are used |
| 3685 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 3686 | // selection. |
| 3687 | bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 3688 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 3689 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3690 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 3691 | CurInstIterator = BB.begin(); |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 3692 | while (CurInstIterator != BB.end()) |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 3693 | MadeChange |= OptimizeInst(CurInstIterator++); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3694 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 3695 | MadeChange |= DupRetToEnableTailCallOpts(&BB); |
| 3696 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 3697 | return MadeChange; |
| 3698 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3699 | |
| 3700 | // llvm.dbg.value is far away from the value then iSel may not be able |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3701 | // handle it properly. iSel will drop llvm.dbg.value if it can not |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3702 | // find a node corresponding to the value. |
| 3703 | bool CodeGenPrepare::PlaceDbgValues(Function &F) { |
| 3704 | bool MadeChange = false; |
| 3705 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3706 | Instruction *PrevNonDbgInst = nullptr; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3707 | for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) { |
| 3708 | Instruction *Insn = BI; ++BI; |
| 3709 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 3710 | // Leave dbg.values that refer to an alloca alone. These |
| 3711 | // instrinsics describe the address of a variable (= the alloca) |
| 3712 | // being taken. They should not be moved next to the alloca |
| 3713 | // (and to the beginning of the scope), but rather stay close to |
| 3714 | // where said address is used. |
| 3715 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 3716 | PrevNonDbgInst = Insn; |
| 3717 | continue; |
| 3718 | } |
| 3719 | |
| 3720 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 3721 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
| 3722 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 3723 | DVI->removeFromParent(); |
| 3724 | if (isa<PHINode>(VI)) |
| 3725 | DVI->insertBefore(VI->getParent()->getFirstInsertionPt()); |
| 3726 | else |
| 3727 | DVI->insertAfter(VI); |
| 3728 | MadeChange = true; |
| 3729 | ++NumDbgValueMoved; |
| 3730 | } |
| 3731 | } |
| 3732 | } |
| 3733 | return MadeChange; |
| 3734 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 3735 | |
| 3736 | // If there is a sequence that branches based on comparing a single bit |
| 3737 | // against zero that can be combined into a single instruction, and the |
| 3738 | // target supports folding these into a single instruction, sink the |
| 3739 | // mask and compare into the branch uses. Do this before OptimizeBlock -> |
| 3740 | // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being |
| 3741 | // searched for. |
| 3742 | bool CodeGenPrepare::sinkAndCmp(Function &F) { |
| 3743 | if (!EnableAndCmpSinking) |
| 3744 | return false; |
| 3745 | if (!TLI || !TLI->isMaskAndBranchFoldingLegal()) |
| 3746 | return false; |
| 3747 | bool MadeChange = false; |
| 3748 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ) { |
| 3749 | BasicBlock *BB = I++; |
| 3750 | |
| 3751 | // Does this BB end with the following? |
| 3752 | // %andVal = and %val, #single-bit-set |
| 3753 | // %icmpVal = icmp %andResult, 0 |
| 3754 | // br i1 %cmpVal label %dest1, label %dest2" |
| 3755 | BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator()); |
| 3756 | if (!Brcc || !Brcc->isConditional()) |
| 3757 | continue; |
| 3758 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0)); |
| 3759 | if (!Cmp || Cmp->getParent() != BB) |
| 3760 | continue; |
| 3761 | ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1)); |
| 3762 | if (!Zero || !Zero->isZero()) |
| 3763 | continue; |
| 3764 | Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0)); |
| 3765 | if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB) |
| 3766 | continue; |
| 3767 | ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1)); |
| 3768 | if (!Mask || !Mask->getUniqueInteger().isPowerOf2()) |
| 3769 | continue; |
| 3770 | DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump()); |
| 3771 | |
| 3772 | // Push the "and; icmp" for any users that are conditional branches. |
| 3773 | // Since there can only be one branch use per BB, we don't need to keep |
| 3774 | // track of which BBs we insert into. |
| 3775 | for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end(); |
| 3776 | UI != E; ) { |
| 3777 | Use &TheUse = *UI; |
| 3778 | // Find brcc use. |
| 3779 | BranchInst *BrccUser = dyn_cast<BranchInst>(*UI); |
| 3780 | ++UI; |
| 3781 | if (!BrccUser || !BrccUser->isConditional()) |
| 3782 | continue; |
| 3783 | BasicBlock *UserBB = BrccUser->getParent(); |
| 3784 | if (UserBB == BB) continue; |
| 3785 | DEBUG(dbgs() << "found Brcc use\n"); |
| 3786 | |
| 3787 | // Sink the "and; icmp" to use. |
| 3788 | MadeChange = true; |
| 3789 | BinaryOperator *NewAnd = |
| 3790 | BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "", |
| 3791 | BrccUser); |
| 3792 | CmpInst *NewCmp = |
| 3793 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero, |
| 3794 | "", BrccUser); |
| 3795 | TheUse = NewCmp; |
| 3796 | ++NumAndCmpsMoved; |
| 3797 | DEBUG(BrccUser->getParent()->dump()); |
| 3798 | } |
| 3799 | } |
| 3800 | return MadeChange; |
| 3801 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame^] | 3802 | |
| 3803 | /// \brief Scale down both weights to fit into uint32_t. |
| 3804 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 3805 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 3806 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 3807 | NewTrue = NewTrue / Scale; |
| 3808 | NewFalse = NewFalse / Scale; |
| 3809 | } |
| 3810 | |
| 3811 | /// \brief Some targets prefer to split a conditional branch like: |
| 3812 | /// \code |
| 3813 | /// %0 = icmp ne i32 %a, 0 |
| 3814 | /// %1 = icmp ne i32 %b, 0 |
| 3815 | /// %or.cond = or i1 %0, %1 |
| 3816 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 3817 | /// \endcode |
| 3818 | /// into multiple branch instructions like: |
| 3819 | /// \code |
| 3820 | /// bb1: |
| 3821 | /// %0 = icmp ne i32 %a, 0 |
| 3822 | /// br i1 %0, label %TrueBB, label %bb2 |
| 3823 | /// bb2: |
| 3824 | /// %1 = icmp ne i32 %b, 0 |
| 3825 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 3826 | /// \endcode |
| 3827 | /// This usually allows instruction selection to do even further optimizations |
| 3828 | /// and combine the compare with the branch instruction. Currently this is |
| 3829 | /// applied for targets which have "cheap" jump instructions. |
| 3830 | /// |
| 3831 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 3832 | /// |
| 3833 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
| 3834 | if (!TM || TM->Options.EnableFastISel != true || |
| 3835 | !TLI || TLI->isJumpExpensive()) |
| 3836 | return false; |
| 3837 | |
| 3838 | bool MadeChange = false; |
| 3839 | for (auto &BB : F) { |
| 3840 | // Does this BB end with the following? |
| 3841 | // %cond1 = icmp|fcmp|binary instruction ... |
| 3842 | // %cond2 = icmp|fcmp|binary instruction ... |
| 3843 | // %cond.or = or|and i1 %cond1, cond2 |
| 3844 | // br i1 %cond.or label %dest1, label %dest2" |
| 3845 | BinaryOperator *LogicOp; |
| 3846 | BasicBlock *TBB, *FBB; |
| 3847 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 3848 | continue; |
| 3849 | |
| 3850 | unsigned Opc; |
| 3851 | Instruction *Cond1, *Cond2; |
| 3852 | if (match(LogicOp, m_And(m_OneUse(m_Instruction(Cond1)), |
| 3853 | m_OneUse(m_Instruction(Cond2))))) |
| 3854 | Opc = Instruction::And; |
| 3855 | else if (match(LogicOp, m_Or(m_OneUse(m_Instruction(Cond1)), |
| 3856 | m_OneUse(m_Instruction(Cond2))))) |
| 3857 | Opc = Instruction::Or; |
| 3858 | else |
| 3859 | continue; |
| 3860 | |
| 3861 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 3862 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 3863 | continue; |
| 3864 | |
| 3865 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 3866 | |
| 3867 | // Create a new BB. |
| 3868 | auto *InsertBefore = std::next(Function::iterator(BB)) |
| 3869 | .getNodePtrUnchecked(); |
| 3870 | auto TmpBB = BasicBlock::Create(BB.getContext(), |
| 3871 | BB.getName() + ".cond.split", |
| 3872 | BB.getParent(), InsertBefore); |
| 3873 | |
| 3874 | // Update original basic block by using the first condition directly by the |
| 3875 | // branch instruction and removing the no longer needed and/or instruction. |
| 3876 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 3877 | Br1->setCondition(Cond1); |
| 3878 | LogicOp->eraseFromParent(); |
| 3879 | Cond2->removeFromParent(); |
| 3880 | // Depending on the conditon we have to either replace the true or the false |
| 3881 | // successor of the original branch instruction. |
| 3882 | if (Opc == Instruction::And) |
| 3883 | Br1->setSuccessor(0, TmpBB); |
| 3884 | else |
| 3885 | Br1->setSuccessor(1, TmpBB); |
| 3886 | |
| 3887 | // Fill in the new basic block. |
| 3888 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
| 3889 | Cond2->insertBefore(Br2); |
| 3890 | |
| 3891 | // Update PHI nodes in both successors. The original BB needs to be |
| 3892 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 3893 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 3894 | // incoming edge to the PHI nodes, because both branch instructions target |
| 3895 | // now the same successor. Depending on the original branch condition |
| 3896 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
| 3897 | // we perfrom the correct update for the PHI nodes. |
| 3898 | // This doesn't change the successor order of the just created branch |
| 3899 | // instruction (or any other instruction). |
| 3900 | if (Opc == Instruction::Or) |
| 3901 | std::swap(TBB, FBB); |
| 3902 | |
| 3903 | // Replace the old BB with the new BB. |
| 3904 | for (auto &I : *TBB) { |
| 3905 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 3906 | if (!PN) |
| 3907 | break; |
| 3908 | int i; |
| 3909 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 3910 | PN->setIncomingBlock(i, TmpBB); |
| 3911 | } |
| 3912 | |
| 3913 | // Add another incoming edge form the new BB. |
| 3914 | for (auto &I : *FBB) { |
| 3915 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 3916 | if (!PN) |
| 3917 | break; |
| 3918 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 3919 | PN->addIncoming(Val, TmpBB); |
| 3920 | } |
| 3921 | |
| 3922 | // Update the branch weights (from SelectionDAGBuilder:: |
| 3923 | // FindMergedConditions). |
| 3924 | if (Opc == Instruction::Or) { |
| 3925 | // Codegen X | Y as: |
| 3926 | // BB1: |
| 3927 | // jmp_if_X TBB |
| 3928 | // jmp TmpBB |
| 3929 | // TmpBB: |
| 3930 | // jmp_if_Y TBB |
| 3931 | // jmp FBB |
| 3932 | // |
| 3933 | |
| 3934 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 3935 | // The requirement is that |
| 3936 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 3937 | // = TrueProb for orignal BB. |
| 3938 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 3939 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 3940 | // assumes that |
| 3941 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 3942 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 3943 | // TmpBB, but the math is more complicated. |
| 3944 | uint64_t TrueWeight, FalseWeight; |
| 3945 | if (Br1->getBranchWeights(TrueWeight, FalseWeight)) { |
| 3946 | uint64_t NewTrueWeight = TrueWeight; |
| 3947 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 3948 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 3949 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 3950 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 3951 | |
| 3952 | NewTrueWeight = TrueWeight; |
| 3953 | NewFalseWeight = 2 * FalseWeight; |
| 3954 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 3955 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 3956 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 3957 | } |
| 3958 | } else { |
| 3959 | // Codegen X & Y as: |
| 3960 | // BB1: |
| 3961 | // jmp_if_X TmpBB |
| 3962 | // jmp FBB |
| 3963 | // TmpBB: |
| 3964 | // jmp_if_Y TBB |
| 3965 | // jmp FBB |
| 3966 | // |
| 3967 | // This requires creation of TmpBB after CurBB. |
| 3968 | |
| 3969 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 3970 | // The requirement is that |
| 3971 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 3972 | // = FalseProb for orignal BB. |
| 3973 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 3974 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 3975 | // assumes that |
| 3976 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 3977 | uint64_t TrueWeight, FalseWeight; |
| 3978 | if (Br1->getBranchWeights(TrueWeight, FalseWeight)) { |
| 3979 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 3980 | uint64_t NewFalseWeight = FalseWeight; |
| 3981 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 3982 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 3983 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 3984 | |
| 3985 | NewTrueWeight = 2 * TrueWeight; |
| 3986 | NewFalseWeight = FalseWeight; |
| 3987 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 3988 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 3989 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 3990 | } |
| 3991 | } |
| 3992 | |
| 3993 | // Request DOM Tree update. |
| 3994 | // Note: No point in getting fancy here, since the DT info is never |
| 3995 | // available to CodeGenPrepare and the existing update code is broken |
| 3996 | // anyways. |
| 3997 | ModifiedDT = true; |
| 3998 | |
| 3999 | MadeChange = true; |
| 4000 | |
| 4001 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 4002 | TmpBB->dump()); |
| 4003 | } |
| 4004 | return MadeChange; |
| 4005 | } |