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" |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/ValueTracking.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 24 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 25 | #include "llvm/IR/Constants.h" |
| 26 | #include "llvm/IR/DataLayout.h" |
| 27 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 28 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 29 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 30 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 31 | #include "llvm/IR/IRBuilder.h" |
| 32 | #include "llvm/IR/InlineAsm.h" |
| 33 | #include "llvm/IR/Instructions.h" |
| 34 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 35 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 36 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Statepoint.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 38 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 39 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 40 | #include "llvm/Pass.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 41 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 42 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 43 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 44 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 45 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 46 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 47 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 48 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 49 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 50 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 51 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 52 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 53 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 54 | #define DEBUG_TYPE "codegenprepare" |
| 55 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 56 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 57 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 58 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 59 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 60 | "sunken Cmps"); |
| 61 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 62 | "of sunken Casts"); |
| 63 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 64 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 65 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 66 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
| 67 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 68 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 69 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 70 | STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 71 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 72 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 73 | static cl::opt<bool> DisableBranchOpts( |
| 74 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 75 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 76 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 77 | static cl::opt<bool> |
| 78 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 79 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 80 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 81 | static cl::opt<bool> DisableSelectToBranch( |
| 82 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 83 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 84 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 85 | static cl::opt<bool> AddrSinkUsingGEPs( |
| 86 | "addr-sink-using-gep", cl::Hidden, cl::init(false), |
| 87 | cl::desc("Address sinking in CGP using GEPs.")); |
| 88 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 89 | static cl::opt<bool> EnableAndCmpSinking( |
| 90 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 91 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 92 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 93 | static cl::opt<bool> DisableStoreExtract( |
| 94 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 95 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 96 | |
| 97 | static cl::opt<bool> StressStoreExtract( |
| 98 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 99 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 100 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 101 | static cl::opt<bool> DisableExtLdPromotion( |
| 102 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 103 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 104 | "CodeGenPrepare")); |
| 105 | |
| 106 | static cl::opt<bool> StressExtLdPromotion( |
| 107 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 108 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 109 | "optimization in CodeGenPrepare")); |
| 110 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 111 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 112 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 113 | typedef PointerIntPair<Type *, 1, bool> TypeIsSExt; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 114 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 115 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 116 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 117 | class CodeGenPrepare : public FunctionPass { |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 118 | const TargetMachine *TM; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 119 | const TargetLowering *TLI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 120 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 121 | const TargetLibraryInfo *TLInfo; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 122 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 123 | /// As we scan instructions optimizing them, this is the next instruction |
| 124 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 125 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 126 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 127 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 128 | /// This allows us to avoid inserting duplicate code for blocks with |
| 129 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 130 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 131 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 132 | /// Keeps track of all instructions inserted for the current function. |
| 133 | SetOfInstrs InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 134 | /// Keeps track of the type of the related instruction before their |
| 135 | /// promotion for the current function. |
| 136 | InstrToOrigTy PromotedInsts; |
| 137 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 138 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 139 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 140 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 141 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 142 | bool OptSize; |
| 143 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 144 | /// DataLayout for the Function being processed. |
| 145 | const DataLayout *DL; |
| 146 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 147 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 148 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 149 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 150 | : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 151 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 152 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 153 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 154 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 155 | const char *getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 156 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 157 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
Chandler Carruth | 7352302 | 2014-01-13 13:07:17 +0000 | [diff] [blame] | 158 | AU.addPreserved<DominatorTreeWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 159 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 160 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 161 | } |
| 162 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 163 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 164 | bool eliminateFallThrough(Function &F); |
| 165 | bool eliminateMostlyEmptyBlocks(Function &F); |
| 166 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 167 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
| 168 | bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT); |
| 169 | bool optimizeInst(Instruction *I, bool& ModifiedDT); |
| 170 | bool optimizeMemoryInst(Instruction *I, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 171 | Type *AccessTy, unsigned AS); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 172 | bool optimizeInlineAsmInst(CallInst *CS); |
| 173 | bool optimizeCallInst(CallInst *CI, bool& ModifiedDT); |
| 174 | bool moveExtToFormExtLoad(Instruction *&I); |
| 175 | bool optimizeExtUses(Instruction *I); |
| 176 | bool optimizeSelectInst(SelectInst *SI); |
| 177 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 178 | bool optimizeSwitchInst(SwitchInst *CI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 179 | bool optimizeExtractElementInst(Instruction *Inst); |
| 180 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 181 | bool placeDbgValues(Function &F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 182 | bool sinkAndCmp(Function &F); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 183 | bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 184 | Instruction *&Inst, |
| 185 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 186 | unsigned CreatedInstCost); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 187 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 188 | bool simplifyOffsetableRelocate(Instruction &I); |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 189 | void stripInvariantGroupMetadata(Instruction &I); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 190 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 191 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 192 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 193 | char CodeGenPrepare::ID = 0; |
Jiangning Liu | d623c52 | 2014-06-11 07:04:37 +0000 | [diff] [blame] | 194 | INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare", |
| 195 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 196 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 197 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 198 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 199 | } |
| 200 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 201 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 202 | if (skipOptnoneFunction(F)) |
| 203 | return false; |
| 204 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 205 | DL = &F.getParent()->getDataLayout(); |
| 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. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 209 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 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); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 217 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 218 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 219 | /// This optimization identifies DIV instructions that can be |
| 220 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 221 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 222 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 223 | TLI->getBypassSlowDivWidths(); |
Evan Cheng | 71be12b | 2012-09-14 21:25:34 +0000 | [diff] [blame] | 224 | for (Function::iterator I = F.begin(); I != F.end(); I++) |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 225 | EverMadeChange |= bypassSlowDivision(F, I, BypassWidths); |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 226 | } |
| 227 | |
| 228 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 229 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 230 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 231 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 232 | // 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] | 233 | // 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] | 234 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 235 | EverMadeChange |= placeDbgValues(F); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 236 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 237 | // If there is a mask, compare against zero, and branch that can be combined |
| 238 | // into a single target instruction, push the mask and compare into branch |
| 239 | // users. Do this before OptimizeBlock -> OptimizeInst -> |
| 240 | // OptimizeCmpExpression, which perturbs the pattern being searched for. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 241 | if (!DisableBranchOpts) { |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 242 | EverMadeChange |= sinkAndCmp(F); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 243 | EverMadeChange |= splitBranchCondition(F); |
| 244 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 245 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 246 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 247 | while (MadeChange) { |
| 248 | MadeChange = false; |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 249 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 250 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 251 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 252 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 253 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 254 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 255 | if (ModifiedDTOnIteration) |
| 256 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 257 | } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 258 | EverMadeChange |= MadeChange; |
| 259 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 260 | |
| 261 | SunkAddrs.clear(); |
| 262 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 263 | if (!DisableBranchOpts) { |
| 264 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 265 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 266 | for (BasicBlock &BB : F) { |
| 267 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 268 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 269 | if (!MadeChange) continue; |
| 270 | |
| 271 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 272 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 273 | if (pred_begin(*II) == pred_end(*II)) |
| 274 | WorkList.insert(*II); |
| 275 | } |
| 276 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 277 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 278 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 279 | while (!WorkList.empty()) { |
| 280 | BasicBlock *BB = *WorkList.begin(); |
| 281 | WorkList.erase(BB); |
| 282 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 283 | |
| 284 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 285 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 286 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 287 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 288 | if (pred_begin(*II) == pred_end(*II)) |
| 289 | WorkList.insert(*II); |
| 290 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 291 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 292 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 293 | // a single edge. |
| 294 | if (EverMadeChange || MadeChange) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 295 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 296 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 297 | EverMadeChange |= MadeChange; |
| 298 | } |
| 299 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 300 | if (!DisableGCOpts) { |
| 301 | SmallVector<Instruction *, 2> Statepoints; |
| 302 | for (BasicBlock &BB : F) |
| 303 | for (Instruction &I : BB) |
| 304 | if (isStatepoint(I)) |
| 305 | Statepoints.push_back(&I); |
| 306 | for (auto &I : Statepoints) |
| 307 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 308 | } |
| 309 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 310 | return EverMadeChange; |
| 311 | } |
| 312 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 313 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 314 | /// basic blocks has a single successor pointing to the other basic block, |
| 315 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 316 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 317 | bool Changed = false; |
| 318 | // 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] | 319 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 320 | BasicBlock *BB = &*I++; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 321 | // If the destination block has a single pred, then this is a trivial |
| 322 | // edge, just collapse it. |
| 323 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 324 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 325 | // Don't merge if BB's address is taken. |
| 326 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 327 | |
| 328 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 329 | if (Term && !Term->isConditional()) { |
| 330 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 331 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 332 | // Remember if SinglePred was the entry block of the function. |
| 333 | // If so, we will need to move BB back to the entry position. |
| 334 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 335 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 336 | |
| 337 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 338 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 339 | |
| 340 | // We have erased a block. Update the iterator. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 341 | I = BB->getIterator(); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 342 | } |
| 343 | } |
| 344 | return Changed; |
| 345 | } |
| 346 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 347 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 348 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 349 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 350 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 351 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 352 | bool MadeChange = false; |
| 353 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 354 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 355 | BasicBlock *BB = &*I++; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 356 | |
| 357 | // If this block doesn't end with an uncond branch, ignore it. |
| 358 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 359 | if (!BI || !BI->isUnconditional()) |
| 360 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 361 | |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 362 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 363 | // node, then other stuff is happening here. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 364 | BasicBlock::iterator BBI = BI->getIterator(); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 365 | if (BBI != BB->begin()) { |
| 366 | --BBI; |
Dale Johannesen | 4026b04 | 2009-03-27 01:13:37 +0000 | [diff] [blame] | 367 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 368 | if (BBI == BB->begin()) |
| 369 | break; |
| 370 | --BBI; |
| 371 | } |
| 372 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 373 | continue; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 374 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 375 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 376 | // Do not break infinite loops. |
| 377 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 378 | if (DestBB == BB) |
| 379 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 380 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 381 | if (!canMergeBlocks(BB, DestBB)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 382 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 383 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 384 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 385 | MadeChange = true; |
| 386 | } |
| 387 | return MadeChange; |
| 388 | } |
| 389 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 390 | /// Return true if we can merge BB into DestBB if there is a single |
| 391 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 392 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 393 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 394 | const BasicBlock *DestBB) const { |
| 395 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 396 | // the successor. If there are more complex condition (e.g. preheaders), |
| 397 | // don't mess around with them. |
| 398 | BasicBlock::const_iterator BBI = BB->begin(); |
| 399 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 400 | for (const User *U : PN->users()) { |
| 401 | const Instruction *UI = cast<Instruction>(U); |
| 402 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 403 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 404 | // If User is inside DestBB block and it is a PHINode then check |
| 405 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 406 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 407 | if (UI->getParent() == DestBB) { |
| 408 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 409 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 410 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 411 | if (Insn && Insn->getParent() == BB && |
| 412 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 413 | return false; |
| 414 | } |
| 415 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 416 | } |
| 417 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 418 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 419 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 420 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 421 | // can't merge the block. |
| 422 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 423 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 424 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 425 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 426 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 427 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 428 | // It is faster to get preds from a PHI than with pred_iterator. |
| 429 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 430 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 431 | } else { |
| 432 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 433 | } |
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 | // Walk the preds of DestBB. |
| 436 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 437 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 438 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 439 | BBI = DestBB->begin(); |
| 440 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 441 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 442 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 443 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 444 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 445 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 446 | if (V2PN->getParent() == BB) |
| 447 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 448 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 449 | // If there is a conflict, bail out. |
| 450 | if (V1 != V2) return false; |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | return true; |
| 456 | } |
| 457 | |
| 458 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 459 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 460 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 461 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 462 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 463 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 464 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 465 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 466 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 467 | // If the destination block has a single pred, then this is a trivial edge, |
| 468 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 469 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 470 | if (SinglePred != DestBB) { |
| 471 | // Remember if SinglePred was the entry block of the function. If so, we |
| 472 | // will need to move BB back to the entry position. |
| 473 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 474 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 475 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 476 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 477 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 478 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 479 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 480 | return; |
| 481 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 482 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 483 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 484 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 485 | // to handle the new incoming edges it is about to have. |
| 486 | PHINode *PN; |
| 487 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 488 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 489 | // Remove the incoming value for BB, and remember it. |
| 490 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 491 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 492 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 493 | // value that dominates BB. |
| 494 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 495 | if (InValPhi && InValPhi->getParent() == BB) { |
| 496 | // Add all of the input values of the input PHI as inputs of this phi. |
| 497 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 498 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 499 | InValPhi->getIncomingBlock(i)); |
| 500 | } else { |
| 501 | // Otherwise, add one instance of the dominating value for each edge that |
| 502 | // we will be adding. |
| 503 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 504 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 505 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 506 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 507 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 508 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 509 | } |
| 510 | } |
| 511 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 512 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 513 | // The PHIs are now updated, change everything that refers to BB to use |
| 514 | // DestBB and remove BB. |
| 515 | BB->replaceAllUsesWith(DestBB); |
| 516 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 517 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 518 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 519 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 520 | } |
| 521 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 522 | // Computes a map of base pointer relocation instructions to corresponding |
| 523 | // derived pointer relocation instructions given a vector of all relocate calls |
| 524 | static void computeBaseDerivedRelocateMap( |
| 525 | const SmallVectorImpl<User *> &AllRelocateCalls, |
| 526 | DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> & |
| 527 | RelocateInstMap) { |
| 528 | // Collect information in two maps: one primarily for locating the base object |
| 529 | // while filling the second map; the second map is the final structure holding |
| 530 | // a mapping between Base and corresponding Derived relocate calls |
| 531 | DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap; |
| 532 | for (auto &U : AllRelocateCalls) { |
| 533 | GCRelocateOperands ThisRelocate(U); |
| 534 | IntrinsicInst *I = cast<IntrinsicInst>(U); |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 535 | auto K = std::make_pair(ThisRelocate.getBasePtrIndex(), |
| 536 | ThisRelocate.getDerivedPtrIndex()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 537 | RelocateIdxMap.insert(std::make_pair(K, I)); |
| 538 | } |
| 539 | for (auto &Item : RelocateIdxMap) { |
| 540 | std::pair<unsigned, unsigned> Key = Item.first; |
| 541 | if (Key.first == Key.second) |
| 542 | // Base relocation: nothing to insert |
| 543 | continue; |
| 544 | |
| 545 | IntrinsicInst *I = Item.second; |
| 546 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 547 | |
| 548 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 549 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 550 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 551 | // TODO: We might want to insert a new base object relocate and gep off |
| 552 | // that, if there are enough derived object relocates. |
| 553 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 554 | |
| 555 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 556 | } |
| 557 | } |
| 558 | |
| 559 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 560 | // small integer constants |
| 561 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 562 | SmallVectorImpl<Value *> &OffsetV) { |
| 563 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 564 | // Only accept small constant integer operands |
| 565 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 566 | if (!Op || Op->getZExtValue() > 20) |
| 567 | return false; |
| 568 | } |
| 569 | |
| 570 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 571 | OffsetV.push_back(GEP->getOperand(i)); |
| 572 | return true; |
| 573 | } |
| 574 | |
| 575 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 576 | // replace, computes a replacement, and affects it. |
| 577 | static bool |
| 578 | simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase, |
| 579 | const SmallVectorImpl<IntrinsicInst *> &Targets) { |
| 580 | bool MadeChange = false; |
| 581 | for (auto &ToReplace : Targets) { |
| 582 | GCRelocateOperands MasterRelocate(RelocatedBase); |
| 583 | GCRelocateOperands ThisRelocate(ToReplace); |
| 584 | |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 585 | assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 586 | "Not relocating a derived object of the original base object"); |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 587 | if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 588 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 589 | continue; |
| 590 | } |
| 591 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 592 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 593 | // Base and derived relocates are in different basic blocks. |
| 594 | // In this case transform is only valid when base dominates derived |
| 595 | // relocate. However it would be too expensive to check dominance |
| 596 | // for each such relocate, so we skip the whole transformation. |
| 597 | continue; |
| 598 | } |
| 599 | |
Sanjoy Das | 499d703 | 2015-05-06 02:36:26 +0000 | [diff] [blame] | 600 | Value *Base = ThisRelocate.getBasePtr(); |
| 601 | auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 602 | if (!Derived || Derived->getPointerOperand() != Base) |
| 603 | continue; |
| 604 | |
| 605 | SmallVector<Value *, 2> OffsetV; |
| 606 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 607 | continue; |
| 608 | |
| 609 | // Create a Builder and replace the target callsite with a gep |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 610 | assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator"); |
| 611 | |
| 612 | // Insert after RelocatedBase |
| 613 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 614 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 615 | |
| 616 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 617 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 618 | // match, and we should reuse it to get the derived pointer. But it could be |
| 619 | // cases like this: |
| 620 | // bb1: |
| 621 | // ... |
| 622 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 623 | // br label %merge |
| 624 | // |
| 625 | // bb2: |
| 626 | // ... |
| 627 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 628 | // br label %merge |
| 629 | // |
| 630 | // merge: |
| 631 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 632 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 633 | // |
| 634 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 635 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 636 | // the extra bitcast should be optimized away in later passes. |
| 637 | Instruction *ActualRelocatedBase = RelocatedBase; |
| 638 | if (RelocatedBase->getType() != Base->getType()) { |
| 639 | ActualRelocatedBase = |
| 640 | cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType())); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 641 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 642 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 643 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 644 | Instruction *ReplacementInst = cast<Instruction>(Replacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 645 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 646 | // If the newly generated derived pointer's type does not match the original derived |
| 647 | // pointer's type, cast the new derived pointer to match it. Same reasoning as above. |
| 648 | Instruction *ActualReplacement = ReplacementInst; |
| 649 | if (ReplacementInst->getType() != ToReplace->getType()) { |
| 650 | ActualReplacement = |
| 651 | cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType())); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 652 | } |
| 653 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 654 | ToReplace->eraseFromParent(); |
| 655 | |
| 656 | MadeChange = true; |
| 657 | } |
| 658 | return MadeChange; |
| 659 | } |
| 660 | |
| 661 | // Turns this: |
| 662 | // |
| 663 | // %base = ... |
| 664 | // %ptr = gep %base + 15 |
| 665 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 666 | // %base' = relocate(%tok, i32 4, i32 4) |
| 667 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 668 | // %val = load %ptr' |
| 669 | // |
| 670 | // into this: |
| 671 | // |
| 672 | // %base = ... |
| 673 | // %ptr = gep %base + 15 |
| 674 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 675 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 676 | // %ptr' = gep %base' + 15 |
| 677 | // %val = load %ptr' |
| 678 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 679 | bool MadeChange = false; |
| 680 | SmallVector<User *, 2> AllRelocateCalls; |
| 681 | |
| 682 | for (auto *U : I.users()) |
| 683 | if (isGCRelocate(dyn_cast<Instruction>(U))) |
| 684 | // Collect all the relocate calls associated with a statepoint |
| 685 | AllRelocateCalls.push_back(U); |
| 686 | |
| 687 | // We need atleast one base pointer relocation + one derived pointer |
| 688 | // relocation to mangle |
| 689 | if (AllRelocateCalls.size() < 2) |
| 690 | return false; |
| 691 | |
| 692 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 693 | // corresponding derived relocate instructions |
| 694 | DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap; |
| 695 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 696 | if (RelocateInstMap.empty()) |
| 697 | return false; |
| 698 | |
| 699 | for (auto &Item : RelocateInstMap) |
| 700 | // Item.first is the RelocatedBase to offset against |
| 701 | // Item.second is the vector of Targets to replace |
| 702 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 703 | return MadeChange; |
| 704 | } |
| 705 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 706 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 707 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 708 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 709 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 710 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 711 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 712 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 713 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 714 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 715 | UI != E; ) { |
| 716 | Use &TheUse = UI.getUse(); |
| 717 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 718 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 719 | // Figure out which BB this cast is used in. For PHI's this is the |
| 720 | // appropriate predecessor block. |
| 721 | BasicBlock *UserBB = User->getParent(); |
| 722 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 723 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 724 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 725 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 726 | // Preincrement use iterator so we don't invalidate it. |
| 727 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 728 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 729 | // If this user is in the same block as the cast, don't change the cast. |
| 730 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 731 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 732 | // If we have already inserted a cast into this block, use it. |
| 733 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 734 | |
| 735 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 736 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 737 | assert(InsertPt != UserBB->end()); |
| 738 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 739 | CI->getType(), "", &*InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 740 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 741 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 742 | // 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] | 743 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 744 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 745 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 746 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 747 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 748 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 749 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 750 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 751 | MadeChange = true; |
| 752 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 753 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 754 | return MadeChange; |
| 755 | } |
| 756 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 757 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 758 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 759 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 760 | /// |
| 761 | /// Return true if any changes are made. |
| 762 | /// |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 763 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 764 | const DataLayout &DL) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 765 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 766 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 767 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 768 | |
| 769 | // This is an fp<->int conversion? |
| 770 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 771 | return false; |
| 772 | |
| 773 | // If this is an extension, it will be a zero or sign extension, which |
| 774 | // isn't a noop. |
| 775 | if (SrcVT.bitsLT(DstVT)) return false; |
| 776 | |
| 777 | // If these values will be promoted, find out what they will be promoted |
| 778 | // to. This helps us consider truncates on PPC as noop copies when they |
| 779 | // are. |
| 780 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 781 | TargetLowering::TypePromoteInteger) |
| 782 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 783 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 784 | TargetLowering::TypePromoteInteger) |
| 785 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 786 | |
| 787 | // If, after promotion, these are the same types, this is a noop copy. |
| 788 | if (SrcVT != DstVT) |
| 789 | return false; |
| 790 | |
| 791 | return SinkCast(CI); |
| 792 | } |
| 793 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 794 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 795 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 796 | /// |
| 797 | /// Return true if any changes were made. |
| 798 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 799 | Value *A, *B; |
| 800 | Instruction *AddI; |
| 801 | if (!match(CI, |
| 802 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 803 | return false; |
| 804 | |
| 805 | Type *Ty = AddI->getType(); |
| 806 | if (!isa<IntegerType>(Ty)) |
| 807 | return false; |
| 808 | |
| 809 | // We don't want to move around uses of condition values this late, so we we |
| 810 | // check if it is legal to create the call to the intrinsic in the basic |
| 811 | // block containing the icmp: |
| 812 | |
| 813 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 814 | return false; |
| 815 | |
| 816 | #ifndef NDEBUG |
| 817 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 818 | // for now: |
| 819 | if (AddI->hasOneUse()) |
| 820 | assert(*AddI->user_begin() == CI && "expected!"); |
| 821 | #endif |
| 822 | |
| 823 | Module *M = CI->getParent()->getParent()->getParent(); |
| 824 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 825 | |
| 826 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 827 | |
| 828 | auto *UAddWithOverflow = |
| 829 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 830 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 831 | auto *Overflow = |
| 832 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 833 | |
| 834 | CI->replaceAllUsesWith(Overflow); |
| 835 | AddI->replaceAllUsesWith(UAdd); |
| 836 | CI->eraseFromParent(); |
| 837 | AddI->eraseFromParent(); |
| 838 | return true; |
| 839 | } |
| 840 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 841 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 842 | /// registers that must be created and coalesced. This is a clear win except on |
| 843 | /// targets with multiple condition code registers (PowerPC), where it might |
| 844 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 845 | /// |
| 846 | /// Return true if any changes are made. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 847 | static bool SinkCmpExpression(CmpInst *CI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 848 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 849 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 850 | /// Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 851 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 852 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 853 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 854 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 855 | UI != E; ) { |
| 856 | Use &TheUse = UI.getUse(); |
| 857 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 858 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 859 | // Preincrement use iterator so we don't invalidate it. |
| 860 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 861 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 862 | // Don't bother for PHI nodes. |
| 863 | if (isa<PHINode>(User)) |
| 864 | continue; |
| 865 | |
| 866 | // Figure out which BB this cmp is used in. |
| 867 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 868 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 869 | // If this user is in the same block as the cmp, don't change the cmp. |
| 870 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 871 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 872 | // If we have already inserted a cmp into this block, use it. |
| 873 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 874 | |
| 875 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 876 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 877 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 878 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 879 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 880 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 881 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 882 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 883 | // Replace a use of the cmp with a use of the new cmp. |
| 884 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 885 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 886 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 887 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 888 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 889 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 890 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 891 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 892 | MadeChange = true; |
| 893 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 894 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 895 | return MadeChange; |
| 896 | } |
| 897 | |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 898 | static bool OptimizeCmpExpression(CmpInst *CI) { |
| 899 | if (SinkCmpExpression(CI)) |
| 900 | return true; |
| 901 | |
| 902 | if (CombineUAddWithOverflow(CI)) |
| 903 | return true; |
| 904 | |
| 905 | return false; |
| 906 | } |
| 907 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 908 | /// Check if the candidates could be combined with a shift instruction, which |
| 909 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 910 | /// 1. Truncate instruction |
| 911 | /// 2. And instruction and the imm is a mask of the low bits: |
| 912 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 913 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 914 | if (!isa<TruncInst>(User)) { |
| 915 | if (User->getOpcode() != Instruction::And || |
| 916 | !isa<ConstantInt>(User->getOperand(1))) |
| 917 | return false; |
| 918 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 919 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 920 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 921 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 922 | return false; |
| 923 | } |
| 924 | return true; |
| 925 | } |
| 926 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 927 | /// Sink both shift and truncate instruction to the use of truncate's BB. |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 928 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 929 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 930 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 931 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 932 | BasicBlock *UserBB = User->getParent(); |
| 933 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 934 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 935 | bool MadeChange = false; |
| 936 | |
| 937 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 938 | TruncE = TruncI->user_end(); |
| 939 | TruncUI != TruncE;) { |
| 940 | |
| 941 | Use &TruncTheUse = TruncUI.getUse(); |
| 942 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 943 | // Preincrement use iterator so we don't invalidate it. |
| 944 | |
| 945 | ++TruncUI; |
| 946 | |
| 947 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 948 | if (!ISDOpcode) |
| 949 | continue; |
| 950 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 951 | // If the use is actually a legal node, there will not be an |
| 952 | // implicit truncate. |
| 953 | // FIXME: always querying the result type is just an |
| 954 | // approximation; some nodes' legality is determined by the |
| 955 | // 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] | 956 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 957 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 958 | continue; |
| 959 | |
| 960 | // Don't bother for PHI nodes. |
| 961 | if (isa<PHINode>(TruncUser)) |
| 962 | continue; |
| 963 | |
| 964 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 965 | |
| 966 | if (UserBB == TruncUserBB) |
| 967 | continue; |
| 968 | |
| 969 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 970 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 971 | |
| 972 | if (!InsertedShift && !InsertedTrunc) { |
| 973 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 974 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 975 | // Sink the shift |
| 976 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 977 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 978 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 979 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 980 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 981 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 982 | |
| 983 | // Sink the trunc |
| 984 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 985 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 986 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 987 | |
| 988 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 989 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 990 | |
| 991 | MadeChange = true; |
| 992 | |
| 993 | TruncTheUse = InsertedTrunc; |
| 994 | } |
| 995 | } |
| 996 | return MadeChange; |
| 997 | } |
| 998 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 999 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1000 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1001 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1002 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1003 | /// BB1: |
| 1004 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1005 | /// BB2: |
| 1006 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1007 | /// ==> |
| 1008 | /// |
| 1009 | /// BB2: |
| 1010 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1011 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1012 | /// |
| 1013 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1014 | /// instruction. |
| 1015 | /// Return true if any changes are made. |
| 1016 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1017 | const TargetLowering &TLI, |
| 1018 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1019 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1020 | |
| 1021 | /// Only insert instructions in each block once. |
| 1022 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1023 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1024 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1025 | |
| 1026 | bool MadeChange = false; |
| 1027 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1028 | UI != E;) { |
| 1029 | Use &TheUse = UI.getUse(); |
| 1030 | Instruction *User = cast<Instruction>(*UI); |
| 1031 | // Preincrement use iterator so we don't invalidate it. |
| 1032 | ++UI; |
| 1033 | |
| 1034 | // Don't bother for PHI nodes. |
| 1035 | if (isa<PHINode>(User)) |
| 1036 | continue; |
| 1037 | |
| 1038 | if (!isExtractBitsCandidateUse(User)) |
| 1039 | continue; |
| 1040 | |
| 1041 | BasicBlock *UserBB = User->getParent(); |
| 1042 | |
| 1043 | if (UserBB == DefBB) { |
| 1044 | // If the shift and truncate instruction are in the same BB. The use of |
| 1045 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1046 | // legal. In this case, we would like to sink both shift and truncate |
| 1047 | // instruction to the BB of TruncUse. |
| 1048 | // for example: |
| 1049 | // BB1: |
| 1050 | // i64 shift.result = lshr i64 opnd, imm |
| 1051 | // trunc.result = trunc shift.result to i16 |
| 1052 | // |
| 1053 | // BB2: |
| 1054 | // ----> We will have an implicit truncate here if the architecture does |
| 1055 | // not have i16 compare. |
| 1056 | // cmp i16 trunc.result, opnd2 |
| 1057 | // |
| 1058 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1059 | // If the type of the truncate is legal, no trucate will be |
| 1060 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1061 | && |
| 1062 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1063 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1064 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1065 | |
| 1066 | continue; |
| 1067 | } |
| 1068 | // If we have already inserted a shift into this block, use it. |
| 1069 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1070 | |
| 1071 | if (!InsertedShift) { |
| 1072 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1073 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1074 | |
| 1075 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1076 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1077 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1078 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1079 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1080 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1081 | |
| 1082 | MadeChange = true; |
| 1083 | } |
| 1084 | |
| 1085 | // Replace a use of the shift with a use of the new shift. |
| 1086 | TheUse = InsertedShift; |
| 1087 | } |
| 1088 | |
| 1089 | // If we removed all uses, nuke the shift. |
| 1090 | if (ShiftI->use_empty()) |
| 1091 | ShiftI->eraseFromParent(); |
| 1092 | |
| 1093 | return MadeChange; |
| 1094 | } |
| 1095 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1096 | // Translate a masked load intrinsic like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1097 | // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, |
| 1098 | // <16 x i1> %mask, <16 x i32> %passthru) |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1099 | // to a chain of basic blocks, with loading element one-by-one if |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1100 | // the appropriate mask bit is set |
| 1101 | // |
| 1102 | // %1 = bitcast i8* %addr to i32* |
| 1103 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1104 | // %3 = icmp eq i1 %2, true |
| 1105 | // br i1 %3, label %cond.load, label %else |
| 1106 | // |
| 1107 | //cond.load: ; preds = %0 |
| 1108 | // %4 = getelementptr i32* %1, i32 0 |
| 1109 | // %5 = load i32* %4 |
| 1110 | // %6 = insertelement <16 x i32> undef, i32 %5, i32 0 |
| 1111 | // br label %else |
| 1112 | // |
| 1113 | //else: ; preds = %0, %cond.load |
| 1114 | // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] |
| 1115 | // %7 = extractelement <16 x i1> %mask, i32 1 |
| 1116 | // %8 = icmp eq i1 %7, true |
| 1117 | // br i1 %8, label %cond.load1, label %else2 |
| 1118 | // |
| 1119 | //cond.load1: ; preds = %else |
| 1120 | // %9 = getelementptr i32* %1, i32 1 |
| 1121 | // %10 = load i32* %9 |
| 1122 | // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 |
| 1123 | // br label %else2 |
| 1124 | // |
| 1125 | //else2: ; preds = %else, %cond.load1 |
| 1126 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1127 | // %12 = extractelement <16 x i1> %mask, i32 2 |
| 1128 | // %13 = icmp eq i1 %12, true |
| 1129 | // br i1 %13, label %cond.load4, label %else5 |
| 1130 | // |
| 1131 | static void ScalarizeMaskedLoad(CallInst *CI) { |
| 1132 | Value *Ptr = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1133 | Value *Alignment = CI->getArgOperand(1); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1134 | Value *Mask = CI->getArgOperand(2); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1135 | Value *Src0 = CI->getArgOperand(3); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1136 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1137 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1138 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1139 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1140 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1141 | Type *EltTy = CI->getType()->getVectorElementType(); |
| 1142 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1143 | IRBuilder<> Builder(CI->getContext()); |
| 1144 | Instruction *InsertPt = CI; |
| 1145 | BasicBlock *IfBlock = CI->getParent(); |
| 1146 | BasicBlock *CondBlock = nullptr; |
| 1147 | BasicBlock *PrevIfBlock = CI->getParent(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1148 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1149 | Builder.SetInsertPoint(InsertPt); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1150 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1151 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1152 | // Short-cut if the mask is all-true. |
| 1153 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1154 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1155 | |
| 1156 | if (IsAllOnesMask) { |
| 1157 | Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal); |
| 1158 | CI->replaceAllUsesWith(NewI); |
| 1159 | CI->eraseFromParent(); |
| 1160 | return; |
| 1161 | } |
| 1162 | |
| 1163 | // Adjust alignment for the scalar instruction. |
| 1164 | AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1165 | // Bitcast %addr fron i8* to EltTy* |
| 1166 | Type *NewPtrType = |
| 1167 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1168 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1169 | unsigned VectorWidth = VecType->getNumElements(); |
| 1170 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1171 | Value *UndefVal = UndefValue::get(VecType); |
| 1172 | |
| 1173 | // The result vector |
| 1174 | Value *VResult = UndefVal; |
| 1175 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1176 | if (isa<ConstantVector>(Mask)) { |
| 1177 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1178 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1179 | continue; |
| 1180 | Value *Gep = |
| 1181 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1182 | LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
| 1183 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1184 | Builder.getInt32(Idx)); |
| 1185 | } |
| 1186 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1187 | CI->replaceAllUsesWith(NewI); |
| 1188 | CI->eraseFromParent(); |
| 1189 | return; |
| 1190 | } |
| 1191 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1192 | PHINode *Phi = nullptr; |
| 1193 | Value *PrevPhi = UndefVal; |
| 1194 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1195 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1196 | |
| 1197 | // Fill the "else" block, created in the previous iteration |
| 1198 | // |
| 1199 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1200 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1201 | // %to_load = icmp eq i1 %mask_1, true |
| 1202 | // br i1 %to_load, label %cond.load, label %else |
| 1203 | // |
| 1204 | if (Idx > 0) { |
| 1205 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1206 | Phi->addIncoming(VResult, CondBlock); |
| 1207 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1208 | PrevPhi = Phi; |
| 1209 | VResult = Phi; |
| 1210 | } |
| 1211 | |
| 1212 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1213 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1214 | ConstantInt::get(Predicate->getType(), 1)); |
| 1215 | |
| 1216 | // Create "cond" block |
| 1217 | // |
| 1218 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1219 | // %Elt = load i32* %EltAddr |
| 1220 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1221 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1222 | CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1223 | Builder.SetInsertPoint(InsertPt); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1224 | |
| 1225 | Value *Gep = |
| 1226 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1227 | LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1228 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); |
| 1229 | |
| 1230 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1231 | BasicBlock *NewIfBlock = |
| 1232 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1233 | Builder.SetInsertPoint(InsertPt); |
| 1234 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1235 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1236 | OldBr->eraseFromParent(); |
| 1237 | PrevIfBlock = IfBlock; |
| 1238 | IfBlock = NewIfBlock; |
| 1239 | } |
| 1240 | |
| 1241 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1242 | Phi->addIncoming(VResult, CondBlock); |
| 1243 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1244 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1245 | CI->replaceAllUsesWith(NewI); |
| 1246 | CI->eraseFromParent(); |
| 1247 | } |
| 1248 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1249 | // Translate a masked store intrinsic, like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1250 | // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, |
| 1251 | // <16 x i1> %mask) |
| 1252 | // to a chain of basic blocks, that stores element one-by-one if |
| 1253 | // the appropriate mask bit is set |
| 1254 | // |
| 1255 | // %1 = bitcast i8* %addr to i32* |
| 1256 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1257 | // %3 = icmp eq i1 %2, true |
| 1258 | // br i1 %3, label %cond.store, label %else |
| 1259 | // |
| 1260 | // cond.store: ; preds = %0 |
| 1261 | // %4 = extractelement <16 x i32> %val, i32 0 |
| 1262 | // %5 = getelementptr i32* %1, i32 0 |
| 1263 | // store i32 %4, i32* %5 |
| 1264 | // br label %else |
| 1265 | // |
| 1266 | // else: ; preds = %0, %cond.store |
| 1267 | // %6 = extractelement <16 x i1> %mask, i32 1 |
| 1268 | // %7 = icmp eq i1 %6, true |
| 1269 | // br i1 %7, label %cond.store1, label %else2 |
| 1270 | // |
| 1271 | // cond.store1: ; preds = %else |
| 1272 | // %8 = extractelement <16 x i32> %val, i32 1 |
| 1273 | // %9 = getelementptr i32* %1, i32 1 |
| 1274 | // store i32 %8, i32* %9 |
| 1275 | // br label %else2 |
| 1276 | // . . . |
| 1277 | static void ScalarizeMaskedStore(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1278 | Value *Src = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1279 | Value *Ptr = CI->getArgOperand(1); |
| 1280 | Value *Alignment = CI->getArgOperand(2); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1281 | Value *Mask = CI->getArgOperand(3); |
| 1282 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1283 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1284 | VectorType *VecType = dyn_cast<VectorType>(Src->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1285 | assert(VecType && "Unexpected data type in masked store intrinsic"); |
| 1286 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1287 | Type *EltTy = VecType->getElementType(); |
| 1288 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1289 | IRBuilder<> Builder(CI->getContext()); |
| 1290 | Instruction *InsertPt = CI; |
| 1291 | BasicBlock *IfBlock = CI->getParent(); |
| 1292 | Builder.SetInsertPoint(InsertPt); |
| 1293 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1294 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1295 | // Short-cut if the mask is all-true. |
| 1296 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1297 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1298 | |
| 1299 | if (IsAllOnesMask) { |
| 1300 | Builder.CreateAlignedStore(Src, Ptr, AlignVal); |
| 1301 | CI->eraseFromParent(); |
| 1302 | return; |
| 1303 | } |
| 1304 | |
| 1305 | // Adjust alignment for the scalar instruction. |
| 1306 | AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1307 | // Bitcast %addr fron i8* to EltTy* |
| 1308 | Type *NewPtrType = |
| 1309 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1310 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1311 | unsigned VectorWidth = VecType->getNumElements(); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1312 | |
| 1313 | if (isa<ConstantVector>(Mask)) { |
| 1314 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1315 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1316 | continue; |
| 1317 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
| 1318 | Value *Gep = |
| 1319 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1320 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
| 1321 | } |
| 1322 | CI->eraseFromParent(); |
| 1323 | return; |
| 1324 | } |
| 1325 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1326 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1327 | |
| 1328 | // Fill the "else" block, created in the previous iteration |
| 1329 | // |
| 1330 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1331 | // %to_store = icmp eq i1 %mask_1, true |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1332 | // br i1 %to_store, label %cond.store, label %else |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1333 | // |
| 1334 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1335 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1336 | ConstantInt::get(Predicate->getType(), 1)); |
| 1337 | |
| 1338 | // Create "cond" block |
| 1339 | // |
| 1340 | // %OneElt = extractelement <16 x i32> %Src, i32 Idx |
| 1341 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1342 | // %store i32 %OneElt, i32* %EltAddr |
| 1343 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1344 | BasicBlock *CondBlock = |
| 1345 | IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1346 | Builder.SetInsertPoint(InsertPt); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1347 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1348 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1349 | Value *Gep = |
| 1350 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1351 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1352 | |
| 1353 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1354 | BasicBlock *NewIfBlock = |
| 1355 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1356 | Builder.SetInsertPoint(InsertPt); |
| 1357 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1358 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1359 | OldBr->eraseFromParent(); |
| 1360 | IfBlock = NewIfBlock; |
| 1361 | } |
| 1362 | CI->eraseFromParent(); |
| 1363 | } |
| 1364 | |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1365 | // Translate a masked gather intrinsic like |
| 1366 | // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4, |
| 1367 | // <16 x i1> %Mask, <16 x i32> %Src) |
| 1368 | // to a chain of basic blocks, with loading element one-by-one if |
| 1369 | // the appropriate mask bit is set |
| 1370 | // |
| 1371 | // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind |
| 1372 | // % Mask0 = extractelement <16 x i1> %Mask, i32 0 |
| 1373 | // % ToLoad0 = icmp eq i1 % Mask0, true |
| 1374 | // br i1 % ToLoad0, label %cond.load, label %else |
| 1375 | // |
| 1376 | // cond.load: |
| 1377 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1378 | // % Load0 = load i32, i32* % Ptr0, align 4 |
| 1379 | // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0 |
| 1380 | // br label %else |
| 1381 | // |
| 1382 | // else: |
| 1383 | // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0] |
| 1384 | // % Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1385 | // % ToLoad1 = icmp eq i1 % Mask1, true |
| 1386 | // br i1 % ToLoad1, label %cond.load1, label %else2 |
| 1387 | // |
| 1388 | // cond.load1: |
| 1389 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1390 | // % Load1 = load i32, i32* % Ptr1, align 4 |
| 1391 | // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1 |
| 1392 | // br label %else2 |
| 1393 | // . . . |
| 1394 | // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src |
| 1395 | // ret <16 x i32> %Result |
| 1396 | static void ScalarizeMaskedGather(CallInst *CI) { |
| 1397 | Value *Ptrs = CI->getArgOperand(0); |
| 1398 | Value *Alignment = CI->getArgOperand(1); |
| 1399 | Value *Mask = CI->getArgOperand(2); |
| 1400 | Value *Src0 = CI->getArgOperand(3); |
| 1401 | |
| 1402 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
| 1403 | |
| 1404 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1405 | |
| 1406 | IRBuilder<> Builder(CI->getContext()); |
| 1407 | Instruction *InsertPt = CI; |
| 1408 | BasicBlock *IfBlock = CI->getParent(); |
| 1409 | BasicBlock *CondBlock = nullptr; |
| 1410 | BasicBlock *PrevIfBlock = CI->getParent(); |
| 1411 | Builder.SetInsertPoint(InsertPt); |
| 1412 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1413 | |
| 1414 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1415 | |
| 1416 | Value *UndefVal = UndefValue::get(VecType); |
| 1417 | |
| 1418 | // The result vector |
| 1419 | Value *VResult = UndefVal; |
| 1420 | unsigned VectorWidth = VecType->getNumElements(); |
| 1421 | |
| 1422 | // Shorten the way if the mask is a vector of constants. |
| 1423 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1424 | |
| 1425 | if (IsConstMask) { |
| 1426 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1427 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1428 | continue; |
| 1429 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1430 | "Ptr" + Twine(Idx)); |
| 1431 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1432 | "Load" + Twine(Idx)); |
| 1433 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1434 | Builder.getInt32(Idx), |
| 1435 | "Res" + Twine(Idx)); |
| 1436 | } |
| 1437 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1438 | CI->replaceAllUsesWith(NewI); |
| 1439 | CI->eraseFromParent(); |
| 1440 | return; |
| 1441 | } |
| 1442 | |
| 1443 | PHINode *Phi = nullptr; |
| 1444 | Value *PrevPhi = UndefVal; |
| 1445 | |
| 1446 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1447 | |
| 1448 | // Fill the "else" block, created in the previous iteration |
| 1449 | // |
| 1450 | // %Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1451 | // %ToLoad1 = icmp eq i1 %Mask1, true |
| 1452 | // br i1 %ToLoad1, label %cond.load, label %else |
| 1453 | // |
| 1454 | if (Idx > 0) { |
| 1455 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1456 | Phi->addIncoming(VResult, CondBlock); |
| 1457 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1458 | PrevPhi = Phi; |
| 1459 | VResult = Phi; |
| 1460 | } |
| 1461 | |
| 1462 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1463 | Builder.getInt32(Idx), |
| 1464 | "Mask" + Twine(Idx)); |
| 1465 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1466 | ConstantInt::get(Predicate->getType(), 1), |
| 1467 | "ToLoad" + Twine(Idx)); |
| 1468 | |
| 1469 | // Create "cond" block |
| 1470 | // |
| 1471 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1472 | // %Elt = load i32* %EltAddr |
| 1473 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1474 | // |
| 1475 | CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); |
| 1476 | Builder.SetInsertPoint(InsertPt); |
| 1477 | |
| 1478 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1479 | "Ptr" + Twine(Idx)); |
| 1480 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1481 | "Load" + Twine(Idx)); |
| 1482 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx), |
| 1483 | "Res" + Twine(Idx)); |
| 1484 | |
| 1485 | // Create "else" block, fill it in the next iteration |
| 1486 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1487 | Builder.SetInsertPoint(InsertPt); |
| 1488 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1489 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1490 | OldBr->eraseFromParent(); |
| 1491 | PrevIfBlock = IfBlock; |
| 1492 | IfBlock = NewIfBlock; |
| 1493 | } |
| 1494 | |
| 1495 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1496 | Phi->addIncoming(VResult, CondBlock); |
| 1497 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1498 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1499 | CI->replaceAllUsesWith(NewI); |
| 1500 | CI->eraseFromParent(); |
| 1501 | } |
| 1502 | |
| 1503 | // Translate a masked scatter intrinsic, like |
| 1504 | // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4, |
| 1505 | // <16 x i1> %Mask) |
| 1506 | // to a chain of basic blocks, that stores element one-by-one if |
| 1507 | // the appropriate mask bit is set. |
| 1508 | // |
| 1509 | // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind |
| 1510 | // % Mask0 = extractelement <16 x i1> % Mask, i32 0 |
| 1511 | // % ToStore0 = icmp eq i1 % Mask0, true |
| 1512 | // br i1 %ToStore0, label %cond.store, label %else |
| 1513 | // |
| 1514 | // cond.store: |
| 1515 | // % Elt0 = extractelement <16 x i32> %Src, i32 0 |
| 1516 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1517 | // store i32 %Elt0, i32* % Ptr0, align 4 |
| 1518 | // br label %else |
| 1519 | // |
| 1520 | // else: |
| 1521 | // % Mask1 = extractelement <16 x i1> % Mask, i32 1 |
| 1522 | // % ToStore1 = icmp eq i1 % Mask1, true |
| 1523 | // br i1 % ToStore1, label %cond.store1, label %else2 |
| 1524 | // |
| 1525 | // cond.store1: |
| 1526 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1527 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1528 | // store i32 % Elt1, i32* % Ptr1, align 4 |
| 1529 | // br label %else2 |
| 1530 | // . . . |
| 1531 | static void ScalarizeMaskedScatter(CallInst *CI) { |
| 1532 | Value *Src = CI->getArgOperand(0); |
| 1533 | Value *Ptrs = CI->getArgOperand(1); |
| 1534 | Value *Alignment = CI->getArgOperand(2); |
| 1535 | Value *Mask = CI->getArgOperand(3); |
| 1536 | |
| 1537 | assert(isa<VectorType>(Src->getType()) && |
| 1538 | "Unexpected data type in masked scatter intrinsic"); |
| 1539 | assert(isa<VectorType>(Ptrs->getType()) && |
| 1540 | isa<PointerType>(Ptrs->getType()->getVectorElementType()) && |
| 1541 | "Vector of pointers is expected in masked scatter intrinsic"); |
| 1542 | |
| 1543 | IRBuilder<> Builder(CI->getContext()); |
| 1544 | Instruction *InsertPt = CI; |
| 1545 | BasicBlock *IfBlock = CI->getParent(); |
| 1546 | Builder.SetInsertPoint(InsertPt); |
| 1547 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1548 | |
| 1549 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1550 | unsigned VectorWidth = Src->getType()->getVectorNumElements(); |
| 1551 | |
| 1552 | // Shorten the way if the mask is a vector of constants. |
| 1553 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1554 | |
| 1555 | if (IsConstMask) { |
| 1556 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1557 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1558 | continue; |
| 1559 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1560 | "Elt" + Twine(Idx)); |
| 1561 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1562 | "Ptr" + Twine(Idx)); |
| 1563 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1564 | } |
| 1565 | CI->eraseFromParent(); |
| 1566 | return; |
| 1567 | } |
| 1568 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1569 | // Fill the "else" block, created in the previous iteration |
| 1570 | // |
| 1571 | // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx |
| 1572 | // % ToStore = icmp eq i1 % Mask1, true |
| 1573 | // br i1 % ToStore, label %cond.store, label %else |
| 1574 | // |
| 1575 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1576 | Builder.getInt32(Idx), |
| 1577 | "Mask" + Twine(Idx)); |
| 1578 | Value *Cmp = |
| 1579 | Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1580 | ConstantInt::get(Predicate->getType(), 1), |
| 1581 | "ToStore" + Twine(Idx)); |
| 1582 | |
| 1583 | // Create "cond" block |
| 1584 | // |
| 1585 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1586 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1587 | // %store i32 % Elt1, i32* % Ptr1 |
| 1588 | // |
| 1589 | BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); |
| 1590 | Builder.SetInsertPoint(InsertPt); |
| 1591 | |
| 1592 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 1593 | "Elt" + Twine(Idx)); |
| 1594 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1595 | "Ptr" + Twine(Idx)); |
| 1596 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 1597 | |
| 1598 | // Create "else" block, fill it in the next iteration |
| 1599 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1600 | Builder.SetInsertPoint(InsertPt); |
| 1601 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1602 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1603 | OldBr->eraseFromParent(); |
| 1604 | IfBlock = NewIfBlock; |
| 1605 | } |
| 1606 | CI->eraseFromParent(); |
| 1607 | } |
| 1608 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1609 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1610 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1611 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1612 | // Lower inline assembly if we can. |
| 1613 | // If we found an inline asm expession, and if the target knows how to |
| 1614 | // lower it to normal LLVM code, do so now. |
| 1615 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 1616 | if (TLI->ExpandInlineAsm(CI)) { |
| 1617 | // Avoid invalidating the iterator. |
| 1618 | CurInstIterator = BB->begin(); |
| 1619 | // Avoid processing instructions out of order, which could cause |
| 1620 | // reuse before a value is defined. |
| 1621 | SunkAddrs.clear(); |
| 1622 | return true; |
| 1623 | } |
| 1624 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1625 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1626 | return true; |
| 1627 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1628 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1629 | // Align the pointer arguments to this call if the target thinks it's a good |
| 1630 | // idea |
| 1631 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1632 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1633 | for (auto &Arg : CI->arg_operands()) { |
| 1634 | // We want to align both objects whose address is used directly and |
| 1635 | // objects whose address is used in casts and GEPs, though it only makes |
| 1636 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 1637 | // if size - offset meets the size threshold. |
| 1638 | if (!Arg->getType()->isPointerTy()) |
| 1639 | continue; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1640 | APInt Offset(DL->getPointerSizeInBits( |
| 1641 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 1642 | 0); |
| 1643 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1644 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1645 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 1646 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1647 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1648 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 1649 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1650 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1651 | // Global variables can only be aligned if they are defined in this |
| 1652 | // object (i.e. they are uniquely initialized in this object), and |
| 1653 | // over-aligning global variables that have an explicit section is |
| 1654 | // forbidden. |
| 1655 | GlobalVariable *GV; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1656 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() && |
| 1657 | !GV->hasSection() && GV->getAlignment() < PrefAlign && |
| 1658 | DL->getTypeAllocSize(GV->getType()->getElementType()) >= |
| 1659 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1660 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1661 | } |
| 1662 | // If this is a memcpy (or similar) then we may be able to improve the |
| 1663 | // alignment |
| 1664 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1665 | unsigned Align = getKnownAlignment(MI->getDest(), *DL); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1666 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1667 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL)); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame^] | 1668 | if (Align > MI->getAlignment()) |
| 1669 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1670 | } |
| 1671 | } |
| 1672 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1673 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1674 | if (II) { |
| 1675 | switch (II->getIntrinsicID()) { |
| 1676 | default: break; |
| 1677 | case Intrinsic::objectsize: { |
| 1678 | // Lower all uses of llvm.objectsize.* |
| 1679 | bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1); |
| 1680 | Type *ReturnTy = CI->getType(); |
| 1681 | Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1682 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1683 | // Substituting this can cause recursive simplifications, which can |
| 1684 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 1685 | // happens. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1686 | WeakVH IterHandle(&*CurInstIterator); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1687 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1688 | replaceAndRecursivelySimplify(CI, RetVal, |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 1689 | TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1690 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1691 | // If the iterator instruction was recursively deleted, start over at the |
| 1692 | // start of the block. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1693 | if (IterHandle != CurInstIterator.getNodePtrUnchecked()) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1694 | CurInstIterator = BB->begin(); |
| 1695 | SunkAddrs.clear(); |
| 1696 | } |
| 1697 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 1698 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1699 | case Intrinsic::masked_load: { |
| 1700 | // Scalarize unsupported vector masked load |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 1701 | if (!TTI->isLegalMaskedLoad(CI->getType())) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1702 | ScalarizeMaskedLoad(CI); |
| 1703 | ModifiedDT = true; |
| 1704 | return true; |
| 1705 | } |
| 1706 | return false; |
| 1707 | } |
| 1708 | case Intrinsic::masked_store: { |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 1709 | if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1710 | ScalarizeMaskedStore(CI); |
| 1711 | ModifiedDT = true; |
| 1712 | return true; |
| 1713 | } |
| 1714 | return false; |
| 1715 | } |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1716 | case Intrinsic::masked_gather: { |
| 1717 | if (!TTI->isLegalMaskedGather(CI->getType())) { |
| 1718 | ScalarizeMaskedGather(CI); |
| 1719 | ModifiedDT = true; |
| 1720 | return true; |
| 1721 | } |
| 1722 | return false; |
| 1723 | } |
| 1724 | case Intrinsic::masked_scatter: { |
| 1725 | if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) { |
| 1726 | ScalarizeMaskedScatter(CI); |
| 1727 | ModifiedDT = true; |
| 1728 | return true; |
| 1729 | } |
| 1730 | return false; |
| 1731 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1732 | case Intrinsic::aarch64_stlxr: |
| 1733 | case Intrinsic::aarch64_stxr: { |
| 1734 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 1735 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 1736 | ExtVal->getParent() == CI->getParent()) |
| 1737 | return false; |
| 1738 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 1739 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 1740 | // Mark this instruction as "inserted by CGP", so that other |
| 1741 | // optimizations don't touch it. |
| 1742 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1743 | return true; |
| 1744 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 1745 | case Intrinsic::invariant_group_barrier: |
| 1746 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 1747 | II->eraseFromParent(); |
| 1748 | return true; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1749 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1750 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1751 | if (TLI) { |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1752 | // Unknown address space. |
| 1753 | // TODO: Target hook to pick which address space the intrinsic cares |
| 1754 | // about? |
| 1755 | unsigned AddrSpace = ~0u; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1756 | SmallVector<Value*, 2> PtrOps; |
| 1757 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 1758 | if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1759 | while (!PtrOps.empty()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1760 | if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1761 | return true; |
| 1762 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 1763 | } |
| 1764 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1765 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1766 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 1767 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 1768 | // Lower all default uses of _chk calls. This is very similar |
| 1769 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1770 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 1771 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1772 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1773 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 1774 | CI->replaceAllUsesWith(V); |
| 1775 | CI->eraseFromParent(); |
| 1776 | return true; |
| 1777 | } |
| 1778 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1779 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1780 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1781 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 1782 | /// to enable tail call optimizations. The case it is currently looking for is: |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1783 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1784 | /// bb0: |
| 1785 | /// %tmp0 = tail call i32 @f0() |
| 1786 | /// br label %return |
| 1787 | /// bb1: |
| 1788 | /// %tmp1 = tail call i32 @f1() |
| 1789 | /// br label %return |
| 1790 | /// bb2: |
| 1791 | /// %tmp2 = tail call i32 @f2() |
| 1792 | /// br label %return |
| 1793 | /// return: |
| 1794 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 1795 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1796 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1797 | /// |
| 1798 | /// => |
| 1799 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1800 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1801 | /// bb0: |
| 1802 | /// %tmp0 = tail call i32 @f0() |
| 1803 | /// ret i32 %tmp0 |
| 1804 | /// bb1: |
| 1805 | /// %tmp1 = tail call i32 @f1() |
| 1806 | /// ret i32 %tmp1 |
| 1807 | /// bb2: |
| 1808 | /// %tmp2 = tail call i32 @f2() |
| 1809 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1810 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1811 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 1812 | if (!TLI) |
| 1813 | return false; |
| 1814 | |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 1815 | ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 1816 | if (!RI) |
| 1817 | return false; |
| 1818 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1819 | PHINode *PN = nullptr; |
| 1820 | BitCastInst *BCI = nullptr; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1821 | Value *V = RI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1822 | if (V) { |
| 1823 | BCI = dyn_cast<BitCastInst>(V); |
| 1824 | if (BCI) |
| 1825 | V = BCI->getOperand(0); |
| 1826 | |
| 1827 | PN = dyn_cast<PHINode>(V); |
| 1828 | if (!PN) |
| 1829 | return false; |
| 1830 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1831 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1832 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1833 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1834 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1835 | // It's not safe to eliminate the sign / zero extension of the return value. |
| 1836 | // See llvm::isInTailCallPosition(). |
| 1837 | const Function *F = BB->getParent(); |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1838 | AttributeSet CallerAttrs = F->getAttributes(); |
| 1839 | if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) || |
| 1840 | CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1841 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1842 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1843 | // Make sure there are no instructions between the PHI and return, or that the |
| 1844 | // return is the first instruction in the block. |
| 1845 | if (PN) { |
| 1846 | BasicBlock::iterator BI = BB->begin(); |
| 1847 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1848 | if (&*BI == BCI) |
| 1849 | // Also skip over the bitcast. |
| 1850 | ++BI; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1851 | if (&*BI != RI) |
| 1852 | return false; |
| 1853 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1854 | BasicBlock::iterator BI = BB->begin(); |
| 1855 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
| 1856 | if (&*BI != RI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1857 | return false; |
| 1858 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1859 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1860 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 1861 | /// call. |
| 1862 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1863 | if (PN) { |
| 1864 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 1865 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 1866 | // Make sure the phi value is indeed produced by the tail call. |
| 1867 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
| 1868 | TLI->mayBeEmittedAsTailCall(CI)) |
| 1869 | TailCalls.push_back(CI); |
| 1870 | } |
| 1871 | } else { |
| 1872 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1873 | 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] | 1874 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1875 | continue; |
| 1876 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1877 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1878 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 1879 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1880 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 1881 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1882 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1883 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1884 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Cameron Zwarich | 2edfe77 | 2011-03-24 15:54:11 +0000 | [diff] [blame] | 1885 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1886 | TailCalls.push_back(CI); |
| 1887 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1888 | } |
| 1889 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1890 | bool Changed = false; |
| 1891 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 1892 | CallInst *CI = TailCalls[i]; |
| 1893 | CallSite CS(CI); |
| 1894 | |
| 1895 | // Conservatively require the attributes of the call to match those of the |
| 1896 | // return. Ignore noalias because it doesn't affect the call sequence. |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1897 | AttributeSet CalleeAttrs = CS.getAttributes(); |
| 1898 | if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1899 | removeAttribute(Attribute::NoAlias) != |
Bill Wendling | 658d24d | 2013-01-18 21:53:16 +0000 | [diff] [blame] | 1900 | AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex). |
Bill Wendling | 3d7b0b8 | 2012-12-19 07:18:57 +0000 | [diff] [blame] | 1901 | removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1902 | continue; |
| 1903 | |
| 1904 | // Make sure the call instruction is followed by an unconditional branch to |
| 1905 | // the return block. |
| 1906 | BasicBlock *CallBB = CI->getParent(); |
| 1907 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 1908 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 1909 | continue; |
| 1910 | |
| 1911 | // Duplicate the return into CallBB. |
| 1912 | (void)FoldReturnIntoUncondBranch(RI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 1913 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1914 | ++NumRetsDup; |
| 1915 | } |
| 1916 | |
| 1917 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 1918 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1919 | BB->eraseFromParent(); |
| 1920 | |
| 1921 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1922 | } |
| 1923 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1924 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1925 | // Memory Optimization |
| 1926 | //===----------------------------------------------------------------------===// |
| 1927 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1928 | namespace { |
| 1929 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1930 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1931 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 1932 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1933 | Value *BaseReg; |
| 1934 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1935 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1936 | void print(raw_ostream &OS) const; |
| 1937 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1938 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1939 | bool operator==(const ExtAddrMode& O) const { |
| 1940 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 1941 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 1942 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 1943 | } |
| 1944 | }; |
| 1945 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 1946 | #ifndef NDEBUG |
| 1947 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 1948 | AM.print(OS); |
| 1949 | return OS; |
| 1950 | } |
| 1951 | #endif |
| 1952 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1953 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 1954 | bool NeedPlus = false; |
| 1955 | OS << "["; |
| 1956 | if (BaseGV) { |
| 1957 | OS << (NeedPlus ? " + " : "") |
| 1958 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1959 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1960 | NeedPlus = true; |
| 1961 | } |
| 1962 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 1963 | if (BaseOffs) { |
| 1964 | OS << (NeedPlus ? " + " : "") |
| 1965 | << BaseOffs; |
| 1966 | NeedPlus = true; |
| 1967 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1968 | |
| 1969 | if (BaseReg) { |
| 1970 | OS << (NeedPlus ? " + " : "") |
| 1971 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1972 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1973 | NeedPlus = true; |
| 1974 | } |
| 1975 | if (Scale) { |
| 1976 | OS << (NeedPlus ? " + " : "") |
| 1977 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 1978 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1979 | } |
| 1980 | |
| 1981 | OS << ']'; |
| 1982 | } |
| 1983 | |
| 1984 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
| 1985 | void ExtAddrMode::dump() const { |
| 1986 | print(dbgs()); |
| 1987 | dbgs() << '\n'; |
| 1988 | } |
| 1989 | #endif |
| 1990 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 1991 | /// \brief This class provides transaction based operation on the IR. |
| 1992 | /// Every change made through this class is recorded in the internal state and |
| 1993 | /// can be undone (rollback) until commit is called. |
| 1994 | class TypePromotionTransaction { |
| 1995 | |
| 1996 | /// \brief This represents the common interface of the individual transaction. |
| 1997 | /// Each class implements the logic for doing one specific modification on |
| 1998 | /// the IR via the TypePromotionTransaction. |
| 1999 | class TypePromotionAction { |
| 2000 | protected: |
| 2001 | /// The Instruction modified. |
| 2002 | Instruction *Inst; |
| 2003 | |
| 2004 | public: |
| 2005 | /// \brief Constructor of the action. |
| 2006 | /// The constructor performs the related action on the IR. |
| 2007 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2008 | |
| 2009 | virtual ~TypePromotionAction() {} |
| 2010 | |
| 2011 | /// \brief Undo the modification done by this action. |
| 2012 | /// When this method is called, the IR must be in the same state as it was |
| 2013 | /// before this action was applied. |
| 2014 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2015 | /// state as it was directly after this action was applied. |
| 2016 | virtual void undo() = 0; |
| 2017 | |
| 2018 | /// \brief Advocate every change made by this action. |
| 2019 | /// When the results on the IR of the action are to be kept, it is important |
| 2020 | /// to call this function, otherwise hidden information may be kept forever. |
| 2021 | virtual void commit() { |
| 2022 | // Nothing to be done, this action is not doing anything. |
| 2023 | } |
| 2024 | }; |
| 2025 | |
| 2026 | /// \brief Utility to remember the position of an instruction. |
| 2027 | class InsertionHandler { |
| 2028 | /// Position of an instruction. |
| 2029 | /// Either an instruction: |
| 2030 | /// - Is the first in a basic block: BB is used. |
| 2031 | /// - Has a previous instructon: PrevInst is used. |
| 2032 | union { |
| 2033 | Instruction *PrevInst; |
| 2034 | BasicBlock *BB; |
| 2035 | } Point; |
| 2036 | /// Remember whether or not the instruction had a previous instruction. |
| 2037 | bool HasPrevInstruction; |
| 2038 | |
| 2039 | public: |
| 2040 | /// \brief Record the position of \p Inst. |
| 2041 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2042 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2043 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2044 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2045 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2046 | else |
| 2047 | Point.BB = Inst->getParent(); |
| 2048 | } |
| 2049 | |
| 2050 | /// \brief Insert \p Inst at the recorded position. |
| 2051 | void insert(Instruction *Inst) { |
| 2052 | if (HasPrevInstruction) { |
| 2053 | if (Inst->getParent()) |
| 2054 | Inst->removeFromParent(); |
| 2055 | Inst->insertAfter(Point.PrevInst); |
| 2056 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2057 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2058 | if (Inst->getParent()) |
| 2059 | Inst->moveBefore(Position); |
| 2060 | else |
| 2061 | Inst->insertBefore(Position); |
| 2062 | } |
| 2063 | } |
| 2064 | }; |
| 2065 | |
| 2066 | /// \brief Move an instruction before another. |
| 2067 | class InstructionMoveBefore : public TypePromotionAction { |
| 2068 | /// Original position of the instruction. |
| 2069 | InsertionHandler Position; |
| 2070 | |
| 2071 | public: |
| 2072 | /// \brief Move \p Inst before \p Before. |
| 2073 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2074 | : TypePromotionAction(Inst), Position(Inst) { |
| 2075 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 2076 | Inst->moveBefore(Before); |
| 2077 | } |
| 2078 | |
| 2079 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2080 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2081 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 2082 | Position.insert(Inst); |
| 2083 | } |
| 2084 | }; |
| 2085 | |
| 2086 | /// \brief Set the operand of an instruction with a new value. |
| 2087 | class OperandSetter : public TypePromotionAction { |
| 2088 | /// Original operand of the instruction. |
| 2089 | Value *Origin; |
| 2090 | /// Index of the modified instruction. |
| 2091 | unsigned Idx; |
| 2092 | |
| 2093 | public: |
| 2094 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 2095 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2096 | : TypePromotionAction(Inst), Idx(Idx) { |
| 2097 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2098 | << "for:" << *Inst << "\n" |
| 2099 | << "with:" << *NewVal << "\n"); |
| 2100 | Origin = Inst->getOperand(Idx); |
| 2101 | Inst->setOperand(Idx, NewVal); |
| 2102 | } |
| 2103 | |
| 2104 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2105 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2106 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2107 | << "for: " << *Inst << "\n" |
| 2108 | << "with: " << *Origin << "\n"); |
| 2109 | Inst->setOperand(Idx, Origin); |
| 2110 | } |
| 2111 | }; |
| 2112 | |
| 2113 | /// \brief Hide the operands of an instruction. |
| 2114 | /// Do as if this instruction was not using any of its operands. |
| 2115 | class OperandsHider : public TypePromotionAction { |
| 2116 | /// The list of original operands. |
| 2117 | SmallVector<Value *, 4> OriginalValues; |
| 2118 | |
| 2119 | public: |
| 2120 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 2121 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 2122 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 2123 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2124 | OriginalValues.reserve(NumOpnds); |
| 2125 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2126 | // Save the current operand. |
| 2127 | Value *Val = Inst->getOperand(It); |
| 2128 | OriginalValues.push_back(Val); |
| 2129 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2130 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2131 | // that we are not willing to pay. |
| 2132 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2133 | } |
| 2134 | } |
| 2135 | |
| 2136 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2137 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2138 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 2139 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2140 | Inst->setOperand(It, OriginalValues[It]); |
| 2141 | } |
| 2142 | }; |
| 2143 | |
| 2144 | /// \brief Build a truncate instruction. |
| 2145 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2146 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2147 | public: |
| 2148 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 2149 | /// result. |
| 2150 | /// trunc Opnd to Ty. |
| 2151 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2152 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2153 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 2154 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2155 | } |
| 2156 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2157 | /// \brief Get the built value. |
| 2158 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2159 | |
| 2160 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2161 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2162 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 2163 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2164 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2165 | } |
| 2166 | }; |
| 2167 | |
| 2168 | /// \brief Build a sign extension instruction. |
| 2169 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2170 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2171 | public: |
| 2172 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 2173 | /// result. |
| 2174 | /// sext Opnd to Ty. |
| 2175 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2176 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2177 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2178 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 2179 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2180 | } |
| 2181 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2182 | /// \brief Get the built value. |
| 2183 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2184 | |
| 2185 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2186 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2187 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 2188 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2189 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2190 | } |
| 2191 | }; |
| 2192 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2193 | /// \brief Build a zero extension instruction. |
| 2194 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2195 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2196 | public: |
| 2197 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 2198 | /// result. |
| 2199 | /// zext Opnd to Ty. |
| 2200 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2201 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2202 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2203 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 2204 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2205 | } |
| 2206 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2207 | /// \brief Get the built value. |
| 2208 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2209 | |
| 2210 | /// \brief Remove the built instruction. |
| 2211 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2212 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 2213 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2214 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2215 | } |
| 2216 | }; |
| 2217 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2218 | /// \brief Mutate an instruction to another type. |
| 2219 | class TypeMutator : public TypePromotionAction { |
| 2220 | /// Record the original type. |
| 2221 | Type *OrigTy; |
| 2222 | |
| 2223 | public: |
| 2224 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 2225 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2226 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 2227 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2228 | << "\n"); |
| 2229 | Inst->mutateType(NewTy); |
| 2230 | } |
| 2231 | |
| 2232 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2233 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2234 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2235 | << "\n"); |
| 2236 | Inst->mutateType(OrigTy); |
| 2237 | } |
| 2238 | }; |
| 2239 | |
| 2240 | /// \brief Replace the uses of an instruction by another instruction. |
| 2241 | class UsesReplacer : public TypePromotionAction { |
| 2242 | /// Helper structure to keep track of the replaced uses. |
| 2243 | struct InstructionAndIdx { |
| 2244 | /// The instruction using the instruction. |
| 2245 | Instruction *Inst; |
| 2246 | /// The index where this instruction is used for Inst. |
| 2247 | unsigned Idx; |
| 2248 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2249 | : Inst(Inst), Idx(Idx) {} |
| 2250 | }; |
| 2251 | |
| 2252 | /// Keep track of the original uses (pair Instruction, Index). |
| 2253 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 2254 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 2255 | |
| 2256 | public: |
| 2257 | /// \brief Replace all the use of \p Inst by \p New. |
| 2258 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 2259 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2260 | << "\n"); |
| 2261 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2262 | for (Use &U : Inst->uses()) { |
| 2263 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2264 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2265 | } |
| 2266 | // Now, we can replace the uses. |
| 2267 | Inst->replaceAllUsesWith(New); |
| 2268 | } |
| 2269 | |
| 2270 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2271 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2272 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 2273 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2274 | EndIt = OriginalUses.end(); |
| 2275 | UseIt != EndIt; ++UseIt) { |
| 2276 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2277 | } |
| 2278 | } |
| 2279 | }; |
| 2280 | |
| 2281 | /// \brief Remove an instruction from the IR. |
| 2282 | class InstructionRemover : public TypePromotionAction { |
| 2283 | /// Original position of the instruction. |
| 2284 | InsertionHandler Inserter; |
| 2285 | /// Helper structure to hide all the link to the instruction. In other |
| 2286 | /// words, this helps to do as if the instruction was removed. |
| 2287 | OperandsHider Hider; |
| 2288 | /// Keep track of the uses replaced, if any. |
| 2289 | UsesReplacer *Replacer; |
| 2290 | |
| 2291 | public: |
| 2292 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 2293 | /// uses with New. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2294 | /// \pre If !Inst->use_empty(), then New != nullptr |
| 2295 | InstructionRemover(Instruction *Inst, Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2296 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2297 | Replacer(nullptr) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2298 | if (New) |
| 2299 | Replacer = new UsesReplacer(Inst, New); |
| 2300 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
| 2301 | Inst->removeFromParent(); |
| 2302 | } |
| 2303 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2304 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2305 | |
| 2306 | /// \brief Really remove the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2307 | void commit() override { delete Inst; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2308 | |
| 2309 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 2310 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2311 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2312 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 2313 | Inserter.insert(Inst); |
| 2314 | if (Replacer) |
| 2315 | Replacer->undo(); |
| 2316 | Hider.undo(); |
| 2317 | } |
| 2318 | }; |
| 2319 | |
| 2320 | public: |
| 2321 | /// Restoration point. |
| 2322 | /// The restoration point is a pointer to an action instead of an iterator |
| 2323 | /// because the iterator may be invalidated but not the pointer. |
| 2324 | typedef const TypePromotionAction *ConstRestorationPt; |
| 2325 | /// Advocate every changes made in that transaction. |
| 2326 | void commit(); |
| 2327 | /// Undo all the changes made after the given point. |
| 2328 | void rollback(ConstRestorationPt Point); |
| 2329 | /// Get the current restoration point. |
| 2330 | ConstRestorationPt getRestorationPoint() const; |
| 2331 | |
| 2332 | /// \name API for IR modification with state keeping to support rollback. |
| 2333 | /// @{ |
| 2334 | /// Same as Instruction::setOperand. |
| 2335 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 2336 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2337 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2338 | /// Same as Value::replaceAllUsesWith. |
| 2339 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 2340 | /// Same as Value::mutateType. |
| 2341 | void mutateType(Instruction *Inst, Type *NewTy); |
| 2342 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2343 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2344 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2345 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2346 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2347 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2348 | /// Same as Instruction::moveBefore. |
| 2349 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2350 | /// @} |
| 2351 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2352 | private: |
| 2353 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2354 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 2355 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2356 | }; |
| 2357 | |
| 2358 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2359 | Value *NewVal) { |
| 2360 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2361 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2362 | } |
| 2363 | |
| 2364 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2365 | Value *NewVal) { |
| 2366 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2367 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2368 | } |
| 2369 | |
| 2370 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2371 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2372 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2373 | } |
| 2374 | |
| 2375 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2376 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2377 | } |
| 2378 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2379 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2380 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2381 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2382 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2383 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2384 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2385 | } |
| 2386 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2387 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2388 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2389 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2390 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2391 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2392 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2393 | } |
| 2394 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2395 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2396 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2397 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2398 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2399 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2400 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2401 | } |
| 2402 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2403 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2404 | Instruction *Before) { |
| 2405 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2406 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2407 | } |
| 2408 | |
| 2409 | TypePromotionTransaction::ConstRestorationPt |
| 2410 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2411 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2412 | } |
| 2413 | |
| 2414 | void TypePromotionTransaction::commit() { |
| 2415 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2416 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2417 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2418 | Actions.clear(); |
| 2419 | } |
| 2420 | |
| 2421 | void TypePromotionTransaction::rollback( |
| 2422 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2423 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2424 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2425 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2426 | } |
| 2427 | } |
| 2428 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2429 | /// \brief A helper class for matching addressing modes. |
| 2430 | /// |
| 2431 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2432 | class AddressingModeMatcher { |
| 2433 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2434 | const TargetMachine &TM; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2435 | const TargetLowering &TLI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2436 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2437 | |
| 2438 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2439 | /// the memory instruction that we're computing this address for. |
| 2440 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2441 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2442 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2443 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2444 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2445 | /// part of the return value of this addressing mode matching stuff. |
| 2446 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2447 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2448 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2449 | const SetOfInstrs &InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2450 | /// A map from the instructions to their type before promotion. |
| 2451 | InstrToOrigTy &PromotedInsts; |
| 2452 | /// The ongoing transaction where every action should be registered. |
| 2453 | TypePromotionTransaction &TPT; |
| 2454 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2455 | /// This is set to true when we should not do profitability checks. |
| 2456 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2457 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2458 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2459 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2460 | const TargetMachine &TM, Type *AT, unsigned AS, |
| 2461 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2462 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2463 | InstrToOrigTy &PromotedInsts, |
| 2464 | TypePromotionTransaction &TPT) |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2465 | : AddrModeInsts(AMI), TM(TM), |
| 2466 | TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent()) |
| 2467 | ->getTargetLowering()), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2468 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 2469 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
| 2470 | PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2471 | IgnoreProfitability = false; |
| 2472 | } |
| 2473 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2474 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2475 | /// Find the maximal addressing mode that a load/store of V can fold, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2476 | /// give an access type of AccessTy. This returns a list of involved |
| 2477 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2478 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2479 | /// optimizations. |
| 2480 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 2481 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2482 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2483 | Instruction *MemoryInst, |
| 2484 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2485 | const TargetMachine &TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2486 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2487 | InstrToOrigTy &PromotedInsts, |
| 2488 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2489 | ExtAddrMode Result; |
| 2490 | |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2491 | bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2492 | MemoryInst, Result, InsertedInsts, |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2493 | PromotedInsts, TPT).matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2494 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2495 | return Result; |
| 2496 | } |
| 2497 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2498 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 2499 | bool matchAddr(Value *V, unsigned Depth); |
| 2500 | bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2501 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2502 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2503 | ExtAddrMode &AMBefore, |
| 2504 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2505 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 2506 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2507 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2508 | }; |
| 2509 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2510 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2511 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 2512 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2513 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2514 | unsigned Depth) { |
| 2515 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 2516 | // mode. Just process that directly. |
| 2517 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2518 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2519 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2520 | // If the scale is 0, it takes nothing to add this. |
| 2521 | if (Scale == 0) |
| 2522 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2523 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2524 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 2525 | // need an available scale field. |
| 2526 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 2527 | return false; |
| 2528 | |
| 2529 | ExtAddrMode TestAddrMode = AddrMode; |
| 2530 | |
| 2531 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 2532 | // [A+B + A*7] -> [B+A*8]. |
| 2533 | TestAddrMode.Scale += Scale; |
| 2534 | TestAddrMode.ScaledReg = ScaleReg; |
| 2535 | |
| 2536 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 2537 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2538 | return false; |
| 2539 | |
| 2540 | // It was legal, so commit it. |
| 2541 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2542 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2543 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 2544 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 2545 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2546 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2547 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 2548 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 2549 | TestAddrMode.ScaledReg = AddLHS; |
| 2550 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2551 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2552 | // If this addressing mode is legal, commit it and remember that we folded |
| 2553 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 2554 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2555 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 2556 | AddrMode = TestAddrMode; |
| 2557 | return true; |
| 2558 | } |
| 2559 | } |
| 2560 | |
| 2561 | // Otherwise, not (x+c)*scale, just return what we have. |
| 2562 | return true; |
| 2563 | } |
| 2564 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2565 | /// This is a little filter, which returns true if an addressing computation |
| 2566 | /// involving I might be folded into a load/store accessing it. |
| 2567 | /// This doesn't need to be perfect, but needs to accept at least |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2568 | /// the set of instructions that MatchOperationAddr can. |
| 2569 | static bool MightBeFoldableInst(Instruction *I) { |
| 2570 | switch (I->getOpcode()) { |
| 2571 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 2572 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2573 | // Don't touch identity bitcasts. |
| 2574 | if (I->getType() == I->getOperand(0)->getType()) |
| 2575 | return false; |
| 2576 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 2577 | case Instruction::PtrToInt: |
| 2578 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 2579 | return true; |
| 2580 | case Instruction::IntToPtr: |
| 2581 | // We know the input is intptr_t, so this is foldable. |
| 2582 | return true; |
| 2583 | case Instruction::Add: |
| 2584 | return true; |
| 2585 | case Instruction::Mul: |
| 2586 | case Instruction::Shl: |
| 2587 | // Can only handle X*C and X << C. |
| 2588 | return isa<ConstantInt>(I->getOperand(1)); |
| 2589 | case Instruction::GetElementPtr: |
| 2590 | return true; |
| 2591 | default: |
| 2592 | return false; |
| 2593 | } |
| 2594 | } |
| 2595 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2596 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 2597 | /// \note \p Val is assumed to be the product of some type promotion. |
| 2598 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 2599 | /// to be legal, as the non-promoted value would have had the same state. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 2600 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 2601 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2602 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 2603 | if (!PromotedInst) |
| 2604 | return false; |
| 2605 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 2606 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 2607 | if (!ISDOpcode) |
| 2608 | return true; |
| 2609 | // Otherwise, check if the promoted instruction is legal or not. |
| 2610 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 2611 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2612 | } |
| 2613 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2614 | /// \brief Hepler class to perform type promotion. |
| 2615 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2616 | /// \brief Utility function to check whether or not a sign or zero extension |
| 2617 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 2618 | /// either using the operands of \p Inst or promoting \p Inst. |
| 2619 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2620 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2621 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2622 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2623 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2624 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2625 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2626 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2627 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 2628 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2629 | |
| 2630 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 2631 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2632 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 2633 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2634 | } |
| 2635 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2636 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2637 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2638 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2639 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2640 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2641 | /// Newly added extensions are inserted in \p Exts. |
| 2642 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2643 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2644 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2645 | static Value *promoteOperandForTruncAndAnyExt( |
| 2646 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2647 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2648 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2649 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2650 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2651 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2652 | /// operand is promotable and is not a supported trunc or sext. |
| 2653 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2654 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2655 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2656 | /// Newly added extensions are inserted in \p Exts. |
| 2657 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2658 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2659 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2660 | static Value *promoteOperandForOther(Instruction *Ext, |
| 2661 | TypePromotionTransaction &TPT, |
| 2662 | InstrToOrigTy &PromotedInsts, |
| 2663 | unsigned &CreatedInstsCost, |
| 2664 | SmallVectorImpl<Instruction *> *Exts, |
| 2665 | SmallVectorImpl<Instruction *> *Truncs, |
| 2666 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2667 | |
| 2668 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2669 | static Value *signExtendOperandForOther( |
| 2670 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2671 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2672 | SmallVectorImpl<Instruction *> *Exts, |
| 2673 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2674 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2675 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2676 | } |
| 2677 | |
| 2678 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2679 | static Value *zeroExtendOperandForOther( |
| 2680 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 2681 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 2682 | SmallVectorImpl<Instruction *> *Exts, |
| 2683 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 2684 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 2685 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2686 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2687 | |
| 2688 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2689 | /// Type for the utility function that promotes the operand of Ext. |
| 2690 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2691 | InstrToOrigTy &PromotedInsts, |
| 2692 | unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2693 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2694 | SmallVectorImpl<Instruction *> *Truncs, |
| 2695 | const TargetLowering &TLI); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2696 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 2697 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2698 | /// \return NULL if no promotable action is possible with the current |
| 2699 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2700 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 2701 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2702 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 2703 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 2704 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2705 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2706 | const TargetLowering &TLI, |
| 2707 | const InstrToOrigTy &PromotedInsts); |
| 2708 | }; |
| 2709 | |
| 2710 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2711 | Type *ConsideredExtType, |
| 2712 | const InstrToOrigTy &PromotedInsts, |
| 2713 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2714 | // The promotion helper does not know how to deal with vector types yet. |
| 2715 | // To be able to fix that, we would need to fix the places where we |
| 2716 | // statically extend, e.g., constants and such. |
| 2717 | if (Inst->getType()->isVectorTy()) |
| 2718 | return false; |
| 2719 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2720 | // We can always get through zext. |
| 2721 | if (isa<ZExtInst>(Inst)) |
| 2722 | return true; |
| 2723 | |
| 2724 | // sext(sext) is ok too. |
| 2725 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2726 | return true; |
| 2727 | |
| 2728 | // We can get through binary operator, if it is legal. In other words, the |
| 2729 | // binary operator must have a nuw or nsw flag. |
| 2730 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 2731 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2732 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 2733 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2734 | return true; |
| 2735 | |
| 2736 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2737 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2738 | if (!isa<TruncInst>(Inst)) |
| 2739 | return false; |
| 2740 | |
| 2741 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2742 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2743 | // If the type is larger than the result type of the extension, we cannot. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2744 | if (!OpndVal->getType()->isIntegerTy() || |
| 2745 | OpndVal->getType()->getIntegerBitWidth() > |
| 2746 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2747 | return false; |
| 2748 | |
| 2749 | // If the operand of the truncate is not an instruction, we will not have |
| 2750 | // any information on the dropped bits. |
| 2751 | // (Actually we could for constant but it is not worth the extra logic). |
| 2752 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 2753 | if (!Opnd) |
| 2754 | return false; |
| 2755 | |
| 2756 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2757 | // I.e., check that trunc just drops extended bits of the same kind of |
| 2758 | // the extension. |
| 2759 | // #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] | 2760 | const Type *OpndType; |
| 2761 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 2762 | if (It != PromotedInsts.end() && It->second.getInt() == IsSExt) |
| 2763 | OpndType = It->second.getPointer(); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2764 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 2765 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2766 | else |
| 2767 | return false; |
| 2768 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2769 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 2770 | return Inst->getType()->getIntegerBitWidth() >= |
| 2771 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2772 | } |
| 2773 | |
| 2774 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2775 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2776 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2777 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 2778 | "Unexpected instruction type"); |
| 2779 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 2780 | Type *ExtTy = Ext->getType(); |
| 2781 | bool IsSExt = isa<SExtInst>(Ext); |
| 2782 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2783 | // get through. |
| 2784 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2785 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2786 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2787 | |
| 2788 | // Do not promote if the operand has been added by codegenprepare. |
| 2789 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 2790 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2791 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2792 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2793 | |
| 2794 | // SExt or Trunc instructions. |
| 2795 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2796 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 2797 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2798 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2799 | |
| 2800 | // Regular instruction. |
| 2801 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2802 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2803 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2804 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2805 | } |
| 2806 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2807 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2808 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2809 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2810 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2811 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2812 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 2813 | // get through it and this method should not be called. |
| 2814 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2815 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2816 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2817 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2818 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2819 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2820 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2821 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2822 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 2823 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 2824 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2825 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2826 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2827 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 2828 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2829 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 2830 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2831 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2832 | |
| 2833 | // Remove dead code. |
| 2834 | if (SExtOpnd->use_empty()) |
| 2835 | TPT.eraseInstruction(SExtOpnd); |
| 2836 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 2837 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2838 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2839 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2840 | if (ExtInst) { |
| 2841 | if (Exts) |
| 2842 | Exts->push_back(ExtInst); |
| 2843 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 2844 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2845 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2846 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2847 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 2848 | // At this point we have: ext ty opnd to ty. |
| 2849 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 2850 | Value *NextVal = ExtInst->getOperand(0); |
| 2851 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2852 | return NextVal; |
| 2853 | } |
| 2854 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2855 | Value *TypePromotionHelper::promoteOperandForOther( |
| 2856 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2857 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2858 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2859 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 2860 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2861 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2862 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2863 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2864 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2865 | if (!ExtOpnd->hasOneUse()) { |
| 2866 | // ExtOpnd will be promoted. |
| 2867 | // 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] | 2868 | // promoted version. |
| 2869 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2870 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2871 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 2872 | ITrunc->removeFromParent(); |
| 2873 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2874 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2875 | if (Truncs) |
| 2876 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2877 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2878 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2879 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2880 | // Restore the operand of Ext (which has been replaced by the previous call |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2881 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2882 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2883 | } |
| 2884 | |
| 2885 | // Get through the Instruction: |
| 2886 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2887 | // 2. Replace the uses of Ext by Inst. |
| 2888 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2889 | |
| 2890 | // Remember the original type of the instruction before promotion. |
| 2891 | // 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] | 2892 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 2893 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2894 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2895 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2896 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2897 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2898 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2899 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2900 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2901 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 2902 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2903 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2904 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 2905 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 2906 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2907 | DEBUG(dbgs() << "No need to propagate\n"); |
| 2908 | continue; |
| 2909 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2910 | // Check if we can statically extend the operand. |
| 2911 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2912 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2913 | DEBUG(dbgs() << "Statically extend\n"); |
| 2914 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 2915 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 2916 | : Cst->getValue().zext(BitWidth); |
| 2917 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2918 | continue; |
| 2919 | } |
| 2920 | // UndefValue are typed, so we have to statically sign extend them. |
| 2921 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2922 | DEBUG(dbgs() << "Statically extend\n"); |
| 2923 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2924 | continue; |
| 2925 | } |
| 2926 | |
| 2927 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2928 | // Check if Ext was reused to extend an operand. |
| 2929 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2930 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2931 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 2932 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 2933 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 2934 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 2935 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 2936 | continue; |
| 2937 | } |
| 2938 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2939 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 2940 | if (Exts) |
| 2941 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2942 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2943 | |
| 2944 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2945 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 2946 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2947 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2948 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2949 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2950 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2951 | if (ExtForOpnd == Ext) { |
| 2952 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 2953 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2954 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 2955 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2956 | } |
| 2957 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2958 | /// Check whether or not promoting an instruction to a wider type is profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2959 | /// \p NewCost gives the cost of extension instructions created by the |
| 2960 | /// promotion. |
| 2961 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 2962 | /// plus the number of instructions that have been |
| 2963 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2964 | /// \p PromotedOperand is the value that has been promoted. |
| 2965 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2966 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2967 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 2968 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 2969 | // The cost of the new extensions is greater than the cost of the |
| 2970 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2971 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2972 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2973 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 2974 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2975 | return true; |
| 2976 | // The promotion is neutral but it may help folding the sign extension in |
| 2977 | // loads for instance. |
| 2978 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 2979 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2980 | } |
| 2981 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2982 | /// Given an instruction or constant expr, see if we can fold the operation |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2983 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2984 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2985 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 2986 | /// not AddrInst has to be folded into the addressing mode on success. |
| 2987 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 2988 | /// because it has been moved away. |
| 2989 | /// Thus AddrInst must not be added in the matched instructions. |
| 2990 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 2991 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 2992 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2993 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2994 | unsigned Depth, |
| 2995 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2996 | // Avoid exponential behavior on extremely deep expression trees. |
| 2997 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2998 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2999 | // By default, all matched instructions stay in place. |
| 3000 | if (MovedAway) |
| 3001 | *MovedAway = false; |
| 3002 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3003 | switch (Opcode) { |
| 3004 | case Instruction::PtrToInt: |
| 3005 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3006 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3007 | case Instruction::IntToPtr: { |
| 3008 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3009 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3010 | // This inttoptr is a no-op if the integer type is pointer sized. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3011 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3012 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3013 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3014 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3015 | case Instruction::BitCast: |
| 3016 | // BitCast is always a noop, and we can handle it as long as it is |
| 3017 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 3018 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 3019 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 3020 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3021 | // and we don't want to mess around with them. Assume it knows what it |
| 3022 | // is doing. |
| 3023 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3024 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3025 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3026 | case Instruction::AddrSpaceCast: { |
| 3027 | unsigned SrcAS |
| 3028 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3029 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3030 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3031 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3032 | return false; |
| 3033 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3034 | case Instruction::Add: { |
| 3035 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3036 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3037 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3038 | // Start a transaction at this point. |
| 3039 | // The LHS may match but not the RHS. |
| 3040 | // Therefore, we need a higher level restoration point to undo partially |
| 3041 | // matched operation. |
| 3042 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3043 | TPT.getRestorationPoint(); |
| 3044 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3045 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3046 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3047 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3048 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3049 | // Restore the old addr mode info. |
| 3050 | AddrMode = BackupAddrMode; |
| 3051 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3052 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3053 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3054 | // Otherwise this was over-aggressive. Try merging in the LHS then the RHS. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3055 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3056 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3057 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3058 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3059 | // Otherwise we definitely can't merge the ADD in. |
| 3060 | AddrMode = BackupAddrMode; |
| 3061 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3062 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3063 | break; |
| 3064 | } |
| 3065 | //case Instruction::Or: |
| 3066 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3067 | //break; |
| 3068 | case Instruction::Mul: |
| 3069 | case Instruction::Shl: { |
| 3070 | // Can only handle X*C and X << C. |
| 3071 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3072 | if (!RHS) |
| 3073 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3074 | int64_t Scale = RHS->getSExtValue(); |
| 3075 | if (Opcode == Instruction::Shl) |
| 3076 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3077 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3078 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3079 | } |
| 3080 | case Instruction::GetElementPtr: { |
| 3081 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3082 | // one variable offset. |
| 3083 | int VariableOperand = -1; |
| 3084 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3085 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3086 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3087 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3088 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
| 3089 | if (StructType *STy = dyn_cast<StructType>(*GTI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3090 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3091 | unsigned Idx = |
| 3092 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3093 | ConstantOffset += SL->getElementOffset(Idx); |
| 3094 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3095 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3096 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 3097 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 3098 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 3099 | // We only allow one variable index at the moment. |
| 3100 | if (VariableOperand != -1) |
| 3101 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3102 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3103 | // Remember the variable index. |
| 3104 | VariableOperand = i; |
| 3105 | VariableScale = TypeSize; |
| 3106 | } |
| 3107 | } |
| 3108 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3109 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3110 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3111 | // just add it to the disp field and check validity. |
| 3112 | if (VariableOperand == -1) { |
| 3113 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3114 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3115 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3116 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3117 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3118 | return true; |
| 3119 | } |
| 3120 | AddrMode.BaseOffs -= ConstantOffset; |
| 3121 | return false; |
| 3122 | } |
| 3123 | |
| 3124 | // Save the valid addressing mode in case we can't match. |
| 3125 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3126 | unsigned OldSize = AddrModeInsts.size(); |
| 3127 | |
| 3128 | // See if the scale and offset amount is valid for this target. |
| 3129 | AddrMode.BaseOffs += ConstantOffset; |
| 3130 | |
| 3131 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3132 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3133 | // If it couldn't be matched, just stuff the value in a register. |
| 3134 | if (AddrMode.HasBaseReg) { |
| 3135 | AddrMode = BackupAddrMode; |
| 3136 | AddrModeInsts.resize(OldSize); |
| 3137 | return false; |
| 3138 | } |
| 3139 | AddrMode.HasBaseReg = true; |
| 3140 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3141 | } |
| 3142 | |
| 3143 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3144 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3145 | Depth)) { |
| 3146 | // If it couldn't be matched, try stuffing the base into a register |
| 3147 | // instead of matching it, and retrying the match of the scale. |
| 3148 | AddrMode = BackupAddrMode; |
| 3149 | AddrModeInsts.resize(OldSize); |
| 3150 | if (AddrMode.HasBaseReg) |
| 3151 | return false; |
| 3152 | AddrMode.HasBaseReg = true; |
| 3153 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3154 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3155 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3156 | VariableScale, Depth)) { |
| 3157 | // If even that didn't work, bail. |
| 3158 | AddrMode = BackupAddrMode; |
| 3159 | AddrModeInsts.resize(OldSize); |
| 3160 | return false; |
| 3161 | } |
| 3162 | } |
| 3163 | |
| 3164 | return true; |
| 3165 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3166 | case Instruction::SExt: |
| 3167 | case Instruction::ZExt: { |
| 3168 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3169 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3170 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3171 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3172 | // 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] | 3173 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3174 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3175 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3176 | if (!TPH) |
| 3177 | return false; |
| 3178 | |
| 3179 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3180 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3181 | unsigned CreatedInstsCost = 0; |
| 3182 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3183 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3184 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3185 | // SExt has been moved away. |
| 3186 | // Thus either it will be rematched later in the recursive calls or it is |
| 3187 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3188 | // E.g., |
| 3189 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3190 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3191 | // addr = gep base, idx |
| 3192 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3193 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3194 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3195 | // addr = gep base, op <- match |
| 3196 | if (MovedAway) |
| 3197 | *MovedAway = true; |
| 3198 | |
| 3199 | assert(PromotedOperand && |
| 3200 | "TypePromotionHelper should have filtered out those cases"); |
| 3201 | |
| 3202 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3203 | unsigned OldSize = AddrModeInsts.size(); |
| 3204 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3205 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3206 | // The total of the new cost is equal to the cost of the created |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3207 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3208 | // The total of the old cost is equal to the cost of the extension plus |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3209 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3210 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3211 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3212 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3213 | AddrMode = BackupAddrMode; |
| 3214 | AddrModeInsts.resize(OldSize); |
| 3215 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 3216 | TPT.rollback(LastKnownGood); |
| 3217 | return false; |
| 3218 | } |
| 3219 | return true; |
| 3220 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3221 | } |
| 3222 | return false; |
| 3223 | } |
| 3224 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3225 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 3226 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 3227 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 3228 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3229 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3230 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3231 | // Start a transaction at this point that we will rollback if the matching |
| 3232 | // fails. |
| 3233 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3234 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3235 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 3236 | // Fold in immediates if legal for the target. |
| 3237 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3238 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3239 | return true; |
| 3240 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 3241 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 3242 | // 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] | 3243 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3244 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3245 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3246 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3247 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3248 | } |
| 3249 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 3250 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3251 | unsigned OldSize = AddrModeInsts.size(); |
| 3252 | |
| 3253 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3254 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3255 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3256 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3257 | // to check here. |
| 3258 | if (MovedAway) |
| 3259 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3260 | // Okay, it's possible to fold this. Check to see if it is actually |
| 3261 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 3262 | // register pressure too much. |
| 3263 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3264 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3265 | AddrModeInsts.push_back(I); |
| 3266 | return true; |
| 3267 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3268 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3269 | // It isn't profitable to do this, roll back. |
| 3270 | //cerr << "NOT FOLDING: " << *I; |
| 3271 | AddrMode = BackupAddrMode; |
| 3272 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3273 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3274 | } |
| 3275 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3276 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3277 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3278 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3279 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 3280 | // Null pointer gets folded without affecting the addressing mode. |
| 3281 | return true; |
| 3282 | } |
| 3283 | |
| 3284 | // Worse case, the target should support [reg] addressing modes. :) |
| 3285 | if (!AddrMode.HasBaseReg) { |
| 3286 | AddrMode.HasBaseReg = true; |
| 3287 | AddrMode.BaseReg = Addr; |
| 3288 | // Still check for legality in case the target supports [imm] but not [i+r]. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3289 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3290 | return true; |
| 3291 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3292 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3293 | } |
| 3294 | |
| 3295 | // If the base register is already taken, see if we can do [r+r]. |
| 3296 | if (AddrMode.Scale == 0) { |
| 3297 | AddrMode.Scale = 1; |
| 3298 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3299 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3300 | return true; |
| 3301 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3302 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3303 | } |
| 3304 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3305 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3306 | return false; |
| 3307 | } |
| 3308 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3309 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 3310 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3311 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3312 | const TargetMachine &TM) { |
| 3313 | const Function *F = CI->getParent()->getParent(); |
| 3314 | const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering(); |
| 3315 | const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3316 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3317 | TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI, |
| 3318 | ImmutableCallSite(CI)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3319 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3320 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3321 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3322 | // Compute the constraint code and ConstraintType to use. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3323 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3324 | |
| 3325 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 3326 | // operand, we can't fold it! |
| 3327 | if (OpInfo.CallOperandVal == OpVal && |
| 3328 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 3329 | !OpInfo.isIndirect)) |
| 3330 | return false; |
| 3331 | } |
| 3332 | |
| 3333 | return true; |
| 3334 | } |
| 3335 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3336 | /// Recursively walk all the uses of I until we find a memory use. |
| 3337 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3338 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3339 | static bool FindAllMemoryUses( |
| 3340 | Instruction *I, |
| 3341 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
| 3342 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3343 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3344 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3345 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3346 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3347 | // If this is an obviously unfoldable instruction, bail out. |
| 3348 | if (!MightBeFoldableInst(I)) |
| 3349 | return true; |
| 3350 | |
| 3351 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3352 | for (Use &U : I->uses()) { |
| 3353 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3354 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3355 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 3356 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3357 | continue; |
| 3358 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3359 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3360 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 3361 | unsigned opNo = U.getOperandNo(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3362 | if (opNo == 0) return true; // Storing addr, not into addr. |
| 3363 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 3364 | continue; |
| 3365 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3366 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3367 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3368 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 3369 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3370 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3371 | // If this is a memory operand, we're cool, otherwise bail out. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3372 | if (!IsOperandAMemoryOperand(CI, IA, I, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3373 | return true; |
| 3374 | continue; |
| 3375 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3376 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3377 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3378 | return true; |
| 3379 | } |
| 3380 | |
| 3381 | return false; |
| 3382 | } |
| 3383 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3384 | /// Return true if Val is already known to be live at the use site that we're |
| 3385 | /// folding it into. If so, there is no cost to include it in the addressing |
| 3386 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 3387 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3388 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3389 | Value *KnownLive2) { |
| 3390 | // 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] | 3391 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3392 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3393 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3394 | // All values other than instructions and arguments (e.g. constants) are live. |
| 3395 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3396 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3397 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 3398 | // true because it is just a reference to the stack/frame pointer, which is |
| 3399 | // live for the whole function. |
| 3400 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 3401 | if (AI->isStaticAlloca()) |
| 3402 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3403 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3404 | // Check to see if this value is already used in the memory instruction's |
| 3405 | // block. If so, it's already live into the block at the very least, so we |
| 3406 | // can reasonably fold it. |
| 3407 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 3408 | } |
| 3409 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3410 | /// It is possible for the addressing mode of the machine to fold the specified |
| 3411 | /// instruction into a load or store that ultimately uses it. |
| 3412 | /// However, the specified instruction has multiple uses. |
| 3413 | /// Given this, it may actually increase register pressure to fold it |
| 3414 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3415 | /// |
| 3416 | /// X = ... |
| 3417 | /// Y = X+1 |
| 3418 | /// use(Y) -> nonload/store |
| 3419 | /// Z = Y+1 |
| 3420 | /// load Z |
| 3421 | /// |
| 3422 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 3423 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 3424 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 3425 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 3426 | /// number of computations either. |
| 3427 | /// |
| 3428 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 3429 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 3430 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 3431 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3432 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3433 | ExtAddrMode &AMAfter) { |
| 3434 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3435 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3436 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 3437 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 3438 | // the set of registers referenced by AMAfter and subtract out those |
| 3439 | // referenced by AMBefore: this is the set of values which folding in this |
| 3440 | // address extends the lifetime of. |
| 3441 | // |
| 3442 | // Note that there are only two potential values being referenced here, |
| 3443 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 3444 | // folded immediates). |
| 3445 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3446 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3447 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 3448 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3449 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3450 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3451 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3452 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3453 | |
| 3454 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 3455 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3456 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3457 | return true; |
| 3458 | |
| 3459 | // If all uses of this instruction are ultimately load/store/inlineasm's, |
| 3460 | // check to see if their addressing modes will include this instruction. If |
| 3461 | // so, we can fold it into all uses, so it doesn't matter if it has multiple |
| 3462 | // uses. |
| 3463 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 3464 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3465 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3466 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3467 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3468 | // Now that we know that all uses of this instruction are part of a chain of |
| 3469 | // computation involving only operations that could theoretically be folded |
| 3470 | // into a memory use, loop over each of these uses and see if they could |
| 3471 | // *actually* fold the instruction. |
| 3472 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 3473 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 3474 | Instruction *User = MemoryUses[i].first; |
| 3475 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3476 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3477 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 3478 | // know what it accesses. |
| 3479 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3480 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 3481 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3482 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3483 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 3484 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3485 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3486 | // Do a match against the root of this address, ignoring profitability. This |
| 3487 | // will tell us if the addressing mode for the memory operation will |
| 3488 | // *actually* cover the shared instruction. |
| 3489 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3490 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3491 | TPT.getRestorationPoint(); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3492 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3493 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3494 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3495 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3496 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3497 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 3498 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 3499 | // The match was to check the profitability, the changes made are not |
| 3500 | // part of the original matcher. Therefore, they should be dropped |
| 3501 | // otherwise the original matcher will not present the right state. |
| 3502 | TPT.rollback(LastKnownGood); |
| 3503 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3504 | // If the match didn't cover I, then it won't be shared by it. |
| 3505 | if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(), |
| 3506 | I) == MatchedAddrModeInsts.end()) |
| 3507 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3508 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3509 | MatchedAddrModeInsts.clear(); |
| 3510 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3511 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3512 | return true; |
| 3513 | } |
| 3514 | |
| 3515 | } // end anonymous namespace |
| 3516 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3517 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3518 | /// different basic block than BB. |
| 3519 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 3520 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 3521 | return I->getParent() != BB; |
| 3522 | return false; |
| 3523 | } |
| 3524 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3525 | /// Load and Store Instructions often have addressing modes that can do |
| 3526 | /// significant amounts of computation. As such, instruction selection will try |
| 3527 | /// to get the load or store to do as much computation as possible for the |
| 3528 | /// program. The problem is that isel can only see within a single block. As |
| 3529 | /// such, we sink as much legal addressing mode work into the block as possible. |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 3530 | /// |
| 3531 | /// This method is used to optimize both load/store and inline asms with memory |
| 3532 | /// operands. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3533 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3534 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3535 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3536 | |
| 3537 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3538 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 3539 | SmallVector<Value*, 8> worklist; |
| 3540 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3541 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3542 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3543 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 3544 | // the addressing mode obtained from the non-PHI roots of the graph |
| 3545 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3546 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3547 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3548 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3549 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 3550 | ExtAddrMode AddrMode; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3551 | TypePromotionTransaction TPT; |
| 3552 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3553 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3554 | while (!worklist.empty()) { |
| 3555 | Value *V = worklist.back(); |
| 3556 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3557 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3558 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3559 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3560 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3561 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3562 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3563 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3564 | // For a PHI node, push all of its incoming values. |
| 3565 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 3566 | for (Value *IncValue : P->incoming_values()) |
| 3567 | worklist.push_back(IncValue); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3568 | continue; |
| 3569 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3570 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3571 | // For non-PHIs, determine the addressing mode being computed. |
| 3572 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3573 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3574 | V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3575 | InsertedInsts, PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 3576 | |
| 3577 | // This check is broken into two cases with very similar code to avoid using |
| 3578 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 3579 | // calling getNumUses() unconditionally caused a significant compile-time |
| 3580 | // regression. |
| 3581 | if (!Consensus) { |
| 3582 | Consensus = V; |
| 3583 | AddrMode = NewAddrMode; |
| 3584 | AddrModeInsts = NewAddrModeInsts; |
| 3585 | continue; |
| 3586 | } else if (NewAddrMode == AddrMode) { |
| 3587 | if (!IsNumUsesConsensusValid) { |
| 3588 | NumUsesConsensus = Consensus->getNumUses(); |
| 3589 | IsNumUsesConsensusValid = true; |
| 3590 | } |
| 3591 | |
| 3592 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 3593 | // for all other roots of the PHI traversal. Also, when choosing one |
| 3594 | // such root as representative, select the one with the most uses in order |
| 3595 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 3596 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3597 | unsigned NumUses = V->getNumUses(); |
| 3598 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3599 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 3600 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3601 | AddrModeInsts = NewAddrModeInsts; |
| 3602 | } |
| 3603 | continue; |
| 3604 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3605 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3606 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3607 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3608 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3609 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 3610 | // If the addressing mode couldn't be determined, or if multiple different |
| 3611 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3612 | if (!Consensus) { |
| 3613 | TPT.rollback(LastKnownGood); |
| 3614 | return false; |
| 3615 | } |
| 3616 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3617 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3618 | // Check to see if any of the instructions supersumed by this addr mode are |
| 3619 | // non-local to I's BB. |
| 3620 | bool AnyNonLocal = false; |
| 3621 | for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) { |
Chris Lattner | 6d71b7f | 2008-11-26 03:20:37 +0000 | [diff] [blame] | 3622 | if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) { |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3623 | AnyNonLocal = true; |
| 3624 | break; |
| 3625 | } |
| 3626 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3627 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3628 | // If all the instructions matched are already in this BB, don't do anything. |
| 3629 | if (!AnyNonLocal) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3630 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3631 | return false; |
| 3632 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3633 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3634 | // Insert this computation right after this user. Since our caller is |
| 3635 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 3636 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3637 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3638 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3639 | // Now that we determined the addressing expression we want to use and know |
| 3640 | // that we have to sink it into this block. Check to see if we have already |
| 3641 | // done this for some other load/store instr in this block. If so, reuse the |
| 3642 | // computation. |
| 3643 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 3644 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3645 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3646 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3647 | if (SunkAddr->getType() != Addr->getType()) |
Benjamin Kramer | 547b6c5 | 2011-09-27 20:39:19 +0000 | [diff] [blame] | 3648 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 3649 | } else if (AddrSinkUsingGEPs || |
| 3650 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Eric Christopher | 2c63549 | 2015-01-27 07:54:39 +0000 | [diff] [blame] | 3651 | TM->getSubtargetImpl(*MemoryInst->getParent()->getParent()) |
| 3652 | ->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3653 | // By default, we use the GEP-based method when AA is used later. This |
| 3654 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 3655 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3656 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3657 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3658 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3659 | |
| 3660 | // First, find the pointer. |
| 3661 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 3662 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3663 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3664 | } |
| 3665 | |
| 3666 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 3667 | // We can't add more than one pointer together, nor can we scale a |
| 3668 | // pointer (both of which seem meaningless). |
| 3669 | if (ResultPtr || AddrMode.Scale != 1) |
| 3670 | return false; |
| 3671 | |
| 3672 | ResultPtr = AddrMode.ScaledReg; |
| 3673 | AddrMode.Scale = 0; |
| 3674 | } |
| 3675 | |
| 3676 | if (AddrMode.BaseGV) { |
| 3677 | if (ResultPtr) |
| 3678 | return false; |
| 3679 | |
| 3680 | ResultPtr = AddrMode.BaseGV; |
| 3681 | } |
| 3682 | |
| 3683 | // If the real base value actually came from an inttoptr, then the matcher |
| 3684 | // will look through it and provide only the integer value. In that case, |
| 3685 | // use it here. |
| 3686 | if (!ResultPtr && AddrMode.BaseReg) { |
| 3687 | ResultPtr = |
| 3688 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3689 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3690 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 3691 | ResultPtr = |
| 3692 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 3693 | AddrMode.Scale = 0; |
| 3694 | } |
| 3695 | |
| 3696 | if (!ResultPtr && |
| 3697 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 3698 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 3699 | } else if (!ResultPtr) { |
| 3700 | return false; |
| 3701 | } else { |
| 3702 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3703 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 3704 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3705 | |
| 3706 | // Start with the base register. Do this first so that subsequent address |
| 3707 | // matching finds it last, which will prevent it from trying to match it |
| 3708 | // as the scaled value in case it happens to be a mul. That would be |
| 3709 | // problematic if we've sunk a different mul for the scale, because then |
| 3710 | // we'd end up sinking both muls. |
| 3711 | if (AddrMode.BaseReg) { |
| 3712 | Value *V = AddrMode.BaseReg; |
| 3713 | if (V->getType() != IntPtrTy) |
| 3714 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 3715 | |
| 3716 | ResultIndex = V; |
| 3717 | } |
| 3718 | |
| 3719 | // Add the scale value. |
| 3720 | if (AddrMode.Scale) { |
| 3721 | Value *V = AddrMode.ScaledReg; |
| 3722 | if (V->getType() == IntPtrTy) { |
| 3723 | // done. |
| 3724 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 3725 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 3726 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 3727 | } else { |
| 3728 | // It is only safe to sign extend the BaseReg if we know that the math |
| 3729 | // required to create it did not overflow before we extend it. Since |
| 3730 | // the original IR value was tossed in favor of a constant back when |
| 3731 | // the AddrMode was created we need to bail out gracefully if widths |
| 3732 | // do not match instead of extending it. |
| 3733 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 3734 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 3735 | I->eraseFromParent(); |
| 3736 | return false; |
| 3737 | } |
| 3738 | |
| 3739 | if (AddrMode.Scale != 1) |
| 3740 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 3741 | "sunkaddr"); |
| 3742 | if (ResultIndex) |
| 3743 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 3744 | else |
| 3745 | ResultIndex = V; |
| 3746 | } |
| 3747 | |
| 3748 | // Add in the Base Offset if present. |
| 3749 | if (AddrMode.BaseOffs) { |
| 3750 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 3751 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 3752 | // We need to add this separately from the scale above to help with |
| 3753 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3754 | if (ResultPtr->getType() != I8PtrTy) |
| 3755 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3756 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3757 | } |
| 3758 | |
| 3759 | ResultIndex = V; |
| 3760 | } |
| 3761 | |
| 3762 | if (!ResultIndex) { |
| 3763 | SunkAddr = ResultPtr; |
| 3764 | } else { |
| 3765 | if (ResultPtr->getType() != I8PtrTy) |
| 3766 | ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 3767 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 3768 | } |
| 3769 | |
| 3770 | if (SunkAddr->getType() != Addr->getType()) |
| 3771 | SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType()); |
| 3772 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3773 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 3774 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 3775 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3776 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3777 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3778 | |
| 3779 | // Start with the base register. Do this first so that subsequent address |
| 3780 | // matching finds it last, which will prevent it from trying to match it |
| 3781 | // as the scaled value in case it happens to be a mul. That would be |
| 3782 | // problematic if we've sunk a different mul for the scale, because then |
| 3783 | // we'd end up sinking both muls. |
| 3784 | if (AddrMode.BaseReg) { |
| 3785 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3786 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3787 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3788 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3789 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 3790 | Result = V; |
| 3791 | } |
| 3792 | |
| 3793 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3794 | if (AddrMode.Scale) { |
| 3795 | Value *V = AddrMode.ScaledReg; |
| 3796 | if (V->getType() == IntPtrTy) { |
| 3797 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 3798 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3799 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3800 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 3801 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3802 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3803 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 3804 | // It is only safe to sign extend the BaseReg if we know that the math |
| 3805 | // required to create it did not overflow before we extend it. Since |
| 3806 | // the original IR value was tossed in favor of a constant back when |
| 3807 | // the AddrMode was created we need to bail out gracefully if widths |
| 3808 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 3809 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 3810 | if (I && (Result != AddrMode.BaseReg)) |
| 3811 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 3812 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3813 | } |
| 3814 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3815 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 3816 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3817 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3818 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3819 | else |
| 3820 | Result = V; |
| 3821 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3822 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3823 | // Add in the BaseGV if present. |
| 3824 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3825 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3826 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3827 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3828 | else |
| 3829 | Result = V; |
| 3830 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3831 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3832 | // Add in the Base Offset if present. |
| 3833 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 3834 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3835 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3836 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3837 | else |
| 3838 | Result = V; |
| 3839 | } |
| 3840 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3841 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 3842 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3843 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 3844 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3845 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3846 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3847 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 3848 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3849 | // If we have no uses, recursively delete the value and all dead instructions |
| 3850 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 3851 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3852 | // This can cause recursive deletion, which can invalidate our iterator. |
| 3853 | // Use a WeakVH to hold onto it in case this happens. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 3854 | WeakVH IterHandle(&*CurInstIterator); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3855 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3856 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 3857 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3858 | |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 3859 | if (IterHandle != CurInstIterator.getNodePtrUnchecked()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 3860 | // If the iterator instruction was recursively deleted, start over at the |
| 3861 | // start of the block. |
| 3862 | CurInstIterator = BB->begin(); |
| 3863 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3864 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 3865 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 3866 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 3867 | return true; |
| 3868 | } |
| 3869 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3870 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 3871 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3872 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3873 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3874 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3875 | const TargetRegisterInfo *TRI = |
| 3876 | TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3877 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 3878 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 3879 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 3880 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3881 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 3882 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3883 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 3884 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3885 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 3886 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 3887 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 3888 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3889 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 3890 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 3891 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 3892 | } |
| 3893 | |
| 3894 | return MadeChange; |
| 3895 | } |
| 3896 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3897 | /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or |
| 3898 | /// sign extensions. |
| 3899 | static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) { |
| 3900 | assert(!Inst->use_empty() && "Input must have at least one use"); |
| 3901 | const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin()); |
| 3902 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 3903 | Type *ExtTy = FirstUser->getType(); |
| 3904 | for (const User *U : Inst->users()) { |
| 3905 | const Instruction *UI = cast<Instruction>(U); |
| 3906 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 3907 | return false; |
| 3908 | Type *CurTy = UI->getType(); |
| 3909 | // Same input and output types: Same instruction after CSE. |
| 3910 | if (CurTy == ExtTy) |
| 3911 | continue; |
| 3912 | |
| 3913 | // If IsSExt is true, we are in this situation: |
| 3914 | // a = Inst |
| 3915 | // b = sext ty1 a to ty2 |
| 3916 | // c = sext ty1 a to ty3 |
| 3917 | // Assuming ty2 is shorter than ty3, this could be turned into: |
| 3918 | // a = Inst |
| 3919 | // b = sext ty1 a to ty2 |
| 3920 | // c = sext ty2 b to ty3 |
| 3921 | // However, the last sext is not free. |
| 3922 | if (IsSExt) |
| 3923 | return false; |
| 3924 | |
| 3925 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 3926 | // In that case, we would not account for a different use. |
| 3927 | Type *NarrowTy; |
| 3928 | Type *LargeTy; |
| 3929 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 3930 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 3931 | NarrowTy = CurTy; |
| 3932 | LargeTy = ExtTy; |
| 3933 | } else { |
| 3934 | NarrowTy = ExtTy; |
| 3935 | LargeTy = CurTy; |
| 3936 | } |
| 3937 | |
| 3938 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 3939 | return false; |
| 3940 | } |
| 3941 | // All uses are the same or can be derived from one another for free. |
| 3942 | return true; |
| 3943 | } |
| 3944 | |
| 3945 | /// \brief Try to form ExtLd by promoting \p Exts until they reach a |
| 3946 | /// load instruction. |
| 3947 | /// If an ext(load) can be formed, it is returned via \p LI for the load |
| 3948 | /// and \p Inst for the extension. |
| 3949 | /// Otherwise LI == nullptr and Inst == nullptr. |
| 3950 | /// When some promotion happened, \p TPT contains the proper state to |
| 3951 | /// revert them. |
| 3952 | /// |
| 3953 | /// \return true when promoting was necessary to expose the ext(load) |
| 3954 | /// opportunity, false otherwise. |
| 3955 | /// |
| 3956 | /// Example: |
| 3957 | /// \code |
| 3958 | /// %ld = load i32* %addr |
| 3959 | /// %add = add nuw i32 %ld, 4 |
| 3960 | /// %zext = zext i32 %add to i64 |
| 3961 | /// \endcode |
| 3962 | /// => |
| 3963 | /// \code |
| 3964 | /// %ld = load i32* %addr |
| 3965 | /// %zext = zext i32 %ld to i64 |
| 3966 | /// %add = add nuw i64 %zext, 4 |
| 3967 | /// \encode |
| 3968 | /// Thanks to the promotion, we can match zext(load i32*) to i64. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3969 | bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3970 | LoadInst *&LI, Instruction *&Inst, |
| 3971 | const SmallVectorImpl<Instruction *> &Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3972 | unsigned CreatedInstsCost = 0) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3973 | // Iterate over all the extensions to see if one form an ext(load). |
| 3974 | for (auto I : Exts) { |
| 3975 | // Check if we directly have ext(load). |
| 3976 | if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) { |
| 3977 | Inst = I; |
| 3978 | // No promotion happened here. |
| 3979 | return false; |
| 3980 | } |
| 3981 | // Check whether or not we want to do any promotion. |
| 3982 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
| 3983 | continue; |
| 3984 | // Get the action to perform the promotion. |
| 3985 | TypePromotionHelper::Action TPH = TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3986 | I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3987 | // Check if we can promote. |
| 3988 | if (!TPH) |
| 3989 | continue; |
| 3990 | // Save the current state. |
| 3991 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3992 | TPT.getRestorationPoint(); |
| 3993 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3994 | unsigned NewCreatedInstsCost = 0; |
| 3995 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3996 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3997 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 3998 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3999 | assert(PromotedVal && |
| 4000 | "TypePromotionHelper should have filtered out those cases"); |
| 4001 | |
| 4002 | // We would be able to merge only one extension in a load. |
| 4003 | // Therefore, if we have more than 1 new extension we heuristically |
| 4004 | // cut this search path, because it means we degrade the code quality. |
| 4005 | // With exactly 2, the transformation is neutral, because we will merge |
| 4006 | // one extension but leave one. However, we optimistically keep going, |
| 4007 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4008 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
| 4009 | TotalCreatedInstsCost -= ExtCost; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4010 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4011 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4012 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4013 | // The promotion is not profitable, rollback to the previous state. |
| 4014 | TPT.rollback(LastKnownGood); |
| 4015 | continue; |
| 4016 | } |
| 4017 | // The promotion is profitable. |
| 4018 | // Check if it exposes an ext(load). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4019 | (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4020 | if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4021 | // If we have created a new extension, i.e., now we have two |
| 4022 | // extensions. We must make sure one of them is merged with |
| 4023 | // the load, otherwise we may degrade the code quality. |
| 4024 | (LI->hasOneUse() || hasSameExtUse(LI, *TLI)))) |
| 4025 | // Promotion happened. |
| 4026 | return true; |
| 4027 | // If this does not help to expose an ext(load) then, rollback. |
| 4028 | TPT.rollback(LastKnownGood); |
| 4029 | } |
| 4030 | // None of the extension can form an ext(load). |
| 4031 | LI = nullptr; |
| 4032 | Inst = nullptr; |
| 4033 | return false; |
| 4034 | } |
| 4035 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4036 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 4037 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 4038 | /// extend into the load. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4039 | /// \p I[in/out] the extension may be modified during the process if some |
| 4040 | /// promotions apply. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4041 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4042 | bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4043 | // Try to promote a chain of computation if it allows to form |
| 4044 | // an extended load. |
| 4045 | TypePromotionTransaction TPT; |
| 4046 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4047 | TPT.getRestorationPoint(); |
| 4048 | SmallVector<Instruction *, 1> Exts; |
| 4049 | Exts.push_back(I); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4050 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4051 | LoadInst *LI = nullptr; |
| 4052 | Instruction *OldExt = I; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4053 | bool HasPromoted = extLdPromotion(TPT, LI, I, Exts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4054 | if (!LI || !I) { |
| 4055 | assert(!HasPromoted && !LI && "If we did not match any load instruction " |
| 4056 | "the code must remain the same"); |
| 4057 | I = OldExt; |
| 4058 | return false; |
| 4059 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4060 | |
| 4061 | // 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] | 4062 | // Make the cheap checks first if we did not promote. |
| 4063 | // If we promoted, we need to check if it is indeed profitable. |
| 4064 | if (!HasPromoted && LI->getParent() == I->getParent()) |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4065 | return false; |
| 4066 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4067 | EVT VT = TLI->getValueType(*DL, I->getType()); |
| 4068 | EVT LoadVT = TLI->getValueType(*DL, LI->getType()); |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 4069 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4070 | // If the load has other users and the truncate is not free, this probably |
| 4071 | // isn't worthwhile. |
Ahmed Bougacha | 55e3c2d | 2014-12-05 18:04:40 +0000 | [diff] [blame] | 4072 | if (!LI->hasOneUse() && TLI && |
| 4073 | (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4074 | !TLI->isTruncateFree(I->getType(), LI->getType())) { |
| 4075 | I = OldExt; |
| 4076 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4077 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4078 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4079 | |
| 4080 | // Check whether the target supports casts folded into loads. |
| 4081 | unsigned LType; |
| 4082 | if (isa<ZExtInst>(I)) |
| 4083 | LType = ISD::ZEXTLOAD; |
| 4084 | else { |
| 4085 | assert(isa<SExtInst>(I) && "Unexpected ext type!"); |
| 4086 | LType = ISD::SEXTLOAD; |
| 4087 | } |
Ahmed Bougacha | 2b6917b | 2015-01-08 00:51:32 +0000 | [diff] [blame] | 4088 | if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4089 | I = OldExt; |
| 4090 | TPT.rollback(LastKnownGood); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4091 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4092 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4093 | |
| 4094 | // Move the extend into the same block as the load, so that SelectionDAG |
| 4095 | // can fold it. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4096 | TPT.commit(); |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4097 | I->removeFromParent(); |
| 4098 | I->insertAfter(LI); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4099 | ++NumExtsMoved; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4100 | return true; |
| 4101 | } |
| 4102 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4103 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4104 | BasicBlock *DefBB = I->getParent(); |
| 4105 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 4106 | // 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] | 4107 | // other uses of the source with result of extension. |
| 4108 | Value *Src = I->getOperand(0); |
| 4109 | if (Src->hasOneUse()) |
| 4110 | return false; |
| 4111 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 4112 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 4113 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4114 | return false; |
| 4115 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4116 | // 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] | 4117 | // this block. |
| 4118 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4119 | return false; |
| 4120 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4121 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4122 | for (User *U : I->users()) { |
| 4123 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4124 | |
| 4125 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4126 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4127 | if (UserBB == DefBB) continue; |
| 4128 | DefIsLiveOut = true; |
| 4129 | break; |
| 4130 | } |
| 4131 | if (!DefIsLiveOut) |
| 4132 | return false; |
| 4133 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 4134 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4135 | for (User *U : Src->users()) { |
| 4136 | Instruction *UI = cast<Instruction>(U); |
| 4137 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4138 | if (UserBB == DefBB) continue; |
| 4139 | // Be conservative. We don't want this xform to end up introducing |
| 4140 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4141 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 4142 | return false; |
| 4143 | } |
| 4144 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4145 | // InsertedTruncs - Only insert one trunc in each block once. |
| 4146 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 4147 | |
| 4148 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4149 | for (Use &U : Src->uses()) { |
| 4150 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4151 | |
| 4152 | // Figure out which BB this ext is used in. |
| 4153 | BasicBlock *UserBB = User->getParent(); |
| 4154 | if (UserBB == DefBB) continue; |
| 4155 | |
| 4156 | // Both src and def are live in this block. Rewrite the use. |
| 4157 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 4158 | |
| 4159 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 4160 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4161 | assert(InsertPt != UserBB->end()); |
| 4162 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4163 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4164 | } |
| 4165 | |
| 4166 | // 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] | 4167 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4168 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4169 | MadeChange = true; |
| 4170 | } |
| 4171 | |
| 4172 | return MadeChange; |
| 4173 | } |
| 4174 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4175 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 4176 | /// that is only used once. |
| 4177 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 4178 | auto *I = dyn_cast<Instruction>(V); |
| 4179 | // If it's safe to speculatively execute, then it should not have side |
| 4180 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 4181 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 4182 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4183 | } |
| 4184 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4185 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4186 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
| 4187 | SelectInst *SI) { |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4188 | // FIXME: This should use the same heuristics as IfConversion to determine |
| 4189 | // whether a select is better represented as a branch. This requires that |
| 4190 | // branch probability metadata is preserved for the select, which is not the |
| 4191 | // case currently. |
| 4192 | |
| 4193 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 4194 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 4195 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 4196 | // comparison condition. If the compare has more than one use, there's |
| 4197 | // probably another cmov or setcc around, so it's not worth emitting a branch. |
Sanjay Patel | 5e5f0e9 | 2015-09-28 21:44:46 +0000 | [diff] [blame] | 4198 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4199 | return false; |
| 4200 | |
| 4201 | Value *CmpOp0 = Cmp->getOperand(0); |
| 4202 | Value *CmpOp1 = Cmp->getOperand(1); |
| 4203 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 4204 | // Emit "cmov on compare with a memory operand" as a branch to avoid stalls |
| 4205 | // on a load from memory. But if the load is used more than once, do not |
| 4206 | // change the select to a branch because the load is probably needed |
| 4207 | // regardless of whether the branch is taken or not. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4208 | if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) || |
| 4209 | (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse())) |
| 4210 | return true; |
| 4211 | |
| 4212 | // If either operand of the select is expensive and only needed on one side |
| 4213 | // of the select, we should form a branch. |
| 4214 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 4215 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 4216 | return true; |
| 4217 | |
| 4218 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4219 | } |
| 4220 | |
| 4221 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4222 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 4223 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4224 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4225 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 4226 | |
| 4227 | // Can we convert the 'select' to CF ? |
| 4228 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4229 | return false; |
| 4230 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4231 | TargetLowering::SelectSupportKind SelectKind; |
| 4232 | if (VectorCond) |
| 4233 | SelectKind = TargetLowering::VectorMaskSelect; |
| 4234 | else if (SI->getType()->isVectorTy()) |
| 4235 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 4236 | else |
| 4237 | SelectKind = TargetLowering::ScalarValSelect; |
| 4238 | |
| 4239 | // Do we have efficient codegen support for this kind of 'selects' ? |
| 4240 | if (TLI->isSelectSupported(SelectKind)) { |
| 4241 | // We have efficient codegen support for the select instruction. |
| 4242 | // Check if it is profitable to keep this 'select'. |
| 4243 | if (!TLI->isPredictableSelectExpensive() || |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4244 | !isFormingBranchFromSelectProfitable(TTI, SI)) |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 4245 | return false; |
| 4246 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4247 | |
| 4248 | ModifiedDT = true; |
| 4249 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4250 | // Transform a sequence like this: |
| 4251 | // start: |
| 4252 | // %cmp = cmp uge i32 %a, %b |
| 4253 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 4254 | // |
| 4255 | // Into: |
| 4256 | // start: |
| 4257 | // %cmp = cmp uge i32 %a, %b |
| 4258 | // br i1 %cmp, label %select.true, label %select.false |
| 4259 | // select.true: |
| 4260 | // br label %select.end |
| 4261 | // select.false: |
| 4262 | // br label %select.end |
| 4263 | // select.end: |
| 4264 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 4265 | // |
| 4266 | // In addition, we may sink instructions that produce %c or %d from |
| 4267 | // the entry block into the destination(s) of the new branch. |
| 4268 | // If the true or false blocks do not contain a sunken instruction, that |
| 4269 | // block and its branch may be optimized away. In that case, one side of the |
| 4270 | // first branch will point directly to select.end, and the corresponding PHI |
| 4271 | // predecessor block will be the start block. |
| 4272 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4273 | // First, we split the block containing the select into 2 blocks. |
| 4274 | BasicBlock *StartBlock = SI->getParent(); |
| 4275 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4276 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4277 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4278 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4279 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4280 | |
| 4281 | // These are the new basic blocks for the conditional branch. |
| 4282 | // At least one will become an actual new basic block. |
| 4283 | BasicBlock *TrueBlock = nullptr; |
| 4284 | BasicBlock *FalseBlock = nullptr; |
| 4285 | |
| 4286 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 4287 | // them speculatively. |
| 4288 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 4289 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 4290 | EndBlock->getParent(), EndBlock); |
| 4291 | auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
| 4292 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 4293 | TrueInst->moveBefore(TrueBranch); |
| 4294 | } |
| 4295 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 4296 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 4297 | EndBlock->getParent(), EndBlock); |
| 4298 | auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 4299 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 4300 | FalseInst->moveBefore(FalseBranch); |
| 4301 | } |
| 4302 | |
| 4303 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 4304 | // for a new input value to the PHI. |
| 4305 | if (TrueBlock == FalseBlock) { |
| 4306 | assert(TrueBlock == nullptr && |
| 4307 | "Unexpected basic block transform while optimizing select"); |
| 4308 | |
| 4309 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 4310 | EndBlock->getParent(), EndBlock); |
| 4311 | BranchInst::Create(EndBlock, FalseBlock); |
| 4312 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4313 | |
| 4314 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4315 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 4316 | // of the condition, it means that side of the branch goes to the end block |
| 4317 | // directly and the path originates from the start block from the point of |
| 4318 | // view of the new PHI. |
| 4319 | if (TrueBlock == nullptr) { |
| 4320 | BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI); |
| 4321 | TrueBlock = StartBlock; |
| 4322 | } else if (FalseBlock == nullptr) { |
| 4323 | BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI); |
| 4324 | FalseBlock = StartBlock; |
| 4325 | } else { |
| 4326 | BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI); |
| 4327 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4328 | |
| 4329 | // The select itself is replaced with a PHI Node. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4330 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4331 | PN->takeName(SI); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 4332 | PN->addIncoming(SI->getTrueValue(), TrueBlock); |
| 4333 | PN->addIncoming(SI->getFalseValue(), FalseBlock); |
| 4334 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4335 | SI->replaceAllUsesWith(PN); |
| 4336 | SI->eraseFromParent(); |
| 4337 | |
| 4338 | // Instruct OptimizeBlock to skip to the next block. |
| 4339 | CurInstIterator = StartBlock->end(); |
| 4340 | ++NumSelectsExpanded; |
| 4341 | return true; |
| 4342 | } |
| 4343 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 4344 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4345 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 4346 | int SplatElem = -1; |
| 4347 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 4348 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 4349 | return false; |
| 4350 | SplatElem = Mask[i]; |
| 4351 | } |
| 4352 | |
| 4353 | return true; |
| 4354 | } |
| 4355 | |
| 4356 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 4357 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 4358 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 4359 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4360 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4361 | BasicBlock *DefBB = SVI->getParent(); |
| 4362 | |
| 4363 | // Only do this xform if variable vector shifts are particularly expensive. |
| 4364 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 4365 | return false; |
| 4366 | |
| 4367 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 4368 | // constant splat. |
| 4369 | if (!isBroadcastShuffle(SVI)) |
| 4370 | return false; |
| 4371 | |
| 4372 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 4373 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 4374 | |
| 4375 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4376 | for (User *U : SVI->users()) { |
| 4377 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4378 | |
| 4379 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4380 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4381 | if (UserBB == DefBB) continue; |
| 4382 | |
| 4383 | // 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] | 4384 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4385 | |
| 4386 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 4387 | // already have a copy. |
| 4388 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 4389 | |
| 4390 | if (!InsertedShuffle) { |
| 4391 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4392 | assert(InsertPt != UserBB->end()); |
| 4393 | InsertedShuffle = |
| 4394 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 4395 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4396 | } |
| 4397 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4398 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4399 | MadeChange = true; |
| 4400 | } |
| 4401 | |
| 4402 | // If we removed all uses, nuke the shuffle. |
| 4403 | if (SVI->use_empty()) { |
| 4404 | SVI->eraseFromParent(); |
| 4405 | MadeChange = true; |
| 4406 | } |
| 4407 | |
| 4408 | return MadeChange; |
| 4409 | } |
| 4410 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 4411 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 4412 | if (!TLI || !DL) |
| 4413 | return false; |
| 4414 | |
| 4415 | Value *Cond = SI->getCondition(); |
| 4416 | Type *OldType = Cond->getType(); |
| 4417 | LLVMContext &Context = Cond->getContext(); |
| 4418 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 4419 | unsigned RegWidth = RegType.getSizeInBits(); |
| 4420 | |
| 4421 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 4422 | return false; |
| 4423 | |
| 4424 | // If the register width is greater than the type width, expand the condition |
| 4425 | // of the switch instruction and each case constant to the width of the |
| 4426 | // register. By widening the type of the switch condition, subsequent |
| 4427 | // comparisons (for case comparisons) will not need to be extended to the |
| 4428 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 4429 | // where N is the number of cases in the switch. |
| 4430 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 4431 | |
| 4432 | // Zero-extend the switch condition and case constants unless the switch |
| 4433 | // condition is a function argument that is already being sign-extended. |
| 4434 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 4435 | // everything instead. |
| 4436 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 4437 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 4438 | if (Arg->hasSExtAttr()) |
| 4439 | ExtType = Instruction::SExt; |
| 4440 | |
| 4441 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 4442 | ExtInst->insertBefore(SI); |
| 4443 | SI->setCondition(ExtInst); |
| 4444 | for (SwitchInst::CaseIt Case : SI->cases()) { |
| 4445 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 4446 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 4447 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 4448 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 4449 | } |
| 4450 | |
| 4451 | return true; |
| 4452 | } |
| 4453 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4454 | namespace { |
| 4455 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 4456 | /// This class is used to move downward extractelement transition. |
| 4457 | /// E.g., |
| 4458 | /// a = vector_op <2 x i32> |
| 4459 | /// b = extractelement <2 x i32> a, i32 0 |
| 4460 | /// c = scalar_op b |
| 4461 | /// store c |
| 4462 | /// |
| 4463 | /// => |
| 4464 | /// a = vector_op <2 x i32> |
| 4465 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 4466 | /// * d = extractelement <2 x i32> c, i32 0 |
| 4467 | /// * store d |
| 4468 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 4469 | /// transition. |
| 4470 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4471 | /// DataLayout associated with the current module. |
| 4472 | const DataLayout &DL; |
| 4473 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4474 | /// Used to perform some checks on the legality of vector operations. |
| 4475 | const TargetLowering &TLI; |
| 4476 | |
| 4477 | /// Used to estimated the cost of the promoted chain. |
| 4478 | const TargetTransformInfo &TTI; |
| 4479 | |
| 4480 | /// The transition being moved downwards. |
| 4481 | Instruction *Transition; |
| 4482 | /// The sequence of instructions to be promoted. |
| 4483 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 4484 | /// Cost of combining a store and an extract. |
| 4485 | unsigned StoreExtractCombineCost; |
| 4486 | /// Instruction that will be combined with the transition. |
| 4487 | Instruction *CombineInst; |
| 4488 | |
| 4489 | /// \brief The instruction that represents the current end of the transition. |
| 4490 | /// Since we are faking the promotion until we reach the end of the chain |
| 4491 | /// of computation, we need a way to get the current end of the transition. |
| 4492 | Instruction *getEndOfTransition() const { |
| 4493 | if (InstsToBePromoted.empty()) |
| 4494 | return Transition; |
| 4495 | return InstsToBePromoted.back(); |
| 4496 | } |
| 4497 | |
| 4498 | /// \brief Return the index of the original value in the transition. |
| 4499 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 4500 | /// c, is at index 0. |
| 4501 | unsigned getTransitionOriginalValueIdx() const { |
| 4502 | assert(isa<ExtractElementInst>(Transition) && |
| 4503 | "Other kind of transitions are not supported yet"); |
| 4504 | return 0; |
| 4505 | } |
| 4506 | |
| 4507 | /// \brief Return the index of the index in the transition. |
| 4508 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 4509 | /// is at index 1. |
| 4510 | unsigned getTransitionIdx() const { |
| 4511 | assert(isa<ExtractElementInst>(Transition) && |
| 4512 | "Other kind of transitions are not supported yet"); |
| 4513 | return 1; |
| 4514 | } |
| 4515 | |
| 4516 | /// \brief Get the type of the transition. |
| 4517 | /// This is the type of the original value. |
| 4518 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 4519 | /// transition is <2 x i32>. |
| 4520 | Type *getTransitionType() const { |
| 4521 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 4522 | } |
| 4523 | |
| 4524 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 4525 | /// I.e., we have the following sequence: |
| 4526 | /// Def = Transition <ty1> a to <ty2> |
| 4527 | /// b = ToBePromoted <ty2> Def, ... |
| 4528 | /// => |
| 4529 | /// b = ToBePromoted <ty1> a, ... |
| 4530 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 4531 | void promoteImpl(Instruction *ToBePromoted); |
| 4532 | |
| 4533 | /// \brief Check whether or not it is profitable to promote all the |
| 4534 | /// instructions enqueued to be promoted. |
| 4535 | bool isProfitableToPromote() { |
| 4536 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 4537 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 4538 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 4539 | : -1; |
| 4540 | Type *PromotedType = getTransitionType(); |
| 4541 | |
| 4542 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 4543 | unsigned AS = ST->getPointerAddressSpace(); |
| 4544 | unsigned Align = ST->getAlignment(); |
| 4545 | // Check if this store is supported. |
| 4546 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4547 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 4548 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4549 | // If this is not supported, there is no way we can combine |
| 4550 | // the extract with the store. |
| 4551 | return false; |
| 4552 | } |
| 4553 | |
| 4554 | // The scalar chain of computation has to pay for the transition |
| 4555 | // scalar to vector. |
| 4556 | // The vector chain has to account for the combining cost. |
| 4557 | uint64_t ScalarCost = |
| 4558 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 4559 | uint64_t VectorCost = StoreExtractCombineCost; |
| 4560 | for (const auto &Inst : InstsToBePromoted) { |
| 4561 | // Compute the cost. |
| 4562 | // By construction, all instructions being promoted are arithmetic ones. |
| 4563 | // Moreover, one argument is a constant that can be viewed as a splat |
| 4564 | // constant. |
| 4565 | Value *Arg0 = Inst->getOperand(0); |
| 4566 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 4567 | isa<ConstantFP>(Arg0); |
| 4568 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 4569 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 4570 | : TargetTransformInfo::OK_AnyValue; |
| 4571 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 4572 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 4573 | : TargetTransformInfo::OK_AnyValue; |
| 4574 | ScalarCost += TTI.getArithmeticInstrCost( |
| 4575 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 4576 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 4577 | Arg0OVK, Arg1OVK); |
| 4578 | } |
| 4579 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 4580 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 4581 | return ScalarCost > VectorCost; |
| 4582 | } |
| 4583 | |
| 4584 | /// \brief Generate a constant vector with \p Val with the same |
| 4585 | /// number of elements as the transition. |
| 4586 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 4587 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4588 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 4589 | /// otherwise we generate a vector with as many undef as possible: |
| 4590 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 4591 | /// used at the index of the extract. |
| 4592 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 4593 | unsigned ExtractIdx = UINT_MAX; |
| 4594 | if (!UseSplat) { |
| 4595 | // If we cannot determine where the constant must be, we have to |
| 4596 | // use a splat constant. |
| 4597 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 4598 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 4599 | ExtractIdx = CstVal->getSExtValue(); |
| 4600 | else |
| 4601 | UseSplat = true; |
| 4602 | } |
| 4603 | |
| 4604 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 4605 | if (UseSplat) |
| 4606 | return ConstantVector::getSplat(End, Val); |
| 4607 | |
| 4608 | SmallVector<Constant *, 4> ConstVec; |
| 4609 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 4610 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 4611 | if (Idx == ExtractIdx) |
| 4612 | ConstVec.push_back(Val); |
| 4613 | else |
| 4614 | ConstVec.push_back(UndefVal); |
| 4615 | } |
| 4616 | return ConstantVector::get(ConstVec); |
| 4617 | } |
| 4618 | |
| 4619 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 4620 | /// in \p Use can trigger undefined behavior. |
| 4621 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 4622 | unsigned OperandIdx) { |
| 4623 | // This is not safe to introduce undef when the operand is on |
| 4624 | // the right hand side of a division-like instruction. |
| 4625 | if (OperandIdx != 1) |
| 4626 | return false; |
| 4627 | switch (Use->getOpcode()) { |
| 4628 | default: |
| 4629 | return false; |
| 4630 | case Instruction::SDiv: |
| 4631 | case Instruction::UDiv: |
| 4632 | case Instruction::SRem: |
| 4633 | case Instruction::URem: |
| 4634 | return true; |
| 4635 | case Instruction::FDiv: |
| 4636 | case Instruction::FRem: |
| 4637 | return !Use->hasNoNaNs(); |
| 4638 | } |
| 4639 | llvm_unreachable(nullptr); |
| 4640 | } |
| 4641 | |
| 4642 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4643 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 4644 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 4645 | unsigned CombineCost) |
| 4646 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4647 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 4648 | assert(Transition && "Do not know how to promote null"); |
| 4649 | } |
| 4650 | |
| 4651 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 4652 | bool canPromote(const Instruction *ToBePromoted) const { |
| 4653 | // We could support CastInst too. |
| 4654 | return isa<BinaryOperator>(ToBePromoted); |
| 4655 | } |
| 4656 | |
| 4657 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 4658 | /// by moving downward the transition through. |
| 4659 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 4660 | // Promote only if all the operands can be statically expanded. |
| 4661 | // Indeed, we do not want to introduce any new kind of transitions. |
| 4662 | for (const Use &U : ToBePromoted->operands()) { |
| 4663 | const Value *Val = U.get(); |
| 4664 | if (Val == getEndOfTransition()) { |
| 4665 | // If the use is a division and the transition is on the rhs, |
| 4666 | // we cannot promote the operation, otherwise we may create a |
| 4667 | // division by zero. |
| 4668 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 4669 | return false; |
| 4670 | continue; |
| 4671 | } |
| 4672 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 4673 | !isa<ConstantFP>(Val)) |
| 4674 | return false; |
| 4675 | } |
| 4676 | // Check that the resulting operation is legal. |
| 4677 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 4678 | if (!ISDOpcode) |
| 4679 | return false; |
| 4680 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 4681 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4682 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4683 | } |
| 4684 | |
| 4685 | /// \brief Check whether or not \p Use can be combined |
| 4686 | /// with the transition. |
| 4687 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 4688 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 4689 | |
| 4690 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 4691 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 4692 | InstsToBePromoted.push_back(ToBePromoted); |
| 4693 | } |
| 4694 | |
| 4695 | /// \brief Set the instruction that will be combined with the transition. |
| 4696 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 4697 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 4698 | CombineInst = ToBeCombined; |
| 4699 | } |
| 4700 | |
| 4701 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 4702 | /// is profitable. |
| 4703 | /// \return True if the promotion happened, false otherwise. |
| 4704 | bool promote() { |
| 4705 | // Check if there is something to promote. |
| 4706 | // Right now, if we do not have anything to combine with, |
| 4707 | // we assume the promotion is not profitable. |
| 4708 | if (InstsToBePromoted.empty() || !CombineInst) |
| 4709 | return false; |
| 4710 | |
| 4711 | // Check cost. |
| 4712 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 4713 | return false; |
| 4714 | |
| 4715 | // Promote. |
| 4716 | for (auto &ToBePromoted : InstsToBePromoted) |
| 4717 | promoteImpl(ToBePromoted); |
| 4718 | InstsToBePromoted.clear(); |
| 4719 | return true; |
| 4720 | } |
| 4721 | }; |
| 4722 | } // End of anonymous namespace. |
| 4723 | |
| 4724 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 4725 | // At this point, we know that all the operands of ToBePromoted but Def |
| 4726 | // can be statically promoted. |
| 4727 | // For Def, we need to use its parameter in ToBePromoted: |
| 4728 | // b = ToBePromoted ty1 a |
| 4729 | // Def = Transition ty1 b to ty2 |
| 4730 | // Move the transition down. |
| 4731 | // 1. Replace all uses of the promoted operation by the transition. |
| 4732 | // = ... b => = ... Def. |
| 4733 | assert(ToBePromoted->getType() == Transition->getType() && |
| 4734 | "The type of the result of the transition does not match " |
| 4735 | "the final type"); |
| 4736 | ToBePromoted->replaceAllUsesWith(Transition); |
| 4737 | // 2. Update the type of the uses. |
| 4738 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 4739 | Type *TransitionTy = getTransitionType(); |
| 4740 | ToBePromoted->mutateType(TransitionTy); |
| 4741 | // 3. Update all the operands of the promoted operation with promoted |
| 4742 | // operands. |
| 4743 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 4744 | for (Use &U : ToBePromoted->operands()) { |
| 4745 | Value *Val = U.get(); |
| 4746 | Value *NewVal = nullptr; |
| 4747 | if (Val == Transition) |
| 4748 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 4749 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 4750 | isa<ConstantFP>(Val)) { |
| 4751 | // Use a splat constant if it is not safe to use undef. |
| 4752 | NewVal = getConstantVector( |
| 4753 | cast<Constant>(Val), |
| 4754 | isa<UndefValue>(Val) || |
| 4755 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 4756 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 4757 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 4758 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4759 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 4760 | } |
| 4761 | Transition->removeFromParent(); |
| 4762 | Transition->insertAfter(ToBePromoted); |
| 4763 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 4764 | } |
| 4765 | |
| 4766 | /// Some targets can do store(extractelement) with one instruction. |
| 4767 | /// Try to push the extractelement towards the stores when the target |
| 4768 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4769 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4770 | unsigned CombineCost = UINT_MAX; |
| 4771 | if (DisableStoreExtract || !TLI || |
| 4772 | (!StressStoreExtract && |
| 4773 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 4774 | Inst->getOperand(1), CombineCost))) |
| 4775 | return false; |
| 4776 | |
| 4777 | // At this point we know that Inst is a vector to scalar transition. |
| 4778 | // Try to move it down the def-use chain, until: |
| 4779 | // - We can combine the transition with its single use |
| 4780 | // => we got rid of the transition. |
| 4781 | // - We escape the current basic block |
| 4782 | // => we would need to check that we are moving it at a cheaper place and |
| 4783 | // we do not do that for now. |
| 4784 | BasicBlock *Parent = Inst->getParent(); |
| 4785 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4786 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4787 | // If the transition has more than one use, assume this is not going to be |
| 4788 | // beneficial. |
| 4789 | while (Inst->hasOneUse()) { |
| 4790 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 4791 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 4792 | |
| 4793 | if (ToBePromoted->getParent() != Parent) { |
| 4794 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 4795 | << ToBePromoted->getParent()->getName() |
| 4796 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 4797 | return false; |
| 4798 | } |
| 4799 | |
| 4800 | if (VPH.canCombine(ToBePromoted)) { |
| 4801 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 4802 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 4803 | VPH.recordCombineInstruction(ToBePromoted); |
| 4804 | bool Changed = VPH.promote(); |
| 4805 | NumStoreExtractExposed += Changed; |
| 4806 | return Changed; |
| 4807 | } |
| 4808 | |
| 4809 | DEBUG(dbgs() << "Try promoting.\n"); |
| 4810 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 4811 | return false; |
| 4812 | |
| 4813 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 4814 | |
| 4815 | VPH.enqueueForPromotion(ToBePromoted); |
| 4816 | Inst = ToBePromoted; |
| 4817 | } |
| 4818 | return false; |
| 4819 | } |
| 4820 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4821 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4822 | // Bail out if we inserted the instruction to prevent optimizations from |
| 4823 | // stepping on each other's toes. |
| 4824 | if (InsertedInsts.count(I)) |
| 4825 | return false; |
| 4826 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4827 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 4828 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 4829 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 4830 | // trivial PHI, go ahead and zap it here. |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4831 | if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4832 | P->replaceAllUsesWith(V); |
| 4833 | P->eraseFromParent(); |
| 4834 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4835 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4836 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4837 | return false; |
| 4838 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4839 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4840 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4841 | // If the source of the cast is a constant, then this should have |
| 4842 | // already been constant folded. The only reason NOT to constant fold |
| 4843 | // it is if something (e.g. LSR) was careful to place the constant |
| 4844 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 4845 | // the address of globals out of a loop). If this is the case, we don't |
| 4846 | // want to forward-subst the cast. |
| 4847 | if (isa<Constant>(CI->getOperand(0))) |
| 4848 | return false; |
| 4849 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4850 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4851 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4852 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4853 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 4854 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 4855 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4856 | if (TLI && |
| 4857 | TLI->getTypeAction(CI->getContext(), |
| 4858 | TLI->getValueType(*DL, CI->getType())) == |
| 4859 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 4860 | return SinkCast(CI); |
| 4861 | } else { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4862 | bool MadeChange = moveExtToFormExtLoad(I); |
| 4863 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 4864 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4865 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4866 | return false; |
| 4867 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4868 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4869 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 4870 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
| 4871 | return OptimizeCmpExpression(CI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4872 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4873 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 4874 | stripInvariantGroupMetadata(*LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4875 | if (TLI) { |
| 4876 | unsigned AS = LI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4877 | return optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4878 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 4879 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4880 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4881 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4882 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 4883 | stripInvariantGroupMetadata(*SI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4884 | if (TLI) { |
| 4885 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4886 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4887 | SI->getOperand(0)->getType(), AS); |
| 4888 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4889 | return false; |
| 4890 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4891 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 4892 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 4893 | |
| 4894 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 4895 | BinOp->getOpcode() == Instruction::LShr)) { |
| 4896 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 4897 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4898 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 4899 | |
| 4900 | return false; |
| 4901 | } |
| 4902 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4903 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 4904 | if (GEPI->hasAllZeroIndices()) { |
| 4905 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 4906 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 4907 | GEPI->getName(), GEPI); |
| 4908 | GEPI->replaceAllUsesWith(NC); |
| 4909 | GEPI->eraseFromParent(); |
| 4910 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4911 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4912 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 4913 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4914 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4915 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4916 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4917 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4918 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4919 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4920 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4921 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 4922 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4923 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4924 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 4925 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 4926 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 4927 | return optimizeSwitchInst(Switch); |
| 4928 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4929 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4930 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 4931 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 4932 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 4933 | } |
| 4934 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 4935 | // In this pass we look for GEP and cast instructions that are used |
| 4936 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 4937 | // selection. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4938 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 4939 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 4940 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4941 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4942 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 4943 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4944 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 4945 | if (ModifiedDT) |
| 4946 | return true; |
| 4947 | } |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4948 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 4949 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 4950 | return MadeChange; |
| 4951 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4952 | |
| 4953 | // 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] | 4954 | // 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] | 4955 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4956 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4957 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 4958 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4959 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 4960 | for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4961 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4962 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 4963 | // Leave dbg.values that refer to an alloca alone. These |
| 4964 | // instrinsics describe the address of a variable (= the alloca) |
| 4965 | // being taken. They should not be moved next to the alloca |
| 4966 | // (and to the beginning of the scope), but rather stay close to |
| 4967 | // where said address is used. |
| 4968 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4969 | PrevNonDbgInst = Insn; |
| 4970 | continue; |
| 4971 | } |
| 4972 | |
| 4973 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 4974 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
| 4975 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 4976 | DVI->removeFromParent(); |
| 4977 | if (isa<PHINode>(VI)) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4978 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 4979 | else |
| 4980 | DVI->insertAfter(VI); |
| 4981 | MadeChange = true; |
| 4982 | ++NumDbgValueMoved; |
| 4983 | } |
| 4984 | } |
| 4985 | } |
| 4986 | return MadeChange; |
| 4987 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 4988 | |
| 4989 | // If there is a sequence that branches based on comparing a single bit |
| 4990 | // against zero that can be combined into a single instruction, and the |
| 4991 | // target supports folding these into a single instruction, sink the |
| 4992 | // mask and compare into the branch uses. Do this before OptimizeBlock -> |
| 4993 | // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being |
| 4994 | // searched for. |
| 4995 | bool CodeGenPrepare::sinkAndCmp(Function &F) { |
| 4996 | if (!EnableAndCmpSinking) |
| 4997 | return false; |
| 4998 | if (!TLI || !TLI->isMaskAndBranchFoldingLegal()) |
| 4999 | return false; |
| 5000 | bool MadeChange = false; |
| 5001 | for (Function::iterator I = F.begin(), E = F.end(); I != E; ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5002 | BasicBlock *BB = &*I++; |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 5003 | |
| 5004 | // Does this BB end with the following? |
| 5005 | // %andVal = and %val, #single-bit-set |
| 5006 | // %icmpVal = icmp %andResult, 0 |
| 5007 | // br i1 %cmpVal label %dest1, label %dest2" |
| 5008 | BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator()); |
| 5009 | if (!Brcc || !Brcc->isConditional()) |
| 5010 | continue; |
| 5011 | ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0)); |
| 5012 | if (!Cmp || Cmp->getParent() != BB) |
| 5013 | continue; |
| 5014 | ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1)); |
| 5015 | if (!Zero || !Zero->isZero()) |
| 5016 | continue; |
| 5017 | Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0)); |
| 5018 | if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB) |
| 5019 | continue; |
| 5020 | ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1)); |
| 5021 | if (!Mask || !Mask->getUniqueInteger().isPowerOf2()) |
| 5022 | continue; |
| 5023 | DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump()); |
| 5024 | |
| 5025 | // Push the "and; icmp" for any users that are conditional branches. |
| 5026 | // Since there can only be one branch use per BB, we don't need to keep |
| 5027 | // track of which BBs we insert into. |
| 5028 | for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end(); |
| 5029 | UI != E; ) { |
| 5030 | Use &TheUse = *UI; |
| 5031 | // Find brcc use. |
| 5032 | BranchInst *BrccUser = dyn_cast<BranchInst>(*UI); |
| 5033 | ++UI; |
| 5034 | if (!BrccUser || !BrccUser->isConditional()) |
| 5035 | continue; |
| 5036 | BasicBlock *UserBB = BrccUser->getParent(); |
| 5037 | if (UserBB == BB) continue; |
| 5038 | DEBUG(dbgs() << "found Brcc use\n"); |
| 5039 | |
| 5040 | // Sink the "and; icmp" to use. |
| 5041 | MadeChange = true; |
| 5042 | BinaryOperator *NewAnd = |
| 5043 | BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "", |
| 5044 | BrccUser); |
| 5045 | CmpInst *NewCmp = |
| 5046 | CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero, |
| 5047 | "", BrccUser); |
| 5048 | TheUse = NewCmp; |
| 5049 | ++NumAndCmpsMoved; |
| 5050 | DEBUG(BrccUser->getParent()->dump()); |
| 5051 | } |
| 5052 | } |
| 5053 | return MadeChange; |
| 5054 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5055 | |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 5056 | /// \brief Retrieve the probabilities of a conditional branch. Returns true on |
| 5057 | /// success, or returns false if no or invalid metadata was found. |
| 5058 | static bool extractBranchMetadata(BranchInst *BI, |
| 5059 | uint64_t &ProbTrue, uint64_t &ProbFalse) { |
| 5060 | assert(BI->isConditional() && |
| 5061 | "Looking for probabilities on unconditional branch?"); |
| 5062 | auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof); |
| 5063 | if (!ProfileData || ProfileData->getNumOperands() != 3) |
| 5064 | return false; |
| 5065 | |
Duncan P. N. Exon Smith | 5bf8fef | 2014-12-09 18:38:53 +0000 | [diff] [blame] | 5066 | const auto *CITrue = |
| 5067 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1)); |
| 5068 | const auto *CIFalse = |
| 5069 | mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2)); |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 5070 | if (!CITrue || !CIFalse) |
| 5071 | return false; |
| 5072 | |
| 5073 | ProbTrue = CITrue->getValue().getZExtValue(); |
| 5074 | ProbFalse = CIFalse->getValue().getZExtValue(); |
| 5075 | |
| 5076 | return true; |
| 5077 | } |
| 5078 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5079 | /// \brief Scale down both weights to fit into uint32_t. |
| 5080 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 5081 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 5082 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 5083 | NewTrue = NewTrue / Scale; |
| 5084 | NewFalse = NewFalse / Scale; |
| 5085 | } |
| 5086 | |
| 5087 | /// \brief Some targets prefer to split a conditional branch like: |
| 5088 | /// \code |
| 5089 | /// %0 = icmp ne i32 %a, 0 |
| 5090 | /// %1 = icmp ne i32 %b, 0 |
| 5091 | /// %or.cond = or i1 %0, %1 |
| 5092 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 5093 | /// \endcode |
| 5094 | /// into multiple branch instructions like: |
| 5095 | /// \code |
| 5096 | /// bb1: |
| 5097 | /// %0 = icmp ne i32 %a, 0 |
| 5098 | /// br i1 %0, label %TrueBB, label %bb2 |
| 5099 | /// bb2: |
| 5100 | /// %1 = icmp ne i32 %b, 0 |
| 5101 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 5102 | /// \endcode |
| 5103 | /// This usually allows instruction selection to do even further optimizations |
| 5104 | /// and combine the compare with the branch instruction. Currently this is |
| 5105 | /// applied for targets which have "cheap" jump instructions. |
| 5106 | /// |
| 5107 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 5108 | /// |
| 5109 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 5110 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5111 | return false; |
| 5112 | |
| 5113 | bool MadeChange = false; |
| 5114 | for (auto &BB : F) { |
| 5115 | // Does this BB end with the following? |
| 5116 | // %cond1 = icmp|fcmp|binary instruction ... |
| 5117 | // %cond2 = icmp|fcmp|binary instruction ... |
| 5118 | // %cond.or = or|and i1 %cond1, cond2 |
| 5119 | // br i1 %cond.or label %dest1, label %dest2" |
| 5120 | BinaryOperator *LogicOp; |
| 5121 | BasicBlock *TBB, *FBB; |
| 5122 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 5123 | continue; |
| 5124 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 5125 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 5126 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 5127 | continue; |
| 5128 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5129 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5130 | Value *Cond1, *Cond2; |
| 5131 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 5132 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5133 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5134 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 5135 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5136 | Opc = Instruction::Or; |
| 5137 | else |
| 5138 | continue; |
| 5139 | |
| 5140 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 5141 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 5142 | continue; |
| 5143 | |
| 5144 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 5145 | |
| 5146 | // Create a new BB. |
| 5147 | auto *InsertBefore = std::next(Function::iterator(BB)) |
| 5148 | .getNodePtrUnchecked(); |
| 5149 | auto TmpBB = BasicBlock::Create(BB.getContext(), |
| 5150 | BB.getName() + ".cond.split", |
| 5151 | BB.getParent(), InsertBefore); |
| 5152 | |
| 5153 | // Update original basic block by using the first condition directly by the |
| 5154 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5155 | Br1->setCondition(Cond1); |
| 5156 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5157 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5158 | // Depending on the conditon we have to either replace the true or the false |
| 5159 | // successor of the original branch instruction. |
| 5160 | if (Opc == Instruction::And) |
| 5161 | Br1->setSuccessor(0, TmpBB); |
| 5162 | else |
| 5163 | Br1->setSuccessor(1, TmpBB); |
| 5164 | |
| 5165 | // Fill in the new basic block. |
| 5166 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 5167 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 5168 | I->removeFromParent(); |
| 5169 | I->insertBefore(Br2); |
| 5170 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5171 | |
| 5172 | // Update PHI nodes in both successors. The original BB needs to be |
| 5173 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 5174 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 5175 | // incoming edge to the PHI nodes, because both branch instructions target |
| 5176 | // now the same successor. Depending on the original branch condition |
| 5177 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
| 5178 | // we perfrom the correct update for the PHI nodes. |
| 5179 | // This doesn't change the successor order of the just created branch |
| 5180 | // instruction (or any other instruction). |
| 5181 | if (Opc == Instruction::Or) |
| 5182 | std::swap(TBB, FBB); |
| 5183 | |
| 5184 | // Replace the old BB with the new BB. |
| 5185 | for (auto &I : *TBB) { |
| 5186 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 5187 | if (!PN) |
| 5188 | break; |
| 5189 | int i; |
| 5190 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 5191 | PN->setIncomingBlock(i, TmpBB); |
| 5192 | } |
| 5193 | |
| 5194 | // Add another incoming edge form the new BB. |
| 5195 | for (auto &I : *FBB) { |
| 5196 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 5197 | if (!PN) |
| 5198 | break; |
| 5199 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 5200 | PN->addIncoming(Val, TmpBB); |
| 5201 | } |
| 5202 | |
| 5203 | // Update the branch weights (from SelectionDAGBuilder:: |
| 5204 | // FindMergedConditions). |
| 5205 | if (Opc == Instruction::Or) { |
| 5206 | // Codegen X | Y as: |
| 5207 | // BB1: |
| 5208 | // jmp_if_X TBB |
| 5209 | // jmp TmpBB |
| 5210 | // TmpBB: |
| 5211 | // jmp_if_Y TBB |
| 5212 | // jmp FBB |
| 5213 | // |
| 5214 | |
| 5215 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 5216 | // The requirement is that |
| 5217 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 5218 | // = TrueProb for orignal BB. |
| 5219 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 5220 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 5221 | // assumes that |
| 5222 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 5223 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 5224 | // TmpBB, but the math is more complicated. |
| 5225 | uint64_t TrueWeight, FalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 5226 | if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5227 | uint64_t NewTrueWeight = TrueWeight; |
| 5228 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 5229 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5230 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 5231 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5232 | |
| 5233 | NewTrueWeight = TrueWeight; |
| 5234 | NewFalseWeight = 2 * FalseWeight; |
| 5235 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5236 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 5237 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5238 | } |
| 5239 | } else { |
| 5240 | // Codegen X & Y as: |
| 5241 | // BB1: |
| 5242 | // jmp_if_X TmpBB |
| 5243 | // jmp FBB |
| 5244 | // TmpBB: |
| 5245 | // jmp_if_Y TBB |
| 5246 | // jmp FBB |
| 5247 | // |
| 5248 | // This requires creation of TmpBB after CurBB. |
| 5249 | |
| 5250 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 5251 | // The requirement is that |
| 5252 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 5253 | // = FalseProb for orignal BB. |
| 5254 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 5255 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 5256 | // assumes that |
| 5257 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 5258 | uint64_t TrueWeight, FalseWeight; |
Juergen Ributzka | 194350a | 2014-12-09 17:32:12 +0000 | [diff] [blame] | 5259 | if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5260 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 5261 | uint64_t NewFalseWeight = FalseWeight; |
| 5262 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5263 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 5264 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5265 | |
| 5266 | NewTrueWeight = 2 * TrueWeight; |
| 5267 | NewFalseWeight = FalseWeight; |
| 5268 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 5269 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 5270 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 5271 | } |
| 5272 | } |
| 5273 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5274 | // Note: No point in getting fancy here, since the DT info is never |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 5275 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 5276 | ModifiedDT = true; |
| 5277 | |
| 5278 | MadeChange = true; |
| 5279 | |
| 5280 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 5281 | TmpBB->dump()); |
| 5282 | } |
| 5283 | return MadeChange; |
| 5284 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5285 | |
| 5286 | void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) { |
Piotr Padlewski | ea09288 | 2015-09-17 20:25:07 +0000 | [diff] [blame] | 5287 | if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group)) |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 5288 | I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID()); |
| 5289 | } |