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