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" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/SetVector.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/SmallSet.h" |
| 20 | #include "llvm/ADT/Statistic.h" |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 22 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/CFG.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/InstructionSimplify.h" |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/LoopInfo.h" |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/ProfileSummaryInfo.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/TargetTransformInfo.h" |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/ValueTracking.h" |
Petar Jovanovic | 644b8c1 | 2016-04-13 12:25:25 +0000 | [diff] [blame] | 30 | #include "llvm/Analysis/MemoryBuiltins.h" |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 31 | #include "llvm/CodeGen/Analysis.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 32 | #include "llvm/IR/CallSite.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 33 | #include "llvm/IR/Constants.h" |
| 34 | #include "llvm/IR/DataLayout.h" |
| 35 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 36 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 37 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 38 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 39 | #include "llvm/IR/IRBuilder.h" |
| 40 | #include "llvm/IR/InlineAsm.h" |
| 41 | #include "llvm/IR/Instructions.h" |
| 42 | #include "llvm/IR/IntrinsicInst.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 43 | #include "llvm/IR/MDBuilder.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 44 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 45 | #include "llvm/IR/Statepoint.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 46 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 47 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 48 | #include "llvm/Pass.h" |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 49 | #include "llvm/Support/BranchProbability.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 50 | #include "llvm/Support/CommandLine.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 51 | #include "llvm/Support/Debug.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 52 | #include "llvm/Support/raw_ostream.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 53 | #include "llvm/Target/TargetLowering.h" |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 54 | #include "llvm/Target/TargetSubtargetInfo.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 55 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
| 56 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 57 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 58 | #include "llvm/Transforms/Utils/Cloning.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 59 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 60 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 61 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 62 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 63 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 64 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 65 | #define DEBUG_TYPE "codegenprepare" |
| 66 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 67 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 68 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 69 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 70 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 71 | "sunken Cmps"); |
| 72 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 73 | "of sunken Casts"); |
| 74 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 75 | "computations were sunk"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 76 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 77 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 78 | STATISTIC(NumAndsAdded, |
| 79 | "Number of and mask instructions added to form ext loads"); |
| 80 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 81 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 82 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 83 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 84 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 85 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 86 | static cl::opt<bool> DisableBranchOpts( |
| 87 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 88 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 89 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 90 | static cl::opt<bool> |
| 91 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 92 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 93 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 94 | static cl::opt<bool> DisableSelectToBranch( |
| 95 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 96 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 97 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 98 | static cl::opt<bool> AddrSinkUsingGEPs( |
Eli Friedman | 5fba1e5 | 2017-04-06 22:42:18 +0000 | [diff] [blame^] | 99 | "addr-sink-using-gep", cl::Hidden, cl::init(true), |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 100 | cl::desc("Address sinking in CGP using GEPs.")); |
| 101 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 102 | static cl::opt<bool> EnableAndCmpSinking( |
| 103 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 104 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 105 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 106 | static cl::opt<bool> DisableStoreExtract( |
| 107 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 108 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 109 | |
| 110 | static cl::opt<bool> StressStoreExtract( |
| 111 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 112 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 113 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 114 | static cl::opt<bool> DisableExtLdPromotion( |
| 115 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 116 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 117 | "CodeGenPrepare")); |
| 118 | |
| 119 | static cl::opt<bool> StressExtLdPromotion( |
| 120 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 121 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 122 | "optimization in CodeGenPrepare")); |
| 123 | |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 124 | static cl::opt<bool> DisablePreheaderProtect( |
| 125 | "disable-preheader-prot", cl::Hidden, cl::init(false), |
| 126 | cl::desc("Disable protection against removing loop preheaders")); |
| 127 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 128 | static cl::opt<bool> ProfileGuidedSectionPrefix( |
| 129 | "profile-guided-section-prefix", cl::Hidden, cl::init(true), |
| 130 | cl::desc("Use profile info to add section prefix for hot/cold functions")); |
| 131 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 132 | static cl::opt<unsigned> FreqRatioToSkipMerge( |
| 133 | "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), |
| 134 | cl::desc("Skip merging empty blocks if (frequency of empty block) / " |
| 135 | "(frequency of destination block) is greater than this ratio")); |
| 136 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 137 | static cl::opt<bool> ForceSplitStore( |
| 138 | "force-split-store", cl::Hidden, cl::init(false), |
| 139 | cl::desc("Force store splitting no matter what the target query says.")); |
| 140 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 141 | static cl::opt<bool> |
| 142 | EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, |
| 143 | cl::desc("Enable merging of redundant sexts when one is dominating" |
| 144 | " the other."), cl::init(true)); |
| 145 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 146 | namespace { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 147 | typedef SmallPtrSet<Instruction *, 16> SetOfInstrs; |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 148 | typedef PointerIntPair<Type *, 1, bool> TypeIsSExt; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 149 | typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 150 | typedef SmallVector<Instruction *, 16> SExts; |
| 151 | typedef DenseMap<Value *, SExts> ValueToSExts; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 152 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 153 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 154 | class CodeGenPrepare : public FunctionPass { |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 155 | const TargetMachine *TM; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 156 | const TargetSubtargetInfo *SubtargetInfo; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 157 | const TargetLowering *TLI; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 158 | const TargetRegisterInfo *TRI; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 159 | const TargetTransformInfo *TTI; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 160 | const TargetLibraryInfo *TLInfo; |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 161 | const LoopInfo *LI; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 162 | std::unique_ptr<BlockFrequencyInfo> BFI; |
| 163 | std::unique_ptr<BranchProbabilityInfo> BPI; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 164 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 165 | /// As we scan instructions optimizing them, this is the next instruction |
| 166 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 167 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 168 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 169 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 170 | /// This allows us to avoid inserting duplicate code for blocks with |
| 171 | /// multiple load/stores of the same address. |
Nick Lewycky | 5fb1963 | 2013-05-08 09:00:10 +0000 | [diff] [blame] | 172 | ValueMap<Value*, Value*> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 173 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 174 | /// Keeps track of all instructions inserted for the current function. |
| 175 | SetOfInstrs InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 176 | /// Keeps track of the type of the related instruction before their |
| 177 | /// promotion for the current function. |
| 178 | InstrToOrigTy PromotedInsts; |
| 179 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 180 | /// Keep track of instructions removed during promotion. |
| 181 | SetOfInstrs RemovedInsts; |
| 182 | |
| 183 | /// Keep track of sext chains based on their initial value. |
| 184 | DenseMap<Value *, Instruction *> SeenChainsForSExt; |
| 185 | |
| 186 | /// Keep track of SExt promoted. |
| 187 | ValueToSExts ValToSExtendedUses; |
| 188 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 189 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 190 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 191 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 192 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 193 | bool OptSize; |
| 194 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 195 | /// DataLayout for the Function being processed. |
| 196 | const DataLayout *DL; |
| 197 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 198 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 199 | static char ID; // Pass identification, replacement for typeid |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 200 | explicit CodeGenPrepare(const TargetMachine *TM = nullptr) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 201 | : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) { |
Owen Anderson | 6c18d1a | 2010-10-19 17:21:58 +0000 | [diff] [blame] | 202 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 203 | } |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 204 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 205 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 206 | StringRef getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 207 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 208 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 209 | // FIXME: When we can selectively preserve passes, preserve the domtree. |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 210 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 211 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 212 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 213 | AU.addRequired<LoopInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 214 | } |
| 215 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 216 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 217 | bool eliminateFallThrough(Function &F); |
| 218 | bool eliminateMostlyEmptyBlocks(Function &F); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 219 | BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 220 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 221 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 222 | bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, |
| 223 | bool isPreheader); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 224 | bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT); |
| 225 | bool optimizeInst(Instruction *I, bool& ModifiedDT); |
| 226 | bool optimizeMemoryInst(Instruction *I, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 227 | Type *AccessTy, unsigned AS); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 228 | bool optimizeInlineAsmInst(CallInst *CS); |
| 229 | bool optimizeCallInst(CallInst *CI, bool& ModifiedDT); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 230 | bool optimizeExt(Instruction *&I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 231 | bool optimizeExtUses(Instruction *I); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 232 | bool optimizeLoadExt(LoadInst *I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 233 | bool optimizeSelectInst(SelectInst *SI); |
| 234 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 235 | bool optimizeSwitchInst(SwitchInst *CI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 236 | bool optimizeExtractElementInst(Instruction *Inst); |
| 237 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 238 | bool placeDbgValues(Function &F); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 239 | bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, |
| 240 | LoadInst *&LI, Instruction *&Inst, bool HasPromoted); |
| 241 | bool tryToPromoteExts(TypePromotionTransaction &TPT, |
| 242 | const SmallVectorImpl<Instruction *> &Exts, |
| 243 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 244 | unsigned CreatedInstsCost = 0); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 245 | bool mergeSExts(Function &F); |
| 246 | bool performAddressTypePromotion( |
| 247 | Instruction *&Inst, |
| 248 | bool AllowPromotionWithoutCommonHeader, |
| 249 | bool HasPromoted, TypePromotionTransaction &TPT, |
| 250 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 251 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 252 | bool simplifyOffsetableRelocate(Instruction &I); |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 253 | bool splitIndirectCriticalEdges(Function &F); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 254 | }; |
Alexander Kornienko | f00654e | 2015-06-23 09:49:53 +0000 | [diff] [blame] | 255 | } |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 256 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 257 | char CodeGenPrepare::ID = 0; |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 258 | INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare", |
| 259 | "Optimize for code generation", false, false) |
| 260 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) |
| 261 | INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare", |
| 262 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 263 | |
Bill Wendling | 7a639ea | 2013-06-19 21:07:11 +0000 | [diff] [blame] | 264 | FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) { |
| 265 | return new CodeGenPrepare(TM); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 266 | } |
| 267 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 268 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 269 | if (skipFunction(F)) |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 270 | return false; |
| 271 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 272 | DL = &F.getParent()->getDataLayout(); |
| 273 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 274 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 275 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 276 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 277 | PromotedInsts.clear(); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 278 | BFI.reset(); |
| 279 | BPI.reset(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 280 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 281 | ModifiedDT = false; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 282 | if (TM) { |
| 283 | SubtargetInfo = TM->getSubtargetImpl(F); |
| 284 | TLI = SubtargetInfo->getTargetLowering(); |
| 285 | TRI = SubtargetInfo->getRegisterInfo(); |
| 286 | } |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 287 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 288 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 289 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 290 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 291 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 292 | if (ProfileGuidedSectionPrefix) { |
| 293 | ProfileSummaryInfo *PSI = |
| 294 | getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); |
Dehao Chen | 775341a | 2017-03-23 23:14:11 +0000 | [diff] [blame] | 295 | if (PSI->isFunctionHotInCallGraph(&F)) |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 296 | F.setSectionPrefix(".hot"); |
Dehao Chen | 775341a | 2017-03-23 23:14:11 +0000 | [diff] [blame] | 297 | else if (PSI->isFunctionColdInCallGraph(&F)) |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 298 | F.setSectionPrefix(".cold"); |
| 299 | } |
| 300 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 301 | /// This optimization identifies DIV instructions that can be |
| 302 | /// profitably bypassed and carried out with a shorter, faster divide. |
Preston Gurd | 485296d | 2013-03-04 18:13:57 +0000 | [diff] [blame] | 303 | if (!OptSize && TLI && TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 304 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 305 | TLI->getBypassSlowDivWidths(); |
Eric Christopher | 49a7d6c | 2016-01-04 23:18:58 +0000 | [diff] [blame] | 306 | BasicBlock* BB = &*F.begin(); |
| 307 | while (BB != nullptr) { |
| 308 | // bypassSlowDivision may create new BBs, but we don't want to reapply the |
| 309 | // optimization to those blocks. |
| 310 | BasicBlock* Next = BB->getNextNode(); |
| 311 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); |
| 312 | BB = Next; |
| 313 | } |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 314 | } |
| 315 | |
| 316 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 317 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 318 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 319 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 320 | // 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] | 321 | // 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] | 322 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 323 | EverMadeChange |= placeDbgValues(F); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 324 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 325 | if (!DisableBranchOpts) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 326 | EverMadeChange |= splitBranchCondition(F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 327 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 328 | // Split some critical edges where one of the sources is an indirect branch, |
| 329 | // to help generate sane code for PHIs involving such edges. |
| 330 | EverMadeChange |= splitIndirectCriticalEdges(F); |
| 331 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 332 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 333 | while (MadeChange) { |
| 334 | MadeChange = false; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 335 | SeenChainsForSExt.clear(); |
| 336 | ValToSExtendedUses.clear(); |
| 337 | RemovedInsts.clear(); |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 338 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 339 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 340 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 341 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 342 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 343 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 344 | if (ModifiedDTOnIteration) |
| 345 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 346 | } |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 347 | if (EnableTypePromotionMerge && !ValToSExtendedUses.empty()) |
| 348 | MadeChange |= mergeSExts(F); |
| 349 | |
| 350 | // Really free removed instructions during promotion. |
| 351 | for (Instruction *I : RemovedInsts) |
| 352 | delete I; |
| 353 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 354 | EverMadeChange |= MadeChange; |
| 355 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 356 | |
| 357 | SunkAddrs.clear(); |
| 358 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 359 | if (!DisableBranchOpts) { |
| 360 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 361 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 362 | for (BasicBlock &BB : F) { |
| 363 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 364 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 365 | if (!MadeChange) continue; |
| 366 | |
| 367 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 368 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 369 | if (pred_begin(*II) == pred_end(*II)) |
| 370 | WorkList.insert(*II); |
| 371 | } |
| 372 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 373 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 374 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 375 | while (!WorkList.empty()) { |
| 376 | BasicBlock *BB = *WorkList.begin(); |
| 377 | WorkList.erase(BB); |
| 378 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 379 | |
| 380 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 381 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 382 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 383 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 384 | if (pred_begin(*II) == pred_end(*II)) |
| 385 | WorkList.insert(*II); |
| 386 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 387 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 388 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 389 | // a single edge. |
| 390 | if (EverMadeChange || MadeChange) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 391 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 392 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 393 | EverMadeChange |= MadeChange; |
| 394 | } |
| 395 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 396 | if (!DisableGCOpts) { |
| 397 | SmallVector<Instruction *, 2> Statepoints; |
| 398 | for (BasicBlock &BB : F) |
| 399 | for (Instruction &I : BB) |
| 400 | if (isStatepoint(I)) |
| 401 | Statepoints.push_back(&I); |
| 402 | for (auto &I : Statepoints) |
| 403 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 404 | } |
| 405 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 406 | return EverMadeChange; |
| 407 | } |
| 408 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 409 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 410 | /// basic blocks has a single successor pointing to the other basic block, |
| 411 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 412 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 413 | bool Changed = false; |
| 414 | // 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] | 415 | 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] | 416 | BasicBlock *BB = &*I++; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 417 | // If the destination block has a single pred, then this is a trivial |
| 418 | // edge, just collapse it. |
| 419 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 420 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 421 | // Don't merge if BB's address is taken. |
| 422 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 423 | |
| 424 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 425 | if (Term && !Term->isConditional()) { |
| 426 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 427 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 428 | // Remember if SinglePred was the entry block of the function. |
| 429 | // If so, we will need to move BB back to the entry position. |
| 430 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 431 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 432 | |
| 433 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 434 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 435 | |
| 436 | // We have erased a block. Update the iterator. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 437 | I = BB->getIterator(); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 438 | } |
| 439 | } |
| 440 | return Changed; |
| 441 | } |
| 442 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 443 | /// Find a destination block from BB if BB is mergeable empty block. |
| 444 | BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { |
| 445 | // If this block doesn't end with an uncond branch, ignore it. |
| 446 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 447 | if (!BI || !BI->isUnconditional()) |
| 448 | return nullptr; |
| 449 | |
| 450 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 451 | // node, then other stuff is happening here. |
| 452 | BasicBlock::iterator BBI = BI->getIterator(); |
| 453 | if (BBI != BB->begin()) { |
| 454 | --BBI; |
| 455 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 456 | if (BBI == BB->begin()) |
| 457 | break; |
| 458 | --BBI; |
| 459 | } |
| 460 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 461 | return nullptr; |
| 462 | } |
| 463 | |
| 464 | // Do not break infinite loops. |
| 465 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 466 | if (DestBB == BB) |
| 467 | return nullptr; |
| 468 | |
| 469 | if (!canMergeBlocks(BB, DestBB)) |
| 470 | DestBB = nullptr; |
| 471 | |
| 472 | return DestBB; |
| 473 | } |
| 474 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 475 | // Return the unique indirectbr predecessor of a block. This may return null |
| 476 | // even if such a predecessor exists, if it's not useful for splitting. |
| 477 | // If a predecessor is found, OtherPreds will contain all other (non-indirectbr) |
| 478 | // predecessors of BB. |
| 479 | static BasicBlock * |
| 480 | findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) { |
| 481 | // If the block doesn't have any PHIs, we don't care about it, since there's |
| 482 | // no point in splitting it. |
| 483 | PHINode *PN = dyn_cast<PHINode>(BB->begin()); |
| 484 | if (!PN) |
| 485 | return nullptr; |
| 486 | |
| 487 | // Verify we have exactly one IBR predecessor. |
| 488 | // Conservatively bail out if one of the other predecessors is not a "regular" |
| 489 | // terminator (that is, not a switch or a br). |
| 490 | BasicBlock *IBB = nullptr; |
| 491 | for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) { |
| 492 | BasicBlock *PredBB = PN->getIncomingBlock(Pred); |
| 493 | TerminatorInst *PredTerm = PredBB->getTerminator(); |
| 494 | switch (PredTerm->getOpcode()) { |
| 495 | case Instruction::IndirectBr: |
| 496 | if (IBB) |
| 497 | return nullptr; |
| 498 | IBB = PredBB; |
| 499 | break; |
| 500 | case Instruction::Br: |
| 501 | case Instruction::Switch: |
| 502 | OtherPreds.push_back(PredBB); |
| 503 | continue; |
| 504 | default: |
| 505 | return nullptr; |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | return IBB; |
| 510 | } |
| 511 | |
| 512 | // Split critical edges where the source of the edge is an indirectbr |
| 513 | // instruction. This isn't always possible, but we can handle some easy cases. |
| 514 | // This is useful because MI is unable to split such critical edges, |
| 515 | // which means it will not be able to sink instructions along those edges. |
| 516 | // This is especially painful for indirect branches with many successors, where |
| 517 | // we end up having to prepare all outgoing values in the origin block. |
| 518 | // |
| 519 | // Our normal algorithm for splitting critical edges requires us to update |
| 520 | // the outgoing edges of the edge origin block, but for an indirectbr this |
| 521 | // is hard, since it would require finding and updating the block addresses |
| 522 | // the indirect branch uses. But if a block only has a single indirectbr |
| 523 | // predecessor, with the others being regular branches, we can do it in a |
| 524 | // different way. |
| 525 | // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr. |
| 526 | // We can split D into D0 and D1, where D0 contains only the PHIs from D, |
| 527 | // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and |
| 528 | // create the following structure: |
| 529 | // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1 |
| 530 | bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) { |
| 531 | // Check whether the function has any indirectbrs, and collect which blocks |
| 532 | // they may jump to. Since most functions don't have indirect branches, |
| 533 | // this lowers the common case's overhead to O(Blocks) instead of O(Edges). |
| 534 | SmallSetVector<BasicBlock *, 16> Targets; |
| 535 | for (auto &BB : F) { |
| 536 | auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator()); |
| 537 | if (!IBI) |
| 538 | continue; |
| 539 | |
| 540 | for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ) |
| 541 | Targets.insert(IBI->getSuccessor(Succ)); |
| 542 | } |
| 543 | |
| 544 | if (Targets.empty()) |
| 545 | return false; |
| 546 | |
| 547 | bool Changed = false; |
| 548 | for (BasicBlock *Target : Targets) { |
| 549 | SmallVector<BasicBlock *, 16> OtherPreds; |
| 550 | BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds); |
| 551 | // If we did not found an indirectbr, or the indirectbr is the only |
| 552 | // incoming edge, this isn't the kind of edge we're looking for. |
| 553 | if (!IBRPred || OtherPreds.empty()) |
| 554 | continue; |
| 555 | |
| 556 | // Don't even think about ehpads/landingpads. |
| 557 | Instruction *FirstNonPHI = Target->getFirstNonPHI(); |
| 558 | if (FirstNonPHI->isEHPad() || Target->isLandingPad()) |
| 559 | continue; |
| 560 | |
| 561 | BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split"); |
| 562 | // It's possible Target was its own successor through an indirectbr. |
| 563 | // In this case, the indirectbr now comes from BodyBlock. |
| 564 | if (IBRPred == Target) |
| 565 | IBRPred = BodyBlock; |
| 566 | |
| 567 | // At this point Target only has PHIs, and BodyBlock has the rest of the |
| 568 | // block's body. Create a copy of Target that will be used by the "direct" |
| 569 | // preds. |
| 570 | ValueToValueMapTy VMap; |
| 571 | BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F); |
| 572 | |
| 573 | for (BasicBlock *Pred : OtherPreds) |
| 574 | Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc); |
| 575 | |
| 576 | // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that |
| 577 | // they are clones, so the number of PHIs are the same. |
| 578 | // (a) Remove the edge coming from IBRPred from the "Direct" PHI |
| 579 | // (b) Leave that as the only edge in the "Indirect" PHI. |
| 580 | // (c) Merge the two in the body block. |
| 581 | BasicBlock::iterator Indirect = Target->begin(), |
| 582 | End = Target->getFirstNonPHI()->getIterator(); |
| 583 | BasicBlock::iterator Direct = DirectSucc->begin(); |
| 584 | BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt(); |
| 585 | |
| 586 | assert(&*End == Target->getTerminator() && |
| 587 | "Block was expected to only contain PHIs"); |
| 588 | |
| 589 | while (Indirect != End) { |
| 590 | PHINode *DirPHI = cast<PHINode>(Direct); |
| 591 | PHINode *IndPHI = cast<PHINode>(Indirect); |
| 592 | |
| 593 | // Now, clean up - the direct block shouldn't get the indirect value, |
| 594 | // and vice versa. |
| 595 | DirPHI->removeIncomingValue(IBRPred); |
| 596 | Direct++; |
| 597 | |
| 598 | // Advance the pointer here, to avoid invalidation issues when the old |
| 599 | // PHI is erased. |
| 600 | Indirect++; |
| 601 | |
| 602 | PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI); |
| 603 | NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred), |
| 604 | IBRPred); |
| 605 | |
| 606 | // Create a PHI in the body block, to merge the direct and indirect |
| 607 | // predecessors. |
| 608 | PHINode *MergePHI = |
| 609 | PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert); |
| 610 | MergePHI->addIncoming(NewIndPHI, Target); |
| 611 | MergePHI->addIncoming(DirPHI, DirectSucc); |
| 612 | |
| 613 | IndPHI->replaceAllUsesWith(MergePHI); |
| 614 | IndPHI->eraseFromParent(); |
| 615 | } |
| 616 | |
| 617 | Changed = true; |
| 618 | } |
| 619 | |
| 620 | return Changed; |
| 621 | } |
| 622 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 623 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 624 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 625 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 626 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 627 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 628 | SmallPtrSet<BasicBlock *, 16> Preheaders; |
| 629 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); |
| 630 | while (!LoopList.empty()) { |
| 631 | Loop *L = LoopList.pop_back_val(); |
| 632 | LoopList.insert(LoopList.end(), L->begin(), L->end()); |
| 633 | if (BasicBlock *Preheader = L->getLoopPreheader()) |
| 634 | Preheaders.insert(Preheader); |
| 635 | } |
| 636 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 637 | bool MadeChange = false; |
| 638 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 639 | 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] | 640 | BasicBlock *BB = &*I++; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 641 | BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); |
| 642 | if (!DestBB || |
| 643 | !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 644 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 645 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 646 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 647 | MadeChange = true; |
| 648 | } |
| 649 | return MadeChange; |
| 650 | } |
| 651 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 652 | bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, |
| 653 | BasicBlock *DestBB, |
| 654 | bool isPreheader) { |
| 655 | // Do not delete loop preheaders if doing so would create a critical edge. |
| 656 | // Loop preheaders can be good locations to spill registers. If the |
| 657 | // preheader is deleted and we create a critical edge, registers may be |
| 658 | // spilled in the loop body instead. |
| 659 | if (!DisablePreheaderProtect && isPreheader && |
| 660 | !(BB->getSinglePredecessor() && |
| 661 | BB->getSinglePredecessor()->getSingleSuccessor())) |
| 662 | return false; |
| 663 | |
| 664 | // Try to skip merging if the unique predecessor of BB is terminated by a |
| 665 | // switch or indirect branch instruction, and BB is used as an incoming block |
| 666 | // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to |
| 667 | // add COPY instructions in the predecessor of BB instead of BB (if it is not |
| 668 | // merged). Note that the critical edge created by merging such blocks wont be |
| 669 | // split in MachineSink because the jump table is not analyzable. By keeping |
| 670 | // such empty block (BB), ISel will place COPY instructions in BB, not in the |
| 671 | // predecessor of BB. |
| 672 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 673 | if (!Pred || |
| 674 | !(isa<SwitchInst>(Pred->getTerminator()) || |
| 675 | isa<IndirectBrInst>(Pred->getTerminator()))) |
| 676 | return true; |
| 677 | |
| 678 | if (BB->getTerminator() != BB->getFirstNonPHI()) |
| 679 | return true; |
| 680 | |
| 681 | // We use a simple cost heuristic which determine skipping merging is |
| 682 | // profitable if the cost of skipping merging is less than the cost of |
| 683 | // merging : Cost(skipping merging) < Cost(merging BB), where the |
| 684 | // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and |
| 685 | // the Cost(merging BB) is Freq(Pred) * Cost(Copy). |
| 686 | // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : |
| 687 | // Freq(Pred) / Freq(BB) > 2. |
| 688 | // Note that if there are multiple empty blocks sharing the same incoming |
| 689 | // value for the PHIs in the DestBB, we consider them together. In such |
| 690 | // case, Cost(merging BB) will be the sum of their frequencies. |
| 691 | |
| 692 | if (!isa<PHINode>(DestBB->begin())) |
| 693 | return true; |
| 694 | |
| 695 | SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; |
| 696 | |
| 697 | // Find all other incoming blocks from which incoming values of all PHIs in |
| 698 | // DestBB are the same as the ones from BB. |
| 699 | for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E; |
| 700 | ++PI) { |
| 701 | BasicBlock *DestBBPred = *PI; |
| 702 | if (DestBBPred == BB) |
| 703 | continue; |
| 704 | |
| 705 | bool HasAllSameValue = true; |
| 706 | BasicBlock::const_iterator DestBBI = DestBB->begin(); |
| 707 | while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) { |
| 708 | if (DestPN->getIncomingValueForBlock(BB) != |
| 709 | DestPN->getIncomingValueForBlock(DestBBPred)) { |
| 710 | HasAllSameValue = false; |
| 711 | break; |
| 712 | } |
| 713 | } |
| 714 | if (HasAllSameValue) |
| 715 | SameIncomingValueBBs.insert(DestBBPred); |
| 716 | } |
| 717 | |
| 718 | // See if all BB's incoming values are same as the value from Pred. In this |
| 719 | // case, no reason to skip merging because COPYs are expected to be place in |
| 720 | // Pred already. |
| 721 | if (SameIncomingValueBBs.count(Pred)) |
| 722 | return true; |
| 723 | |
| 724 | if (!BFI) { |
| 725 | Function &F = *BB->getParent(); |
| 726 | LoopInfo LI{DominatorTree(F)}; |
| 727 | BPI.reset(new BranchProbabilityInfo(F, LI)); |
| 728 | BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); |
| 729 | } |
| 730 | |
| 731 | BlockFrequency PredFreq = BFI->getBlockFreq(Pred); |
| 732 | BlockFrequency BBFreq = BFI->getBlockFreq(BB); |
| 733 | |
| 734 | for (auto SameValueBB : SameIncomingValueBBs) |
| 735 | if (SameValueBB->getUniquePredecessor() == Pred && |
| 736 | DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) |
| 737 | BBFreq += BFI->getBlockFreq(SameValueBB); |
| 738 | |
| 739 | return PredFreq.getFrequency() <= |
| 740 | BBFreq.getFrequency() * FreqRatioToSkipMerge; |
| 741 | } |
| 742 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 743 | /// Return true if we can merge BB into DestBB if there is a single |
| 744 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 745 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 746 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 747 | const BasicBlock *DestBB) const { |
| 748 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 749 | // the successor. If there are more complex condition (e.g. preheaders), |
| 750 | // don't mess around with them. |
| 751 | BasicBlock::const_iterator BBI = BB->begin(); |
| 752 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 753 | for (const User *U : PN->users()) { |
| 754 | const Instruction *UI = cast<Instruction>(U); |
| 755 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 756 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 757 | // If User is inside DestBB block and it is a PHINode then check |
| 758 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 759 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 760 | if (UI->getParent() == DestBB) { |
| 761 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 762 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 763 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 764 | if (Insn && Insn->getParent() == BB && |
| 765 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 766 | return false; |
| 767 | } |
| 768 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 769 | } |
| 770 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 771 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 772 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 773 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 774 | // can't merge the block. |
| 775 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 776 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 777 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 778 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 779 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 780 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 781 | // It is faster to get preds from a PHI than with pred_iterator. |
| 782 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 783 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 784 | } else { |
| 785 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 786 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 787 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 788 | // Walk the preds of DestBB. |
| 789 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 790 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 791 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 792 | BBI = DestBB->begin(); |
| 793 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 794 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 795 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 796 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 797 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 798 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 799 | if (V2PN->getParent() == BB) |
| 800 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 801 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 802 | // If there is a conflict, bail out. |
| 803 | if (V1 != V2) return false; |
| 804 | } |
| 805 | } |
| 806 | } |
| 807 | |
| 808 | return true; |
| 809 | } |
| 810 | |
| 811 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 812 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 813 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 814 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 815 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 816 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 817 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 818 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 819 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 820 | // If the destination block has a single pred, then this is a trivial edge, |
| 821 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 822 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 823 | if (SinglePred != DestBB) { |
| 824 | // Remember if SinglePred was the entry block of the function. If so, we |
| 825 | // will need to move BB back to the entry position. |
| 826 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 827 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 828 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 829 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 830 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 831 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 832 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 833 | return; |
| 834 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 835 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 836 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 837 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 838 | // to handle the new incoming edges it is about to have. |
| 839 | PHINode *PN; |
| 840 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 841 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 842 | // Remove the incoming value for BB, and remember it. |
| 843 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 844 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 845 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 846 | // value that dominates BB. |
| 847 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 848 | if (InValPhi && InValPhi->getParent() == BB) { |
| 849 | // Add all of the input values of the input PHI as inputs of this phi. |
| 850 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 851 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 852 | InValPhi->getIncomingBlock(i)); |
| 853 | } else { |
| 854 | // Otherwise, add one instance of the dominating value for each edge that |
| 855 | // we will be adding. |
| 856 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 857 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 858 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 859 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 860 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 861 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 862 | } |
| 863 | } |
| 864 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 865 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 866 | // The PHIs are now updated, change everything that refers to BB to use |
| 867 | // DestBB and remove BB. |
| 868 | BB->replaceAllUsesWith(DestBB); |
| 869 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 870 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 871 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 872 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 873 | } |
| 874 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 875 | // Computes a map of base pointer relocation instructions to corresponding |
| 876 | // derived pointer relocation instructions given a vector of all relocate calls |
| 877 | static void computeBaseDerivedRelocateMap( |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 878 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, |
| 879 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> |
| 880 | &RelocateInstMap) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 881 | // Collect information in two maps: one primarily for locating the base object |
| 882 | // while filling the second map; the second map is the final structure holding |
| 883 | // a mapping between Base and corresponding Derived relocate calls |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 884 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; |
| 885 | for (auto *ThisRelocate : AllRelocateCalls) { |
| 886 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), |
| 887 | ThisRelocate->getDerivedPtrIndex()); |
| 888 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 889 | } |
| 890 | for (auto &Item : RelocateIdxMap) { |
| 891 | std::pair<unsigned, unsigned> Key = Item.first; |
| 892 | if (Key.first == Key.second) |
| 893 | // Base relocation: nothing to insert |
| 894 | continue; |
| 895 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 896 | GCRelocateInst *I = Item.second; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 897 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 898 | |
| 899 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 900 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 901 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 902 | // TODO: We might want to insert a new base object relocate and gep off |
| 903 | // that, if there are enough derived object relocates. |
| 904 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 905 | |
| 906 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 907 | } |
| 908 | } |
| 909 | |
| 910 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 911 | // small integer constants |
| 912 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 913 | SmallVectorImpl<Value *> &OffsetV) { |
| 914 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 915 | // Only accept small constant integer operands |
| 916 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 917 | if (!Op || Op->getZExtValue() > 20) |
| 918 | return false; |
| 919 | } |
| 920 | |
| 921 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 922 | OffsetV.push_back(GEP->getOperand(i)); |
| 923 | return true; |
| 924 | } |
| 925 | |
| 926 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 927 | // replace, computes a replacement, and affects it. |
| 928 | static bool |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 929 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, |
| 930 | const SmallVectorImpl<GCRelocateInst *> &Targets) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 931 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 932 | for (GCRelocateInst *ToReplace : Targets) { |
| 933 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 934 | "Not relocating a derived object of the original base object"); |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 935 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 936 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 937 | continue; |
| 938 | } |
| 939 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 940 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 941 | // Base and derived relocates are in different basic blocks. |
| 942 | // In this case transform is only valid when base dominates derived |
| 943 | // relocate. However it would be too expensive to check dominance |
| 944 | // for each such relocate, so we skip the whole transformation. |
| 945 | continue; |
| 946 | } |
| 947 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 948 | Value *Base = ToReplace->getBasePtr(); |
| 949 | auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 950 | if (!Derived || Derived->getPointerOperand() != Base) |
| 951 | continue; |
| 952 | |
| 953 | SmallVector<Value *, 2> OffsetV; |
| 954 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 955 | continue; |
| 956 | |
| 957 | // Create a Builder and replace the target callsite with a gep |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 958 | assert(RelocatedBase->getNextNode() && |
| 959 | "Should always have one since it's not a terminator"); |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 960 | |
| 961 | // Insert after RelocatedBase |
| 962 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 963 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 964 | |
| 965 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 966 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 967 | // match, and we should reuse it to get the derived pointer. But it could be |
| 968 | // cases like this: |
| 969 | // bb1: |
| 970 | // ... |
| 971 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 972 | // br label %merge |
| 973 | // |
| 974 | // bb2: |
| 975 | // ... |
| 976 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 977 | // br label %merge |
| 978 | // |
| 979 | // merge: |
| 980 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 981 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 982 | // |
| 983 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 984 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 985 | // the extra bitcast should be optimized away in later passes. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 986 | Value *ActualRelocatedBase = RelocatedBase; |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 987 | if (RelocatedBase->getType() != Base->getType()) { |
| 988 | ActualRelocatedBase = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 989 | Builder.CreateBitCast(RelocatedBase, Base->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 990 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 991 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 992 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 993 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 994 | // If the newly generated derived pointer's type does not match the original derived |
| 995 | // pointer's type, cast the new derived pointer to match it. Same reasoning as above. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 996 | Value *ActualReplacement = Replacement; |
| 997 | if (Replacement->getType() != ToReplace->getType()) { |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 998 | ActualReplacement = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 999 | Builder.CreateBitCast(Replacement, ToReplace->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1000 | } |
| 1001 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1002 | ToReplace->eraseFromParent(); |
| 1003 | |
| 1004 | MadeChange = true; |
| 1005 | } |
| 1006 | return MadeChange; |
| 1007 | } |
| 1008 | |
| 1009 | // Turns this: |
| 1010 | // |
| 1011 | // %base = ... |
| 1012 | // %ptr = gep %base + 15 |
| 1013 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 1014 | // %base' = relocate(%tok, i32 4, i32 4) |
| 1015 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 1016 | // %val = load %ptr' |
| 1017 | // |
| 1018 | // into this: |
| 1019 | // |
| 1020 | // %base = ... |
| 1021 | // %ptr = gep %base + 15 |
| 1022 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 1023 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 1024 | // %ptr' = gep %base' + 15 |
| 1025 | // %val = load %ptr' |
| 1026 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 1027 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1028 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1029 | |
| 1030 | for (auto *U : I.users()) |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1031 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1032 | // Collect all the relocate calls associated with a statepoint |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1033 | AllRelocateCalls.push_back(Relocate); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1034 | |
| 1035 | // We need atleast one base pointer relocation + one derived pointer |
| 1036 | // relocation to mangle |
| 1037 | if (AllRelocateCalls.size() < 2) |
| 1038 | return false; |
| 1039 | |
| 1040 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 1041 | // corresponding derived relocate instructions |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1042 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1043 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 1044 | if (RelocateInstMap.empty()) |
| 1045 | return false; |
| 1046 | |
| 1047 | for (auto &Item : RelocateInstMap) |
| 1048 | // Item.first is the RelocatedBase to offset against |
| 1049 | // Item.second is the vector of Targets to replace |
| 1050 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 1051 | return MadeChange; |
| 1052 | } |
| 1053 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1054 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 1055 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1056 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1057 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1058 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1059 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1060 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1061 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1062 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1063 | UI != E; ) { |
| 1064 | Use &TheUse = UI.getUse(); |
| 1065 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1066 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1067 | // Figure out which BB this cast is used in. For PHI's this is the |
| 1068 | // appropriate predecessor block. |
| 1069 | BasicBlock *UserBB = User->getParent(); |
| 1070 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1071 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1072 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1073 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1074 | // Preincrement use iterator so we don't invalidate it. |
| 1075 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1076 | |
David Majnemer | 0c80e2e | 2016-04-27 19:36:38 +0000 | [diff] [blame] | 1077 | // The first insertion point of a block containing an EH pad is after the |
| 1078 | // pad. If the pad is the user, we cannot sink the cast past the pad. |
| 1079 | if (User->isEHPad()) |
| 1080 | continue; |
| 1081 | |
Andrew Kaylor | d0430e8 | 2015-11-23 19:16:15 +0000 | [diff] [blame] | 1082 | // If the block selected to receive the cast is an EH pad that does not |
| 1083 | // allow non-PHI instructions before the terminator, we can't sink the |
| 1084 | // cast. |
| 1085 | if (UserBB->getTerminator()->isEHPad()) |
| 1086 | continue; |
| 1087 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1088 | // If this user is in the same block as the cast, don't change the cast. |
| 1089 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1090 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1091 | // If we have already inserted a cast into this block, use it. |
| 1092 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 1093 | |
| 1094 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1095 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1096 | assert(InsertPt != UserBB->end()); |
| 1097 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 1098 | CI->getType(), "", &*InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1099 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1100 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1101 | // 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] | 1102 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1103 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1104 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1105 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1106 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1107 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1108 | if (CI->use_empty()) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1109 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1110 | MadeChange = true; |
| 1111 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1112 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1113 | return MadeChange; |
| 1114 | } |
| 1115 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1116 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 1117 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 1118 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1119 | /// |
| 1120 | /// Return true if any changes are made. |
| 1121 | /// |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1122 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 1123 | const DataLayout &DL) { |
Justin Lebar | 3e50a5b | 2016-11-21 22:49:15 +0000 | [diff] [blame] | 1124 | // Sink only "cheap" (or nop) address-space casts. This is a weaker condition |
| 1125 | // than sinking only nop casts, but is helpful on some platforms. |
| 1126 | if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { |
| 1127 | if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(), |
| 1128 | ASC->getDestAddressSpace())) |
| 1129 | return false; |
| 1130 | } |
| 1131 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1132 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1133 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 1134 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1135 | |
| 1136 | // This is an fp<->int conversion? |
| 1137 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 1138 | return false; |
| 1139 | |
| 1140 | // If this is an extension, it will be a zero or sign extension, which |
| 1141 | // isn't a noop. |
| 1142 | if (SrcVT.bitsLT(DstVT)) return false; |
| 1143 | |
| 1144 | // If these values will be promoted, find out what they will be promoted |
| 1145 | // to. This helps us consider truncates on PPC as noop copies when they |
| 1146 | // are. |
| 1147 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 1148 | TargetLowering::TypePromoteInteger) |
| 1149 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 1150 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 1151 | TargetLowering::TypePromoteInteger) |
| 1152 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 1153 | |
| 1154 | // If, after promotion, these are the same types, this is a noop copy. |
| 1155 | if (SrcVT != DstVT) |
| 1156 | return false; |
| 1157 | |
| 1158 | return SinkCast(CI); |
| 1159 | } |
| 1160 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1161 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 1162 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1163 | /// |
| 1164 | /// Return true if any changes were made. |
| 1165 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 1166 | Value *A, *B; |
| 1167 | Instruction *AddI; |
| 1168 | if (!match(CI, |
| 1169 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 1170 | return false; |
| 1171 | |
| 1172 | Type *Ty = AddI->getType(); |
| 1173 | if (!isa<IntegerType>(Ty)) |
| 1174 | return false; |
| 1175 | |
| 1176 | // We don't want to move around uses of condition values this late, so we we |
| 1177 | // check if it is legal to create the call to the intrinsic in the basic |
| 1178 | // block containing the icmp: |
| 1179 | |
| 1180 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 1181 | return false; |
| 1182 | |
| 1183 | #ifndef NDEBUG |
| 1184 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 1185 | // for now: |
| 1186 | if (AddI->hasOneUse()) |
| 1187 | assert(*AddI->user_begin() == CI && "expected!"); |
| 1188 | #endif |
| 1189 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 1190 | Module *M = CI->getModule(); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1191 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 1192 | |
| 1193 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 1194 | |
| 1195 | auto *UAddWithOverflow = |
| 1196 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 1197 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 1198 | auto *Overflow = |
| 1199 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 1200 | |
| 1201 | CI->replaceAllUsesWith(Overflow); |
| 1202 | AddI->replaceAllUsesWith(UAdd); |
| 1203 | CI->eraseFromParent(); |
| 1204 | AddI->eraseFromParent(); |
| 1205 | return true; |
| 1206 | } |
| 1207 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1208 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 1209 | /// registers that must be created and coalesced. This is a clear win except on |
| 1210 | /// targets with multiple condition code registers (PowerPC), where it might |
| 1211 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1212 | /// |
| 1213 | /// Return true if any changes are made. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1214 | static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1215 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1216 | |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1217 | // Avoid sinking soft-FP comparisons, since this can move them into a loop. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1218 | if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI)) |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1219 | return false; |
| 1220 | |
| 1221 | // Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1222 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1223 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1224 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1225 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1226 | UI != E; ) { |
| 1227 | Use &TheUse = UI.getUse(); |
| 1228 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1229 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1230 | // Preincrement use iterator so we don't invalidate it. |
| 1231 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1232 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1233 | // Don't bother for PHI nodes. |
| 1234 | if (isa<PHINode>(User)) |
| 1235 | continue; |
| 1236 | |
| 1237 | // Figure out which BB this cmp is used in. |
| 1238 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1239 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1240 | // If this user is in the same block as the cmp, don't change the cmp. |
| 1241 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1242 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1243 | // If we have already inserted a cmp into this block, use it. |
| 1244 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 1245 | |
| 1246 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1247 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1248 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1249 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1250 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 1251 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Wolfgang Pieb | e51bede | 2016-10-06 21:43:45 +0000 | [diff] [blame] | 1252 | // Propagate the debug info. |
| 1253 | InsertedCmp->setDebugLoc(CI->getDebugLoc()); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1254 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1255 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1256 | // Replace a use of the cmp with a use of the new cmp. |
| 1257 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1258 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1259 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1260 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1261 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1262 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1263 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1264 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1265 | MadeChange = true; |
| 1266 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1267 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1268 | return MadeChange; |
| 1269 | } |
| 1270 | |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 1271 | static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1272 | if (SinkCmpExpression(CI, TLI)) |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1273 | return true; |
| 1274 | |
| 1275 | if (CombineUAddWithOverflow(CI)) |
| 1276 | return true; |
| 1277 | |
| 1278 | return false; |
| 1279 | } |
| 1280 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 1281 | /// Duplicate and sink the given 'and' instruction into user blocks where it is |
| 1282 | /// used in a compare to allow isel to generate better code for targets where |
| 1283 | /// this operation can be combined. |
| 1284 | /// |
| 1285 | /// Return true if any changes are made. |
| 1286 | static bool sinkAndCmp0Expression(Instruction *AndI, |
| 1287 | const TargetLowering &TLI, |
| 1288 | SetOfInstrs &InsertedInsts) { |
| 1289 | // Double-check that we're not trying to optimize an instruction that was |
| 1290 | // already optimized by some other part of this pass. |
| 1291 | assert(!InsertedInsts.count(AndI) && |
| 1292 | "Attempting to optimize already optimized and instruction"); |
| 1293 | (void) InsertedInsts; |
| 1294 | |
| 1295 | // Nothing to do for single use in same basic block. |
| 1296 | if (AndI->hasOneUse() && |
| 1297 | AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) |
| 1298 | return false; |
| 1299 | |
| 1300 | // Try to avoid cases where sinking/duplicating is likely to increase register |
| 1301 | // pressure. |
| 1302 | if (!isa<ConstantInt>(AndI->getOperand(0)) && |
| 1303 | !isa<ConstantInt>(AndI->getOperand(1)) && |
| 1304 | AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) |
| 1305 | return false; |
| 1306 | |
| 1307 | for (auto *U : AndI->users()) { |
| 1308 | Instruction *User = cast<Instruction>(U); |
| 1309 | |
| 1310 | // Only sink for and mask feeding icmp with 0. |
| 1311 | if (!isa<ICmpInst>(User)) |
| 1312 | return false; |
| 1313 | |
| 1314 | auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); |
| 1315 | if (!CmpC || !CmpC->isZero()) |
| 1316 | return false; |
| 1317 | } |
| 1318 | |
| 1319 | if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) |
| 1320 | return false; |
| 1321 | |
| 1322 | DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n"); |
| 1323 | DEBUG(AndI->getParent()->dump()); |
| 1324 | |
| 1325 | // Push the 'and' into the same block as the icmp 0. There should only be |
| 1326 | // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any |
| 1327 | // others, so we don't need to keep track of which BBs we insert into. |
| 1328 | for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); |
| 1329 | UI != E; ) { |
| 1330 | Use &TheUse = UI.getUse(); |
| 1331 | Instruction *User = cast<Instruction>(*UI); |
| 1332 | |
| 1333 | // Preincrement use iterator so we don't invalidate it. |
| 1334 | ++UI; |
| 1335 | |
| 1336 | DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n"); |
| 1337 | |
| 1338 | // Keep the 'and' in the same place if the use is already in the same block. |
| 1339 | Instruction *InsertPt = |
| 1340 | User->getParent() == AndI->getParent() ? AndI : User; |
| 1341 | Instruction *InsertedAnd = |
| 1342 | BinaryOperator::Create(Instruction::And, AndI->getOperand(0), |
| 1343 | AndI->getOperand(1), "", InsertPt); |
| 1344 | // Propagate the debug info. |
| 1345 | InsertedAnd->setDebugLoc(AndI->getDebugLoc()); |
| 1346 | |
| 1347 | // Replace a use of the 'and' with a use of the new 'and'. |
| 1348 | TheUse = InsertedAnd; |
| 1349 | ++NumAndUses; |
| 1350 | DEBUG(User->getParent()->dump()); |
| 1351 | } |
| 1352 | |
| 1353 | // We removed all uses, nuke the and. |
| 1354 | AndI->eraseFromParent(); |
| 1355 | return true; |
| 1356 | } |
| 1357 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1358 | /// Check if the candidates could be combined with a shift instruction, which |
| 1359 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1360 | /// 1. Truncate instruction |
| 1361 | /// 2. And instruction and the imm is a mask of the low bits: |
| 1362 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 1363 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1364 | if (!isa<TruncInst>(User)) { |
| 1365 | if (User->getOpcode() != Instruction::And || |
| 1366 | !isa<ConstantInt>(User->getOperand(1))) |
| 1367 | return false; |
| 1368 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1369 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1370 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1371 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1372 | return false; |
| 1373 | } |
| 1374 | return true; |
| 1375 | } |
| 1376 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1377 | /// 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] | 1378 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1379 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 1380 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1381 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1382 | BasicBlock *UserBB = User->getParent(); |
| 1383 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 1384 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 1385 | bool MadeChange = false; |
| 1386 | |
| 1387 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 1388 | TruncE = TruncI->user_end(); |
| 1389 | TruncUI != TruncE;) { |
| 1390 | |
| 1391 | Use &TruncTheUse = TruncUI.getUse(); |
| 1392 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 1393 | // Preincrement use iterator so we don't invalidate it. |
| 1394 | |
| 1395 | ++TruncUI; |
| 1396 | |
| 1397 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 1398 | if (!ISDOpcode) |
| 1399 | continue; |
| 1400 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 1401 | // If the use is actually a legal node, there will not be an |
| 1402 | // implicit truncate. |
| 1403 | // FIXME: always querying the result type is just an |
| 1404 | // approximation; some nodes' legality is determined by the |
| 1405 | // 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] | 1406 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1407 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1408 | continue; |
| 1409 | |
| 1410 | // Don't bother for PHI nodes. |
| 1411 | if (isa<PHINode>(TruncUser)) |
| 1412 | continue; |
| 1413 | |
| 1414 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 1415 | |
| 1416 | if (UserBB == TruncUserBB) |
| 1417 | continue; |
| 1418 | |
| 1419 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 1420 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 1421 | |
| 1422 | if (!InsertedShift && !InsertedTrunc) { |
| 1423 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1424 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1425 | // Sink the shift |
| 1426 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1427 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1428 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1429 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1430 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1431 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1432 | |
| 1433 | // Sink the trunc |
| 1434 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 1435 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1436 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1437 | |
| 1438 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1439 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1440 | |
| 1441 | MadeChange = true; |
| 1442 | |
| 1443 | TruncTheUse = InsertedTrunc; |
| 1444 | } |
| 1445 | } |
| 1446 | return MadeChange; |
| 1447 | } |
| 1448 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1449 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1450 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1451 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1452 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1453 | /// BB1: |
| 1454 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1455 | /// BB2: |
| 1456 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1457 | /// ==> |
| 1458 | /// |
| 1459 | /// BB2: |
| 1460 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1461 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1462 | /// |
| 1463 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1464 | /// instruction. |
| 1465 | /// Return true if any changes are made. |
| 1466 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1467 | const TargetLowering &TLI, |
| 1468 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1469 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1470 | |
| 1471 | /// Only insert instructions in each block once. |
| 1472 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1473 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1474 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1475 | |
| 1476 | bool MadeChange = false; |
| 1477 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1478 | UI != E;) { |
| 1479 | Use &TheUse = UI.getUse(); |
| 1480 | Instruction *User = cast<Instruction>(*UI); |
| 1481 | // Preincrement use iterator so we don't invalidate it. |
| 1482 | ++UI; |
| 1483 | |
| 1484 | // Don't bother for PHI nodes. |
| 1485 | if (isa<PHINode>(User)) |
| 1486 | continue; |
| 1487 | |
| 1488 | if (!isExtractBitsCandidateUse(User)) |
| 1489 | continue; |
| 1490 | |
| 1491 | BasicBlock *UserBB = User->getParent(); |
| 1492 | |
| 1493 | if (UserBB == DefBB) { |
| 1494 | // If the shift and truncate instruction are in the same BB. The use of |
| 1495 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1496 | // legal. In this case, we would like to sink both shift and truncate |
| 1497 | // instruction to the BB of TruncUse. |
| 1498 | // for example: |
| 1499 | // BB1: |
| 1500 | // i64 shift.result = lshr i64 opnd, imm |
| 1501 | // trunc.result = trunc shift.result to i16 |
| 1502 | // |
| 1503 | // BB2: |
| 1504 | // ----> We will have an implicit truncate here if the architecture does |
| 1505 | // not have i16 compare. |
| 1506 | // cmp i16 trunc.result, opnd2 |
| 1507 | // |
| 1508 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1509 | // If the type of the truncate is legal, no trucate will be |
| 1510 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1511 | && |
| 1512 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1513 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1514 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1515 | |
| 1516 | continue; |
| 1517 | } |
| 1518 | // If we have already inserted a shift into this block, use it. |
| 1519 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1520 | |
| 1521 | if (!InsertedShift) { |
| 1522 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1523 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1524 | |
| 1525 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1526 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1527 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1528 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1529 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1530 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1531 | |
| 1532 | MadeChange = true; |
| 1533 | } |
| 1534 | |
| 1535 | // Replace a use of the shift with a use of the new shift. |
| 1536 | TheUse = InsertedShift; |
| 1537 | } |
| 1538 | |
| 1539 | // If we removed all uses, nuke the shift. |
| 1540 | if (ShiftI->use_empty()) |
| 1541 | ShiftI->eraseFromParent(); |
| 1542 | |
| 1543 | return MadeChange; |
| 1544 | } |
| 1545 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1546 | // Translate a masked load intrinsic like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1547 | // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align, |
| 1548 | // <16 x i1> %mask, <16 x i32> %passthru) |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 1549 | // 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] | 1550 | // the appropriate mask bit is set |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1551 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1552 | // %1 = bitcast i8* %addr to i32* |
| 1553 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1554 | // %3 = icmp eq i1 %2, true |
| 1555 | // br i1 %3, label %cond.load, label %else |
| 1556 | // |
| 1557 | //cond.load: ; preds = %0 |
| 1558 | // %4 = getelementptr i32* %1, i32 0 |
| 1559 | // %5 = load i32* %4 |
| 1560 | // %6 = insertelement <16 x i32> undef, i32 %5, i32 0 |
| 1561 | // br label %else |
| 1562 | // |
| 1563 | //else: ; preds = %0, %cond.load |
| 1564 | // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ] |
| 1565 | // %7 = extractelement <16 x i1> %mask, i32 1 |
| 1566 | // %8 = icmp eq i1 %7, true |
| 1567 | // br i1 %8, label %cond.load1, label %else2 |
| 1568 | // |
| 1569 | //cond.load1: ; preds = %else |
| 1570 | // %9 = getelementptr i32* %1, i32 1 |
| 1571 | // %10 = load i32* %9 |
| 1572 | // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1 |
| 1573 | // br label %else2 |
| 1574 | // |
| 1575 | //else2: ; preds = %else, %cond.load1 |
| 1576 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1577 | // %12 = extractelement <16 x i1> %mask, i32 2 |
| 1578 | // %13 = icmp eq i1 %12, true |
| 1579 | // br i1 %13, label %cond.load4, label %else5 |
| 1580 | // |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1581 | static void scalarizeMaskedLoad(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1582 | Value *Ptr = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1583 | Value *Alignment = CI->getArgOperand(1); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1584 | Value *Mask = CI->getArgOperand(2); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1585 | Value *Src0 = CI->getArgOperand(3); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1586 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1587 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1588 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1589 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1590 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1591 | Type *EltTy = CI->getType()->getVectorElementType(); |
| 1592 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1593 | IRBuilder<> Builder(CI->getContext()); |
| 1594 | Instruction *InsertPt = CI; |
| 1595 | BasicBlock *IfBlock = CI->getParent(); |
| 1596 | BasicBlock *CondBlock = nullptr; |
| 1597 | BasicBlock *PrevIfBlock = CI->getParent(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1598 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1599 | Builder.SetInsertPoint(InsertPt); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1600 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1601 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1602 | // Short-cut if the mask is all-true. |
| 1603 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1604 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1605 | |
| 1606 | if (IsAllOnesMask) { |
| 1607 | Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal); |
| 1608 | CI->replaceAllUsesWith(NewI); |
| 1609 | CI->eraseFromParent(); |
| 1610 | return; |
| 1611 | } |
| 1612 | |
| 1613 | // Adjust alignment for the scalar instruction. |
| 1614 | AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1615 | // Bitcast %addr fron i8* to EltTy* |
| 1616 | Type *NewPtrType = |
| 1617 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1618 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1619 | unsigned VectorWidth = VecType->getNumElements(); |
| 1620 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1621 | Value *UndefVal = UndefValue::get(VecType); |
| 1622 | |
| 1623 | // The result vector |
| 1624 | Value *VResult = UndefVal; |
| 1625 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1626 | if (isa<ConstantVector>(Mask)) { |
| 1627 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1628 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1629 | continue; |
| 1630 | Value *Gep = |
| 1631 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1632 | LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
| 1633 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1634 | Builder.getInt32(Idx)); |
| 1635 | } |
| 1636 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1637 | CI->replaceAllUsesWith(NewI); |
| 1638 | CI->eraseFromParent(); |
| 1639 | return; |
| 1640 | } |
| 1641 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1642 | PHINode *Phi = nullptr; |
| 1643 | Value *PrevPhi = UndefVal; |
| 1644 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1645 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1646 | |
| 1647 | // Fill the "else" block, created in the previous iteration |
| 1648 | // |
| 1649 | // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ] |
| 1650 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1651 | // %to_load = icmp eq i1 %mask_1, true |
| 1652 | // br i1 %to_load, label %cond.load, label %else |
| 1653 | // |
| 1654 | if (Idx > 0) { |
| 1655 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1656 | Phi->addIncoming(VResult, CondBlock); |
| 1657 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1658 | PrevPhi = Phi; |
| 1659 | VResult = Phi; |
| 1660 | } |
| 1661 | |
| 1662 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1663 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1664 | ConstantInt::get(Predicate->getType(), 1)); |
| 1665 | |
| 1666 | // Create "cond" block |
| 1667 | // |
| 1668 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1669 | // %Elt = load i32* %EltAddr |
| 1670 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1671 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1672 | CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1673 | Builder.SetInsertPoint(InsertPt); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1674 | |
| 1675 | Value *Gep = |
| 1676 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1677 | LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1678 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx)); |
| 1679 | |
| 1680 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1681 | BasicBlock *NewIfBlock = |
| 1682 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1683 | Builder.SetInsertPoint(InsertPt); |
| 1684 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1685 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1686 | OldBr->eraseFromParent(); |
| 1687 | PrevIfBlock = IfBlock; |
| 1688 | IfBlock = NewIfBlock; |
| 1689 | } |
| 1690 | |
| 1691 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1692 | Phi->addIncoming(VResult, CondBlock); |
| 1693 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1694 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1695 | CI->replaceAllUsesWith(NewI); |
| 1696 | CI->eraseFromParent(); |
| 1697 | } |
| 1698 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1699 | // Translate a masked store intrinsic, like |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1700 | // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align, |
| 1701 | // <16 x i1> %mask) |
| 1702 | // to a chain of basic blocks, that stores element one-by-one if |
| 1703 | // the appropriate mask bit is set |
| 1704 | // |
| 1705 | // %1 = bitcast i8* %addr to i32* |
| 1706 | // %2 = extractelement <16 x i1> %mask, i32 0 |
| 1707 | // %3 = icmp eq i1 %2, true |
| 1708 | // br i1 %3, label %cond.store, label %else |
| 1709 | // |
| 1710 | // cond.store: ; preds = %0 |
| 1711 | // %4 = extractelement <16 x i32> %val, i32 0 |
| 1712 | // %5 = getelementptr i32* %1, i32 0 |
| 1713 | // store i32 %4, i32* %5 |
| 1714 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1715 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1716 | // else: ; preds = %0, %cond.store |
| 1717 | // %6 = extractelement <16 x i1> %mask, i32 1 |
| 1718 | // %7 = icmp eq i1 %6, true |
| 1719 | // br i1 %7, label %cond.store1, label %else2 |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1720 | // |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1721 | // cond.store1: ; preds = %else |
| 1722 | // %8 = extractelement <16 x i32> %val, i32 1 |
| 1723 | // %9 = getelementptr i32* %1, i32 1 |
| 1724 | // store i32 %8, i32* %9 |
| 1725 | // br label %else2 |
| 1726 | // . . . |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1727 | static void scalarizeMaskedStore(CallInst *CI) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1728 | Value *Src = CI->getArgOperand(0); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1729 | Value *Ptr = CI->getArgOperand(1); |
| 1730 | Value *Alignment = CI->getArgOperand(2); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1731 | Value *Mask = CI->getArgOperand(3); |
| 1732 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1733 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1734 | VectorType *VecType = dyn_cast<VectorType>(Src->getType()); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1735 | assert(VecType && "Unexpected data type in masked store intrinsic"); |
| 1736 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1737 | Type *EltTy = VecType->getElementType(); |
| 1738 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1739 | IRBuilder<> Builder(CI->getContext()); |
| 1740 | Instruction *InsertPt = CI; |
| 1741 | BasicBlock *IfBlock = CI->getParent(); |
| 1742 | Builder.SetInsertPoint(InsertPt); |
| 1743 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1744 | |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1745 | // Short-cut if the mask is all-true. |
| 1746 | bool IsAllOnesMask = isa<Constant>(Mask) && |
| 1747 | cast<Constant>(Mask)->isAllOnesValue(); |
| 1748 | |
| 1749 | if (IsAllOnesMask) { |
| 1750 | Builder.CreateAlignedStore(Src, Ptr, AlignVal); |
| 1751 | CI->eraseFromParent(); |
| 1752 | return; |
| 1753 | } |
| 1754 | |
| 1755 | // Adjust alignment for the scalar instruction. |
| 1756 | AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1757 | // Bitcast %addr fron i8* to EltTy* |
| 1758 | Type *NewPtrType = |
| 1759 | EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace()); |
| 1760 | Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1761 | unsigned VectorWidth = VecType->getNumElements(); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1762 | |
| 1763 | if (isa<ConstantVector>(Mask)) { |
| 1764 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1765 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1766 | continue; |
| 1767 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
| 1768 | Value *Gep = |
| 1769 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
| 1770 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
| 1771 | } |
| 1772 | CI->eraseFromParent(); |
| 1773 | return; |
| 1774 | } |
| 1775 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1776 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1777 | |
| 1778 | // Fill the "else" block, created in the previous iteration |
| 1779 | // |
| 1780 | // %mask_1 = extractelement <16 x i1> %mask, i32 Idx |
| 1781 | // %to_store = icmp eq i1 %mask_1, true |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1782 | // br i1 %to_store, label %cond.store, label %else |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1783 | // |
| 1784 | Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx)); |
| 1785 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1786 | ConstantInt::get(Predicate->getType(), 1)); |
| 1787 | |
| 1788 | // Create "cond" block |
| 1789 | // |
| 1790 | // %OneElt = extractelement <16 x i32> %Src, i32 Idx |
| 1791 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1792 | // %store i32 %OneElt, i32* %EltAddr |
| 1793 | // |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1794 | BasicBlock *CondBlock = |
| 1795 | IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1796 | Builder.SetInsertPoint(InsertPt); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1797 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1798 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx)); |
David Blaikie | aa41cd5 | 2015-04-03 21:33:42 +0000 | [diff] [blame] | 1799 | Value *Gep = |
| 1800 | Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx)); |
Elena Demikhovsky | 3ad76a1 | 2015-10-21 11:50:54 +0000 | [diff] [blame] | 1801 | Builder.CreateAlignedStore(OneElt, Gep, AlignVal); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1802 | |
| 1803 | // Create "else" block, fill it in the next iteration |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1804 | BasicBlock *NewIfBlock = |
| 1805 | CondBlock->splitBasicBlock(InsertPt->getIterator(), "else"); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1806 | Builder.SetInsertPoint(InsertPt); |
| 1807 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1808 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1809 | OldBr->eraseFromParent(); |
| 1810 | IfBlock = NewIfBlock; |
| 1811 | } |
| 1812 | CI->eraseFromParent(); |
| 1813 | } |
| 1814 | |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1815 | // Translate a masked gather intrinsic like |
| 1816 | // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4, |
| 1817 | // <16 x i1> %Mask, <16 x i32> %Src) |
| 1818 | // to a chain of basic blocks, with loading element one-by-one if |
| 1819 | // the appropriate mask bit is set |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1820 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1821 | // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind |
| 1822 | // % Mask0 = extractelement <16 x i1> %Mask, i32 0 |
| 1823 | // % ToLoad0 = icmp eq i1 % Mask0, true |
| 1824 | // br i1 % ToLoad0, label %cond.load, label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1825 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1826 | // cond.load: |
| 1827 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1828 | // % Load0 = load i32, i32* % Ptr0, align 4 |
| 1829 | // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0 |
| 1830 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1831 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1832 | // else: |
| 1833 | // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0] |
| 1834 | // % Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1835 | // % ToLoad1 = icmp eq i1 % Mask1, true |
| 1836 | // br i1 % ToLoad1, label %cond.load1, label %else2 |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1837 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1838 | // cond.load1: |
| 1839 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1840 | // % Load1 = load i32, i32* % Ptr1, align 4 |
| 1841 | // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1 |
| 1842 | // br label %else2 |
| 1843 | // . . . |
| 1844 | // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src |
| 1845 | // ret <16 x i32> %Result |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1846 | static void scalarizeMaskedGather(CallInst *CI) { |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1847 | Value *Ptrs = CI->getArgOperand(0); |
| 1848 | Value *Alignment = CI->getArgOperand(1); |
| 1849 | Value *Mask = CI->getArgOperand(2); |
| 1850 | Value *Src0 = CI->getArgOperand(3); |
| 1851 | |
| 1852 | VectorType *VecType = dyn_cast<VectorType>(CI->getType()); |
| 1853 | |
| 1854 | assert(VecType && "Unexpected return type of masked load intrinsic"); |
| 1855 | |
| 1856 | IRBuilder<> Builder(CI->getContext()); |
| 1857 | Instruction *InsertPt = CI; |
| 1858 | BasicBlock *IfBlock = CI->getParent(); |
| 1859 | BasicBlock *CondBlock = nullptr; |
| 1860 | BasicBlock *PrevIfBlock = CI->getParent(); |
| 1861 | Builder.SetInsertPoint(InsertPt); |
| 1862 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 1863 | |
| 1864 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1865 | |
| 1866 | Value *UndefVal = UndefValue::get(VecType); |
| 1867 | |
| 1868 | // The result vector |
| 1869 | Value *VResult = UndefVal; |
| 1870 | unsigned VectorWidth = VecType->getNumElements(); |
| 1871 | |
| 1872 | // Shorten the way if the mask is a vector of constants. |
| 1873 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 1874 | |
| 1875 | if (IsConstMask) { |
| 1876 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1877 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 1878 | continue; |
| 1879 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1880 | "Ptr" + Twine(Idx)); |
| 1881 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1882 | "Load" + Twine(Idx)); |
| 1883 | VResult = Builder.CreateInsertElement(VResult, Load, |
| 1884 | Builder.getInt32(Idx), |
| 1885 | "Res" + Twine(Idx)); |
| 1886 | } |
| 1887 | Value *NewI = Builder.CreateSelect(Mask, VResult, Src0); |
| 1888 | CI->replaceAllUsesWith(NewI); |
| 1889 | CI->eraseFromParent(); |
| 1890 | return; |
| 1891 | } |
| 1892 | |
| 1893 | PHINode *Phi = nullptr; |
| 1894 | Value *PrevPhi = UndefVal; |
| 1895 | |
| 1896 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 1897 | |
| 1898 | // Fill the "else" block, created in the previous iteration |
| 1899 | // |
| 1900 | // %Mask1 = extractelement <16 x i1> %Mask, i32 1 |
| 1901 | // %ToLoad1 = icmp eq i1 %Mask1, true |
| 1902 | // br i1 %ToLoad1, label %cond.load, label %else |
| 1903 | // |
| 1904 | if (Idx > 0) { |
| 1905 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.else"); |
| 1906 | Phi->addIncoming(VResult, CondBlock); |
| 1907 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1908 | PrevPhi = Phi; |
| 1909 | VResult = Phi; |
| 1910 | } |
| 1911 | |
| 1912 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 1913 | Builder.getInt32(Idx), |
| 1914 | "Mask" + Twine(Idx)); |
| 1915 | Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 1916 | ConstantInt::get(Predicate->getType(), 1), |
| 1917 | "ToLoad" + Twine(Idx)); |
| 1918 | |
| 1919 | // Create "cond" block |
| 1920 | // |
| 1921 | // %EltAddr = getelementptr i32* %1, i32 0 |
| 1922 | // %Elt = load i32* %EltAddr |
| 1923 | // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx |
| 1924 | // |
| 1925 | CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load"); |
| 1926 | Builder.SetInsertPoint(InsertPt); |
| 1927 | |
| 1928 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 1929 | "Ptr" + Twine(Idx)); |
| 1930 | LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal, |
| 1931 | "Load" + Twine(Idx)); |
| 1932 | VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx), |
| 1933 | "Res" + Twine(Idx)); |
| 1934 | |
| 1935 | // Create "else" block, fill it in the next iteration |
| 1936 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 1937 | Builder.SetInsertPoint(InsertPt); |
| 1938 | Instruction *OldBr = IfBlock->getTerminator(); |
| 1939 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 1940 | OldBr->eraseFromParent(); |
| 1941 | PrevIfBlock = IfBlock; |
| 1942 | IfBlock = NewIfBlock; |
| 1943 | } |
| 1944 | |
| 1945 | Phi = Builder.CreatePHI(VecType, 2, "res.phi.select"); |
| 1946 | Phi->addIncoming(VResult, CondBlock); |
| 1947 | Phi->addIncoming(PrevPhi, PrevIfBlock); |
| 1948 | Value *NewI = Builder.CreateSelect(Mask, Phi, Src0); |
| 1949 | CI->replaceAllUsesWith(NewI); |
| 1950 | CI->eraseFromParent(); |
| 1951 | } |
| 1952 | |
| 1953 | // Translate a masked scatter intrinsic, like |
| 1954 | // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4, |
| 1955 | // <16 x i1> %Mask) |
| 1956 | // to a chain of basic blocks, that stores element one-by-one if |
| 1957 | // the appropriate mask bit is set. |
| 1958 | // |
| 1959 | // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind |
| 1960 | // % Mask0 = extractelement <16 x i1> % Mask, i32 0 |
| 1961 | // % ToStore0 = icmp eq i1 % Mask0, true |
| 1962 | // br i1 %ToStore0, label %cond.store, label %else |
| 1963 | // |
| 1964 | // cond.store: |
| 1965 | // % Elt0 = extractelement <16 x i32> %Src, i32 0 |
| 1966 | // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0 |
| 1967 | // store i32 %Elt0, i32* % Ptr0, align 4 |
| 1968 | // br label %else |
Junmo Park | aa9243a | 2016-01-08 04:20:32 +0000 | [diff] [blame] | 1969 | // |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1970 | // else: |
| 1971 | // % Mask1 = extractelement <16 x i1> % Mask, i32 1 |
| 1972 | // % ToStore1 = icmp eq i1 % Mask1, true |
| 1973 | // br i1 % ToStore1, label %cond.store1, label %else2 |
| 1974 | // |
| 1975 | // cond.store1: |
| 1976 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 1977 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 1978 | // store i32 % Elt1, i32* % Ptr1, align 4 |
| 1979 | // br label %else2 |
| 1980 | // . . . |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 1981 | static void scalarizeMaskedScatter(CallInst *CI) { |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 1982 | Value *Src = CI->getArgOperand(0); |
| 1983 | Value *Ptrs = CI->getArgOperand(1); |
| 1984 | Value *Alignment = CI->getArgOperand(2); |
| 1985 | Value *Mask = CI->getArgOperand(3); |
| 1986 | |
| 1987 | assert(isa<VectorType>(Src->getType()) && |
| 1988 | "Unexpected data type in masked scatter intrinsic"); |
| 1989 | assert(isa<VectorType>(Ptrs->getType()) && |
| 1990 | isa<PointerType>(Ptrs->getType()->getVectorElementType()) && |
| 1991 | "Vector of pointers is expected in masked scatter intrinsic"); |
| 1992 | |
| 1993 | IRBuilder<> Builder(CI->getContext()); |
| 1994 | Instruction *InsertPt = CI; |
| 1995 | BasicBlock *IfBlock = CI->getParent(); |
| 1996 | Builder.SetInsertPoint(InsertPt); |
| 1997 | Builder.SetCurrentDebugLocation(CI->getDebugLoc()); |
| 1998 | |
| 1999 | unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue(); |
| 2000 | unsigned VectorWidth = Src->getType()->getVectorNumElements(); |
| 2001 | |
| 2002 | // Shorten the way if the mask is a vector of constants. |
| 2003 | bool IsConstMask = isa<ConstantVector>(Mask); |
| 2004 | |
| 2005 | if (IsConstMask) { |
| 2006 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 2007 | if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue()) |
| 2008 | continue; |
| 2009 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 2010 | "Elt" + Twine(Idx)); |
| 2011 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 2012 | "Ptr" + Twine(Idx)); |
| 2013 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 2014 | } |
| 2015 | CI->eraseFromParent(); |
| 2016 | return; |
| 2017 | } |
| 2018 | for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) { |
| 2019 | // Fill the "else" block, created in the previous iteration |
| 2020 | // |
| 2021 | // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx |
| 2022 | // % ToStore = icmp eq i1 % Mask1, true |
| 2023 | // br i1 % ToStore, label %cond.store, label %else |
| 2024 | // |
| 2025 | Value *Predicate = Builder.CreateExtractElement(Mask, |
| 2026 | Builder.getInt32(Idx), |
| 2027 | "Mask" + Twine(Idx)); |
| 2028 | Value *Cmp = |
| 2029 | Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate, |
| 2030 | ConstantInt::get(Predicate->getType(), 1), |
| 2031 | "ToStore" + Twine(Idx)); |
| 2032 | |
| 2033 | // Create "cond" block |
| 2034 | // |
| 2035 | // % Elt1 = extractelement <16 x i32> %Src, i32 1 |
| 2036 | // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1 |
| 2037 | // %store i32 % Elt1, i32* % Ptr1 |
| 2038 | // |
| 2039 | BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store"); |
| 2040 | Builder.SetInsertPoint(InsertPt); |
| 2041 | |
| 2042 | Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx), |
| 2043 | "Elt" + Twine(Idx)); |
| 2044 | Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx), |
| 2045 | "Ptr" + Twine(Idx)); |
| 2046 | Builder.CreateAlignedStore(OneElt, Ptr, AlignVal); |
| 2047 | |
| 2048 | // Create "else" block, fill it in the next iteration |
| 2049 | BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else"); |
| 2050 | Builder.SetInsertPoint(InsertPt); |
| 2051 | Instruction *OldBr = IfBlock->getTerminator(); |
| 2052 | BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr); |
| 2053 | OldBr->eraseFromParent(); |
| 2054 | IfBlock = NewIfBlock; |
| 2055 | } |
| 2056 | CI->eraseFromParent(); |
| 2057 | } |
| 2058 | |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 2059 | /// If counting leading or trailing zeros is an expensive operation and a zero |
| 2060 | /// input is defined, add a check for zero to avoid calling the intrinsic. |
| 2061 | /// |
| 2062 | /// We want to transform: |
| 2063 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) |
| 2064 | /// |
| 2065 | /// into: |
| 2066 | /// entry: |
| 2067 | /// %cmpz = icmp eq i64 %A, 0 |
| 2068 | /// br i1 %cmpz, label %cond.end, label %cond.false |
| 2069 | /// cond.false: |
| 2070 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) |
| 2071 | /// br label %cond.end |
| 2072 | /// cond.end: |
| 2073 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] |
| 2074 | /// |
| 2075 | /// If the transform is performed, return true and set ModifiedDT to true. |
| 2076 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, |
| 2077 | const TargetLowering *TLI, |
| 2078 | const DataLayout *DL, |
| 2079 | bool &ModifiedDT) { |
| 2080 | if (!TLI || !DL) |
| 2081 | return false; |
| 2082 | |
| 2083 | // If a zero input is undefined, it doesn't make sense to despeculate that. |
| 2084 | if (match(CountZeros->getOperand(1), m_One())) |
| 2085 | return false; |
| 2086 | |
| 2087 | // If it's cheap to speculate, there's nothing to do. |
| 2088 | auto IntrinsicID = CountZeros->getIntrinsicID(); |
| 2089 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || |
| 2090 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) |
| 2091 | return false; |
| 2092 | |
| 2093 | // Only handle legal scalar cases. Anything else requires too much work. |
| 2094 | Type *Ty = CountZeros->getType(); |
| 2095 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); |
Jun Bum Lim | be11bdc | 2016-05-13 18:38:35 +0000 | [diff] [blame] | 2096 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 2097 | return false; |
| 2098 | |
| 2099 | // The intrinsic will be sunk behind a compare against zero and branch. |
| 2100 | BasicBlock *StartBlock = CountZeros->getParent(); |
| 2101 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); |
| 2102 | |
| 2103 | // Create another block after the count zero intrinsic. A PHI will be added |
| 2104 | // in this block to select the result of the intrinsic or the bit-width |
| 2105 | // constant if the input to the intrinsic is zero. |
| 2106 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); |
| 2107 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); |
| 2108 | |
| 2109 | // Set up a builder to create a compare, conditional branch, and PHI. |
| 2110 | IRBuilder<> Builder(CountZeros->getContext()); |
| 2111 | Builder.SetInsertPoint(StartBlock->getTerminator()); |
| 2112 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); |
| 2113 | |
| 2114 | // Replace the unconditional branch that was created by the first split with |
| 2115 | // a compare against zero and a conditional branch. |
| 2116 | Value *Zero = Constant::getNullValue(Ty); |
| 2117 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); |
| 2118 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); |
| 2119 | StartBlock->getTerminator()->eraseFromParent(); |
| 2120 | |
| 2121 | // Create a PHI in the end block to select either the output of the intrinsic |
| 2122 | // or the bit width of the operand. |
| 2123 | Builder.SetInsertPoint(&EndBlock->front()); |
| 2124 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); |
| 2125 | CountZeros->replaceAllUsesWith(PN); |
| 2126 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); |
| 2127 | PN->addIncoming(BitWidth, StartBlock); |
| 2128 | PN->addIncoming(CountZeros, CallBlock); |
| 2129 | |
| 2130 | // We are explicitly handling the zero case, so we can set the intrinsic's |
| 2131 | // undefined zero argument to 'true'. This will also prevent reprocessing the |
| 2132 | // intrinsic; we only despeculate when a zero input is defined. |
| 2133 | CountZeros->setArgOperand(1, Builder.getTrue()); |
| 2134 | ModifiedDT = true; |
| 2135 | return true; |
| 2136 | } |
| 2137 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2138 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2139 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2140 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2141 | // Lower inline assembly if we can. |
| 2142 | // If we found an inline asm expession, and if the target knows how to |
| 2143 | // lower it to normal LLVM code, do so now. |
| 2144 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 2145 | if (TLI->ExpandInlineAsm(CI)) { |
| 2146 | // Avoid invalidating the iterator. |
| 2147 | CurInstIterator = BB->begin(); |
| 2148 | // Avoid processing instructions out of order, which could cause |
| 2149 | // reuse before a value is defined. |
| 2150 | SunkAddrs.clear(); |
| 2151 | return true; |
| 2152 | } |
| 2153 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2154 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 2155 | return true; |
| 2156 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2157 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2158 | // Align the pointer arguments to this call if the target thinks it's a good |
| 2159 | // idea |
| 2160 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2161 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2162 | for (auto &Arg : CI->arg_operands()) { |
| 2163 | // We want to align both objects whose address is used directly and |
| 2164 | // objects whose address is used in casts and GEPs, though it only makes |
| 2165 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 2166 | // if size - offset meets the size threshold. |
| 2167 | if (!Arg->getType()->isPointerTy()) |
| 2168 | continue; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2169 | APInt Offset(DL->getPointerSizeInBits( |
| 2170 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 2171 | 0); |
| 2172 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2173 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2174 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 2175 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2176 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2177 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 2178 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2179 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2180 | // Global variables can only be aligned if they are defined in this |
| 2181 | // object (i.e. they are uniquely initialized in this object), and |
| 2182 | // over-aligning global variables that have an explicit section is |
| 2183 | // forbidden. |
| 2184 | GlobalVariable *GV; |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 2185 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && |
Tim Northover | 918f050 | 2016-07-18 18:28:52 +0000 | [diff] [blame] | 2186 | GV->getPointerAlignment(*DL) < PrefAlign && |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 2187 | DL->getTypeAllocSize(GV->getValueType()) >= |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2188 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 2189 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2190 | } |
| 2191 | // If this is a memcpy (or similar) then we may be able to improve the |
| 2192 | // alignment |
| 2193 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2194 | unsigned Align = getKnownAlignment(MI->getDest(), *DL); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2195 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2196 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL)); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 2197 | if (Align > MI->getAlignment()) |
| 2198 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 2199 | } |
| 2200 | } |
| 2201 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 2202 | // If we have a cold call site, try to sink addressing computation into the |
| 2203 | // cold block. This interacts with our handling for loads and stores to |
| 2204 | // ensure that we can fold all uses of a potential addressing computation |
| 2205 | // into their uses. TODO: generalize this to work over profiling data |
| 2206 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 2207 | for (auto &Arg : CI->arg_operands()) { |
| 2208 | if (!Arg->getType()->isPointerTy()) |
| 2209 | continue; |
| 2210 | unsigned AS = Arg->getType()->getPointerAddressSpace(); |
| 2211 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); |
| 2212 | } |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 2213 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2214 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2215 | if (II) { |
| 2216 | switch (II->getIntrinsicID()) { |
| 2217 | default: break; |
| 2218 | case Intrinsic::objectsize: { |
| 2219 | // Lower all uses of llvm.objectsize.* |
George Burgess IV | 3f08914 | 2016-12-20 23:46:36 +0000 | [diff] [blame] | 2220 | ConstantInt *RetVal = |
| 2221 | lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2222 | // Substituting this can cause recursive simplifications, which can |
| 2223 | // invalidate our iterator. Use a WeakVH to hold onto it in case this |
| 2224 | // happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 2225 | Value *CurValue = &*CurInstIterator; |
| 2226 | WeakVH IterHandle(CurValue); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 2227 | |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 2228 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 2229 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2230 | // If the iterator instruction was recursively deleted, start over at the |
| 2231 | // start of the block. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 2232 | if (IterHandle != CurValue) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2233 | CurInstIterator = BB->begin(); |
| 2234 | SunkAddrs.clear(); |
| 2235 | } |
| 2236 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 2237 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2238 | case Intrinsic::masked_load: { |
| 2239 | // Scalarize unsupported vector masked load |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 2240 | if (!TTI->isLegalMaskedLoad(CI->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2241 | scalarizeMaskedLoad(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2242 | ModifiedDT = true; |
| 2243 | return true; |
| 2244 | } |
| 2245 | return false; |
| 2246 | } |
| 2247 | case Intrinsic::masked_store: { |
Elena Demikhovsky | 20662e3 | 2015-10-19 07:43:38 +0000 | [diff] [blame] | 2248 | if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2249 | scalarizeMaskedStore(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2250 | ModifiedDT = true; |
| 2251 | return true; |
| 2252 | } |
| 2253 | return false; |
| 2254 | } |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 2255 | case Intrinsic::masked_gather: { |
| 2256 | if (!TTI->isLegalMaskedGather(CI->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2257 | scalarizeMaskedGather(CI); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 2258 | ModifiedDT = true; |
| 2259 | return true; |
| 2260 | } |
| 2261 | return false; |
| 2262 | } |
| 2263 | case Intrinsic::masked_scatter: { |
| 2264 | if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) { |
Sanjay Patel | 3388d1f | 2016-01-22 21:11:47 +0000 | [diff] [blame] | 2265 | scalarizeMaskedScatter(CI); |
Elena Demikhovsky | 0928585 | 2015-10-25 15:37:55 +0000 | [diff] [blame] | 2266 | ModifiedDT = true; |
| 2267 | return true; |
| 2268 | } |
| 2269 | return false; |
| 2270 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 2271 | case Intrinsic::aarch64_stlxr: |
| 2272 | case Intrinsic::aarch64_stxr: { |
| 2273 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 2274 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 2275 | ExtVal->getParent() == CI->getParent()) |
| 2276 | return false; |
| 2277 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 2278 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2279 | // Mark this instruction as "inserted by CGP", so that other |
| 2280 | // optimizations don't touch it. |
| 2281 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 2282 | return true; |
| 2283 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 2284 | case Intrinsic::invariant_group_barrier: |
| 2285 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 2286 | II->eraseFromParent(); |
| 2287 | return true; |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 2288 | |
| 2289 | case Intrinsic::cttz: |
| 2290 | case Intrinsic::ctlz: |
| 2291 | // If counting zeros is expensive, try to avoid it. |
| 2292 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2293 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2294 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2295 | if (TLI) { |
| 2296 | SmallVector<Value*, 2> PtrOps; |
| 2297 | Type *AccessTy; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 2298 | if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) |
| 2299 | while (!PtrOps.empty()) { |
| 2300 | Value *PtrVal = PtrOps.pop_back_val(); |
| 2301 | unsigned AS = PtrVal->getType()->getPointerAddressSpace(); |
| 2302 | if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2303 | return true; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 2304 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 2305 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 2306 | } |
| 2307 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2308 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2309 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 2310 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 2311 | // Lower all default uses of _chk calls. This is very similar |
| 2312 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2313 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 2314 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 2315 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 2316 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 2317 | CI->replaceAllUsesWith(V); |
| 2318 | CI->eraseFromParent(); |
| 2319 | return true; |
| 2320 | } |
| 2321 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 2322 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 2323 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2324 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 2325 | /// 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] | 2326 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2327 | /// bb0: |
| 2328 | /// %tmp0 = tail call i32 @f0() |
| 2329 | /// br label %return |
| 2330 | /// bb1: |
| 2331 | /// %tmp1 = tail call i32 @f1() |
| 2332 | /// br label %return |
| 2333 | /// bb2: |
| 2334 | /// %tmp2 = tail call i32 @f2() |
| 2335 | /// br label %return |
| 2336 | /// return: |
| 2337 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 2338 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2339 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2340 | /// |
| 2341 | /// => |
| 2342 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2343 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2344 | /// bb0: |
| 2345 | /// %tmp0 = tail call i32 @f0() |
| 2346 | /// ret i32 %tmp0 |
| 2347 | /// bb1: |
| 2348 | /// %tmp1 = tail call i32 @f1() |
| 2349 | /// ret i32 %tmp1 |
| 2350 | /// bb2: |
| 2351 | /// %tmp2 = tail call i32 @f2() |
| 2352 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 2353 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2354 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 2355 | if (!TLI) |
| 2356 | return false; |
| 2357 | |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2358 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 2359 | if (!RetI) |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 2360 | return false; |
| 2361 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2362 | PHINode *PN = nullptr; |
| 2363 | BitCastInst *BCI = nullptr; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2364 | Value *V = RetI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 2365 | if (V) { |
| 2366 | BCI = dyn_cast<BitCastInst>(V); |
| 2367 | if (BCI) |
| 2368 | V = BCI->getOperand(0); |
| 2369 | |
| 2370 | PN = dyn_cast<PHINode>(V); |
| 2371 | if (!PN) |
| 2372 | return false; |
| 2373 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2374 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2375 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2376 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2377 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2378 | // Make sure there are no instructions between the PHI and return, or that the |
| 2379 | // return is the first instruction in the block. |
| 2380 | if (PN) { |
| 2381 | BasicBlock::iterator BI = BB->begin(); |
| 2382 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 2383 | if (&*BI == BCI) |
| 2384 | // Also skip over the bitcast. |
| 2385 | ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2386 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2387 | return false; |
| 2388 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2389 | BasicBlock::iterator BI = BB->begin(); |
| 2390 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2391 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2392 | return false; |
| 2393 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2394 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2395 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 2396 | /// call. |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2397 | const Function *F = BB->getParent(); |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2398 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2399 | if (PN) { |
| 2400 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 2401 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 2402 | // Make sure the phi value is indeed produced by the tail call. |
| 2403 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2404 | TLI->mayBeEmittedAsTailCall(CI) && |
| 2405 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2406 | TailCalls.push_back(CI); |
| 2407 | } |
| 2408 | } else { |
| 2409 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2410 | 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] | 2411 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2412 | continue; |
| 2413 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 2414 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2415 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 2416 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2417 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 2418 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2419 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 2420 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2421 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 2422 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && |
| 2423 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 2424 | TailCalls.push_back(CI); |
| 2425 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2426 | } |
| 2427 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2428 | bool Changed = false; |
| 2429 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 2430 | CallInst *CI = TailCalls[i]; |
| 2431 | CallSite CS(CI); |
| 2432 | |
| 2433 | // Conservatively require the attributes of the call to match those of the |
| 2434 | // return. Ignore noalias because it doesn't affect the call sequence. |
Reid Kleckner | b518054 | 2017-03-21 16:57:19 +0000 | [diff] [blame] | 2435 | AttributeList CalleeAttrs = CS.getAttributes(); |
| 2436 | if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 2437 | .removeAttribute(Attribute::NoAlias) != |
| 2438 | AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 2439 | .removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2440 | continue; |
| 2441 | |
| 2442 | // Make sure the call instruction is followed by an unconditional branch to |
| 2443 | // the return block. |
| 2444 | BasicBlock *CallBB = CI->getParent(); |
| 2445 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 2446 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 2447 | continue; |
| 2448 | |
| 2449 | // Duplicate the return into CallBB. |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2450 | (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 2451 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2452 | ++NumRetsDup; |
| 2453 | } |
| 2454 | |
| 2455 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 2456 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2457 | BB->eraseFromParent(); |
| 2458 | |
| 2459 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2460 | } |
| 2461 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2462 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2463 | // Memory Optimization |
| 2464 | //===----------------------------------------------------------------------===// |
| 2465 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2466 | namespace { |
| 2467 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2468 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2469 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 2470 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2471 | Value *BaseReg; |
| 2472 | Value *ScaledReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2473 | ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {} |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2474 | void print(raw_ostream &OS) const; |
| 2475 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2476 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2477 | bool operator==(const ExtAddrMode& O) const { |
| 2478 | return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) && |
| 2479 | (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) && |
| 2480 | (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale); |
| 2481 | } |
| 2482 | }; |
| 2483 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 2484 | #ifndef NDEBUG |
| 2485 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 2486 | AM.print(OS); |
| 2487 | return OS; |
| 2488 | } |
| 2489 | #endif |
| 2490 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2491 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 2492 | bool NeedPlus = false; |
| 2493 | OS << "["; |
| 2494 | if (BaseGV) { |
| 2495 | OS << (NeedPlus ? " + " : "") |
| 2496 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2497 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2498 | NeedPlus = true; |
| 2499 | } |
| 2500 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 2501 | if (BaseOffs) { |
| 2502 | OS << (NeedPlus ? " + " : "") |
| 2503 | << BaseOffs; |
| 2504 | NeedPlus = true; |
| 2505 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2506 | |
| 2507 | if (BaseReg) { |
| 2508 | OS << (NeedPlus ? " + " : "") |
| 2509 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2510 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2511 | NeedPlus = true; |
| 2512 | } |
| 2513 | if (Scale) { |
| 2514 | OS << (NeedPlus ? " + " : "") |
| 2515 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2516 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2517 | } |
| 2518 | |
| 2519 | OS << ']'; |
| 2520 | } |
| 2521 | |
| 2522 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Yaron Keren | eb2a254 | 2016-01-29 20:50:44 +0000 | [diff] [blame] | 2523 | LLVM_DUMP_METHOD void ExtAddrMode::dump() const { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2524 | print(dbgs()); |
| 2525 | dbgs() << '\n'; |
| 2526 | } |
| 2527 | #endif |
| 2528 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2529 | /// \brief This class provides transaction based operation on the IR. |
| 2530 | /// Every change made through this class is recorded in the internal state and |
| 2531 | /// can be undone (rollback) until commit is called. |
| 2532 | class TypePromotionTransaction { |
| 2533 | |
| 2534 | /// \brief This represents the common interface of the individual transaction. |
| 2535 | /// Each class implements the logic for doing one specific modification on |
| 2536 | /// the IR via the TypePromotionTransaction. |
| 2537 | class TypePromotionAction { |
| 2538 | protected: |
| 2539 | /// The Instruction modified. |
| 2540 | Instruction *Inst; |
| 2541 | |
| 2542 | public: |
| 2543 | /// \brief Constructor of the action. |
| 2544 | /// The constructor performs the related action on the IR. |
| 2545 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2546 | |
| 2547 | virtual ~TypePromotionAction() {} |
| 2548 | |
| 2549 | /// \brief Undo the modification done by this action. |
| 2550 | /// When this method is called, the IR must be in the same state as it was |
| 2551 | /// before this action was applied. |
| 2552 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2553 | /// state as it was directly after this action was applied. |
| 2554 | virtual void undo() = 0; |
| 2555 | |
| 2556 | /// \brief Advocate every change made by this action. |
| 2557 | /// When the results on the IR of the action are to be kept, it is important |
| 2558 | /// to call this function, otherwise hidden information may be kept forever. |
| 2559 | virtual void commit() { |
| 2560 | // Nothing to be done, this action is not doing anything. |
| 2561 | } |
| 2562 | }; |
| 2563 | |
| 2564 | /// \brief Utility to remember the position of an instruction. |
| 2565 | class InsertionHandler { |
| 2566 | /// Position of an instruction. |
| 2567 | /// Either an instruction: |
| 2568 | /// - Is the first in a basic block: BB is used. |
| 2569 | /// - Has a previous instructon: PrevInst is used. |
| 2570 | union { |
| 2571 | Instruction *PrevInst; |
| 2572 | BasicBlock *BB; |
| 2573 | } Point; |
| 2574 | /// Remember whether or not the instruction had a previous instruction. |
| 2575 | bool HasPrevInstruction; |
| 2576 | |
| 2577 | public: |
| 2578 | /// \brief Record the position of \p Inst. |
| 2579 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2580 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2581 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2582 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2583 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2584 | else |
| 2585 | Point.BB = Inst->getParent(); |
| 2586 | } |
| 2587 | |
| 2588 | /// \brief Insert \p Inst at the recorded position. |
| 2589 | void insert(Instruction *Inst) { |
| 2590 | if (HasPrevInstruction) { |
| 2591 | if (Inst->getParent()) |
| 2592 | Inst->removeFromParent(); |
| 2593 | Inst->insertAfter(Point.PrevInst); |
| 2594 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2595 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2596 | if (Inst->getParent()) |
| 2597 | Inst->moveBefore(Position); |
| 2598 | else |
| 2599 | Inst->insertBefore(Position); |
| 2600 | } |
| 2601 | } |
| 2602 | }; |
| 2603 | |
| 2604 | /// \brief Move an instruction before another. |
| 2605 | class InstructionMoveBefore : public TypePromotionAction { |
| 2606 | /// Original position of the instruction. |
| 2607 | InsertionHandler Position; |
| 2608 | |
| 2609 | public: |
| 2610 | /// \brief Move \p Inst before \p Before. |
| 2611 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2612 | : TypePromotionAction(Inst), Position(Inst) { |
| 2613 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 2614 | Inst->moveBefore(Before); |
| 2615 | } |
| 2616 | |
| 2617 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2618 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2619 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 2620 | Position.insert(Inst); |
| 2621 | } |
| 2622 | }; |
| 2623 | |
| 2624 | /// \brief Set the operand of an instruction with a new value. |
| 2625 | class OperandSetter : public TypePromotionAction { |
| 2626 | /// Original operand of the instruction. |
| 2627 | Value *Origin; |
| 2628 | /// Index of the modified instruction. |
| 2629 | unsigned Idx; |
| 2630 | |
| 2631 | public: |
| 2632 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 2633 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2634 | : TypePromotionAction(Inst), Idx(Idx) { |
| 2635 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2636 | << "for:" << *Inst << "\n" |
| 2637 | << "with:" << *NewVal << "\n"); |
| 2638 | Origin = Inst->getOperand(Idx); |
| 2639 | Inst->setOperand(Idx, NewVal); |
| 2640 | } |
| 2641 | |
| 2642 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2643 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2644 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2645 | << "for: " << *Inst << "\n" |
| 2646 | << "with: " << *Origin << "\n"); |
| 2647 | Inst->setOperand(Idx, Origin); |
| 2648 | } |
| 2649 | }; |
| 2650 | |
| 2651 | /// \brief Hide the operands of an instruction. |
| 2652 | /// Do as if this instruction was not using any of its operands. |
| 2653 | class OperandsHider : public TypePromotionAction { |
| 2654 | /// The list of original operands. |
| 2655 | SmallVector<Value *, 4> OriginalValues; |
| 2656 | |
| 2657 | public: |
| 2658 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 2659 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 2660 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 2661 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2662 | OriginalValues.reserve(NumOpnds); |
| 2663 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2664 | // Save the current operand. |
| 2665 | Value *Val = Inst->getOperand(It); |
| 2666 | OriginalValues.push_back(Val); |
| 2667 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2668 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2669 | // that we are not willing to pay. |
| 2670 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2671 | } |
| 2672 | } |
| 2673 | |
| 2674 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2675 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2676 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 2677 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2678 | Inst->setOperand(It, OriginalValues[It]); |
| 2679 | } |
| 2680 | }; |
| 2681 | |
| 2682 | /// \brief Build a truncate instruction. |
| 2683 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2684 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2685 | public: |
| 2686 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 2687 | /// result. |
| 2688 | /// trunc Opnd to Ty. |
| 2689 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2690 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2691 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 2692 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2693 | } |
| 2694 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2695 | /// \brief Get the built value. |
| 2696 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2697 | |
| 2698 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2699 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2700 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 2701 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2702 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2703 | } |
| 2704 | }; |
| 2705 | |
| 2706 | /// \brief Build a sign extension instruction. |
| 2707 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2708 | Value *Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2709 | public: |
| 2710 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 2711 | /// result. |
| 2712 | /// sext Opnd to Ty. |
| 2713 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2714 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2715 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2716 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 2717 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2718 | } |
| 2719 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2720 | /// \brief Get the built value. |
| 2721 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2722 | |
| 2723 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2724 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2725 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 2726 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2727 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2728 | } |
| 2729 | }; |
| 2730 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2731 | /// \brief Build a zero extension instruction. |
| 2732 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2733 | Value *Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2734 | public: |
| 2735 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 2736 | /// result. |
| 2737 | /// zext Opnd to Ty. |
| 2738 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2739 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2740 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2741 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 2742 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2743 | } |
| 2744 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2745 | /// \brief Get the built value. |
| 2746 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2747 | |
| 2748 | /// \brief Remove the built instruction. |
| 2749 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2750 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 2751 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2752 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2753 | } |
| 2754 | }; |
| 2755 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2756 | /// \brief Mutate an instruction to another type. |
| 2757 | class TypeMutator : public TypePromotionAction { |
| 2758 | /// Record the original type. |
| 2759 | Type *OrigTy; |
| 2760 | |
| 2761 | public: |
| 2762 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 2763 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2764 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 2765 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2766 | << "\n"); |
| 2767 | Inst->mutateType(NewTy); |
| 2768 | } |
| 2769 | |
| 2770 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2771 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2772 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2773 | << "\n"); |
| 2774 | Inst->mutateType(OrigTy); |
| 2775 | } |
| 2776 | }; |
| 2777 | |
| 2778 | /// \brief Replace the uses of an instruction by another instruction. |
| 2779 | class UsesReplacer : public TypePromotionAction { |
| 2780 | /// Helper structure to keep track of the replaced uses. |
| 2781 | struct InstructionAndIdx { |
| 2782 | /// The instruction using the instruction. |
| 2783 | Instruction *Inst; |
| 2784 | /// The index where this instruction is used for Inst. |
| 2785 | unsigned Idx; |
| 2786 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2787 | : Inst(Inst), Idx(Idx) {} |
| 2788 | }; |
| 2789 | |
| 2790 | /// Keep track of the original uses (pair Instruction, Index). |
| 2791 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
| 2792 | typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator; |
| 2793 | |
| 2794 | public: |
| 2795 | /// \brief Replace all the use of \p Inst by \p New. |
| 2796 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 2797 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2798 | << "\n"); |
| 2799 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2800 | for (Use &U : Inst->uses()) { |
| 2801 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2802 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2803 | } |
| 2804 | // Now, we can replace the uses. |
| 2805 | Inst->replaceAllUsesWith(New); |
| 2806 | } |
| 2807 | |
| 2808 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2809 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2810 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 2811 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2812 | EndIt = OriginalUses.end(); |
| 2813 | UseIt != EndIt; ++UseIt) { |
| 2814 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2815 | } |
| 2816 | } |
| 2817 | }; |
| 2818 | |
| 2819 | /// \brief Remove an instruction from the IR. |
| 2820 | class InstructionRemover : public TypePromotionAction { |
| 2821 | /// Original position of the instruction. |
| 2822 | InsertionHandler Inserter; |
| 2823 | /// Helper structure to hide all the link to the instruction. In other |
| 2824 | /// words, this helps to do as if the instruction was removed. |
| 2825 | OperandsHider Hider; |
| 2826 | /// Keep track of the uses replaced, if any. |
| 2827 | UsesReplacer *Replacer; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2828 | /// Keep track of instructions removed. |
| 2829 | SetOfInstrs &RemovedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2830 | |
| 2831 | public: |
| 2832 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 2833 | /// uses with New. |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2834 | /// \p RemovedInsts Keep track of the instructions removed by this Action. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2835 | /// \pre If !Inst->use_empty(), then New != nullptr |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2836 | InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts, |
| 2837 | Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2838 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2839 | Replacer(nullptr), RemovedInsts(RemovedInsts) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2840 | if (New) |
| 2841 | Replacer = new UsesReplacer(Inst, New); |
| 2842 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2843 | RemovedInsts.insert(Inst); |
| 2844 | /// The instructions removed here will be freed after completing |
| 2845 | /// optimizeBlock() for all blocks as we need to keep track of the |
| 2846 | /// removed instructions during promotion. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2847 | Inst->removeFromParent(); |
| 2848 | } |
| 2849 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2850 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2851 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2852 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 2853 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2854 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2855 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 2856 | Inserter.insert(Inst); |
| 2857 | if (Replacer) |
| 2858 | Replacer->undo(); |
| 2859 | Hider.undo(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2860 | RemovedInsts.erase(Inst); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2861 | } |
| 2862 | }; |
| 2863 | |
| 2864 | public: |
| 2865 | /// Restoration point. |
| 2866 | /// The restoration point is a pointer to an action instead of an iterator |
| 2867 | /// because the iterator may be invalidated but not the pointer. |
| 2868 | typedef const TypePromotionAction *ConstRestorationPt; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2869 | |
| 2870 | TypePromotionTransaction(SetOfInstrs &RemovedInsts) |
| 2871 | : RemovedInsts(RemovedInsts) {} |
| 2872 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2873 | /// Advocate every changes made in that transaction. |
| 2874 | void commit(); |
| 2875 | /// Undo all the changes made after the given point. |
| 2876 | void rollback(ConstRestorationPt Point); |
| 2877 | /// Get the current restoration point. |
| 2878 | ConstRestorationPt getRestorationPoint() const; |
| 2879 | |
| 2880 | /// \name API for IR modification with state keeping to support rollback. |
| 2881 | /// @{ |
| 2882 | /// Same as Instruction::setOperand. |
| 2883 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
| 2884 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2885 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2886 | /// Same as Value::replaceAllUsesWith. |
| 2887 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
| 2888 | /// Same as Value::mutateType. |
| 2889 | void mutateType(Instruction *Inst, Type *NewTy); |
| 2890 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2891 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2892 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2893 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2894 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2895 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2896 | /// Same as Instruction::moveBefore. |
| 2897 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2898 | /// @} |
| 2899 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2900 | private: |
| 2901 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2902 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
| 2903 | typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2904 | SetOfInstrs &RemovedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2905 | }; |
| 2906 | |
| 2907 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2908 | Value *NewVal) { |
| 2909 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2910 | make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2911 | } |
| 2912 | |
| 2913 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2914 | Value *NewVal) { |
| 2915 | Actions.push_back( |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2916 | make_unique<TypePromotionTransaction::InstructionRemover>(Inst, |
| 2917 | RemovedInsts, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2918 | } |
| 2919 | |
| 2920 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2921 | Value *New) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2922 | Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2923 | } |
| 2924 | |
| 2925 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2926 | Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2927 | } |
| 2928 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2929 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2930 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2931 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2932 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2933 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2934 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2935 | } |
| 2936 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2937 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2938 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2939 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2940 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2941 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2942 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2943 | } |
| 2944 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2945 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2946 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2947 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2948 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2949 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2950 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2951 | } |
| 2952 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2953 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2954 | Instruction *Before) { |
| 2955 | Actions.push_back( |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2956 | make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2957 | } |
| 2958 | |
| 2959 | TypePromotionTransaction::ConstRestorationPt |
| 2960 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2961 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2962 | } |
| 2963 | |
| 2964 | void TypePromotionTransaction::commit() { |
| 2965 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2966 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2967 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2968 | Actions.clear(); |
| 2969 | } |
| 2970 | |
| 2971 | void TypePromotionTransaction::rollback( |
| 2972 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2973 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2974 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2975 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2976 | } |
| 2977 | } |
| 2978 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2979 | /// \brief A helper class for matching addressing modes. |
| 2980 | /// |
| 2981 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2982 | class AddressingModeMatcher { |
| 2983 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
| 2984 | const TargetLowering &TLI; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2985 | const TargetRegisterInfo &TRI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2986 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2987 | |
| 2988 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2989 | /// the memory instruction that we're computing this address for. |
| 2990 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2991 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2992 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2993 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2994 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2995 | /// part of the return value of this addressing mode matching stuff. |
| 2996 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2997 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2998 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2999 | const SetOfInstrs &InsertedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3000 | /// A map from the instructions to their type before promotion. |
| 3001 | InstrToOrigTy &PromotedInsts; |
| 3002 | /// The ongoing transaction where every action should be registered. |
| 3003 | TypePromotionTransaction &TPT; |
| 3004 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3005 | /// This is set to true when we should not do profitability checks. |
| 3006 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3007 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3008 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3009 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3010 | const TargetLowering &TLI, |
| 3011 | const TargetRegisterInfo &TRI, |
| 3012 | Type *AT, unsigned AS, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3013 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3014 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3015 | InstrToOrigTy &PromotedInsts, |
| 3016 | TypePromotionTransaction &TPT) |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3017 | : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3018 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 3019 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
| 3020 | PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3021 | IgnoreProfitability = false; |
| 3022 | } |
| 3023 | public: |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3024 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3025 | /// 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] | 3026 | /// give an access type of AccessTy. This returns a list of involved |
| 3027 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3028 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3029 | /// optimizations. |
| 3030 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 3031 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3032 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3033 | Instruction *MemoryInst, |
| 3034 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3035 | const TargetLowering &TLI, |
| 3036 | const TargetRegisterInfo &TRI, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3037 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3038 | InstrToOrigTy &PromotedInsts, |
| 3039 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3040 | ExtAddrMode Result; |
| 3041 | |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3042 | bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, |
| 3043 | AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3044 | MemoryInst, Result, InsertedInsts, |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3045 | PromotedInsts, TPT).matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3046 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 3047 | return Result; |
| 3048 | } |
| 3049 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3050 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 3051 | bool matchAddr(Value *V, unsigned Depth); |
| 3052 | bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3053 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3054 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3055 | ExtAddrMode &AMBefore, |
| 3056 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3057 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 3058 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3059 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3060 | }; |
| 3061 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3062 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3063 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 3064 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3065 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3066 | unsigned Depth) { |
| 3067 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 3068 | // mode. Just process that directly. |
| 3069 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3070 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3071 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3072 | // If the scale is 0, it takes nothing to add this. |
| 3073 | if (Scale == 0) |
| 3074 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3075 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3076 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 3077 | // need an available scale field. |
| 3078 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 3079 | return false; |
| 3080 | |
| 3081 | ExtAddrMode TestAddrMode = AddrMode; |
| 3082 | |
| 3083 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 3084 | // [A+B + A*7] -> [B+A*8]. |
| 3085 | TestAddrMode.Scale += Scale; |
| 3086 | TestAddrMode.ScaledReg = ScaleReg; |
| 3087 | |
| 3088 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3089 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3090 | return false; |
| 3091 | |
| 3092 | // It was legal, so commit it. |
| 3093 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3094 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3095 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 3096 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 3097 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3098 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3099 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 3100 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 3101 | TestAddrMode.ScaledReg = AddLHS; |
| 3102 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3103 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3104 | // If this addressing mode is legal, commit it and remember that we folded |
| 3105 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3106 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3107 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 3108 | AddrMode = TestAddrMode; |
| 3109 | return true; |
| 3110 | } |
| 3111 | } |
| 3112 | |
| 3113 | // Otherwise, not (x+c)*scale, just return what we have. |
| 3114 | return true; |
| 3115 | } |
| 3116 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3117 | /// This is a little filter, which returns true if an addressing computation |
| 3118 | /// involving I might be folded into a load/store accessing it. |
| 3119 | /// 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] | 3120 | /// the set of instructions that MatchOperationAddr can. |
| 3121 | static bool MightBeFoldableInst(Instruction *I) { |
| 3122 | switch (I->getOpcode()) { |
| 3123 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 3124 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3125 | // Don't touch identity bitcasts. |
| 3126 | if (I->getType() == I->getOperand(0)->getType()) |
| 3127 | return false; |
| 3128 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 3129 | case Instruction::PtrToInt: |
| 3130 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 3131 | return true; |
| 3132 | case Instruction::IntToPtr: |
| 3133 | // We know the input is intptr_t, so this is foldable. |
| 3134 | return true; |
| 3135 | case Instruction::Add: |
| 3136 | return true; |
| 3137 | case Instruction::Mul: |
| 3138 | case Instruction::Shl: |
| 3139 | // Can only handle X*C and X << C. |
| 3140 | return isa<ConstantInt>(I->getOperand(1)); |
| 3141 | case Instruction::GetElementPtr: |
| 3142 | return true; |
| 3143 | default: |
| 3144 | return false; |
| 3145 | } |
| 3146 | } |
| 3147 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3148 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 3149 | /// \note \p Val is assumed to be the product of some type promotion. |
| 3150 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 3151 | /// 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] | 3152 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 3153 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3154 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 3155 | if (!PromotedInst) |
| 3156 | return false; |
| 3157 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 3158 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 3159 | if (!ISDOpcode) |
| 3160 | return true; |
| 3161 | // Otherwise, check if the promoted instruction is legal or not. |
| 3162 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3163 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3164 | } |
| 3165 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3166 | /// \brief Hepler class to perform type promotion. |
| 3167 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3168 | /// \brief Utility function to check whether or not a sign or zero extension |
| 3169 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 3170 | /// either using the operands of \p Inst or promoting \p Inst. |
| 3171 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3172 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3173 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3174 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3175 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3176 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3177 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3178 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3179 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 3180 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3181 | |
| 3182 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 3183 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3184 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3185 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3186 | } |
| 3187 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3188 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3189 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3190 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3191 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3192 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3193 | /// Newly added extensions are inserted in \p Exts. |
| 3194 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3195 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3196 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3197 | static Value *promoteOperandForTruncAndAnyExt( |
| 3198 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3199 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3200 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3201 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3202 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3203 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3204 | /// operand is promotable and is not a supported trunc or sext. |
| 3205 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3206 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3207 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3208 | /// Newly added extensions are inserted in \p Exts. |
| 3209 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3210 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3211 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3212 | static Value *promoteOperandForOther(Instruction *Ext, |
| 3213 | TypePromotionTransaction &TPT, |
| 3214 | InstrToOrigTy &PromotedInsts, |
| 3215 | unsigned &CreatedInstsCost, |
| 3216 | SmallVectorImpl<Instruction *> *Exts, |
| 3217 | SmallVectorImpl<Instruction *> *Truncs, |
| 3218 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3219 | |
| 3220 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3221 | static Value *signExtendOperandForOther( |
| 3222 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3223 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3224 | SmallVectorImpl<Instruction *> *Exts, |
| 3225 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3226 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3227 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3228 | } |
| 3229 | |
| 3230 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3231 | static Value *zeroExtendOperandForOther( |
| 3232 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3233 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3234 | SmallVectorImpl<Instruction *> *Exts, |
| 3235 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3236 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3237 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3238 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3239 | |
| 3240 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3241 | /// Type for the utility function that promotes the operand of Ext. |
| 3242 | typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3243 | InstrToOrigTy &PromotedInsts, |
| 3244 | unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3245 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3246 | SmallVectorImpl<Instruction *> *Truncs, |
| 3247 | const TargetLowering &TLI); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3248 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 3249 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3250 | /// \return NULL if no promotable action is possible with the current |
| 3251 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3252 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 3253 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3254 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 3255 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 3256 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3257 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3258 | const TargetLowering &TLI, |
| 3259 | const InstrToOrigTy &PromotedInsts); |
| 3260 | }; |
| 3261 | |
| 3262 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3263 | Type *ConsideredExtType, |
| 3264 | const InstrToOrigTy &PromotedInsts, |
| 3265 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3266 | // The promotion helper does not know how to deal with vector types yet. |
| 3267 | // To be able to fix that, we would need to fix the places where we |
| 3268 | // statically extend, e.g., constants and such. |
| 3269 | if (Inst->getType()->isVectorTy()) |
| 3270 | return false; |
| 3271 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3272 | // We can always get through zext. |
| 3273 | if (isa<ZExtInst>(Inst)) |
| 3274 | return true; |
| 3275 | |
| 3276 | // sext(sext) is ok too. |
| 3277 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3278 | return true; |
| 3279 | |
| 3280 | // We can get through binary operator, if it is legal. In other words, the |
| 3281 | // binary operator must have a nuw or nsw flag. |
| 3282 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 3283 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3284 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 3285 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3286 | return true; |
| 3287 | |
| 3288 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3289 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3290 | if (!isa<TruncInst>(Inst)) |
| 3291 | return false; |
| 3292 | |
| 3293 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3294 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3295 | // 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] | 3296 | if (!OpndVal->getType()->isIntegerTy() || |
| 3297 | OpndVal->getType()->getIntegerBitWidth() > |
| 3298 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3299 | return false; |
| 3300 | |
| 3301 | // If the operand of the truncate is not an instruction, we will not have |
| 3302 | // any information on the dropped bits. |
| 3303 | // (Actually we could for constant but it is not worth the extra logic). |
| 3304 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 3305 | if (!Opnd) |
| 3306 | return false; |
| 3307 | |
| 3308 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3309 | // I.e., check that trunc just drops extended bits of the same kind of |
| 3310 | // the extension. |
| 3311 | // #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] | 3312 | const Type *OpndType; |
| 3313 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 3314 | if (It != PromotedInsts.end() && It->second.getInt() == IsSExt) |
| 3315 | OpndType = It->second.getPointer(); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3316 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 3317 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3318 | else |
| 3319 | return false; |
| 3320 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3321 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3322 | return Inst->getType()->getIntegerBitWidth() >= |
| 3323 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3324 | } |
| 3325 | |
| 3326 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3327 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3328 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3329 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 3330 | "Unexpected instruction type"); |
| 3331 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 3332 | Type *ExtTy = Ext->getType(); |
| 3333 | bool IsSExt = isa<SExtInst>(Ext); |
| 3334 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3335 | // get through. |
| 3336 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3337 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3338 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3339 | |
| 3340 | // Do not promote if the operand has been added by codegenprepare. |
| 3341 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 3342 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3343 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3344 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3345 | |
| 3346 | // SExt or Trunc instructions. |
| 3347 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3348 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 3349 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3350 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3351 | |
| 3352 | // Regular instruction. |
| 3353 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3354 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3355 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3356 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3357 | } |
| 3358 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3359 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3360 | llvm::Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3361 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3362 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3363 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3364 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 3365 | // get through it and this method should not be called. |
| 3366 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3367 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3368 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3369 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3370 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3371 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3372 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3373 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3374 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 3375 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 3376 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3377 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3378 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3379 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 3380 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3381 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 3382 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3383 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3384 | |
| 3385 | // Remove dead code. |
| 3386 | if (SExtOpnd->use_empty()) |
| 3387 | TPT.eraseInstruction(SExtOpnd); |
| 3388 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3389 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3390 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3391 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3392 | if (ExtInst) { |
| 3393 | if (Exts) |
| 3394 | Exts->push_back(ExtInst); |
| 3395 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 3396 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3397 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3398 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3399 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3400 | // At this point we have: ext ty opnd to ty. |
| 3401 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 3402 | Value *NextVal = ExtInst->getOperand(0); |
| 3403 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3404 | return NextVal; |
| 3405 | } |
| 3406 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3407 | Value *TypePromotionHelper::promoteOperandForOther( |
| 3408 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3409 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3410 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3411 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 3412 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3413 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3414 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3415 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3416 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3417 | if (!ExtOpnd->hasOneUse()) { |
| 3418 | // ExtOpnd will be promoted. |
| 3419 | // 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] | 3420 | // promoted version. |
| 3421 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3422 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3423 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
| 3424 | ITrunc->removeFromParent(); |
| 3425 | // Insert it just after the definition. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3426 | ITrunc->insertAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3427 | if (Truncs) |
| 3428 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3429 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3430 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3431 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3432 | // 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] | 3433 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3434 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3435 | } |
| 3436 | |
| 3437 | // Get through the Instruction: |
| 3438 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3439 | // 2. Replace the uses of Ext by Inst. |
| 3440 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3441 | |
| 3442 | // Remember the original type of the instruction before promotion. |
| 3443 | // 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] | 3444 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 3445 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3446 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3447 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3448 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3449 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3450 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3451 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3452 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3453 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 3454 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3455 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3456 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 3457 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 3458 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3459 | DEBUG(dbgs() << "No need to propagate\n"); |
| 3460 | continue; |
| 3461 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3462 | // Check if we can statically extend the operand. |
| 3463 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3464 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3465 | DEBUG(dbgs() << "Statically extend\n"); |
| 3466 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 3467 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 3468 | : Cst->getValue().zext(BitWidth); |
| 3469 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3470 | continue; |
| 3471 | } |
| 3472 | // UndefValue are typed, so we have to statically sign extend them. |
| 3473 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3474 | DEBUG(dbgs() << "Statically extend\n"); |
| 3475 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3476 | continue; |
| 3477 | } |
| 3478 | |
| 3479 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3480 | // Check if Ext was reused to extend an operand. |
| 3481 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3482 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3483 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 3484 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 3485 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 3486 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 3487 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 3488 | continue; |
| 3489 | } |
| 3490 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3491 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3492 | if (Exts) |
| 3493 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3494 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3495 | |
| 3496 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3497 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 3498 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3499 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3500 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3501 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3502 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3503 | if (ExtForOpnd == Ext) { |
| 3504 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 3505 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3506 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3507 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3508 | } |
| 3509 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3510 | /// 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] | 3511 | /// \p NewCost gives the cost of extension instructions created by the |
| 3512 | /// promotion. |
| 3513 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 3514 | /// plus the number of instructions that have been |
| 3515 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3516 | /// \p PromotedOperand is the value that has been promoted. |
| 3517 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3518 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3519 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 3520 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 3521 | // The cost of the new extensions is greater than the cost of the |
| 3522 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3523 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3524 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3525 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3526 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3527 | return true; |
| 3528 | // The promotion is neutral but it may help folding the sign extension in |
| 3529 | // loads for instance. |
| 3530 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3531 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3532 | } |
| 3533 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3534 | /// 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] | 3535 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3536 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3537 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 3538 | /// not AddrInst has to be folded into the addressing mode on success. |
| 3539 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 3540 | /// because it has been moved away. |
| 3541 | /// Thus AddrInst must not be added in the matched instructions. |
| 3542 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 3543 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 3544 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3545 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3546 | unsigned Depth, |
| 3547 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3548 | // Avoid exponential behavior on extremely deep expression trees. |
| 3549 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3550 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3551 | // By default, all matched instructions stay in place. |
| 3552 | if (MovedAway) |
| 3553 | *MovedAway = false; |
| 3554 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3555 | switch (Opcode) { |
| 3556 | case Instruction::PtrToInt: |
| 3557 | // 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] | 3558 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3559 | case Instruction::IntToPtr: { |
| 3560 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3561 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3562 | // 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] | 3563 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3564 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3565 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3566 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3567 | case Instruction::BitCast: |
| 3568 | // BitCast is always a noop, and we can handle it as long as it is |
| 3569 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 3570 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 3571 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 3572 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3573 | // and we don't want to mess around with them. Assume it knows what it |
| 3574 | // is doing. |
| 3575 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3576 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3577 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3578 | case Instruction::AddrSpaceCast: { |
| 3579 | unsigned SrcAS |
| 3580 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3581 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3582 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3583 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3584 | return false; |
| 3585 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3586 | case Instruction::Add: { |
| 3587 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3588 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3589 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3590 | // Start a transaction at this point. |
| 3591 | // The LHS may match but not the RHS. |
| 3592 | // Therefore, we need a higher level restoration point to undo partially |
| 3593 | // matched operation. |
| 3594 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3595 | TPT.getRestorationPoint(); |
| 3596 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3597 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3598 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3599 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3600 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3601 | // Restore the old addr mode info. |
| 3602 | AddrMode = BackupAddrMode; |
| 3603 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3604 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3605 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3606 | // 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] | 3607 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3608 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3609 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3610 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3611 | // Otherwise we definitely can't merge the ADD in. |
| 3612 | AddrMode = BackupAddrMode; |
| 3613 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3614 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3615 | break; |
| 3616 | } |
| 3617 | //case Instruction::Or: |
| 3618 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3619 | //break; |
| 3620 | case Instruction::Mul: |
| 3621 | case Instruction::Shl: { |
| 3622 | // Can only handle X*C and X << C. |
| 3623 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3624 | if (!RHS) |
| 3625 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3626 | int64_t Scale = RHS->getSExtValue(); |
| 3627 | if (Opcode == Instruction::Shl) |
| 3628 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3629 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3630 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3631 | } |
| 3632 | case Instruction::GetElementPtr: { |
| 3633 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3634 | // one variable offset. |
| 3635 | int VariableOperand = -1; |
| 3636 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3637 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3638 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3639 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3640 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 3641 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3642 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3643 | unsigned Idx = |
| 3644 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3645 | ConstantOffset += SL->getElementOffset(Idx); |
| 3646 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3647 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3648 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 3649 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 3650 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 3651 | // We only allow one variable index at the moment. |
| 3652 | if (VariableOperand != -1) |
| 3653 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3654 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3655 | // Remember the variable index. |
| 3656 | VariableOperand = i; |
| 3657 | VariableScale = TypeSize; |
| 3658 | } |
| 3659 | } |
| 3660 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3661 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3662 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3663 | // just add it to the disp field and check validity. |
| 3664 | if (VariableOperand == -1) { |
| 3665 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3666 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3667 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3668 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3669 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3670 | return true; |
| 3671 | } |
| 3672 | AddrMode.BaseOffs -= ConstantOffset; |
| 3673 | return false; |
| 3674 | } |
| 3675 | |
| 3676 | // Save the valid addressing mode in case we can't match. |
| 3677 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3678 | unsigned OldSize = AddrModeInsts.size(); |
| 3679 | |
| 3680 | // See if the scale and offset amount is valid for this target. |
| 3681 | AddrMode.BaseOffs += ConstantOffset; |
| 3682 | |
| 3683 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3684 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3685 | // If it couldn't be matched, just stuff the value in a register. |
| 3686 | if (AddrMode.HasBaseReg) { |
| 3687 | AddrMode = BackupAddrMode; |
| 3688 | AddrModeInsts.resize(OldSize); |
| 3689 | return false; |
| 3690 | } |
| 3691 | AddrMode.HasBaseReg = true; |
| 3692 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3693 | } |
| 3694 | |
| 3695 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3696 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3697 | Depth)) { |
| 3698 | // If it couldn't be matched, try stuffing the base into a register |
| 3699 | // instead of matching it, and retrying the match of the scale. |
| 3700 | AddrMode = BackupAddrMode; |
| 3701 | AddrModeInsts.resize(OldSize); |
| 3702 | if (AddrMode.HasBaseReg) |
| 3703 | return false; |
| 3704 | AddrMode.HasBaseReg = true; |
| 3705 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3706 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3707 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3708 | VariableScale, Depth)) { |
| 3709 | // If even that didn't work, bail. |
| 3710 | AddrMode = BackupAddrMode; |
| 3711 | AddrModeInsts.resize(OldSize); |
| 3712 | return false; |
| 3713 | } |
| 3714 | } |
| 3715 | |
| 3716 | return true; |
| 3717 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3718 | case Instruction::SExt: |
| 3719 | case Instruction::ZExt: { |
| 3720 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3721 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3722 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3723 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3724 | // 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] | 3725 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3726 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3727 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3728 | if (!TPH) |
| 3729 | return false; |
| 3730 | |
| 3731 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3732 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3733 | unsigned CreatedInstsCost = 0; |
| 3734 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3735 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3736 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3737 | // SExt has been moved away. |
| 3738 | // Thus either it will be rematched later in the recursive calls or it is |
| 3739 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3740 | // E.g., |
| 3741 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3742 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3743 | // addr = gep base, idx |
| 3744 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3745 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3746 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3747 | // addr = gep base, op <- match |
| 3748 | if (MovedAway) |
| 3749 | *MovedAway = true; |
| 3750 | |
| 3751 | assert(PromotedOperand && |
| 3752 | "TypePromotionHelper should have filtered out those cases"); |
| 3753 | |
| 3754 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3755 | unsigned OldSize = AddrModeInsts.size(); |
| 3756 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3757 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3758 | // 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] | 3759 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3760 | // 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] | 3761 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3762 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3763 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3764 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3765 | AddrMode = BackupAddrMode; |
| 3766 | AddrModeInsts.resize(OldSize); |
| 3767 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 3768 | TPT.rollback(LastKnownGood); |
| 3769 | return false; |
| 3770 | } |
| 3771 | return true; |
| 3772 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3773 | } |
| 3774 | return false; |
| 3775 | } |
| 3776 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3777 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 3778 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 3779 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 3780 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3781 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3782 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3783 | // Start a transaction at this point that we will rollback if the matching |
| 3784 | // fails. |
| 3785 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3786 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3787 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 3788 | // Fold in immediates if legal for the target. |
| 3789 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3790 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3791 | return true; |
| 3792 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 3793 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 3794 | // 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] | 3795 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3796 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3797 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3798 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3799 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3800 | } |
| 3801 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 3802 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3803 | unsigned OldSize = AddrModeInsts.size(); |
| 3804 | |
| 3805 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3806 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3807 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3808 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3809 | // to check here. |
| 3810 | if (MovedAway) |
| 3811 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3812 | // Okay, it's possible to fold this. Check to see if it is actually |
| 3813 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 3814 | // register pressure too much. |
| 3815 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3816 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3817 | AddrModeInsts.push_back(I); |
| 3818 | return true; |
| 3819 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3820 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3821 | // It isn't profitable to do this, roll back. |
| 3822 | //cerr << "NOT FOLDING: " << *I; |
| 3823 | AddrMode = BackupAddrMode; |
| 3824 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3825 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3826 | } |
| 3827 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3828 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3829 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3830 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3831 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 3832 | // Null pointer gets folded without affecting the addressing mode. |
| 3833 | return true; |
| 3834 | } |
| 3835 | |
| 3836 | // Worse case, the target should support [reg] addressing modes. :) |
| 3837 | if (!AddrMode.HasBaseReg) { |
| 3838 | AddrMode.HasBaseReg = true; |
| 3839 | AddrMode.BaseReg = Addr; |
| 3840 | // 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] | 3841 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3842 | return true; |
| 3843 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3844 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3845 | } |
| 3846 | |
| 3847 | // If the base register is already taken, see if we can do [r+r]. |
| 3848 | if (AddrMode.Scale == 0) { |
| 3849 | AddrMode.Scale = 1; |
| 3850 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3851 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3852 | return true; |
| 3853 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3854 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3855 | } |
| 3856 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3857 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3858 | return false; |
| 3859 | } |
| 3860 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3861 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 3862 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3863 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3864 | const TargetLowering &TLI, |
| 3865 | const TargetRegisterInfo &TRI) { |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3866 | const Function *F = CI->getParent()->getParent(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 3867 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3868 | TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 3869 | ImmutableCallSite(CI)); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3870 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3871 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 3872 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3873 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3874 | // Compute the constraint code and ConstraintType to use. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3875 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3876 | |
| 3877 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 3878 | // operand, we can't fold it! |
| 3879 | if (OpInfo.CallOperandVal == OpVal && |
| 3880 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 3881 | !OpInfo.isIndirect)) |
| 3882 | return false; |
| 3883 | } |
| 3884 | |
| 3885 | return true; |
| 3886 | } |
| 3887 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3888 | /// Recursively walk all the uses of I until we find a memory use. |
| 3889 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3890 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 3891 | static bool FindAllMemoryUses( |
| 3892 | Instruction *I, |
| 3893 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3894 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, |
| 3895 | const TargetLowering &TLI, const TargetRegisterInfo &TRI) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3896 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 3897 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3898 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3899 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3900 | // If this is an obviously unfoldable instruction, bail out. |
| 3901 | if (!MightBeFoldableInst(I)) |
| 3902 | return true; |
| 3903 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3904 | const bool OptSize = I->getFunction()->optForSize(); |
| 3905 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3906 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3907 | for (Use &U : I->uses()) { |
| 3908 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3909 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3910 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 3911 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3912 | continue; |
| 3913 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3914 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3915 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 3916 | unsigned opNo = U.getOperandNo(); |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 3917 | if (opNo != StoreInst::getPointerOperandIndex()) |
| 3918 | return true; // Storing addr, not into addr. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3919 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 3920 | continue; |
| 3921 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3922 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 3923 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { |
| 3924 | unsigned opNo = U.getOperandNo(); |
| 3925 | if (opNo != AtomicRMWInst::getPointerOperandIndex()) |
| 3926 | return true; // Storing addr, not into addr. |
| 3927 | MemoryUses.push_back(std::make_pair(RMW, opNo)); |
| 3928 | continue; |
| 3929 | } |
| 3930 | |
| 3931 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { |
| 3932 | unsigned opNo = U.getOperandNo(); |
| 3933 | if (opNo != AtomicCmpXchgInst::getPointerOperandIndex()) |
| 3934 | return true; // Storing addr, not into addr. |
| 3935 | MemoryUses.push_back(std::make_pair(CmpX, opNo)); |
| 3936 | continue; |
| 3937 | } |
| 3938 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 3939 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 3940 | // If this is a cold call, we can sink the addressing calculation into |
| 3941 | // the cold path. See optimizeCallInst |
| 3942 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 3943 | continue; |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 3944 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3945 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 3946 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3947 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3948 | // If this is a memory operand, we're cool, otherwise bail out. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3949 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3950 | return true; |
| 3951 | continue; |
| 3952 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3953 | |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 3954 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3955 | return true; |
| 3956 | } |
| 3957 | |
| 3958 | return false; |
| 3959 | } |
| 3960 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3961 | /// Return true if Val is already known to be live at the use site that we're |
| 3962 | /// folding it into. If so, there is no cost to include it in the addressing |
| 3963 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 3964 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3965 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3966 | Value *KnownLive2) { |
| 3967 | // 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] | 3968 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3969 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3970 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3971 | // All values other than instructions and arguments (e.g. constants) are live. |
| 3972 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3973 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3974 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 3975 | // true because it is just a reference to the stack/frame pointer, which is |
| 3976 | // live for the whole function. |
| 3977 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 3978 | if (AI->isStaticAlloca()) |
| 3979 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3980 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3981 | // Check to see if this value is already used in the memory instruction's |
| 3982 | // block. If so, it's already live into the block at the very least, so we |
| 3983 | // can reasonably fold it. |
| 3984 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 3985 | } |
| 3986 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3987 | /// It is possible for the addressing mode of the machine to fold the specified |
| 3988 | /// instruction into a load or store that ultimately uses it. |
| 3989 | /// However, the specified instruction has multiple uses. |
| 3990 | /// Given this, it may actually increase register pressure to fold it |
| 3991 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3992 | /// |
| 3993 | /// X = ... |
| 3994 | /// Y = X+1 |
| 3995 | /// use(Y) -> nonload/store |
| 3996 | /// Z = Y+1 |
| 3997 | /// load Z |
| 3998 | /// |
| 3999 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 4000 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 4001 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 4002 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 4003 | /// number of computations either. |
| 4004 | /// |
| 4005 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 4006 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 4007 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 4008 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4009 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4010 | ExtAddrMode &AMAfter) { |
| 4011 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4012 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4013 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 4014 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 4015 | // the set of registers referenced by AMAfter and subtract out those |
| 4016 | // referenced by AMBefore: this is the set of values which folding in this |
| 4017 | // address extends the lifetime of. |
| 4018 | // |
| 4019 | // Note that there are only two potential values being referenced here, |
| 4020 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 4021 | // folded immediates). |
| 4022 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4023 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4024 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 4025 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4026 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4027 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4028 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4029 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4030 | |
| 4031 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 4032 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4033 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4034 | return true; |
| 4035 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4036 | // If all uses of this instruction can have the address mode sunk into them, |
| 4037 | // we can remove the addressing mode and effectively trade one live register |
| 4038 | // for another (at worst.) In this context, folding an addressing mode into |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 4039 | // the use is just a particularly nice way of sinking it. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4040 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 4041 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4042 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4043 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4044 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4045 | // Now that we know that all uses of this instruction are part of a chain of |
| 4046 | // computation involving only operations that could theoretically be folded |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4047 | // into a memory use, loop over each of these memory operation uses and see |
| 4048 | // if they could *actually* fold the instruction. The assumption is that |
| 4049 | // addressing modes are cheap and that duplicating the computation involved |
| 4050 | // many times is worthwhile, even on a fastpath. For sinking candidates |
| 4051 | // (i.e. cold call sites), this serves as a way to prevent excessive code |
| 4052 | // growth since most architectures have some reasonable small and fast way to |
| 4053 | // compute an effective address. (i.e LEA on x86) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4054 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 4055 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 4056 | Instruction *User = MemoryUses[i].first; |
| 4057 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4058 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4059 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 4060 | // know what it accesses. |
| 4061 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4062 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 4063 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4064 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4065 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 4066 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4067 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4068 | // Do a match against the root of this address, ignoring profitability. This |
| 4069 | // will tell us if the addressing mode for the memory operation will |
| 4070 | // *actually* cover the shared instruction. |
| 4071 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4072 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4073 | TPT.getRestorationPoint(); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4074 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, |
| 4075 | AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4076 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4077 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4078 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4079 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4080 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 4081 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4082 | // The match was to check the profitability, the changes made are not |
| 4083 | // part of the original matcher. Therefore, they should be dropped |
| 4084 | // otherwise the original matcher will not present the right state. |
| 4085 | TPT.rollback(LastKnownGood); |
| 4086 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4087 | // If the match didn't cover I, then it won't be shared by it. |
David Majnemer | 0d955d0 | 2016-08-11 22:21:41 +0000 | [diff] [blame] | 4088 | if (!is_contained(MatchedAddrModeInsts, I)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4089 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4090 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4091 | MatchedAddrModeInsts.clear(); |
| 4092 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4093 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4094 | return true; |
| 4095 | } |
| 4096 | |
| 4097 | } // end anonymous namespace |
| 4098 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4099 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4100 | /// different basic block than BB. |
| 4101 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 4102 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4103 | return I->getParent() != BB; |
| 4104 | return false; |
| 4105 | } |
| 4106 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4107 | /// Sink addressing mode computation immediate before MemoryInst if doing so |
| 4108 | /// can be done without increasing register pressure. The need for the |
| 4109 | /// register pressure constraint means this can end up being an all or nothing |
| 4110 | /// decision for all uses of the same addressing computation. |
| 4111 | /// |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4112 | /// Load and Store Instructions often have addressing modes that can do |
| 4113 | /// significant amounts of computation. As such, instruction selection will try |
| 4114 | /// to get the load or store to do as much computation as possible for the |
| 4115 | /// program. The problem is that isel can only see within a single block. As |
| 4116 | /// 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] | 4117 | /// |
| 4118 | /// This method is used to optimize both load/store and inline asms with memory |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4119 | /// operands. It's also used to sink addressing computations feeding into cold |
| 4120 | /// call sites into their (cold) basic block. |
| 4121 | /// |
| 4122 | /// The motivation for handling sinking into cold blocks is that doing so can |
| 4123 | /// both enable other address mode sinking (by satisfying the register pressure |
| 4124 | /// constraint above), and reduce register pressure globally (by removing the |
| 4125 | /// addressing mode computation from the fast path entirely.). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4126 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4127 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4128 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4129 | |
| 4130 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4131 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 4132 | SmallVector<Value*, 8> worklist; |
| 4133 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4134 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4135 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4136 | // Use a worklist to iteratively look through PHI nodes, and ensure that |
| 4137 | // the addressing mode obtained from the non-PHI roots of the graph |
| 4138 | // are equivalent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4139 | Value *Consensus = nullptr; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4140 | unsigned NumUsesConsensus = 0; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 4141 | bool IsNumUsesConsensusValid = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4142 | SmallVector<Instruction*, 16> AddrModeInsts; |
| 4143 | ExtAddrMode AddrMode; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4144 | TypePromotionTransaction TPT(RemovedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4145 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4146 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4147 | while (!worklist.empty()) { |
| 4148 | Value *V = worklist.back(); |
| 4149 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4150 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4151 | // Break use-def graph loops. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4152 | if (!Visited.insert(V).second) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4153 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4154 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4155 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4156 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4157 | // For a PHI node, push all of its incoming values. |
| 4158 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 4159 | for (Value *IncValue : P->incoming_values()) |
| 4160 | worklist.push_back(IncValue); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4161 | continue; |
| 4162 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4163 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4164 | // For non-PHIs, determine the addressing mode being computed. Note that |
| 4165 | // the result may differ depending on what other uses our candidate |
| 4166 | // addressing instructions might have. |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4167 | SmallVector<Instruction*, 16> NewAddrModeInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4168 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4169 | V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4170 | InsertedInsts, PromotedInsts, TPT); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 4171 | |
| 4172 | // This check is broken into two cases with very similar code to avoid using |
| 4173 | // getNumUses() as much as possible. Some values have a lot of uses, so |
| 4174 | // calling getNumUses() unconditionally caused a significant compile-time |
| 4175 | // regression. |
| 4176 | if (!Consensus) { |
| 4177 | Consensus = V; |
| 4178 | AddrMode = NewAddrMode; |
| 4179 | AddrModeInsts = NewAddrModeInsts; |
| 4180 | continue; |
| 4181 | } else if (NewAddrMode == AddrMode) { |
| 4182 | if (!IsNumUsesConsensusValid) { |
| 4183 | NumUsesConsensus = Consensus->getNumUses(); |
| 4184 | IsNumUsesConsensusValid = true; |
| 4185 | } |
| 4186 | |
| 4187 | // Ensure that the obtained addressing mode is equivalent to that obtained |
| 4188 | // for all other roots of the PHI traversal. Also, when choosing one |
| 4189 | // such root as representative, select the one with the most uses in order |
| 4190 | // to keep the cost modeling heuristics in AddressingModeMatcher |
| 4191 | // applicable. |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4192 | unsigned NumUses = V->getNumUses(); |
| 4193 | if (NumUses > NumUsesConsensus) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4194 | Consensus = V; |
Cameron Zwarich | b7f8eaa | 2011-03-01 21:13:53 +0000 | [diff] [blame] | 4195 | NumUsesConsensus = NumUses; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4196 | AddrModeInsts = NewAddrModeInsts; |
| 4197 | } |
| 4198 | continue; |
| 4199 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4200 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4201 | Consensus = nullptr; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4202 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4203 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4204 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4205 | // If the addressing mode couldn't be determined, or if multiple different |
| 4206 | // ones were determined, bail out now. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4207 | if (!Consensus) { |
| 4208 | TPT.rollback(LastKnownGood); |
| 4209 | return false; |
| 4210 | } |
| 4211 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4212 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4213 | // If all the instructions matched are already in this BB, don't do anything. |
Justin Lebar | 838c7f5 | 2016-11-21 22:49:11 +0000 | [diff] [blame] | 4214 | if (none_of(AddrModeInsts, [&](Value *V) { |
| 4215 | return IsNonLocalValue(V, MemoryInst->getParent()); |
| 4216 | })) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4217 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4218 | return false; |
| 4219 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4220 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4221 | // Insert this computation right after this user. Since our caller is |
| 4222 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 4223 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4224 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4225 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4226 | // Now that we determined the addressing expression we want to use and know |
| 4227 | // that we have to sink it into this block. Check to see if we have already |
| 4228 | // done this for some other load/store instr in this block. If so, reuse the |
| 4229 | // computation. |
| 4230 | Value *&SunkAddr = SunkAddrs[Addr]; |
| 4231 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4232 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4233 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4234 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4235 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 4236 | } else if (AddrSinkUsingGEPs || |
| 4237 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4238 | SubtargetInfo->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4239 | // By default, we use the GEP-based method when AA is used later. This |
| 4240 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 4241 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4242 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4243 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4244 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4245 | |
| 4246 | // First, find the pointer. |
| 4247 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 4248 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4249 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4250 | } |
| 4251 | |
| 4252 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 4253 | // We can't add more than one pointer together, nor can we scale a |
| 4254 | // pointer (both of which seem meaningless). |
| 4255 | if (ResultPtr || AddrMode.Scale != 1) |
| 4256 | return false; |
| 4257 | |
| 4258 | ResultPtr = AddrMode.ScaledReg; |
| 4259 | AddrMode.Scale = 0; |
| 4260 | } |
| 4261 | |
| 4262 | if (AddrMode.BaseGV) { |
| 4263 | if (ResultPtr) |
| 4264 | return false; |
| 4265 | |
| 4266 | ResultPtr = AddrMode.BaseGV; |
| 4267 | } |
| 4268 | |
| 4269 | // If the real base value actually came from an inttoptr, then the matcher |
| 4270 | // will look through it and provide only the integer value. In that case, |
| 4271 | // use it here. |
| 4272 | if (!ResultPtr && AddrMode.BaseReg) { |
| 4273 | ResultPtr = |
| 4274 | Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr"); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4275 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4276 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 4277 | ResultPtr = |
| 4278 | Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr"); |
| 4279 | AddrMode.Scale = 0; |
| 4280 | } |
| 4281 | |
| 4282 | if (!ResultPtr && |
| 4283 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 4284 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 4285 | } else if (!ResultPtr) { |
| 4286 | return false; |
| 4287 | } else { |
| 4288 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4289 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 4290 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4291 | |
| 4292 | // Start with the base register. Do this first so that subsequent address |
| 4293 | // matching finds it last, which will prevent it from trying to match it |
| 4294 | // as the scaled value in case it happens to be a mul. That would be |
| 4295 | // problematic if we've sunk a different mul for the scale, because then |
| 4296 | // we'd end up sinking both muls. |
| 4297 | if (AddrMode.BaseReg) { |
| 4298 | Value *V = AddrMode.BaseReg; |
| 4299 | if (V->getType() != IntPtrTy) |
| 4300 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 4301 | |
| 4302 | ResultIndex = V; |
| 4303 | } |
| 4304 | |
| 4305 | // Add the scale value. |
| 4306 | if (AddrMode.Scale) { |
| 4307 | Value *V = AddrMode.ScaledReg; |
| 4308 | if (V->getType() == IntPtrTy) { |
| 4309 | // done. |
| 4310 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4311 | cast<IntegerType>(V->getType())->getBitWidth()) { |
| 4312 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
| 4313 | } else { |
| 4314 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4315 | // required to create it did not overflow before we extend it. Since |
| 4316 | // the original IR value was tossed in favor of a constant back when |
| 4317 | // the AddrMode was created we need to bail out gracefully if widths |
| 4318 | // do not match instead of extending it. |
| 4319 | Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex); |
| 4320 | if (I && (ResultIndex != AddrMode.BaseReg)) |
| 4321 | I->eraseFromParent(); |
| 4322 | return false; |
| 4323 | } |
| 4324 | |
| 4325 | if (AddrMode.Scale != 1) |
| 4326 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4327 | "sunkaddr"); |
| 4328 | if (ResultIndex) |
| 4329 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 4330 | else |
| 4331 | ResultIndex = V; |
| 4332 | } |
| 4333 | |
| 4334 | // Add in the Base Offset if present. |
| 4335 | if (AddrMode.BaseOffs) { |
| 4336 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 4337 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 4338 | // We need to add this separately from the scale above to help with |
| 4339 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4340 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4341 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4342 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4343 | } |
| 4344 | |
| 4345 | ResultIndex = V; |
| 4346 | } |
| 4347 | |
| 4348 | if (!ResultIndex) { |
| 4349 | SunkAddr = ResultPtr; |
| 4350 | } else { |
| 4351 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4352 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4353 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4354 | } |
| 4355 | |
| 4356 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4357 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4358 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4359 | } else { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4360 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4361 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4362 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4363 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4364 | |
| 4365 | // Start with the base register. Do this first so that subsequent address |
| 4366 | // matching finds it last, which will prevent it from trying to match it |
| 4367 | // as the scaled value in case it happens to be a mul. That would be |
| 4368 | // problematic if we've sunk a different mul for the scale, because then |
| 4369 | // we'd end up sinking both muls. |
| 4370 | if (AddrMode.BaseReg) { |
| 4371 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4372 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4373 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4374 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4375 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4376 | Result = V; |
| 4377 | } |
| 4378 | |
| 4379 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4380 | if (AddrMode.Scale) { |
| 4381 | Value *V = AddrMode.ScaledReg; |
| 4382 | if (V->getType() == IntPtrTy) { |
| 4383 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4384 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4385 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4386 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4387 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4388 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4389 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4390 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4391 | // required to create it did not overflow before we extend it. Since |
| 4392 | // the original IR value was tossed in favor of a constant back when |
| 4393 | // the AddrMode was created we need to bail out gracefully if widths |
| 4394 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 4395 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 4396 | if (I && (Result != AddrMode.BaseReg)) |
| 4397 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4398 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4399 | } |
| 4400 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4401 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4402 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4403 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4404 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4405 | else |
| 4406 | Result = V; |
| 4407 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4408 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4409 | // Add in the BaseGV if present. |
| 4410 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4411 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4412 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4413 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4414 | else |
| 4415 | Result = V; |
| 4416 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4417 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4418 | // Add in the Base Offset if present. |
| 4419 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4420 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4421 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4422 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4423 | else |
| 4424 | Result = V; |
| 4425 | } |
| 4426 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4427 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 4428 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4429 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4430 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4431 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4432 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4433 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4434 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4435 | // If we have no uses, recursively delete the value and all dead instructions |
| 4436 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4437 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4438 | // This can cause recursive deletion, which can invalidate our iterator. |
| 4439 | // Use a WeakVH to hold onto it in case this happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4440 | Value *CurValue = &*CurInstIterator; |
| 4441 | WeakVH IterHandle(CurValue); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4442 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4443 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 4444 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4445 | |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4446 | if (IterHandle != CurValue) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4447 | // If the iterator instruction was recursively deleted, start over at the |
| 4448 | // start of the block. |
| 4449 | CurInstIterator = BB->begin(); |
| 4450 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4451 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 4452 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4453 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4454 | return true; |
| 4455 | } |
| 4456 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4457 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 4458 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4459 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4460 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4461 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4462 | const TargetRegisterInfo *TRI = |
| 4463 | TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4464 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 4465 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4466 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 4467 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4468 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4469 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4470 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 4471 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4472 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 4473 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 4474 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4475 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4476 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4477 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 4478 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4479 | } |
| 4480 | |
| 4481 | return MadeChange; |
| 4482 | } |
| 4483 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4484 | /// \brief Check if all the uses of \p Val are equivalent (or free) zero or |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4485 | /// sign extensions. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4486 | static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { |
| 4487 | assert(!Val->use_empty() && "Input must have at least one use"); |
| 4488 | const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4489 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 4490 | Type *ExtTy = FirstUser->getType(); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4491 | for (const User *U : Val->users()) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4492 | const Instruction *UI = cast<Instruction>(U); |
| 4493 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 4494 | return false; |
| 4495 | Type *CurTy = UI->getType(); |
| 4496 | // Same input and output types: Same instruction after CSE. |
| 4497 | if (CurTy == ExtTy) |
| 4498 | continue; |
| 4499 | |
| 4500 | // If IsSExt is true, we are in this situation: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4501 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4502 | // b = sext ty1 a to ty2 |
| 4503 | // c = sext ty1 a to ty3 |
| 4504 | // Assuming ty2 is shorter than ty3, this could be turned into: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4505 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4506 | // b = sext ty1 a to ty2 |
| 4507 | // c = sext ty2 b to ty3 |
| 4508 | // However, the last sext is not free. |
| 4509 | if (IsSExt) |
| 4510 | return false; |
| 4511 | |
| 4512 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 4513 | // In that case, we would not account for a different use. |
| 4514 | Type *NarrowTy; |
| 4515 | Type *LargeTy; |
| 4516 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 4517 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 4518 | NarrowTy = CurTy; |
| 4519 | LargeTy = ExtTy; |
| 4520 | } else { |
| 4521 | NarrowTy = ExtTy; |
| 4522 | LargeTy = CurTy; |
| 4523 | } |
| 4524 | |
| 4525 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 4526 | return false; |
| 4527 | } |
| 4528 | // All uses are the same or can be derived from one another for free. |
| 4529 | return true; |
| 4530 | } |
| 4531 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4532 | /// \brief Try to speculatively promote extensions in \p Exts and continue |
| 4533 | /// promoting through newly promoted operands recursively as far as doing so is |
| 4534 | /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. |
| 4535 | /// When some promotion happened, \p TPT contains the proper state to revert |
| 4536 | /// them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4537 | /// |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4538 | /// \return true if some promotion happened, false otherwise. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4539 | bool CodeGenPrepare::tryToPromoteExts( |
| 4540 | TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, |
| 4541 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 4542 | unsigned CreatedInstsCost) { |
| 4543 | bool Promoted = false; |
| 4544 | |
| 4545 | // Iterate over all the extensions to try to promote them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4546 | for (auto I : Exts) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4547 | // Early check if we directly have ext(load). |
| 4548 | if (isa<LoadInst>(I->getOperand(0))) { |
| 4549 | ProfitablyMovedExts.push_back(I); |
| 4550 | continue; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4551 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4552 | |
| 4553 | // Check whether or not we want to do any promotion. The reason we have |
| 4554 | // this check inside the for loop is to catch the case where an extension |
| 4555 | // is directly fed by a load because in such case the extension can be moved |
| 4556 | // up without any promotion on its operands. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4557 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4558 | return false; |
| 4559 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4560 | // Get the action to perform the promotion. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4561 | TypePromotionHelper::Action TPH = |
| 4562 | TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4563 | // Check if we can promote. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4564 | if (!TPH) { |
| 4565 | // Save the current extension as we cannot move up through its operand. |
| 4566 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4567 | continue; |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4568 | } |
| 4569 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4570 | // Save the current state. |
| 4571 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4572 | TPT.getRestorationPoint(); |
| 4573 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4574 | unsigned NewCreatedInstsCost = 0; |
| 4575 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4576 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4577 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 4578 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4579 | assert(PromotedVal && |
| 4580 | "TypePromotionHelper should have filtered out those cases"); |
| 4581 | |
| 4582 | // We would be able to merge only one extension in a load. |
| 4583 | // Therefore, if we have more than 1 new extension we heuristically |
| 4584 | // cut this search path, because it means we degrade the code quality. |
| 4585 | // With exactly 2, the transformation is neutral, because we will merge |
| 4586 | // one extension but leave one. However, we optimistically keep going, |
| 4587 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4588 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4589 | // FIXME: It would be possible to propagate a negative value instead of |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4590 | // conservatively ceiling it to 0. |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4591 | TotalCreatedInstsCost = |
| 4592 | std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4593 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4594 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4595 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4596 | // This promotion is not profitable, rollback to the previous state, and |
| 4597 | // save the current extension in ProfitablyMovedExts as the latest |
| 4598 | // speculative promotion turned out to be unprofitable. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4599 | TPT.rollback(LastKnownGood); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4600 | ProfitablyMovedExts.push_back(I); |
| 4601 | continue; |
| 4602 | } |
| 4603 | // Continue promoting NewExts as far as doing so is profitable. |
| 4604 | SmallVector<Instruction *, 2> NewlyMovedExts; |
| 4605 | (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); |
| 4606 | bool NewPromoted = false; |
| 4607 | for (auto ExtInst : NewlyMovedExts) { |
| 4608 | Instruction *MovedExt = cast<Instruction>(ExtInst); |
| 4609 | Value *ExtOperand = MovedExt->getOperand(0); |
| 4610 | // If we have reached to a load, we need this extra profitability check |
| 4611 | // as it could potentially be merged into an ext(load). |
| 4612 | if (isa<LoadInst>(ExtOperand) && |
| 4613 | !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
| 4614 | (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) |
| 4615 | continue; |
| 4616 | |
| 4617 | ProfitablyMovedExts.push_back(MovedExt); |
| 4618 | NewPromoted = true; |
| 4619 | } |
| 4620 | |
| 4621 | // If none of speculative promotions for NewExts is profitable, rollback |
| 4622 | // and save the current extension (I) as the last profitable extension. |
| 4623 | if (!NewPromoted) { |
| 4624 | TPT.rollback(LastKnownGood); |
| 4625 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4626 | continue; |
| 4627 | } |
| 4628 | // The promotion is profitable. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4629 | Promoted = true; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4630 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4631 | return Promoted; |
| 4632 | } |
| 4633 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4634 | /// Merging redundant sexts when one is dominating the other. |
| 4635 | bool CodeGenPrepare::mergeSExts(Function &F) { |
| 4636 | DominatorTree DT(F); |
| 4637 | bool Changed = false; |
| 4638 | for (auto &Entry : ValToSExtendedUses) { |
| 4639 | SExts &Insts = Entry.second; |
| 4640 | SExts CurPts; |
| 4641 | for (Instruction *Inst : Insts) { |
| 4642 | if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) || |
| 4643 | Inst->getOperand(0) != Entry.first) |
| 4644 | continue; |
| 4645 | bool inserted = false; |
| 4646 | for (auto &Pt : CurPts) { |
| 4647 | if (DT.dominates(Inst, Pt)) { |
| 4648 | Pt->replaceAllUsesWith(Inst); |
| 4649 | RemovedInsts.insert(Pt); |
| 4650 | Pt->removeFromParent(); |
| 4651 | Pt = Inst; |
| 4652 | inserted = true; |
| 4653 | Changed = true; |
| 4654 | break; |
| 4655 | } |
| 4656 | if (!DT.dominates(Pt, Inst)) |
| 4657 | // Give up if we need to merge in a common dominator as the |
| 4658 | // expermients show it is not profitable. |
| 4659 | continue; |
| 4660 | Inst->replaceAllUsesWith(Pt); |
| 4661 | RemovedInsts.insert(Inst); |
| 4662 | Inst->removeFromParent(); |
| 4663 | inserted = true; |
| 4664 | Changed = true; |
| 4665 | break; |
| 4666 | } |
| 4667 | if (!inserted) |
| 4668 | CurPts.push_back(Inst); |
| 4669 | } |
| 4670 | } |
| 4671 | return Changed; |
| 4672 | } |
| 4673 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4674 | /// Return true, if an ext(load) can be formed from an extension in |
| 4675 | /// \p MovedExts. |
| 4676 | bool CodeGenPrepare::canFormExtLd( |
| 4677 | const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, |
| 4678 | Instruction *&Inst, bool HasPromoted) { |
| 4679 | for (auto *MovedExtInst : MovedExts) { |
| 4680 | if (isa<LoadInst>(MovedExtInst->getOperand(0))) { |
| 4681 | LI = cast<LoadInst>(MovedExtInst->getOperand(0)); |
| 4682 | Inst = MovedExtInst; |
| 4683 | break; |
| 4684 | } |
| 4685 | } |
| 4686 | if (!LI) |
| 4687 | return false; |
| 4688 | |
| 4689 | // If they're already in the same block, there's nothing to do. |
| 4690 | // Make the cheap checks first if we did not promote. |
| 4691 | // If we promoted, we need to check if it is indeed profitable. |
| 4692 | if (!HasPromoted && LI->getParent() == Inst->getParent()) |
| 4693 | return false; |
| 4694 | |
| 4695 | EVT VT = TLI->getValueType(*DL, Inst->getType()); |
| 4696 | EVT LoadVT = TLI->getValueType(*DL, LI->getType()); |
| 4697 | |
| 4698 | // If the load has other users and the truncate is not free, this probably |
| 4699 | // isn't worthwhile. |
| 4700 | if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) && |
| 4701 | !TLI->isTruncateFree(Inst->getType(), LI->getType())) |
| 4702 | return false; |
| 4703 | |
| 4704 | // Check whether the target supports casts folded into loads. |
| 4705 | unsigned LType; |
| 4706 | if (isa<ZExtInst>(Inst)) |
| 4707 | LType = ISD::ZEXTLOAD; |
| 4708 | else { |
| 4709 | assert(isa<SExtInst>(Inst) && "Unexpected ext type!"); |
| 4710 | LType = ISD::SEXTLOAD; |
| 4711 | } |
| 4712 | |
| 4713 | return TLI->isLoadExtLegal(LType, VT, LoadVT); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4714 | } |
| 4715 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4716 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 4717 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 4718 | /// extend into the load. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4719 | /// |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4720 | /// E.g., |
| 4721 | /// \code |
| 4722 | /// %ld = load i32* %addr |
| 4723 | /// %add = add nuw i32 %ld, 4 |
| 4724 | /// %zext = zext i32 %add to i64 |
| 4725 | // \endcode |
| 4726 | /// => |
| 4727 | /// \code |
| 4728 | /// %ld = load i32* %addr |
| 4729 | /// %zext = zext i32 %ld to i64 |
| 4730 | /// %add = add nuw i64 %zext, 4 |
| 4731 | /// \encode |
| 4732 | /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which |
| 4733 | /// allow us to match zext(load i32*) to i64. |
| 4734 | /// |
| 4735 | /// Also, try to promote the computations used to obtain a sign extended |
| 4736 | /// value used into memory accesses. |
| 4737 | /// E.g., |
| 4738 | /// \code |
| 4739 | /// a = add nsw i32 b, 3 |
| 4740 | /// d = sext i32 a to i64 |
| 4741 | /// e = getelementptr ..., i64 d |
| 4742 | /// \endcode |
| 4743 | /// => |
| 4744 | /// \code |
| 4745 | /// f = sext i32 b to i64 |
| 4746 | /// a = add nsw i64 f, 3 |
| 4747 | /// e = getelementptr ..., i64 a |
| 4748 | /// \endcode |
| 4749 | /// |
| 4750 | /// \p Inst[in/out] the extension may be modified during the process if some |
| 4751 | /// promotions apply. |
| 4752 | bool CodeGenPrepare::optimizeExt(Instruction *&Inst) { |
| 4753 | // ExtLoad formation and address type promotion infrastructure requires TLI to |
| 4754 | // be effective. |
Chandler Carruth | 0f139b4 | 2016-11-04 06:54:00 +0000 | [diff] [blame] | 4755 | if (!TLI) |
| 4756 | return false; |
| 4757 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4758 | bool AllowPromotionWithoutCommonHeader = false; |
| 4759 | /// See if it is an interesting sext operations for the address type |
| 4760 | /// promotion before trying to promote it, e.g., the ones with the right |
| 4761 | /// type and used in memory accesses. |
| 4762 | bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion( |
| 4763 | *Inst, AllowPromotionWithoutCommonHeader); |
| 4764 | TypePromotionTransaction TPT(RemovedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4765 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4766 | TPT.getRestorationPoint(); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4767 | SmallVector<Instruction *, 1> Exts; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4768 | SmallVector<Instruction *, 2> SpeculativelyMovedExts; |
| 4769 | Exts.push_back(Inst); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4770 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4771 | bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4772 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4773 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4774 | LoadInst *LI = nullptr; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4775 | Instruction *ExtFedByLoad; |
| 4776 | |
| 4777 | // Try to promote a chain of computation if it allows to form an extended |
| 4778 | // load. |
| 4779 | if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) { |
| 4780 | assert(LI && ExtFedByLoad && "Expect a valid load and extension"); |
| 4781 | TPT.commit(); |
| 4782 | // Move the extend into the same block as the load |
| 4783 | ExtFedByLoad->removeFromParent(); |
| 4784 | ExtFedByLoad->insertAfter(LI); |
| 4785 | // CGP does not check if the zext would be speculatively executed when moved |
| 4786 | // to the same basic block as the load. Preserving its original location |
| 4787 | // would pessimize the debugging experience, as well as negatively impact |
| 4788 | // the quality of sample pgo. We don't want to use "line 0" as that has a |
| 4789 | // size cost in the line-table section and logically the zext can be seen as |
| 4790 | // part of the load. Therefore we conservatively reuse the same debug |
| 4791 | // location for the load and the zext. |
| 4792 | ExtFedByLoad->setDebugLoc(LI->getDebugLoc()); |
| 4793 | ++NumExtsMoved; |
| 4794 | Inst = ExtFedByLoad; |
| 4795 | return true; |
| 4796 | } |
| 4797 | |
| 4798 | // Continue promoting SExts if known as considerable depending on targets. |
| 4799 | if (ATPConsiderable && |
| 4800 | performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader, |
| 4801 | HasPromoted, TPT, SpeculativelyMovedExts)) |
| 4802 | return true; |
| 4803 | |
| 4804 | TPT.rollback(LastKnownGood); |
| 4805 | return false; |
| 4806 | } |
| 4807 | |
| 4808 | // Perform address type promotion if doing so is profitable. |
| 4809 | // If AllowPromotionWithoutCommonHeader == false, we should find other sext |
| 4810 | // instructions that sign extended the same initial value. However, if |
| 4811 | // AllowPromotionWithoutCommonHeader == true, we expect promoting the |
| 4812 | // extension is just profitable. |
| 4813 | bool CodeGenPrepare::performAddressTypePromotion( |
| 4814 | Instruction *&Inst, bool AllowPromotionWithoutCommonHeader, |
| 4815 | bool HasPromoted, TypePromotionTransaction &TPT, |
| 4816 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) { |
| 4817 | bool Promoted = false; |
| 4818 | SmallPtrSet<Instruction *, 1> UnhandledExts; |
| 4819 | bool AllSeenFirst = true; |
| 4820 | for (auto I : SpeculativelyMovedExts) { |
| 4821 | Value *HeadOfChain = I->getOperand(0); |
| 4822 | DenseMap<Value *, Instruction *>::iterator AlreadySeen = |
| 4823 | SeenChainsForSExt.find(HeadOfChain); |
| 4824 | // If there is an unhandled SExt which has the same header, try to promote |
| 4825 | // it as well. |
| 4826 | if (AlreadySeen != SeenChainsForSExt.end()) { |
| 4827 | if (AlreadySeen->second != nullptr) |
| 4828 | UnhandledExts.insert(AlreadySeen->second); |
| 4829 | AllSeenFirst = false; |
| 4830 | } |
| 4831 | } |
| 4832 | |
| 4833 | if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader && |
| 4834 | SpeculativelyMovedExts.size() == 1)) { |
| 4835 | TPT.commit(); |
| 4836 | if (HasPromoted) |
| 4837 | Promoted = true; |
| 4838 | for (auto I : SpeculativelyMovedExts) { |
| 4839 | Value *HeadOfChain = I->getOperand(0); |
| 4840 | SeenChainsForSExt[HeadOfChain] = nullptr; |
| 4841 | ValToSExtendedUses[HeadOfChain].push_back(I); |
| 4842 | } |
| 4843 | // Update Inst as promotion happen. |
| 4844 | Inst = SpeculativelyMovedExts.pop_back_val(); |
| 4845 | } else { |
| 4846 | // This is the first chain visited from the header, keep the current chain |
| 4847 | // as unhandled. Defer to promote this until we encounter another SExt |
| 4848 | // chain derived from the same header. |
| 4849 | for (auto I : SpeculativelyMovedExts) { |
| 4850 | Value *HeadOfChain = I->getOperand(0); |
| 4851 | SeenChainsForSExt[HeadOfChain] = Inst; |
| 4852 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4853 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4854 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4855 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4856 | if (!AllSeenFirst && !UnhandledExts.empty()) |
| 4857 | for (auto VisitedSExt : UnhandledExts) { |
| 4858 | if (RemovedInsts.count(VisitedSExt)) |
| 4859 | continue; |
| 4860 | TypePromotionTransaction TPT(RemovedInsts); |
| 4861 | SmallVector<Instruction *, 1> Exts; |
| 4862 | SmallVector<Instruction *, 2> Chains; |
| 4863 | Exts.push_back(VisitedSExt); |
| 4864 | bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains); |
| 4865 | TPT.commit(); |
| 4866 | if (HasPromoted) |
| 4867 | Promoted = true; |
| 4868 | for (auto I : Chains) { |
| 4869 | Value *HeadOfChain = I->getOperand(0); |
| 4870 | // Mark this as handled. |
| 4871 | SeenChainsForSExt[HeadOfChain] = nullptr; |
| 4872 | ValToSExtendedUses[HeadOfChain].push_back(I); |
| 4873 | } |
| 4874 | } |
| 4875 | return Promoted; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4876 | } |
| 4877 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4878 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4879 | BasicBlock *DefBB = I->getParent(); |
| 4880 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 4881 | // 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] | 4882 | // other uses of the source with result of extension. |
| 4883 | Value *Src = I->getOperand(0); |
| 4884 | if (Src->hasOneUse()) |
| 4885 | return false; |
| 4886 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 4887 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 4888 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4889 | return false; |
| 4890 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4891 | // 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] | 4892 | // this block. |
| 4893 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 4894 | return false; |
| 4895 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4896 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4897 | for (User *U : I->users()) { |
| 4898 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4899 | |
| 4900 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4901 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4902 | if (UserBB == DefBB) continue; |
| 4903 | DefIsLiveOut = true; |
| 4904 | break; |
| 4905 | } |
| 4906 | if (!DefIsLiveOut) |
| 4907 | return false; |
| 4908 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 4909 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4910 | for (User *U : Src->users()) { |
| 4911 | Instruction *UI = cast<Instruction>(U); |
| 4912 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 4913 | if (UserBB == DefBB) continue; |
| 4914 | // Be conservative. We don't want this xform to end up introducing |
| 4915 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4916 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 4917 | return false; |
| 4918 | } |
| 4919 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4920 | // InsertedTruncs - Only insert one trunc in each block once. |
| 4921 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 4922 | |
| 4923 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4924 | for (Use &U : Src->uses()) { |
| 4925 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4926 | |
| 4927 | // Figure out which BB this ext is used in. |
| 4928 | BasicBlock *UserBB = User->getParent(); |
| 4929 | if (UserBB == DefBB) continue; |
| 4930 | |
| 4931 | // Both src and def are live in this block. Rewrite the use. |
| 4932 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 4933 | |
| 4934 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 4935 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 4936 | assert(InsertPt != UserBB->end()); |
| 4937 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4938 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4939 | } |
| 4940 | |
| 4941 | // 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] | 4942 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4943 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 4944 | MadeChange = true; |
| 4945 | } |
| 4946 | |
| 4947 | return MadeChange; |
| 4948 | } |
| 4949 | |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 4950 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" |
| 4951 | // just after the load if the target can fold this into one extload instruction, |
| 4952 | // with the hope of eliminating some of the other later "and" instructions using |
| 4953 | // the loaded value. "and"s that are made trivially redundant by the insertion |
| 4954 | // of the new "and" are removed by this function, while others (e.g. those whose |
| 4955 | // path from the load goes through a phi) are left for isel to potentially |
| 4956 | // remove. |
| 4957 | // |
| 4958 | // For example: |
| 4959 | // |
| 4960 | // b0: |
| 4961 | // x = load i32 |
| 4962 | // ... |
| 4963 | // b1: |
| 4964 | // y = and x, 0xff |
| 4965 | // z = use y |
| 4966 | // |
| 4967 | // becomes: |
| 4968 | // |
| 4969 | // b0: |
| 4970 | // x = load i32 |
| 4971 | // x' = and x, 0xff |
| 4972 | // ... |
| 4973 | // b1: |
| 4974 | // z = use x' |
| 4975 | // |
| 4976 | // whereas: |
| 4977 | // |
| 4978 | // b0: |
| 4979 | // x1 = load i32 |
| 4980 | // ... |
| 4981 | // b1: |
| 4982 | // x2 = load i32 |
| 4983 | // ... |
| 4984 | // b2: |
| 4985 | // x = phi x1, x2 |
| 4986 | // y = and x, 0xff |
| 4987 | // |
| 4988 | // becomes (after a call to optimizeLoadExt for each load): |
| 4989 | // |
| 4990 | // b0: |
| 4991 | // x1 = load i32 |
| 4992 | // x1' = and x1, 0xff |
| 4993 | // ... |
| 4994 | // b1: |
| 4995 | // x2 = load i32 |
| 4996 | // x2' = and x2, 0xff |
| 4997 | // ... |
| 4998 | // b2: |
| 4999 | // x = phi x1', x2' |
| 5000 | // y = and x, 0xff |
| 5001 | // |
| 5002 | |
| 5003 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { |
| 5004 | |
| 5005 | if (!Load->isSimple() || |
| 5006 | !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy())) |
| 5007 | return false; |
| 5008 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5009 | // Skip loads we've already transformed. |
| 5010 | if (Load->hasOneUse() && |
| 5011 | InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) |
| 5012 | return false; |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5013 | |
| 5014 | // Look at all uses of Load, looking through phis, to determine how many bits |
| 5015 | // of the loaded value are needed. |
| 5016 | SmallVector<Instruction *, 8> WorkList; |
| 5017 | SmallPtrSet<Instruction *, 16> Visited; |
| 5018 | SmallVector<Instruction *, 8> AndsToMaybeRemove; |
| 5019 | for (auto *U : Load->users()) |
| 5020 | WorkList.push_back(cast<Instruction>(U)); |
| 5021 | |
| 5022 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); |
| 5023 | unsigned BitWidth = LoadResultVT.getSizeInBits(); |
| 5024 | APInt DemandBits(BitWidth, 0); |
| 5025 | APInt WidestAndBits(BitWidth, 0); |
| 5026 | |
| 5027 | while (!WorkList.empty()) { |
| 5028 | Instruction *I = WorkList.back(); |
| 5029 | WorkList.pop_back(); |
| 5030 | |
| 5031 | // Break use-def graph loops. |
| 5032 | if (!Visited.insert(I).second) |
| 5033 | continue; |
| 5034 | |
| 5035 | // For a PHI node, push all of its users. |
| 5036 | if (auto *Phi = dyn_cast<PHINode>(I)) { |
| 5037 | for (auto *U : Phi->users()) |
| 5038 | WorkList.push_back(cast<Instruction>(U)); |
| 5039 | continue; |
| 5040 | } |
| 5041 | |
| 5042 | switch (I->getOpcode()) { |
| 5043 | case llvm::Instruction::And: { |
| 5044 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 5045 | if (!AndC) |
| 5046 | return false; |
| 5047 | APInt AndBits = AndC->getValue(); |
| 5048 | DemandBits |= AndBits; |
| 5049 | // Keep track of the widest and mask we see. |
| 5050 | if (AndBits.ugt(WidestAndBits)) |
| 5051 | WidestAndBits = AndBits; |
| 5052 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) |
| 5053 | AndsToMaybeRemove.push_back(I); |
| 5054 | break; |
| 5055 | } |
| 5056 | |
| 5057 | case llvm::Instruction::Shl: { |
| 5058 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 5059 | if (!ShlC) |
| 5060 | return false; |
| 5061 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); |
| 5062 | auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt); |
| 5063 | DemandBits |= ShlDemandBits; |
| 5064 | break; |
| 5065 | } |
| 5066 | |
| 5067 | case llvm::Instruction::Trunc: { |
| 5068 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); |
| 5069 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); |
| 5070 | auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth); |
| 5071 | DemandBits |= TruncBits; |
| 5072 | break; |
| 5073 | } |
| 5074 | |
| 5075 | default: |
| 5076 | return false; |
| 5077 | } |
| 5078 | } |
| 5079 | |
| 5080 | uint32_t ActiveBits = DemandBits.getActiveBits(); |
| 5081 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the |
| 5082 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, |
| 5083 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but |
| 5084 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR |
| 5085 | // followed by an AND. |
| 5086 | // TODO: Look into removing this restriction by fixing backends to either |
| 5087 | // return false for isLoadExtLegal for i1 or have them select this pattern to |
| 5088 | // a single instruction. |
| 5089 | // |
| 5090 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits |
| 5091 | // mask, since these are the only ands that will be removed by isel. |
Craig Topper | d33ee1b | 2017-04-03 16:34:59 +0000 | [diff] [blame] | 5092 | if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) || |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5093 | WidestAndBits != DemandBits) |
| 5094 | return false; |
| 5095 | |
| 5096 | LLVMContext &Ctx = Load->getType()->getContext(); |
| 5097 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); |
| 5098 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); |
| 5099 | |
| 5100 | // Reject cases that won't be matched as extloads. |
| 5101 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || |
| 5102 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) |
| 5103 | return false; |
| 5104 | |
| 5105 | IRBuilder<> Builder(Load->getNextNode()); |
| 5106 | auto *NewAnd = dyn_cast<Instruction>( |
| 5107 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5108 | // Mark this instruction as "inserted by CGP", so that other |
| 5109 | // optimizations don't touch it. |
| 5110 | InsertedInsts.insert(NewAnd); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5111 | |
| 5112 | // Replace all uses of load with new and (except for the use of load in the |
| 5113 | // new and itself). |
| 5114 | Load->replaceAllUsesWith(NewAnd); |
| 5115 | NewAnd->setOperand(0, Load); |
| 5116 | |
| 5117 | // Remove any and instructions that are now redundant. |
| 5118 | for (auto *And : AndsToMaybeRemove) |
| 5119 | // Check that the and mask is the same as the one we decided to put on the |
| 5120 | // new and. |
| 5121 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { |
| 5122 | And->replaceAllUsesWith(NewAnd); |
| 5123 | if (&*CurInstIterator == And) |
| 5124 | CurInstIterator = std::next(And->getIterator()); |
| 5125 | And->eraseFromParent(); |
| 5126 | ++NumAndUses; |
| 5127 | } |
| 5128 | |
| 5129 | ++NumAndsAdded; |
| 5130 | return true; |
| 5131 | } |
| 5132 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5133 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 5134 | /// that is only used once. |
| 5135 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 5136 | auto *I = dyn_cast<Instruction>(V); |
| 5137 | // If it's safe to speculatively execute, then it should not have side |
| 5138 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 5139 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 5140 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5141 | } |
| 5142 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 5143 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5144 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5145 | const TargetLowering *TLI, |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5146 | SelectInst *SI) { |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5147 | // If even a predictable select is cheap, then a branch can't be cheaper. |
| 5148 | if (!TLI->isPredictableSelectExpensive()) |
| 5149 | return false; |
| 5150 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5151 | // FIXME: This should use the same heuristics as IfConversion to determine |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5152 | // whether a select is better represented as a branch. |
| 5153 | |
| 5154 | // If metadata tells us that the select condition is obviously predictable, |
| 5155 | // then we want to replace the select with a branch. |
| 5156 | uint64_t TrueWeight, FalseWeight; |
| 5157 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { |
| 5158 | uint64_t Max = std::max(TrueWeight, FalseWeight); |
| 5159 | uint64_t Sum = TrueWeight + FalseWeight; |
Sanjay Patel | c7b91e6 | 2016-05-09 17:31:55 +0000 | [diff] [blame] | 5160 | if (Sum != 0) { |
| 5161 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); |
| 5162 | if (Probability > TLI->getPredictableBranchThreshold()) |
| 5163 | return true; |
| 5164 | } |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5165 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5166 | |
| 5167 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 5168 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 5169 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 5170 | // comparison condition. If the compare has more than one use, there's |
| 5171 | // 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] | 5172 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5173 | return false; |
| 5174 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5175 | // If either operand of the select is expensive and only needed on one side |
| 5176 | // of the select, we should form a branch. |
| 5177 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 5178 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 5179 | return true; |
| 5180 | |
| 5181 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5182 | } |
| 5183 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5184 | /// If \p isTrue is true, return the true value of \p SI, otherwise return |
| 5185 | /// false value of \p SI. If the true/false value of \p SI is defined by any |
| 5186 | /// select instructions in \p Selects, look through the defining select |
| 5187 | /// instruction until the true/false value is not defined in \p Selects. |
| 5188 | static Value *getTrueOrFalseValue( |
| 5189 | SelectInst *SI, bool isTrue, |
| 5190 | const SmallPtrSet<const Instruction *, 2> &Selects) { |
| 5191 | Value *V; |
| 5192 | |
| 5193 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); |
| 5194 | DefSI = dyn_cast<SelectInst>(V)) { |
Dehao Chen | c32d712 | 2016-09-12 20:29:54 +0000 | [diff] [blame] | 5195 | assert(DefSI->getCondition() == SI->getCondition() && |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5196 | "The condition of DefSI does not match with SI"); |
| 5197 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); |
| 5198 | } |
| 5199 | return V; |
| 5200 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5201 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5202 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 5203 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5204 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5205 | // Find all consecutive select instructions that share the same condition. |
| 5206 | SmallVector<SelectInst *, 2> ASI; |
| 5207 | ASI.push_back(SI); |
| 5208 | for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); |
| 5209 | It != SI->getParent()->end(); ++It) { |
| 5210 | SelectInst *I = dyn_cast<SelectInst>(&*It); |
| 5211 | if (I && SI->getCondition() == I->getCondition()) { |
| 5212 | ASI.push_back(I); |
| 5213 | } else { |
| 5214 | break; |
| 5215 | } |
| 5216 | } |
| 5217 | |
| 5218 | SelectInst *LastSI = ASI.back(); |
| 5219 | // Increment the current iterator to skip all the rest of select instructions |
| 5220 | // because they will be either "not lowered" or "all lowered" to branch. |
| 5221 | CurInstIterator = std::next(LastSI->getIterator()); |
| 5222 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5223 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 5224 | |
| 5225 | // Can we convert the 'select' to CF ? |
Sanjay Patel | a31b0c0 | 2016-04-26 00:47:39 +0000 | [diff] [blame] | 5226 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond || |
| 5227 | SI->getMetadata(LLVMContext::MD_unpredictable)) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5228 | return false; |
| 5229 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5230 | TargetLowering::SelectSupportKind SelectKind; |
| 5231 | if (VectorCond) |
| 5232 | SelectKind = TargetLowering::VectorMaskSelect; |
| 5233 | else if (SI->getType()->isVectorTy()) |
| 5234 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 5235 | else |
| 5236 | SelectKind = TargetLowering::ScalarValSelect; |
| 5237 | |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5238 | if (TLI->isSelectSupported(SelectKind) && |
| 5239 | !isFormingBranchFromSelectProfitable(TTI, TLI, SI)) |
| 5240 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5241 | |
| 5242 | ModifiedDT = true; |
| 5243 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5244 | // Transform a sequence like this: |
| 5245 | // start: |
| 5246 | // %cmp = cmp uge i32 %a, %b |
| 5247 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 5248 | // |
| 5249 | // Into: |
| 5250 | // start: |
| 5251 | // %cmp = cmp uge i32 %a, %b |
| 5252 | // br i1 %cmp, label %select.true, label %select.false |
| 5253 | // select.true: |
| 5254 | // br label %select.end |
| 5255 | // select.false: |
| 5256 | // br label %select.end |
| 5257 | // select.end: |
| 5258 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 5259 | // |
| 5260 | // In addition, we may sink instructions that produce %c or %d from |
| 5261 | // the entry block into the destination(s) of the new branch. |
| 5262 | // If the true or false blocks do not contain a sunken instruction, that |
| 5263 | // block and its branch may be optimized away. In that case, one side of the |
| 5264 | // first branch will point directly to select.end, and the corresponding PHI |
| 5265 | // predecessor block will be the start block. |
| 5266 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5267 | // First, we split the block containing the select into 2 blocks. |
| 5268 | BasicBlock *StartBlock = SI->getParent(); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5269 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5270 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5271 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5272 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5273 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5274 | |
| 5275 | // These are the new basic blocks for the conditional branch. |
| 5276 | // At least one will become an actual new basic block. |
| 5277 | BasicBlock *TrueBlock = nullptr; |
| 5278 | BasicBlock *FalseBlock = nullptr; |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5279 | BranchInst *TrueBranch = nullptr; |
| 5280 | BranchInst *FalseBranch = nullptr; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5281 | |
| 5282 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 5283 | // them speculatively. |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5284 | for (SelectInst *SI : ASI) { |
| 5285 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 5286 | if (TrueBlock == nullptr) { |
| 5287 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 5288 | EndBlock->getParent(), EndBlock); |
| 5289 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
| 5290 | } |
| 5291 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 5292 | TrueInst->moveBefore(TrueBranch); |
| 5293 | } |
| 5294 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 5295 | if (FalseBlock == nullptr) { |
| 5296 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 5297 | EndBlock->getParent(), EndBlock); |
| 5298 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 5299 | } |
| 5300 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 5301 | FalseInst->moveBefore(FalseBranch); |
| 5302 | } |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5303 | } |
| 5304 | |
| 5305 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 5306 | // for a new input value to the PHI. |
| 5307 | if (TrueBlock == FalseBlock) { |
| 5308 | assert(TrueBlock == nullptr && |
| 5309 | "Unexpected basic block transform while optimizing select"); |
| 5310 | |
| 5311 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 5312 | EndBlock->getParent(), EndBlock); |
| 5313 | BranchInst::Create(EndBlock, FalseBlock); |
| 5314 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5315 | |
| 5316 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5317 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 5318 | // of the condition, it means that side of the branch goes to the end block |
| 5319 | // directly and the path originates from the start block from the point of |
| 5320 | // view of the new PHI. |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5321 | BasicBlock *TT, *FT; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5322 | if (TrueBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5323 | TT = EndBlock; |
| 5324 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5325 | TrueBlock = StartBlock; |
| 5326 | } else if (FalseBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5327 | TT = TrueBlock; |
| 5328 | FT = EndBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5329 | FalseBlock = StartBlock; |
| 5330 | } else { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5331 | TT = TrueBlock; |
| 5332 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5333 | } |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5334 | IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5335 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5336 | SmallPtrSet<const Instruction *, 2> INS; |
| 5337 | INS.insert(ASI.begin(), ASI.end()); |
| 5338 | // Use reverse iterator because later select may use the value of the |
| 5339 | // earlier select, and we need to propagate value through earlier select |
| 5340 | // to get the PHI operand. |
| 5341 | for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { |
| 5342 | SelectInst *SI = *It; |
| 5343 | // The select itself is replaced with a PHI Node. |
| 5344 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
| 5345 | PN->takeName(SI); |
| 5346 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); |
| 5347 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5348 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5349 | SI->replaceAllUsesWith(PN); |
| 5350 | SI->eraseFromParent(); |
| 5351 | INS.erase(SI); |
| 5352 | ++NumSelectsExpanded; |
| 5353 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5354 | |
| 5355 | // Instruct OptimizeBlock to skip to the next block. |
| 5356 | CurInstIterator = StartBlock->end(); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5357 | return true; |
| 5358 | } |
| 5359 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 5360 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5361 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 5362 | int SplatElem = -1; |
| 5363 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 5364 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 5365 | return false; |
| 5366 | SplatElem = Mask[i]; |
| 5367 | } |
| 5368 | |
| 5369 | return true; |
| 5370 | } |
| 5371 | |
| 5372 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 5373 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 5374 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 5375 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5376 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5377 | BasicBlock *DefBB = SVI->getParent(); |
| 5378 | |
| 5379 | // Only do this xform if variable vector shifts are particularly expensive. |
| 5380 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 5381 | return false; |
| 5382 | |
| 5383 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 5384 | // constant splat. |
| 5385 | if (!isBroadcastShuffle(SVI)) |
| 5386 | return false; |
| 5387 | |
| 5388 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 5389 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 5390 | |
| 5391 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5392 | for (User *U : SVI->users()) { |
| 5393 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5394 | |
| 5395 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5396 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5397 | if (UserBB == DefBB) continue; |
| 5398 | |
| 5399 | // 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] | 5400 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5401 | |
| 5402 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 5403 | // already have a copy. |
| 5404 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 5405 | |
| 5406 | if (!InsertedShuffle) { |
| 5407 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5408 | assert(InsertPt != UserBB->end()); |
| 5409 | InsertedShuffle = |
| 5410 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 5411 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5412 | } |
| 5413 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5414 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5415 | MadeChange = true; |
| 5416 | } |
| 5417 | |
| 5418 | // If we removed all uses, nuke the shuffle. |
| 5419 | if (SVI->use_empty()) { |
| 5420 | SVI->eraseFromParent(); |
| 5421 | MadeChange = true; |
| 5422 | } |
| 5423 | |
| 5424 | return MadeChange; |
| 5425 | } |
| 5426 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5427 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 5428 | if (!TLI || !DL) |
| 5429 | return false; |
| 5430 | |
| 5431 | Value *Cond = SI->getCondition(); |
| 5432 | Type *OldType = Cond->getType(); |
| 5433 | LLVMContext &Context = Cond->getContext(); |
| 5434 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 5435 | unsigned RegWidth = RegType.getSizeInBits(); |
| 5436 | |
| 5437 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 5438 | return false; |
| 5439 | |
| 5440 | // If the register width is greater than the type width, expand the condition |
| 5441 | // of the switch instruction and each case constant to the width of the |
| 5442 | // register. By widening the type of the switch condition, subsequent |
| 5443 | // comparisons (for case comparisons) will not need to be extended to the |
| 5444 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 5445 | // where N is the number of cases in the switch. |
| 5446 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 5447 | |
| 5448 | // Zero-extend the switch condition and case constants unless the switch |
| 5449 | // condition is a function argument that is already being sign-extended. |
| 5450 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 5451 | // everything instead. |
| 5452 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 5453 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 5454 | if (Arg->hasSExtAttr()) |
| 5455 | ExtType = Instruction::SExt; |
| 5456 | |
| 5457 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 5458 | ExtInst->insertBefore(SI); |
| 5459 | SI->setCondition(ExtInst); |
| 5460 | for (SwitchInst::CaseIt Case : SI->cases()) { |
| 5461 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 5462 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 5463 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 5464 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 5465 | } |
| 5466 | |
| 5467 | return true; |
| 5468 | } |
| 5469 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5470 | namespace { |
| 5471 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 5472 | /// This class is used to move downward extractelement transition. |
| 5473 | /// E.g., |
| 5474 | /// a = vector_op <2 x i32> |
| 5475 | /// b = extractelement <2 x i32> a, i32 0 |
| 5476 | /// c = scalar_op b |
| 5477 | /// store c |
| 5478 | /// |
| 5479 | /// => |
| 5480 | /// a = vector_op <2 x i32> |
| 5481 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 5482 | /// * d = extractelement <2 x i32> c, i32 0 |
| 5483 | /// * store d |
| 5484 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 5485 | /// transition. |
| 5486 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5487 | /// DataLayout associated with the current module. |
| 5488 | const DataLayout &DL; |
| 5489 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5490 | /// Used to perform some checks on the legality of vector operations. |
| 5491 | const TargetLowering &TLI; |
| 5492 | |
| 5493 | /// Used to estimated the cost of the promoted chain. |
| 5494 | const TargetTransformInfo &TTI; |
| 5495 | |
| 5496 | /// The transition being moved downwards. |
| 5497 | Instruction *Transition; |
| 5498 | /// The sequence of instructions to be promoted. |
| 5499 | SmallVector<Instruction *, 4> InstsToBePromoted; |
| 5500 | /// Cost of combining a store and an extract. |
| 5501 | unsigned StoreExtractCombineCost; |
| 5502 | /// Instruction that will be combined with the transition. |
| 5503 | Instruction *CombineInst; |
| 5504 | |
| 5505 | /// \brief The instruction that represents the current end of the transition. |
| 5506 | /// Since we are faking the promotion until we reach the end of the chain |
| 5507 | /// of computation, we need a way to get the current end of the transition. |
| 5508 | Instruction *getEndOfTransition() const { |
| 5509 | if (InstsToBePromoted.empty()) |
| 5510 | return Transition; |
| 5511 | return InstsToBePromoted.back(); |
| 5512 | } |
| 5513 | |
| 5514 | /// \brief Return the index of the original value in the transition. |
| 5515 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 5516 | /// c, is at index 0. |
| 5517 | unsigned getTransitionOriginalValueIdx() const { |
| 5518 | assert(isa<ExtractElementInst>(Transition) && |
| 5519 | "Other kind of transitions are not supported yet"); |
| 5520 | return 0; |
| 5521 | } |
| 5522 | |
| 5523 | /// \brief Return the index of the index in the transition. |
| 5524 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 5525 | /// is at index 1. |
| 5526 | unsigned getTransitionIdx() const { |
| 5527 | assert(isa<ExtractElementInst>(Transition) && |
| 5528 | "Other kind of transitions are not supported yet"); |
| 5529 | return 1; |
| 5530 | } |
| 5531 | |
| 5532 | /// \brief Get the type of the transition. |
| 5533 | /// This is the type of the original value. |
| 5534 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 5535 | /// transition is <2 x i32>. |
| 5536 | Type *getTransitionType() const { |
| 5537 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 5538 | } |
| 5539 | |
| 5540 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 5541 | /// I.e., we have the following sequence: |
| 5542 | /// Def = Transition <ty1> a to <ty2> |
| 5543 | /// b = ToBePromoted <ty2> Def, ... |
| 5544 | /// => |
| 5545 | /// b = ToBePromoted <ty1> a, ... |
| 5546 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 5547 | void promoteImpl(Instruction *ToBePromoted); |
| 5548 | |
| 5549 | /// \brief Check whether or not it is profitable to promote all the |
| 5550 | /// instructions enqueued to be promoted. |
| 5551 | bool isProfitableToPromote() { |
| 5552 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5553 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 5554 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 5555 | : -1; |
| 5556 | Type *PromotedType = getTransitionType(); |
| 5557 | |
| 5558 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 5559 | unsigned AS = ST->getPointerAddressSpace(); |
| 5560 | unsigned Align = ST->getAlignment(); |
| 5561 | // Check if this store is supported. |
| 5562 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5563 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 5564 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5565 | // If this is not supported, there is no way we can combine |
| 5566 | // the extract with the store. |
| 5567 | return false; |
| 5568 | } |
| 5569 | |
| 5570 | // The scalar chain of computation has to pay for the transition |
| 5571 | // scalar to vector. |
| 5572 | // The vector chain has to account for the combining cost. |
| 5573 | uint64_t ScalarCost = |
| 5574 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 5575 | uint64_t VectorCost = StoreExtractCombineCost; |
| 5576 | for (const auto &Inst : InstsToBePromoted) { |
| 5577 | // Compute the cost. |
| 5578 | // By construction, all instructions being promoted are arithmetic ones. |
| 5579 | // Moreover, one argument is a constant that can be viewed as a splat |
| 5580 | // constant. |
| 5581 | Value *Arg0 = Inst->getOperand(0); |
| 5582 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 5583 | isa<ConstantFP>(Arg0); |
| 5584 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 5585 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5586 | : TargetTransformInfo::OK_AnyValue; |
| 5587 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 5588 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5589 | : TargetTransformInfo::OK_AnyValue; |
| 5590 | ScalarCost += TTI.getArithmeticInstrCost( |
| 5591 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 5592 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 5593 | Arg0OVK, Arg1OVK); |
| 5594 | } |
| 5595 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 5596 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 5597 | return ScalarCost > VectorCost; |
| 5598 | } |
| 5599 | |
| 5600 | /// \brief Generate a constant vector with \p Val with the same |
| 5601 | /// number of elements as the transition. |
| 5602 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 5603 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5604 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 5605 | /// otherwise we generate a vector with as many undef as possible: |
| 5606 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 5607 | /// used at the index of the extract. |
| 5608 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
| 5609 | unsigned ExtractIdx = UINT_MAX; |
| 5610 | if (!UseSplat) { |
| 5611 | // If we cannot determine where the constant must be, we have to |
| 5612 | // use a splat constant. |
| 5613 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 5614 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 5615 | ExtractIdx = CstVal->getSExtValue(); |
| 5616 | else |
| 5617 | UseSplat = true; |
| 5618 | } |
| 5619 | |
| 5620 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 5621 | if (UseSplat) |
| 5622 | return ConstantVector::getSplat(End, Val); |
| 5623 | |
| 5624 | SmallVector<Constant *, 4> ConstVec; |
| 5625 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 5626 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 5627 | if (Idx == ExtractIdx) |
| 5628 | ConstVec.push_back(Val); |
| 5629 | else |
| 5630 | ConstVec.push_back(UndefVal); |
| 5631 | } |
| 5632 | return ConstantVector::get(ConstVec); |
| 5633 | } |
| 5634 | |
| 5635 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 5636 | /// in \p Use can trigger undefined behavior. |
| 5637 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 5638 | unsigned OperandIdx) { |
| 5639 | // This is not safe to introduce undef when the operand is on |
| 5640 | // the right hand side of a division-like instruction. |
| 5641 | if (OperandIdx != 1) |
| 5642 | return false; |
| 5643 | switch (Use->getOpcode()) { |
| 5644 | default: |
| 5645 | return false; |
| 5646 | case Instruction::SDiv: |
| 5647 | case Instruction::UDiv: |
| 5648 | case Instruction::SRem: |
| 5649 | case Instruction::URem: |
| 5650 | return true; |
| 5651 | case Instruction::FDiv: |
| 5652 | case Instruction::FRem: |
| 5653 | return !Use->hasNoNaNs(); |
| 5654 | } |
| 5655 | llvm_unreachable(nullptr); |
| 5656 | } |
| 5657 | |
| 5658 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5659 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 5660 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 5661 | unsigned CombineCost) |
| 5662 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5663 | StoreExtractCombineCost(CombineCost), CombineInst(nullptr) { |
| 5664 | assert(Transition && "Do not know how to promote null"); |
| 5665 | } |
| 5666 | |
| 5667 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 5668 | bool canPromote(const Instruction *ToBePromoted) const { |
| 5669 | // We could support CastInst too. |
| 5670 | return isa<BinaryOperator>(ToBePromoted); |
| 5671 | } |
| 5672 | |
| 5673 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 5674 | /// by moving downward the transition through. |
| 5675 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 5676 | // Promote only if all the operands can be statically expanded. |
| 5677 | // Indeed, we do not want to introduce any new kind of transitions. |
| 5678 | for (const Use &U : ToBePromoted->operands()) { |
| 5679 | const Value *Val = U.get(); |
| 5680 | if (Val == getEndOfTransition()) { |
| 5681 | // If the use is a division and the transition is on the rhs, |
| 5682 | // we cannot promote the operation, otherwise we may create a |
| 5683 | // division by zero. |
| 5684 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 5685 | return false; |
| 5686 | continue; |
| 5687 | } |
| 5688 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 5689 | !isa<ConstantFP>(Val)) |
| 5690 | return false; |
| 5691 | } |
| 5692 | // Check that the resulting operation is legal. |
| 5693 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 5694 | if (!ISDOpcode) |
| 5695 | return false; |
| 5696 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 5697 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5698 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5699 | } |
| 5700 | |
| 5701 | /// \brief Check whether or not \p Use can be combined |
| 5702 | /// with the transition. |
| 5703 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 5704 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 5705 | |
| 5706 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 5707 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 5708 | InstsToBePromoted.push_back(ToBePromoted); |
| 5709 | } |
| 5710 | |
| 5711 | /// \brief Set the instruction that will be combined with the transition. |
| 5712 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 5713 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 5714 | CombineInst = ToBeCombined; |
| 5715 | } |
| 5716 | |
| 5717 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 5718 | /// is profitable. |
| 5719 | /// \return True if the promotion happened, false otherwise. |
| 5720 | bool promote() { |
| 5721 | // Check if there is something to promote. |
| 5722 | // Right now, if we do not have anything to combine with, |
| 5723 | // we assume the promotion is not profitable. |
| 5724 | if (InstsToBePromoted.empty() || !CombineInst) |
| 5725 | return false; |
| 5726 | |
| 5727 | // Check cost. |
| 5728 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 5729 | return false; |
| 5730 | |
| 5731 | // Promote. |
| 5732 | for (auto &ToBePromoted : InstsToBePromoted) |
| 5733 | promoteImpl(ToBePromoted); |
| 5734 | InstsToBePromoted.clear(); |
| 5735 | return true; |
| 5736 | } |
| 5737 | }; |
| 5738 | } // End of anonymous namespace. |
| 5739 | |
| 5740 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 5741 | // At this point, we know that all the operands of ToBePromoted but Def |
| 5742 | // can be statically promoted. |
| 5743 | // For Def, we need to use its parameter in ToBePromoted: |
| 5744 | // b = ToBePromoted ty1 a |
| 5745 | // Def = Transition ty1 b to ty2 |
| 5746 | // Move the transition down. |
| 5747 | // 1. Replace all uses of the promoted operation by the transition. |
| 5748 | // = ... b => = ... Def. |
| 5749 | assert(ToBePromoted->getType() == Transition->getType() && |
| 5750 | "The type of the result of the transition does not match " |
| 5751 | "the final type"); |
| 5752 | ToBePromoted->replaceAllUsesWith(Transition); |
| 5753 | // 2. Update the type of the uses. |
| 5754 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 5755 | Type *TransitionTy = getTransitionType(); |
| 5756 | ToBePromoted->mutateType(TransitionTy); |
| 5757 | // 3. Update all the operands of the promoted operation with promoted |
| 5758 | // operands. |
| 5759 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 5760 | for (Use &U : ToBePromoted->operands()) { |
| 5761 | Value *Val = U.get(); |
| 5762 | Value *NewVal = nullptr; |
| 5763 | if (Val == Transition) |
| 5764 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5765 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 5766 | isa<ConstantFP>(Val)) { |
| 5767 | // Use a splat constant if it is not safe to use undef. |
| 5768 | NewVal = getConstantVector( |
| 5769 | cast<Constant>(Val), |
| 5770 | isa<UndefValue>(Val) || |
| 5771 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 5772 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 5773 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 5774 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5775 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 5776 | } |
| 5777 | Transition->removeFromParent(); |
| 5778 | Transition->insertAfter(ToBePromoted); |
| 5779 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 5780 | } |
| 5781 | |
| 5782 | /// Some targets can do store(extractelement) with one instruction. |
| 5783 | /// Try to push the extractelement towards the stores when the target |
| 5784 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5785 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5786 | unsigned CombineCost = UINT_MAX; |
| 5787 | if (DisableStoreExtract || !TLI || |
| 5788 | (!StressStoreExtract && |
| 5789 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 5790 | Inst->getOperand(1), CombineCost))) |
| 5791 | return false; |
| 5792 | |
| 5793 | // At this point we know that Inst is a vector to scalar transition. |
| 5794 | // Try to move it down the def-use chain, until: |
| 5795 | // - We can combine the transition with its single use |
| 5796 | // => we got rid of the transition. |
| 5797 | // - We escape the current basic block |
| 5798 | // => we would need to check that we are moving it at a cheaper place and |
| 5799 | // we do not do that for now. |
| 5800 | BasicBlock *Parent = Inst->getParent(); |
| 5801 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5802 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5803 | // If the transition has more than one use, assume this is not going to be |
| 5804 | // beneficial. |
| 5805 | while (Inst->hasOneUse()) { |
| 5806 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 5807 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 5808 | |
| 5809 | if (ToBePromoted->getParent() != Parent) { |
| 5810 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 5811 | << ToBePromoted->getParent()->getName() |
| 5812 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 5813 | return false; |
| 5814 | } |
| 5815 | |
| 5816 | if (VPH.canCombine(ToBePromoted)) { |
| 5817 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 5818 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 5819 | VPH.recordCombineInstruction(ToBePromoted); |
| 5820 | bool Changed = VPH.promote(); |
| 5821 | NumStoreExtractExposed += Changed; |
| 5822 | return Changed; |
| 5823 | } |
| 5824 | |
| 5825 | DEBUG(dbgs() << "Try promoting.\n"); |
| 5826 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 5827 | return false; |
| 5828 | |
| 5829 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 5830 | |
| 5831 | VPH.enqueueForPromotion(ToBePromoted); |
| 5832 | Inst = ToBePromoted; |
| 5833 | } |
| 5834 | return false; |
| 5835 | } |
| 5836 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 5837 | /// For the instruction sequence of store below, F and I values |
| 5838 | /// are bundled together as an i64 value before being stored into memory. |
| 5839 | /// Sometimes it is more efficent to generate separate stores for F and I, |
| 5840 | /// which can remove the bitwise instructions or sink them to colder places. |
| 5841 | /// |
| 5842 | /// (store (or (zext (bitcast F to i32) to i64), |
| 5843 | /// (shl (zext I to i64), 32)), addr) --> |
| 5844 | /// (store F, addr) and (store I, addr+4) |
| 5845 | /// |
| 5846 | /// Similarly, splitting for other merged store can also be beneficial, like: |
| 5847 | /// For pair of {i32, i32}, i64 store --> two i32 stores. |
| 5848 | /// For pair of {i32, i16}, i64 store --> two i32 stores. |
| 5849 | /// For pair of {i16, i16}, i32 store --> two i16 stores. |
| 5850 | /// For pair of {i16, i8}, i32 store --> two i16 stores. |
| 5851 | /// For pair of {i8, i8}, i16 store --> two i8 stores. |
| 5852 | /// |
| 5853 | /// We allow each target to determine specifically which kind of splitting is |
| 5854 | /// supported. |
| 5855 | /// |
| 5856 | /// The store patterns are commonly seen from the simple code snippet below |
| 5857 | /// if only std::make_pair(...) is sroa transformed before inlined into hoo. |
| 5858 | /// void goo(const std::pair<int, float> &); |
| 5859 | /// hoo() { |
| 5860 | /// ... |
| 5861 | /// goo(std::make_pair(tmp, ftmp)); |
| 5862 | /// ... |
| 5863 | /// } |
| 5864 | /// |
| 5865 | /// Although we already have similar splitting in DAG Combine, we duplicate |
| 5866 | /// it in CodeGenPrepare to catch the case in which pattern is across |
| 5867 | /// multiple BBs. The logic in DAG Combine is kept to catch case generated |
| 5868 | /// during code expansion. |
| 5869 | static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, |
| 5870 | const TargetLowering &TLI) { |
| 5871 | // Handle simple but common cases only. |
| 5872 | Type *StoreType = SI.getValueOperand()->getType(); |
| 5873 | if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) || |
| 5874 | DL.getTypeSizeInBits(StoreType) == 0) |
| 5875 | return false; |
| 5876 | |
| 5877 | unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; |
| 5878 | Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); |
| 5879 | if (DL.getTypeStoreSizeInBits(SplitStoreType) != |
| 5880 | DL.getTypeSizeInBits(SplitStoreType)) |
| 5881 | return false; |
| 5882 | |
| 5883 | // Match the following patterns: |
| 5884 | // (store (or (zext LValue to i64), |
| 5885 | // (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 5886 | // or |
| 5887 | // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 5888 | // (zext LValue to i64), |
| 5889 | // Expect both operands of OR and the first operand of SHL have only |
| 5890 | // one use. |
| 5891 | Value *LValue, *HValue; |
| 5892 | if (!match(SI.getValueOperand(), |
| 5893 | m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), |
| 5894 | m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), |
| 5895 | m_SpecificInt(HalfValBitSize)))))) |
| 5896 | return false; |
| 5897 | |
| 5898 | // Check LValue and HValue are int with size less or equal than 32. |
| 5899 | if (!LValue->getType()->isIntegerTy() || |
| 5900 | DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || |
| 5901 | !HValue->getType()->isIntegerTy() || |
| 5902 | DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) |
| 5903 | return false; |
| 5904 | |
| 5905 | // If LValue/HValue is a bitcast instruction, use the EVT before bitcast |
| 5906 | // as the input of target query. |
| 5907 | auto *LBC = dyn_cast<BitCastInst>(LValue); |
| 5908 | auto *HBC = dyn_cast<BitCastInst>(HValue); |
| 5909 | EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) |
| 5910 | : EVT::getEVT(LValue->getType()); |
| 5911 | EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) |
| 5912 | : EVT::getEVT(HValue->getType()); |
| 5913 | if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) |
| 5914 | return false; |
| 5915 | |
| 5916 | // Start to split store. |
| 5917 | IRBuilder<> Builder(SI.getContext()); |
| 5918 | Builder.SetInsertPoint(&SI); |
| 5919 | |
| 5920 | // If LValue/HValue is a bitcast in another BB, create a new one in current |
| 5921 | // BB so it may be merged with the splitted stores by dag combiner. |
| 5922 | if (LBC && LBC->getParent() != SI.getParent()) |
| 5923 | LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); |
| 5924 | if (HBC && HBC->getParent() != SI.getParent()) |
| 5925 | HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); |
| 5926 | |
| 5927 | auto CreateSplitStore = [&](Value *V, bool Upper) { |
| 5928 | V = Builder.CreateZExtOrBitCast(V, SplitStoreType); |
| 5929 | Value *Addr = Builder.CreateBitCast( |
| 5930 | SI.getOperand(1), |
| 5931 | SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); |
| 5932 | if (Upper) |
| 5933 | Addr = Builder.CreateGEP( |
| 5934 | SplitStoreType, Addr, |
| 5935 | ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); |
| 5936 | Builder.CreateAlignedStore( |
| 5937 | V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment()); |
| 5938 | }; |
| 5939 | |
| 5940 | CreateSplitStore(LValue, false); |
| 5941 | CreateSplitStore(HValue, true); |
| 5942 | |
| 5943 | // Delete the old store. |
| 5944 | SI.eraseFromParent(); |
| 5945 | return true; |
| 5946 | } |
| 5947 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5948 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 5949 | // Bail out if we inserted the instruction to prevent optimizations from |
| 5950 | // stepping on each other's toes. |
| 5951 | if (InsertedInsts.count(I)) |
| 5952 | return false; |
| 5953 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5954 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 5955 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 5956 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 5957 | // trivial PHI, go ahead and zap it here. |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 5958 | if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5959 | P->replaceAllUsesWith(V); |
| 5960 | P->eraseFromParent(); |
| 5961 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5962 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5963 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5964 | return false; |
| 5965 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5966 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5967 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5968 | // If the source of the cast is a constant, then this should have |
| 5969 | // already been constant folded. The only reason NOT to constant fold |
| 5970 | // it is if something (e.g. LSR) was careful to place the constant |
| 5971 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 5972 | // the address of globals out of a loop). If this is the case, we don't |
| 5973 | // want to forward-subst the cast. |
| 5974 | if (isa<Constant>(CI->getOperand(0))) |
| 5975 | return false; |
| 5976 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5977 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5978 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5979 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5980 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5981 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 5982 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5983 | if (TLI && |
| 5984 | TLI->getTypeAction(CI->getContext(), |
| 5985 | TLI->getValueType(*DL, CI->getType())) == |
| 5986 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5987 | return SinkCast(CI); |
| 5988 | } else { |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5989 | bool MadeChange = optimizeExt(I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5990 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 5991 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 5992 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5993 | return false; |
| 5994 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5995 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 5996 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 5997 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 5998 | return OptimizeCmpExpression(CI, TLI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 5999 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6000 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 6001 | LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6002 | if (TLI) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 6003 | bool Modified = optimizeLoadExt(LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6004 | unsigned AS = LI->getPointerAddressSpace(); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 6005 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 6006 | return Modified; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6007 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 6008 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6009 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6010 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6011 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6012 | if (TLI && splitMergedValStore(*SI, *DL, *TLI)) |
| 6013 | return true; |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 6014 | SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6015 | if (TLI) { |
| 6016 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6017 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6018 | SI->getOperand(0)->getType(), AS); |
| 6019 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6020 | return false; |
| 6021 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6022 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 6023 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { |
| 6024 | unsigned AS = RMW->getPointerAddressSpace(); |
| 6025 | return optimizeMemoryInst(I, RMW->getPointerOperand(), |
| 6026 | RMW->getType(), AS); |
| 6027 | } |
| 6028 | |
| 6029 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { |
| 6030 | unsigned AS = CmpX->getPointerAddressSpace(); |
| 6031 | return optimizeMemoryInst(I, CmpX->getPointerOperand(), |
| 6032 | CmpX->getCompareOperand()->getType(), AS); |
| 6033 | } |
| 6034 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6035 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 6036 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 6037 | if (BinOp && (BinOp->getOpcode() == Instruction::And) && |
| 6038 | EnableAndCmpSinking && TLI) |
| 6039 | return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts); |
| 6040 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6041 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 6042 | BinOp->getOpcode() == Instruction::LShr)) { |
| 6043 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 6044 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6045 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6046 | |
| 6047 | return false; |
| 6048 | } |
| 6049 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6050 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6051 | if (GEPI->hasAllZeroIndices()) { |
| 6052 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 6053 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 6054 | GEPI->getName(), GEPI); |
| 6055 | GEPI->replaceAllUsesWith(NC); |
| 6056 | GEPI->eraseFromParent(); |
| 6057 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6058 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6059 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6060 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6061 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6062 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6063 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6064 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6065 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6066 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 6067 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6068 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 6069 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 6070 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6071 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 6072 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 6073 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 6074 | return optimizeSwitchInst(Switch); |
| 6075 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6076 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6077 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6078 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6079 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6080 | } |
| 6081 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6082 | /// Given an OR instruction, check to see if this is a bitreverse |
| 6083 | /// idiom. If so, insert the new intrinsic and return true. |
| 6084 | static bool makeBitReverse(Instruction &I, const DataLayout &DL, |
| 6085 | const TargetLowering &TLI) { |
| 6086 | if (!I.getType()->isIntegerTy() || |
| 6087 | !TLI.isOperationLegalOrCustom(ISD::BITREVERSE, |
| 6088 | TLI.getValueType(DL, I.getType(), true))) |
| 6089 | return false; |
| 6090 | |
| 6091 | SmallVector<Instruction*, 4> Insts; |
Chad Rosier | a00df49 | 2016-05-25 16:22:14 +0000 | [diff] [blame] | 6092 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6093 | return false; |
| 6094 | Instruction *LastInst = Insts.back(); |
| 6095 | I.replaceAllUsesWith(LastInst); |
| 6096 | RecursivelyDeleteTriviallyDeadInstructions(&I); |
| 6097 | return true; |
| 6098 | } |
| 6099 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 6100 | // In this pass we look for GEP and cast instructions that are used |
| 6101 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 6102 | // selection. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6103 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 6104 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 6105 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 6106 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 6107 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 6108 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 6109 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 6110 | if (ModifiedDT) |
| 6111 | return true; |
| 6112 | } |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 6113 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6114 | bool MadeBitReverse = true; |
| 6115 | while (TLI && MadeBitReverse) { |
| 6116 | MadeBitReverse = false; |
| 6117 | for (auto &I : reverse(BB)) { |
| 6118 | if (makeBitReverse(I, *DL, *TLI)) { |
| 6119 | MadeBitReverse = MadeChange = true; |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 6120 | ModifiedDT = true; |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6121 | break; |
| 6122 | } |
| 6123 | } |
| 6124 | } |
James Molloy | 3ef84c4 | 2016-01-15 10:36:01 +0000 | [diff] [blame] | 6125 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Junmo Park | 7d6c5f1 | 2016-01-28 09:42:39 +0000 | [diff] [blame] | 6126 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 6127 | return MadeChange; |
| 6128 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6129 | |
| 6130 | // 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] | 6131 | // 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] | 6132 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6133 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6134 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 6135 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 6136 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 6137 | 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] | 6138 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6139 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 6140 | // Leave dbg.values that refer to an alloca alone. These |
| 6141 | // instrinsics describe the address of a variable (= the alloca) |
| 6142 | // being taken. They should not be moved next to the alloca |
| 6143 | // (and to the beginning of the scope), but rather stay close to |
| 6144 | // where said address is used. |
| 6145 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6146 | PrevNonDbgInst = Insn; |
| 6147 | continue; |
| 6148 | } |
| 6149 | |
| 6150 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 6151 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
Reid Kleckner | 8de1fe2 | 2015-12-08 23:00:03 +0000 | [diff] [blame] | 6152 | // If VI is a phi in a block with an EHPad terminator, we can't insert |
| 6153 | // after it. |
| 6154 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) |
| 6155 | continue; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6156 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 6157 | DVI->removeFromParent(); |
Reid Kleckner | e18f92b | 2015-12-08 22:33:23 +0000 | [diff] [blame] | 6158 | if (isa<PHINode>(VI)) |
| 6159 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
| 6160 | else |
| 6161 | DVI->insertAfter(VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6162 | MadeChange = true; |
| 6163 | ++NumDbgValueMoved; |
| 6164 | } |
| 6165 | } |
| 6166 | } |
| 6167 | return MadeChange; |
| 6168 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 6169 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6170 | /// \brief Scale down both weights to fit into uint32_t. |
| 6171 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 6172 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
| 6173 | uint32_t Scale = (NewMax / UINT32_MAX) + 1; |
| 6174 | NewTrue = NewTrue / Scale; |
| 6175 | NewFalse = NewFalse / Scale; |
| 6176 | } |
| 6177 | |
| 6178 | /// \brief Some targets prefer to split a conditional branch like: |
| 6179 | /// \code |
| 6180 | /// %0 = icmp ne i32 %a, 0 |
| 6181 | /// %1 = icmp ne i32 %b, 0 |
| 6182 | /// %or.cond = or i1 %0, %1 |
| 6183 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 6184 | /// \endcode |
| 6185 | /// into multiple branch instructions like: |
| 6186 | /// \code |
| 6187 | /// bb1: |
| 6188 | /// %0 = icmp ne i32 %a, 0 |
| 6189 | /// br i1 %0, label %TrueBB, label %bb2 |
| 6190 | /// bb2: |
| 6191 | /// %1 = icmp ne i32 %b, 0 |
| 6192 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 6193 | /// \endcode |
| 6194 | /// This usually allows instruction selection to do even further optimizations |
| 6195 | /// and combine the compare with the branch instruction. Currently this is |
| 6196 | /// applied for targets which have "cheap" jump instructions. |
| 6197 | /// |
| 6198 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 6199 | /// |
| 6200 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 6201 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6202 | return false; |
| 6203 | |
| 6204 | bool MadeChange = false; |
| 6205 | for (auto &BB : F) { |
| 6206 | // Does this BB end with the following? |
| 6207 | // %cond1 = icmp|fcmp|binary instruction ... |
| 6208 | // %cond2 = icmp|fcmp|binary instruction ... |
| 6209 | // %cond.or = or|and i1 %cond1, cond2 |
| 6210 | // br i1 %cond.or label %dest1, label %dest2" |
| 6211 | BinaryOperator *LogicOp; |
| 6212 | BasicBlock *TBB, *FBB; |
| 6213 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 6214 | continue; |
| 6215 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 6216 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 6217 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 6218 | continue; |
| 6219 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6220 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6221 | Value *Cond1, *Cond2; |
| 6222 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 6223 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6224 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6225 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 6226 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6227 | Opc = Instruction::Or; |
| 6228 | else |
| 6229 | continue; |
| 6230 | |
| 6231 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 6232 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 6233 | continue; |
| 6234 | |
| 6235 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 6236 | |
| 6237 | // Create a new BB. |
Duncan P. N. Exon Smith | a848c47 | 2016-02-21 19:52:15 +0000 | [diff] [blame] | 6238 | auto TmpBB = |
| 6239 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", |
| 6240 | BB.getParent(), BB.getNextNode()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6241 | |
| 6242 | // Update original basic block by using the first condition directly by the |
| 6243 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6244 | Br1->setCondition(Cond1); |
| 6245 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6246 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6247 | // Depending on the conditon we have to either replace the true or the false |
| 6248 | // successor of the original branch instruction. |
| 6249 | if (Opc == Instruction::And) |
| 6250 | Br1->setSuccessor(0, TmpBB); |
| 6251 | else |
| 6252 | Br1->setSuccessor(1, TmpBB); |
| 6253 | |
| 6254 | // Fill in the new basic block. |
| 6255 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6256 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 6257 | I->removeFromParent(); |
| 6258 | I->insertBefore(Br2); |
| 6259 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6260 | |
| 6261 | // Update PHI nodes in both successors. The original BB needs to be |
| 6262 | // replaced in one succesor's PHI nodes, because the branch comes now from |
| 6263 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 6264 | // incoming edge to the PHI nodes, because both branch instructions target |
| 6265 | // now the same successor. Depending on the original branch condition |
| 6266 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 6267 | // we perform the correct update for the PHI nodes. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6268 | // This doesn't change the successor order of the just created branch |
| 6269 | // instruction (or any other instruction). |
| 6270 | if (Opc == Instruction::Or) |
| 6271 | std::swap(TBB, FBB); |
| 6272 | |
| 6273 | // Replace the old BB with the new BB. |
| 6274 | for (auto &I : *TBB) { |
| 6275 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 6276 | if (!PN) |
| 6277 | break; |
| 6278 | int i; |
| 6279 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 6280 | PN->setIncomingBlock(i, TmpBB); |
| 6281 | } |
| 6282 | |
| 6283 | // Add another incoming edge form the new BB. |
| 6284 | for (auto &I : *FBB) { |
| 6285 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 6286 | if (!PN) |
| 6287 | break; |
| 6288 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 6289 | PN->addIncoming(Val, TmpBB); |
| 6290 | } |
| 6291 | |
| 6292 | // Update the branch weights (from SelectionDAGBuilder:: |
| 6293 | // FindMergedConditions). |
| 6294 | if (Opc == Instruction::Or) { |
| 6295 | // Codegen X | Y as: |
| 6296 | // BB1: |
| 6297 | // jmp_if_X TBB |
| 6298 | // jmp TmpBB |
| 6299 | // TmpBB: |
| 6300 | // jmp_if_Y TBB |
| 6301 | // jmp FBB |
| 6302 | // |
| 6303 | |
| 6304 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 6305 | // The requirement is that |
| 6306 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 6307 | // = TrueProb for orignal BB. |
| 6308 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 6309 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 6310 | // assumes that |
| 6311 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 6312 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 6313 | // TmpBB, but the math is more complicated. |
| 6314 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6315 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6316 | uint64_t NewTrueWeight = TrueWeight; |
| 6317 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 6318 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6319 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6320 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6321 | |
| 6322 | NewTrueWeight = TrueWeight; |
| 6323 | NewFalseWeight = 2 * FalseWeight; |
| 6324 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6325 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6326 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6327 | } |
| 6328 | } else { |
| 6329 | // Codegen X & Y as: |
| 6330 | // BB1: |
| 6331 | // jmp_if_X TmpBB |
| 6332 | // jmp FBB |
| 6333 | // TmpBB: |
| 6334 | // jmp_if_Y TBB |
| 6335 | // jmp FBB |
| 6336 | // |
| 6337 | // This requires creation of TmpBB after CurBB. |
| 6338 | |
| 6339 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 6340 | // The requirement is that |
| 6341 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 6342 | // = FalseProb for orignal BB. |
| 6343 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 6344 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 6345 | // assumes that |
| 6346 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 6347 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6348 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6349 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 6350 | uint64_t NewFalseWeight = FalseWeight; |
| 6351 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6352 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6353 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6354 | |
| 6355 | NewTrueWeight = 2 * TrueWeight; |
| 6356 | NewFalseWeight = FalseWeight; |
| 6357 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6358 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6359 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6360 | } |
| 6361 | } |
| 6362 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6363 | // 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] | 6364 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6365 | ModifiedDT = true; |
| 6366 | |
| 6367 | MadeChange = true; |
| 6368 | |
| 6369 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 6370 | TmpBB->dump()); |
| 6371 | } |
| 6372 | return MadeChange; |
| 6373 | } |