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 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/APInt.h" |
| 17 | #include "llvm/ADT/ArrayRef.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 18 | #include "llvm/ADT/DenseMap.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 19 | #include "llvm/ADT/PointerIntPair.h" |
| 20 | #include "llvm/ADT/STLExtras.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/SmallPtrSet.h" |
| 22 | #include "llvm/ADT/SmallVector.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 23 | #include "llvm/ADT/Statistic.h" |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 25 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/ConstantFolding.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/InstructionSimplify.h" |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/LoopInfo.h" |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/MemoryBuiltins.h" |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 30 | #include "llvm/Analysis/ProfileSummaryInfo.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 31 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 32 | #include "llvm/Analysis/TargetTransformInfo.h" |
David Blaikie | 31b98d2 | 2018-06-04 21:23:21 +0000 | [diff] [blame] | 33 | #include "llvm/Transforms/Utils/Local.h" |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 34 | #include "llvm/Analysis/ValueTracking.h" |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 35 | #include "llvm/CodeGen/Analysis.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 36 | #include "llvm/CodeGen/ISDOpcodes.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 37 | #include "llvm/CodeGen/SelectionDAGNodes.h" |
David Blaikie | b3bde2e | 2017-11-17 01:07:10 +0000 | [diff] [blame] | 38 | #include "llvm/CodeGen/TargetLowering.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 39 | #include "llvm/CodeGen/TargetPassConfig.h" |
David Blaikie | b3bde2e | 2017-11-17 01:07:10 +0000 | [diff] [blame] | 40 | #include "llvm/CodeGen/TargetSubtargetInfo.h" |
Craig Topper | 2fa1436 | 2018-03-29 17:21:10 +0000 | [diff] [blame] | 41 | #include "llvm/CodeGen/ValueTypes.h" |
Nico Weber | 432a388 | 2018-04-30 14:59:11 +0000 | [diff] [blame] | 42 | #include "llvm/Config/llvm-config.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 43 | #include "llvm/IR/Argument.h" |
| 44 | #include "llvm/IR/Attributes.h" |
| 45 | #include "llvm/IR/BasicBlock.h" |
Chandler Carruth | 219b89b | 2014-03-04 11:01:28 +0000 | [diff] [blame] | 46 | #include "llvm/IR/CallSite.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 47 | #include "llvm/IR/Constant.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 48 | #include "llvm/IR/Constants.h" |
| 49 | #include "llvm/IR/DataLayout.h" |
| 50 | #include "llvm/IR/DerivedTypes.h" |
Chandler Carruth | 5ad5f15 | 2014-01-13 09:26:24 +0000 | [diff] [blame] | 51 | #include "llvm/IR/Dominators.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 52 | #include "llvm/IR/Function.h" |
Chandler Carruth | 03eb0de | 2014-03-04 10:40:04 +0000 | [diff] [blame] | 53 | #include "llvm/IR/GetElementPtrTypeIterator.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 54 | #include "llvm/IR/GlobalValue.h" |
| 55 | #include "llvm/IR/GlobalVariable.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 56 | #include "llvm/IR/IRBuilder.h" |
| 57 | #include "llvm/IR/InlineAsm.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 58 | #include "llvm/IR/InstrTypes.h" |
| 59 | #include "llvm/IR/Instruction.h" |
Chandler Carruth | 9fb823b | 2013-01-02 11:36:10 +0000 | [diff] [blame] | 60 | #include "llvm/IR/Instructions.h" |
| 61 | #include "llvm/IR/IntrinsicInst.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 62 | #include "llvm/IR/Intrinsics.h" |
| 63 | #include "llvm/IR/LLVMContext.h" |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 64 | #include "llvm/IR/MDBuilder.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 65 | #include "llvm/IR/Module.h" |
| 66 | #include "llvm/IR/Operator.h" |
Chandler Carruth | 820a908 | 2014-03-04 11:08:18 +0000 | [diff] [blame] | 67 | #include "llvm/IR/PatternMatch.h" |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 68 | #include "llvm/IR/Statepoint.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 69 | #include "llvm/IR/Type.h" |
| 70 | #include "llvm/IR/Use.h" |
| 71 | #include "llvm/IR/User.h" |
| 72 | #include "llvm/IR/Value.h" |
Chandler Carruth | 4220e9c | 2014-03-04 11:17:44 +0000 | [diff] [blame] | 73 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | a4ea269 | 2014-03-04 11:26:31 +0000 | [diff] [blame] | 74 | #include "llvm/IR/ValueMap.h" |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 75 | #include "llvm/Pass.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 76 | #include "llvm/Support/BlockFrequency.h" |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 77 | #include "llvm/Support/BranchProbability.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 78 | #include "llvm/Support/Casting.h" |
Evan Cheng | 8b637b1 | 2010-08-17 01:34:49 +0000 | [diff] [blame] | 79 | #include "llvm/Support/CommandLine.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 80 | #include "llvm/Support/Compiler.h" |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 81 | #include "llvm/Support/Debug.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 82 | #include "llvm/Support/ErrorHandling.h" |
David Blaikie | 13e77db | 2018-03-23 23:58:25 +0000 | [diff] [blame] | 83 | #include "llvm/Support/MachineValueType.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 84 | #include "llvm/Support/MathExtras.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 85 | #include "llvm/Support/raw_ostream.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 86 | #include "llvm/Target/TargetMachine.h" |
| 87 | #include "llvm/Target/TargetOptions.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 88 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 89 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 90 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 91 | #include <algorithm> |
| 92 | #include <cassert> |
| 93 | #include <cstdint> |
| 94 | #include <iterator> |
| 95 | #include <limits> |
| 96 | #include <memory> |
| 97 | #include <utility> |
| 98 | #include <vector> |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 99 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 100 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 101 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 102 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 103 | #define DEBUG_TYPE "codegenprepare" |
| 104 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 105 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 106 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 107 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 108 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 109 | "sunken Cmps"); |
| 110 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 111 | "of sunken Casts"); |
| 112 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 113 | "computations were sunk"); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 114 | STATISTIC(NumMemoryInstsPhiCreated, |
| 115 | "Number of phis created when address " |
| 116 | "computations were sunk to memory instructions"); |
| 117 | STATISTIC(NumMemoryInstsSelectCreated, |
| 118 | "Number of select created when address " |
| 119 | "computations were sunk to memory instructions"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 120 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 121 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 122 | STATISTIC(NumAndsAdded, |
| 123 | "Number of and mask instructions added to form ext loads"); |
| 124 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 125 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 126 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 127 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 128 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 129 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 130 | static cl::opt<bool> DisableBranchOpts( |
| 131 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 132 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 133 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 134 | static cl::opt<bool> |
| 135 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 136 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 137 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 138 | static cl::opt<bool> DisableSelectToBranch( |
| 139 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 140 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 141 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 142 | static cl::opt<bool> AddrSinkUsingGEPs( |
Eli Friedman | 5fba1e5 | 2017-04-06 22:42:18 +0000 | [diff] [blame] | 143 | "addr-sink-using-gep", cl::Hidden, cl::init(true), |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 144 | cl::desc("Address sinking in CGP using GEPs.")); |
| 145 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 146 | static cl::opt<bool> EnableAndCmpSinking( |
| 147 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 148 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 149 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 150 | static cl::opt<bool> DisableStoreExtract( |
| 151 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 152 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 153 | |
| 154 | static cl::opt<bool> StressStoreExtract( |
| 155 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 156 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 157 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 158 | static cl::opt<bool> DisableExtLdPromotion( |
| 159 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 160 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 161 | "CodeGenPrepare")); |
| 162 | |
| 163 | static cl::opt<bool> StressExtLdPromotion( |
| 164 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 165 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 166 | "optimization in CodeGenPrepare")); |
| 167 | |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 168 | static cl::opt<bool> DisablePreheaderProtect( |
| 169 | "disable-preheader-prot", cl::Hidden, cl::init(false), |
| 170 | cl::desc("Disable protection against removing loop preheaders")); |
| 171 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 172 | static cl::opt<bool> ProfileGuidedSectionPrefix( |
David Callahan | 5960d9b1 | 2017-06-14 20:35:33 +0000 | [diff] [blame] | 173 | "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore, |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 174 | cl::desc("Use profile info to add section prefix for hot/cold functions")); |
| 175 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 176 | static cl::opt<unsigned> FreqRatioToSkipMerge( |
| 177 | "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), |
| 178 | cl::desc("Skip merging empty blocks if (frequency of empty block) / " |
| 179 | "(frequency of destination block) is greater than this ratio")); |
| 180 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 181 | static cl::opt<bool> ForceSplitStore( |
| 182 | "force-split-store", cl::Hidden, cl::init(false), |
| 183 | cl::desc("Force store splitting no matter what the target query says.")); |
| 184 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 185 | static cl::opt<bool> |
| 186 | EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, |
| 187 | cl::desc("Enable merging of redundant sexts when one is dominating" |
| 188 | " the other."), cl::init(true)); |
| 189 | |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 190 | static cl::opt<bool> DisableComplexAddrModes( |
Serguei Katkov | d4df744 | 2017-11-29 09:48:50 +0000 | [diff] [blame] | 191 | "disable-complex-addr-modes", cl::Hidden, cl::init(false), |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 192 | cl::desc("Disables combining addressing modes with different parts " |
| 193 | "in optimizeMemoryInst.")); |
| 194 | |
| 195 | static cl::opt<bool> |
| 196 | AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), |
| 197 | cl::desc("Allow creation of Phis in Address sinking.")); |
| 198 | |
| 199 | static cl::opt<bool> |
Serguei Katkov | 9fe0524 | 2018-01-26 06:26:56 +0000 | [diff] [blame] | 200 | AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true), |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 201 | cl::desc("Allow creation of selects in Address sinking.")); |
| 202 | |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 203 | static cl::opt<bool> AddrSinkCombineBaseReg( |
| 204 | "addr-sink-combine-base-reg", cl::Hidden, cl::init(true), |
| 205 | cl::desc("Allow combining of BaseReg field in Address sinking.")); |
| 206 | |
| 207 | static cl::opt<bool> AddrSinkCombineBaseGV( |
| 208 | "addr-sink-combine-base-gv", cl::Hidden, cl::init(true), |
| 209 | cl::desc("Allow combining of BaseGV field in Address sinking.")); |
| 210 | |
| 211 | static cl::opt<bool> AddrSinkCombineBaseOffs( |
| 212 | "addr-sink-combine-base-offs", cl::Hidden, cl::init(true), |
| 213 | cl::desc("Allow combining of BaseOffs field in Address sinking.")); |
| 214 | |
| 215 | static cl::opt<bool> AddrSinkCombineScaledReg( |
| 216 | "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), |
| 217 | cl::desc("Allow combining of ScaledReg field in Address sinking.")); |
| 218 | |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 219 | static cl::opt<bool> |
| 220 | EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden, |
| 221 | cl::init(true), |
| 222 | cl::desc("Enable splitting large offset of GEP.")); |
| 223 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 224 | namespace { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 225 | |
Guozhi Wei | 8c17f9a | 2018-08-15 22:08:26 +0000 | [diff] [blame] | 226 | enum ExtType { |
| 227 | ZeroExtension, // Zero extension has been seen. |
| 228 | SignExtension, // Sign extension has been seen. |
| 229 | BothExtension // This extension type is used if we saw sext after |
| 230 | // ZeroExtension had been set, or if we saw zext after |
| 231 | // SignExtension had been set. It makes the type |
| 232 | // information of a promoted instruction invalid. |
| 233 | }; |
| 234 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 235 | using SetOfInstrs = SmallPtrSet<Instruction *, 16>; |
Guozhi Wei | 8c17f9a | 2018-08-15 22:08:26 +0000 | [diff] [blame] | 236 | using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 237 | using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>; |
| 238 | using SExts = SmallVector<Instruction *, 16>; |
| 239 | using ValueToSExts = DenseMap<Value *, SExts>; |
| 240 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 241 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 242 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 243 | class CodeGenPrepare : public FunctionPass { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 244 | const TargetMachine *TM = nullptr; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 245 | const TargetSubtargetInfo *SubtargetInfo; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 246 | const TargetLowering *TLI = nullptr; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 247 | const TargetRegisterInfo *TRI; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 248 | const TargetTransformInfo *TTI = nullptr; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 249 | const TargetLibraryInfo *TLInfo; |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 250 | const LoopInfo *LI; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 251 | std::unique_ptr<BlockFrequencyInfo> BFI; |
| 252 | std::unique_ptr<BranchProbabilityInfo> BPI; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 253 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 254 | /// As we scan instructions optimizing them, this is the next instruction |
| 255 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 256 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 257 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 258 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 259 | /// This allows us to avoid inserting duplicate code for blocks with |
Simon Dardis | 230f453 | 2017-11-24 16:45:28 +0000 | [diff] [blame] | 260 | /// multiple load/stores of the same address. The usage of WeakTrackingVH |
| 261 | /// enables SunkAddrs to be treated as a cache whose entries can be |
| 262 | /// invalidated if a sunken address computation has been erased. |
| 263 | ValueMap<Value*, WeakTrackingVH> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 264 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 265 | /// Keeps track of all instructions inserted for the current function. |
| 266 | SetOfInstrs InsertedInsts; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 267 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 268 | /// Keeps track of the type of the related instruction before their |
| 269 | /// promotion for the current function. |
| 270 | InstrToOrigTy PromotedInsts; |
| 271 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 272 | /// Keep track of instructions removed during promotion. |
| 273 | SetOfInstrs RemovedInsts; |
| 274 | |
| 275 | /// Keep track of sext chains based on their initial value. |
| 276 | DenseMap<Value *, Instruction *> SeenChainsForSExt; |
| 277 | |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 278 | /// Keep track of GEPs accessing the same data structures such as structs or |
| 279 | /// arrays that are candidates to be split later because of their large |
| 280 | /// size. |
| 281 | DenseMap< |
| 282 | AssertingVH<Value>, |
| 283 | SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>> |
| 284 | LargeOffsetGEPMap; |
| 285 | |
| 286 | /// Keep track of new GEP base after splitting the GEPs having large offset. |
| 287 | SmallSet<AssertingVH<Value>, 2> NewGEPBases; |
| 288 | |
| 289 | /// Map serial numbers to Large offset GEPs. |
| 290 | DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID; |
| 291 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 292 | /// Keep track of SExt promoted. |
| 293 | ValueToSExts ValToSExtendedUses; |
| 294 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 295 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 296 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 297 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 298 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 299 | bool OptSize; |
| 300 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 301 | /// DataLayout for the Function being processed. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 302 | const DataLayout *DL = nullptr; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 303 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 304 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 305 | static char ID; // Pass identification, replacement for typeid |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 306 | |
| 307 | CodeGenPrepare() : FunctionPass(ID) { |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 308 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 309 | } |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 310 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 311 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 312 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 313 | StringRef getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 314 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 315 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 316 | // FIXME: When we can selectively preserve passes, preserve the domtree. |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 317 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 318 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 319 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 320 | AU.addRequired<LoopInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 321 | } |
| 322 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 323 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 324 | bool eliminateFallThrough(Function &F); |
| 325 | bool eliminateMostlyEmptyBlocks(Function &F); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 326 | BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 327 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 328 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 329 | bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, |
| 330 | bool isPreheader); |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 331 | bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT); |
| 332 | bool optimizeInst(Instruction *I, bool &ModifiedDT); |
Fangrui Song | cb0bab8 | 2018-07-16 18:51:40 +0000 | [diff] [blame] | 333 | bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
| 334 | Type *AccessTy, unsigned AddrSpace); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 335 | bool optimizeInlineAsmInst(CallInst *CS); |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 336 | bool optimizeCallInst(CallInst *CI, bool &ModifiedDT); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 337 | bool optimizeExt(Instruction *&I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 338 | bool optimizeExtUses(Instruction *I); |
Fangrui Song | cb0bab8 | 2018-07-16 18:51:40 +0000 | [diff] [blame] | 339 | bool optimizeLoadExt(LoadInst *Load); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 340 | bool optimizeSelectInst(SelectInst *SI); |
Fangrui Song | cb0bab8 | 2018-07-16 18:51:40 +0000 | [diff] [blame] | 341 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI); |
| 342 | bool optimizeSwitchInst(SwitchInst *SI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 343 | bool optimizeExtractElementInst(Instruction *Inst); |
| 344 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 345 | bool placeDbgValues(Function &F); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 346 | bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, |
| 347 | LoadInst *&LI, Instruction *&Inst, bool HasPromoted); |
| 348 | bool tryToPromoteExts(TypePromotionTransaction &TPT, |
| 349 | const SmallVectorImpl<Instruction *> &Exts, |
| 350 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 351 | unsigned CreatedInstsCost = 0); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 352 | bool mergeSExts(Function &F); |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 353 | bool splitLargeGEPOffsets(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 354 | bool performAddressTypePromotion( |
| 355 | Instruction *&Inst, |
| 356 | bool AllowPromotionWithoutCommonHeader, |
| 357 | bool HasPromoted, TypePromotionTransaction &TPT, |
| 358 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 359 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 360 | bool simplifyOffsetableRelocate(Instruction &I); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 361 | }; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 362 | |
| 363 | } // end anonymous namespace |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 364 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 365 | char CodeGenPrepare::ID = 0; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 366 | |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 367 | INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE, |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 368 | "Optimize for code generation", false, false) |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 369 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 370 | INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 371 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 372 | |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 373 | FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 374 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 375 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 376 | if (skipFunction(F)) |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 377 | return false; |
| 378 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 379 | DL = &F.getParent()->getDataLayout(); |
| 380 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 381 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 382 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 383 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 384 | PromotedInsts.clear(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 385 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 386 | ModifiedDT = false; |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 387 | if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) { |
| 388 | TM = &TPC->getTM<TargetMachine>(); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 389 | SubtargetInfo = TM->getSubtargetImpl(F); |
| 390 | TLI = SubtargetInfo->getTargetLowering(); |
| 391 | TRI = SubtargetInfo->getRegisterInfo(); |
| 392 | } |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 393 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 394 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 395 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Teresa Johnson | a4ce3bf | 2017-12-20 17:53:10 +0000 | [diff] [blame] | 396 | BPI.reset(new BranchProbabilityInfo(F, *LI)); |
| 397 | BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI)); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 398 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 399 | |
Easwaran Raman | 0d55b55 | 2017-11-14 19:31:51 +0000 | [diff] [blame] | 400 | ProfileSummaryInfo *PSI = |
| 401 | getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 402 | if (ProfileGuidedSectionPrefix) { |
Teresa Johnson | a4ce3bf | 2017-12-20 17:53:10 +0000 | [diff] [blame] | 403 | if (PSI->isFunctionHotInCallGraph(&F, *BFI)) |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 404 | F.setSectionPrefix(".hot"); |
Teresa Johnson | a4ce3bf | 2017-12-20 17:53:10 +0000 | [diff] [blame] | 405 | else if (PSI->isFunctionColdInCallGraph(&F, *BFI)) |
Teresa Johnson | 720d9b4 | 2017-05-09 01:43:24 +0000 | [diff] [blame] | 406 | F.setSectionPrefix(".unlikely"); |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 407 | } |
| 408 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 409 | /// This optimization identifies DIV instructions that can be |
| 410 | /// profitably bypassed and carried out with a shorter, faster divide. |
Easwaran Raman | 0d55b55 | 2017-11-14 19:31:51 +0000 | [diff] [blame] | 411 | if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI && |
| 412 | TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 413 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 414 | TLI->getBypassSlowDivWidths(); |
Eric Christopher | 49a7d6c | 2016-01-04 23:18:58 +0000 | [diff] [blame] | 415 | BasicBlock* BB = &*F.begin(); |
| 416 | while (BB != nullptr) { |
| 417 | // bypassSlowDivision may create new BBs, but we don't want to reapply the |
| 418 | // optimization to those blocks. |
| 419 | BasicBlock* Next = BB->getNextNode(); |
| 420 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); |
| 421 | BB = Next; |
| 422 | } |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 423 | } |
| 424 | |
| 425 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 426 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 427 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 428 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 429 | if (!DisableBranchOpts) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 430 | EverMadeChange |= splitBranchCondition(F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 431 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 432 | // Split some critical edges where one of the sources is an indirect branch, |
| 433 | // to help generate sane code for PHIs involving such edges. |
Hiroshi Yamauchi | 9364fa3 | 2017-12-04 20:36:01 +0000 | [diff] [blame] | 434 | EverMadeChange |= SplitIndirectBrCriticalEdges(F); |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 435 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 436 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 437 | while (MadeChange) { |
| 438 | MadeChange = false; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 439 | SeenChainsForSExt.clear(); |
| 440 | ValToSExtendedUses.clear(); |
| 441 | RemovedInsts.clear(); |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 442 | LargeOffsetGEPMap.clear(); |
| 443 | LargeOffsetGEPID.clear(); |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 444 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 445 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 446 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 447 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 448 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 449 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 450 | if (ModifiedDTOnIteration) |
| 451 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 452 | } |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 453 | if (EnableTypePromotionMerge && !ValToSExtendedUses.empty()) |
| 454 | MadeChange |= mergeSExts(F); |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 455 | if (!LargeOffsetGEPMap.empty()) |
| 456 | MadeChange |= splitLargeGEPOffsets(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 457 | |
| 458 | // Really free removed instructions during promotion. |
| 459 | for (Instruction *I : RemovedInsts) |
Reid Kleckner | 96ab872 | 2017-05-18 17:24:10 +0000 | [diff] [blame] | 460 | I->deleteValue(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 461 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 462 | EverMadeChange |= MadeChange; |
| 463 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 464 | |
| 465 | SunkAddrs.clear(); |
| 466 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 467 | if (!DisableBranchOpts) { |
| 468 | MadeChange = false; |
David Stenberg | 23bba56 | 2018-07-02 14:23:48 +0000 | [diff] [blame] | 469 | // Use a set vector to get deterministic iteration order. The order the |
| 470 | // blocks are removed may affect whether or not PHI nodes in successors |
| 471 | // are removed. |
| 472 | SmallSetVector<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 473 | for (BasicBlock &BB : F) { |
| 474 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 475 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 476 | if (!MadeChange) continue; |
| 477 | |
| 478 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 479 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 480 | if (pred_begin(*II) == pred_end(*II)) |
| 481 | WorkList.insert(*II); |
| 482 | } |
| 483 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 484 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 485 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 486 | while (!WorkList.empty()) { |
David Stenberg | 23bba56 | 2018-07-02 14:23:48 +0000 | [diff] [blame] | 487 | BasicBlock *BB = WorkList.pop_back_val(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 488 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 489 | |
| 490 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 491 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 492 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 493 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 494 | if (pred_begin(*II) == pred_end(*II)) |
| 495 | WorkList.insert(*II); |
| 496 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 497 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 498 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 499 | // a single edge. |
| 500 | if (EverMadeChange || MadeChange) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 501 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 502 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 503 | EverMadeChange |= MadeChange; |
| 504 | } |
| 505 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 506 | if (!DisableGCOpts) { |
| 507 | SmallVector<Instruction *, 2> Statepoints; |
| 508 | for (BasicBlock &BB : F) |
| 509 | for (Instruction &I : BB) |
| 510 | if (isStatepoint(I)) |
| 511 | Statepoints.push_back(&I); |
| 512 | for (auto &I : Statepoints) |
| 513 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 514 | } |
| 515 | |
Vedant Kumar | 30406fd | 2018-08-21 23:43:08 +0000 | [diff] [blame] | 516 | // Do this last to clean up use-before-def scenarios introduced by other |
| 517 | // preparatory transforms. |
| 518 | EverMadeChange |= placeDbgValues(F); |
| 519 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 520 | return EverMadeChange; |
| 521 | } |
| 522 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 523 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 524 | /// basic blocks has a single successor pointing to the other basic block, |
| 525 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 526 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 527 | bool Changed = false; |
| 528 | // Scan all of the blocks in the function, except for the entry block. |
Alina Sbirlea | dfd14ad | 2018-06-20 22:01:04 +0000 | [diff] [blame] | 529 | // Use a temporary array to avoid iterator being invalidated when |
| 530 | // deleting blocks. |
| 531 | SmallVector<WeakTrackingVH, 16> Blocks; |
| 532 | for (auto &Block : llvm::make_range(std::next(F.begin()), F.end())) |
| 533 | Blocks.push_back(&Block); |
| 534 | |
| 535 | for (auto &Block : Blocks) { |
| 536 | auto *BB = cast_or_null<BasicBlock>(Block); |
| 537 | if (!BB) |
| 538 | continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 539 | // If the destination block has a single pred, then this is a trivial |
| 540 | // edge, just collapse it. |
| 541 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 542 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 543 | // Don't merge if BB's address is taken. |
| 544 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 545 | |
| 546 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 547 | if (Term && !Term->isConditional()) { |
| 548 | Changed = true; |
Alina Sbirlea | dfd14ad | 2018-06-20 22:01:04 +0000 | [diff] [blame] | 549 | LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 550 | |
Alina Sbirlea | dfd14ad | 2018-06-20 22:01:04 +0000 | [diff] [blame] | 551 | // Merge BB into SinglePred and delete it. |
| 552 | MergeBlockIntoPredecessor(BB); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 553 | } |
| 554 | } |
| 555 | return Changed; |
| 556 | } |
| 557 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 558 | /// Find a destination block from BB if BB is mergeable empty block. |
| 559 | BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { |
| 560 | // If this block doesn't end with an uncond branch, ignore it. |
| 561 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 562 | if (!BI || !BI->isUnconditional()) |
| 563 | return nullptr; |
| 564 | |
| 565 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 566 | // node, then other stuff is happening here. |
| 567 | BasicBlock::iterator BBI = BI->getIterator(); |
| 568 | if (BBI != BB->begin()) { |
| 569 | --BBI; |
| 570 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 571 | if (BBI == BB->begin()) |
| 572 | break; |
| 573 | --BBI; |
| 574 | } |
| 575 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 576 | return nullptr; |
| 577 | } |
| 578 | |
| 579 | // Do not break infinite loops. |
| 580 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 581 | if (DestBB == BB) |
| 582 | return nullptr; |
| 583 | |
| 584 | if (!canMergeBlocks(BB, DestBB)) |
| 585 | DestBB = nullptr; |
| 586 | |
| 587 | return DestBB; |
| 588 | } |
| 589 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 590 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 591 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 592 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 593 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 594 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 595 | SmallPtrSet<BasicBlock *, 16> Preheaders; |
| 596 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); |
| 597 | while (!LoopList.empty()) { |
| 598 | Loop *L = LoopList.pop_back_val(); |
| 599 | LoopList.insert(LoopList.end(), L->begin(), L->end()); |
| 600 | if (BasicBlock *Preheader = L->getLoopPreheader()) |
| 601 | Preheaders.insert(Preheader); |
| 602 | } |
| 603 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 604 | bool MadeChange = false; |
Alina Sbirlea | dfd14ad | 2018-06-20 22:01:04 +0000 | [diff] [blame] | 605 | // Copy blocks into a temporary array to avoid iterator invalidation issues |
| 606 | // as we remove them. |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 607 | // Note that this intentionally skips the entry block. |
Alina Sbirlea | dfd14ad | 2018-06-20 22:01:04 +0000 | [diff] [blame] | 608 | SmallVector<WeakTrackingVH, 16> Blocks; |
| 609 | for (auto &Block : llvm::make_range(std::next(F.begin()), F.end())) |
| 610 | Blocks.push_back(&Block); |
| 611 | |
| 612 | for (auto &Block : Blocks) { |
| 613 | BasicBlock *BB = cast_or_null<BasicBlock>(Block); |
| 614 | if (!BB) |
| 615 | continue; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 616 | BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); |
| 617 | if (!DestBB || |
| 618 | !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 619 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 620 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 621 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 622 | MadeChange = true; |
| 623 | } |
| 624 | return MadeChange; |
| 625 | } |
| 626 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 627 | bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, |
| 628 | BasicBlock *DestBB, |
| 629 | bool isPreheader) { |
| 630 | // Do not delete loop preheaders if doing so would create a critical edge. |
| 631 | // Loop preheaders can be good locations to spill registers. If the |
| 632 | // preheader is deleted and we create a critical edge, registers may be |
| 633 | // spilled in the loop body instead. |
| 634 | if (!DisablePreheaderProtect && isPreheader && |
| 635 | !(BB->getSinglePredecessor() && |
| 636 | BB->getSinglePredecessor()->getSingleSuccessor())) |
| 637 | return false; |
| 638 | |
| 639 | // Try to skip merging if the unique predecessor of BB is terminated by a |
| 640 | // switch or indirect branch instruction, and BB is used as an incoming block |
| 641 | // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to |
| 642 | // add COPY instructions in the predecessor of BB instead of BB (if it is not |
| 643 | // merged). Note that the critical edge created by merging such blocks wont be |
| 644 | // split in MachineSink because the jump table is not analyzable. By keeping |
| 645 | // such empty block (BB), ISel will place COPY instructions in BB, not in the |
| 646 | // predecessor of BB. |
| 647 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 648 | if (!Pred || |
| 649 | !(isa<SwitchInst>(Pred->getTerminator()) || |
| 650 | isa<IndirectBrInst>(Pred->getTerminator()))) |
| 651 | return true; |
| 652 | |
Jonas Devlieghere | 42243df | 2018-08-07 12:14:01 +0000 | [diff] [blame] | 653 | if (BB->getTerminator() != BB->getFirstNonPHIOrDbg()) |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 654 | return true; |
| 655 | |
| 656 | // We use a simple cost heuristic which determine skipping merging is |
| 657 | // profitable if the cost of skipping merging is less than the cost of |
| 658 | // merging : Cost(skipping merging) < Cost(merging BB), where the |
| 659 | // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and |
| 660 | // the Cost(merging BB) is Freq(Pred) * Cost(Copy). |
| 661 | // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : |
| 662 | // Freq(Pred) / Freq(BB) > 2. |
| 663 | // Note that if there are multiple empty blocks sharing the same incoming |
| 664 | // value for the PHIs in the DestBB, we consider them together. In such |
| 665 | // case, Cost(merging BB) will be the sum of their frequencies. |
| 666 | |
| 667 | if (!isa<PHINode>(DestBB->begin())) |
| 668 | return true; |
| 669 | |
| 670 | SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; |
| 671 | |
| 672 | // Find all other incoming blocks from which incoming values of all PHIs in |
| 673 | // DestBB are the same as the ones from BB. |
| 674 | for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E; |
| 675 | ++PI) { |
| 676 | BasicBlock *DestBBPred = *PI; |
| 677 | if (DestBBPred == BB) |
| 678 | continue; |
| 679 | |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 680 | if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) { |
| 681 | return DestPN.getIncomingValueForBlock(BB) == |
| 682 | DestPN.getIncomingValueForBlock(DestBBPred); |
| 683 | })) |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 684 | SameIncomingValueBBs.insert(DestBBPred); |
| 685 | } |
| 686 | |
| 687 | // See if all BB's incoming values are same as the value from Pred. In this |
| 688 | // case, no reason to skip merging because COPYs are expected to be place in |
| 689 | // Pred already. |
| 690 | if (SameIncomingValueBBs.count(Pred)) |
| 691 | return true; |
| 692 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 693 | BlockFrequency PredFreq = BFI->getBlockFreq(Pred); |
| 694 | BlockFrequency BBFreq = BFI->getBlockFreq(BB); |
| 695 | |
| 696 | for (auto SameValueBB : SameIncomingValueBBs) |
| 697 | if (SameValueBB->getUniquePredecessor() == Pred && |
| 698 | DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) |
| 699 | BBFreq += BFI->getBlockFreq(SameValueBB); |
| 700 | |
| 701 | return PredFreq.getFrequency() <= |
| 702 | BBFreq.getFrequency() * FreqRatioToSkipMerge; |
| 703 | } |
| 704 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 705 | /// Return true if we can merge BB into DestBB if there is a single |
| 706 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 707 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 708 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 709 | const BasicBlock *DestBB) const { |
| 710 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 711 | // the successor. If there are more complex condition (e.g. preheaders), |
| 712 | // don't mess around with them. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 713 | for (const PHINode &PN : BB->phis()) { |
| 714 | for (const User *U : PN.users()) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 715 | const Instruction *UI = cast<Instruction>(U); |
| 716 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 717 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 718 | // If User is inside DestBB block and it is a PHINode then check |
| 719 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 720 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 721 | if (UI->getParent() == DestBB) { |
| 722 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 723 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 724 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 725 | if (Insn && Insn->getParent() == BB && |
| 726 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 727 | return false; |
| 728 | } |
| 729 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 730 | } |
| 731 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 732 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 733 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 734 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 735 | // can't merge the block. |
| 736 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 737 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 738 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 739 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 740 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 741 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 742 | // It is faster to get preds from a PHI than with pred_iterator. |
| 743 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 744 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 745 | } else { |
| 746 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 747 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 748 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 749 | // Walk the preds of DestBB. |
| 750 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 751 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 752 | if (BBPreds.count(Pred)) { // Common predecessor? |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 753 | for (const PHINode &PN : DestBB->phis()) { |
| 754 | const Value *V1 = PN.getIncomingValueForBlock(Pred); |
| 755 | const Value *V2 = PN.getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 756 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 757 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 758 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 759 | if (V2PN->getParent() == BB) |
| 760 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 761 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 762 | // If there is a conflict, bail out. |
| 763 | if (V1 != V2) return false; |
| 764 | } |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | return true; |
| 769 | } |
| 770 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 771 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 772 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 773 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 774 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 775 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 776 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 777 | LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" |
| 778 | << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 779 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 780 | // If the destination block has a single pred, then this is a trivial edge, |
| 781 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 782 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 783 | if (SinglePred != DestBB) { |
Alina Sbirlea | dfd14ad | 2018-06-20 22:01:04 +0000 | [diff] [blame] | 784 | assert(SinglePred == BB && |
| 785 | "Single predecessor not the same as predecessor"); |
| 786 | // Merge DestBB into SinglePred/BB and delete it. |
| 787 | MergeBlockIntoPredecessor(DestBB); |
| 788 | // Note: BB(=SinglePred) will not be deleted on this path. |
| 789 | // DestBB(=its single successor) is the one that was deleted. |
| 790 | LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 791 | return; |
| 792 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 793 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 794 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 795 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 796 | // to handle the new incoming edges it is about to have. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 797 | for (PHINode &PN : DestBB->phis()) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 798 | // Remove the incoming value for BB, and remember it. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 799 | Value *InVal = PN.removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 800 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 801 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 802 | // value that dominates BB. |
| 803 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 804 | if (InValPhi && InValPhi->getParent() == BB) { |
| 805 | // Add all of the input values of the input PHI as inputs of this phi. |
| 806 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 807 | PN.addIncoming(InValPhi->getIncomingValue(i), |
| 808 | InValPhi->getIncomingBlock(i)); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 809 | } else { |
| 810 | // Otherwise, add one instance of the dominating value for each edge that |
| 811 | // we will be adding. |
| 812 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 813 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 814 | PN.addIncoming(InVal, BBPN->getIncomingBlock(i)); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 815 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 816 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 817 | PN.addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 818 | } |
| 819 | } |
| 820 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 821 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 822 | // The PHIs are now updated, change everything that refers to BB to use |
| 823 | // DestBB and remove BB. |
| 824 | BB->replaceAllUsesWith(DestBB); |
| 825 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 826 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 827 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 828 | LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 829 | } |
| 830 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 831 | // Computes a map of base pointer relocation instructions to corresponding |
| 832 | // derived pointer relocation instructions given a vector of all relocate calls |
| 833 | static void computeBaseDerivedRelocateMap( |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 834 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, |
| 835 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> |
| 836 | &RelocateInstMap) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 837 | // Collect information in two maps: one primarily for locating the base object |
| 838 | // while filling the second map; the second map is the final structure holding |
| 839 | // a mapping between Base and corresponding Derived relocate calls |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 840 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; |
| 841 | for (auto *ThisRelocate : AllRelocateCalls) { |
| 842 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), |
| 843 | ThisRelocate->getDerivedPtrIndex()); |
| 844 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 845 | } |
| 846 | for (auto &Item : RelocateIdxMap) { |
| 847 | std::pair<unsigned, unsigned> Key = Item.first; |
| 848 | if (Key.first == Key.second) |
| 849 | // Base relocation: nothing to insert |
| 850 | continue; |
| 851 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 852 | GCRelocateInst *I = Item.second; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 853 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 854 | |
| 855 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 856 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 857 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 858 | // TODO: We might want to insert a new base object relocate and gep off |
| 859 | // that, if there are enough derived object relocates. |
| 860 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 861 | |
| 862 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 863 | } |
| 864 | } |
| 865 | |
| 866 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 867 | // small integer constants |
| 868 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 869 | SmallVectorImpl<Value *> &OffsetV) { |
| 870 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 871 | // Only accept small constant integer operands |
| 872 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 873 | if (!Op || Op->getZExtValue() > 20) |
| 874 | return false; |
| 875 | } |
| 876 | |
| 877 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 878 | OffsetV.push_back(GEP->getOperand(i)); |
| 879 | return true; |
| 880 | } |
| 881 | |
| 882 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 883 | // replace, computes a replacement, and affects it. |
| 884 | static bool |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 885 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, |
| 886 | const SmallVectorImpl<GCRelocateInst *> &Targets) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 887 | bool MadeChange = false; |
Serguei Katkov | 9e5604d | 2017-08-17 05:48:30 +0000 | [diff] [blame] | 888 | // We must ensure the relocation of derived pointer is defined after |
| 889 | // relocation of base pointer. If we find a relocation corresponding to base |
| 890 | // defined earlier than relocation of base then we move relocation of base |
| 891 | // right before found relocation. We consider only relocation in the same |
| 892 | // basic block as relocation of base. Relocations from other basic block will |
| 893 | // be skipped by optimization and we do not care about them. |
| 894 | for (auto R = RelocatedBase->getParent()->getFirstInsertionPt(); |
| 895 | &*R != RelocatedBase; ++R) |
| 896 | if (auto RI = dyn_cast<GCRelocateInst>(R)) |
| 897 | if (RI->getStatepoint() == RelocatedBase->getStatepoint()) |
| 898 | if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) { |
| 899 | RelocatedBase->moveBefore(RI); |
| 900 | break; |
| 901 | } |
| 902 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 903 | for (GCRelocateInst *ToReplace : Targets) { |
| 904 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 905 | "Not relocating a derived object of the original base object"); |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 906 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 907 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 908 | continue; |
| 909 | } |
| 910 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 911 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 912 | // Base and derived relocates are in different basic blocks. |
| 913 | // In this case transform is only valid when base dominates derived |
| 914 | // relocate. However it would be too expensive to check dominance |
| 915 | // for each such relocate, so we skip the whole transformation. |
| 916 | continue; |
| 917 | } |
| 918 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 919 | Value *Base = ToReplace->getBasePtr(); |
| 920 | auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 921 | if (!Derived || Derived->getPointerOperand() != Base) |
| 922 | continue; |
| 923 | |
| 924 | SmallVector<Value *, 2> OffsetV; |
| 925 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 926 | continue; |
| 927 | |
| 928 | // Create a Builder and replace the target callsite with a gep |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 929 | assert(RelocatedBase->getNextNode() && |
| 930 | "Should always have one since it's not a terminator"); |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 931 | |
| 932 | // Insert after RelocatedBase |
| 933 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 934 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 935 | |
| 936 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 937 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 938 | // match, and we should reuse it to get the derived pointer. But it could be |
| 939 | // cases like this: |
| 940 | // bb1: |
| 941 | // ... |
| 942 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 943 | // br label %merge |
| 944 | // |
| 945 | // bb2: |
| 946 | // ... |
| 947 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 948 | // br label %merge |
| 949 | // |
| 950 | // merge: |
| 951 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 952 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 953 | // |
| 954 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 955 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 956 | // the extra bitcast should be optimized away in later passes. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 957 | Value *ActualRelocatedBase = RelocatedBase; |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 958 | if (RelocatedBase->getType() != Base->getType()) { |
| 959 | ActualRelocatedBase = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 960 | Builder.CreateBitCast(RelocatedBase, Base->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 961 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 962 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 963 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 964 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 965 | // If the newly generated derived pointer's type does not match the original derived |
| 966 | // 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] | 967 | Value *ActualReplacement = Replacement; |
| 968 | if (Replacement->getType() != ToReplace->getType()) { |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 969 | ActualReplacement = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 970 | Builder.CreateBitCast(Replacement, ToReplace->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 971 | } |
| 972 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 973 | ToReplace->eraseFromParent(); |
| 974 | |
| 975 | MadeChange = true; |
| 976 | } |
| 977 | return MadeChange; |
| 978 | } |
| 979 | |
| 980 | // Turns this: |
| 981 | // |
| 982 | // %base = ... |
| 983 | // %ptr = gep %base + 15 |
| 984 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 985 | // %base' = relocate(%tok, i32 4, i32 4) |
| 986 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 987 | // %val = load %ptr' |
| 988 | // |
| 989 | // into this: |
| 990 | // |
| 991 | // %base = ... |
| 992 | // %ptr = gep %base + 15 |
| 993 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 994 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 995 | // %ptr' = gep %base' + 15 |
| 996 | // %val = load %ptr' |
| 997 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 998 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 999 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1000 | |
| 1001 | for (auto *U : I.users()) |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1002 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1003 | // Collect all the relocate calls associated with a statepoint |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1004 | AllRelocateCalls.push_back(Relocate); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1005 | |
| 1006 | // We need atleast one base pointer relocation + one derived pointer |
| 1007 | // relocation to mangle |
| 1008 | if (AllRelocateCalls.size() < 2) |
| 1009 | return false; |
| 1010 | |
| 1011 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 1012 | // corresponding derived relocate instructions |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1013 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1014 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 1015 | if (RelocateInstMap.empty()) |
| 1016 | return false; |
| 1017 | |
| 1018 | for (auto &Item : RelocateInstMap) |
| 1019 | // Item.first is the RelocatedBase to offset against |
| 1020 | // Item.second is the vector of Targets to replace |
| 1021 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 1022 | return MadeChange; |
| 1023 | } |
| 1024 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1025 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 1026 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1027 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1028 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1029 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1030 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1031 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1032 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1033 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1034 | UI != E; ) { |
| 1035 | Use &TheUse = UI.getUse(); |
| 1036 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1037 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1038 | // Figure out which BB this cast is used in. For PHI's this is the |
| 1039 | // appropriate predecessor block. |
| 1040 | BasicBlock *UserBB = User->getParent(); |
| 1041 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1042 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1043 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1044 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1045 | // Preincrement use iterator so we don't invalidate it. |
| 1046 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1047 | |
David Majnemer | 0c80e2e | 2016-04-27 19:36:38 +0000 | [diff] [blame] | 1048 | // The first insertion point of a block containing an EH pad is after the |
| 1049 | // pad. If the pad is the user, we cannot sink the cast past the pad. |
| 1050 | if (User->isEHPad()) |
| 1051 | continue; |
| 1052 | |
Andrew Kaylor | d0430e8 | 2015-11-23 19:16:15 +0000 | [diff] [blame] | 1053 | // If the block selected to receive the cast is an EH pad that does not |
| 1054 | // allow non-PHI instructions before the terminator, we can't sink the |
| 1055 | // cast. |
| 1056 | if (UserBB->getTerminator()->isEHPad()) |
| 1057 | continue; |
| 1058 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1059 | // If this user is in the same block as the cast, don't change the cast. |
| 1060 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1061 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1062 | // If we have already inserted a cast into this block, use it. |
| 1063 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 1064 | |
| 1065 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1066 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1067 | assert(InsertPt != UserBB->end()); |
| 1068 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 1069 | CI->getType(), "", &*InsertPt); |
Vedant Kumar | 9374c04 | 2018-05-23 22:03:48 +0000 | [diff] [blame] | 1070 | InsertedCast->setDebugLoc(CI->getDebugLoc()); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1071 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1072 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1073 | // 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] | 1074 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1075 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1076 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1077 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1078 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1079 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1080 | if (CI->use_empty()) { |
Adrian Prantl | 261ac8b | 2017-11-03 21:55:03 +0000 | [diff] [blame] | 1081 | salvageDebugInfo(*CI); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1082 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1083 | MadeChange = true; |
| 1084 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1085 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1086 | return MadeChange; |
| 1087 | } |
| 1088 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1089 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 1090 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 1091 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1092 | /// |
| 1093 | /// Return true if any changes are made. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1094 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 1095 | const DataLayout &DL) { |
Justin Lebar | 3e50a5b | 2016-11-21 22:49:15 +0000 | [diff] [blame] | 1096 | // Sink only "cheap" (or nop) address-space casts. This is a weaker condition |
| 1097 | // than sinking only nop casts, but is helpful on some platforms. |
| 1098 | if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { |
| 1099 | if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(), |
| 1100 | ASC->getDestAddressSpace())) |
| 1101 | return false; |
| 1102 | } |
| 1103 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1104 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1105 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 1106 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1107 | |
| 1108 | // This is an fp<->int conversion? |
| 1109 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 1110 | return false; |
| 1111 | |
| 1112 | // If this is an extension, it will be a zero or sign extension, which |
| 1113 | // isn't a noop. |
| 1114 | if (SrcVT.bitsLT(DstVT)) return false; |
| 1115 | |
| 1116 | // If these values will be promoted, find out what they will be promoted |
| 1117 | // to. This helps us consider truncates on PPC as noop copies when they |
| 1118 | // are. |
| 1119 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 1120 | TargetLowering::TypePromoteInteger) |
| 1121 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 1122 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 1123 | TargetLowering::TypePromoteInteger) |
| 1124 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 1125 | |
| 1126 | // If, after promotion, these are the same types, this is a noop copy. |
| 1127 | if (SrcVT != DstVT) |
| 1128 | return false; |
| 1129 | |
| 1130 | return SinkCast(CI); |
| 1131 | } |
| 1132 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1133 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 1134 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1135 | /// |
| 1136 | /// Return true if any changes were made. |
| 1137 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 1138 | Value *A, *B; |
| 1139 | Instruction *AddI; |
| 1140 | if (!match(CI, |
| 1141 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 1142 | return false; |
| 1143 | |
| 1144 | Type *Ty = AddI->getType(); |
| 1145 | if (!isa<IntegerType>(Ty)) |
| 1146 | return false; |
| 1147 | |
| 1148 | // We don't want to move around uses of condition values this late, so we we |
| 1149 | // check if it is legal to create the call to the intrinsic in the basic |
| 1150 | // block containing the icmp: |
| 1151 | |
| 1152 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 1153 | return false; |
| 1154 | |
| 1155 | #ifndef NDEBUG |
| 1156 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 1157 | // for now: |
| 1158 | if (AddI->hasOneUse()) |
| 1159 | assert(*AddI->user_begin() == CI && "expected!"); |
| 1160 | #endif |
| 1161 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 1162 | Module *M = CI->getModule(); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1163 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 1164 | |
| 1165 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 1166 | |
| 1167 | auto *UAddWithOverflow = |
| 1168 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 1169 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 1170 | auto *Overflow = |
| 1171 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 1172 | |
| 1173 | CI->replaceAllUsesWith(Overflow); |
| 1174 | AddI->replaceAllUsesWith(UAdd); |
| 1175 | CI->eraseFromParent(); |
| 1176 | AddI->eraseFromParent(); |
| 1177 | return true; |
| 1178 | } |
| 1179 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1180 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 1181 | /// registers that must be created and coalesced. This is a clear win except on |
| 1182 | /// targets with multiple condition code registers (PowerPC), where it might |
| 1183 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1184 | /// |
| 1185 | /// Return true if any changes are made. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1186 | static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1187 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1188 | |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1189 | // 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] | 1190 | if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI)) |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1191 | return false; |
| 1192 | |
| 1193 | // Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1194 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1195 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1196 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1197 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1198 | UI != E; ) { |
| 1199 | Use &TheUse = UI.getUse(); |
| 1200 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1201 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1202 | // Preincrement use iterator so we don't invalidate it. |
| 1203 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1204 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1205 | // Don't bother for PHI nodes. |
| 1206 | if (isa<PHINode>(User)) |
| 1207 | continue; |
| 1208 | |
| 1209 | // Figure out which BB this cmp is used in. |
| 1210 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1211 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1212 | // If this user is in the same block as the cmp, don't change the cmp. |
| 1213 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1214 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1215 | // If we have already inserted a cmp into this block, use it. |
| 1216 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 1217 | |
| 1218 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1219 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1220 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1221 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1222 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 1223 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Wolfgang Pieb | e51bede | 2016-10-06 21:43:45 +0000 | [diff] [blame] | 1224 | // Propagate the debug info. |
| 1225 | InsertedCmp->setDebugLoc(CI->getDebugLoc()); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1226 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1227 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1228 | // Replace a use of the cmp with a use of the new cmp. |
| 1229 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1230 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1231 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1232 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1233 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1234 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1235 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1236 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1237 | MadeChange = true; |
| 1238 | } |
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 | return MadeChange; |
| 1241 | } |
| 1242 | |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 1243 | static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1244 | if (SinkCmpExpression(CI, TLI)) |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1245 | return true; |
| 1246 | |
| 1247 | if (CombineUAddWithOverflow(CI)) |
| 1248 | return true; |
| 1249 | |
| 1250 | return false; |
| 1251 | } |
| 1252 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 1253 | /// Duplicate and sink the given 'and' instruction into user blocks where it is |
| 1254 | /// used in a compare to allow isel to generate better code for targets where |
| 1255 | /// this operation can be combined. |
| 1256 | /// |
| 1257 | /// Return true if any changes are made. |
| 1258 | static bool sinkAndCmp0Expression(Instruction *AndI, |
| 1259 | const TargetLowering &TLI, |
| 1260 | SetOfInstrs &InsertedInsts) { |
| 1261 | // Double-check that we're not trying to optimize an instruction that was |
| 1262 | // already optimized by some other part of this pass. |
| 1263 | assert(!InsertedInsts.count(AndI) && |
| 1264 | "Attempting to optimize already optimized and instruction"); |
| 1265 | (void) InsertedInsts; |
| 1266 | |
| 1267 | // Nothing to do for single use in same basic block. |
| 1268 | if (AndI->hasOneUse() && |
| 1269 | AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) |
| 1270 | return false; |
| 1271 | |
| 1272 | // Try to avoid cases where sinking/duplicating is likely to increase register |
| 1273 | // pressure. |
| 1274 | if (!isa<ConstantInt>(AndI->getOperand(0)) && |
| 1275 | !isa<ConstantInt>(AndI->getOperand(1)) && |
| 1276 | AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) |
| 1277 | return false; |
| 1278 | |
| 1279 | for (auto *U : AndI->users()) { |
| 1280 | Instruction *User = cast<Instruction>(U); |
| 1281 | |
| 1282 | // Only sink for and mask feeding icmp with 0. |
| 1283 | if (!isa<ICmpInst>(User)) |
| 1284 | return false; |
| 1285 | |
| 1286 | auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); |
| 1287 | if (!CmpC || !CmpC->isZero()) |
| 1288 | return false; |
| 1289 | } |
| 1290 | |
| 1291 | if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) |
| 1292 | return false; |
| 1293 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1294 | LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n"); |
| 1295 | LLVM_DEBUG(AndI->getParent()->dump()); |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 1296 | |
| 1297 | // Push the 'and' into the same block as the icmp 0. There should only be |
| 1298 | // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any |
| 1299 | // others, so we don't need to keep track of which BBs we insert into. |
| 1300 | for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); |
| 1301 | UI != E; ) { |
| 1302 | Use &TheUse = UI.getUse(); |
| 1303 | Instruction *User = cast<Instruction>(*UI); |
| 1304 | |
| 1305 | // Preincrement use iterator so we don't invalidate it. |
| 1306 | ++UI; |
| 1307 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1308 | LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n"); |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 1309 | |
| 1310 | // Keep the 'and' in the same place if the use is already in the same block. |
| 1311 | Instruction *InsertPt = |
| 1312 | User->getParent() == AndI->getParent() ? AndI : User; |
| 1313 | Instruction *InsertedAnd = |
| 1314 | BinaryOperator::Create(Instruction::And, AndI->getOperand(0), |
| 1315 | AndI->getOperand(1), "", InsertPt); |
| 1316 | // Propagate the debug info. |
| 1317 | InsertedAnd->setDebugLoc(AndI->getDebugLoc()); |
| 1318 | |
| 1319 | // Replace a use of the 'and' with a use of the new 'and'. |
| 1320 | TheUse = InsertedAnd; |
| 1321 | ++NumAndUses; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 1322 | LLVM_DEBUG(User->getParent()->dump()); |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 1323 | } |
| 1324 | |
| 1325 | // We removed all uses, nuke the and. |
| 1326 | AndI->eraseFromParent(); |
| 1327 | return true; |
| 1328 | } |
| 1329 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1330 | /// Check if the candidates could be combined with a shift instruction, which |
| 1331 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1332 | /// 1. Truncate instruction |
| 1333 | /// 2. And instruction and the imm is a mask of the low bits: |
| 1334 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 1335 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1336 | if (!isa<TruncInst>(User)) { |
| 1337 | if (User->getOpcode() != Instruction::And || |
| 1338 | !isa<ConstantInt>(User->getOperand(1))) |
| 1339 | return false; |
| 1340 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1341 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1342 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1343 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1344 | return false; |
| 1345 | } |
| 1346 | return true; |
| 1347 | } |
| 1348 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1349 | /// 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] | 1350 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1351 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 1352 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1353 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1354 | BasicBlock *UserBB = User->getParent(); |
| 1355 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 1356 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 1357 | bool MadeChange = false; |
| 1358 | |
| 1359 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 1360 | TruncE = TruncI->user_end(); |
| 1361 | TruncUI != TruncE;) { |
| 1362 | |
| 1363 | Use &TruncTheUse = TruncUI.getUse(); |
| 1364 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 1365 | // Preincrement use iterator so we don't invalidate it. |
| 1366 | |
| 1367 | ++TruncUI; |
| 1368 | |
| 1369 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 1370 | if (!ISDOpcode) |
| 1371 | continue; |
| 1372 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 1373 | // If the use is actually a legal node, there will not be an |
| 1374 | // implicit truncate. |
| 1375 | // FIXME: always querying the result type is just an |
| 1376 | // approximation; some nodes' legality is determined by the |
| 1377 | // 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] | 1378 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1379 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1380 | continue; |
| 1381 | |
| 1382 | // Don't bother for PHI nodes. |
| 1383 | if (isa<PHINode>(TruncUser)) |
| 1384 | continue; |
| 1385 | |
| 1386 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 1387 | |
| 1388 | if (UserBB == TruncUserBB) |
| 1389 | continue; |
| 1390 | |
| 1391 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 1392 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 1393 | |
| 1394 | if (!InsertedShift && !InsertedTrunc) { |
| 1395 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1396 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1397 | // Sink the shift |
| 1398 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1399 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1400 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1401 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1402 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1403 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1404 | |
| 1405 | // Sink the trunc |
| 1406 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 1407 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1408 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1409 | |
| 1410 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1411 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1412 | |
| 1413 | MadeChange = true; |
| 1414 | |
| 1415 | TruncTheUse = InsertedTrunc; |
| 1416 | } |
| 1417 | } |
| 1418 | return MadeChange; |
| 1419 | } |
| 1420 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1421 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1422 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1423 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1424 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1425 | /// BB1: |
| 1426 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1427 | /// BB2: |
| 1428 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1429 | /// ==> |
| 1430 | /// |
| 1431 | /// BB2: |
| 1432 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1433 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1434 | /// |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 1435 | /// CodeGen will recognize the pattern in BB2 and generate BitExtract |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1436 | /// instruction. |
| 1437 | /// Return true if any changes are made. |
| 1438 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1439 | const TargetLowering &TLI, |
| 1440 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1441 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1442 | |
| 1443 | /// Only insert instructions in each block once. |
| 1444 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1445 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1446 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1447 | |
| 1448 | bool MadeChange = false; |
| 1449 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1450 | UI != E;) { |
| 1451 | Use &TheUse = UI.getUse(); |
| 1452 | Instruction *User = cast<Instruction>(*UI); |
| 1453 | // Preincrement use iterator so we don't invalidate it. |
| 1454 | ++UI; |
| 1455 | |
| 1456 | // Don't bother for PHI nodes. |
| 1457 | if (isa<PHINode>(User)) |
| 1458 | continue; |
| 1459 | |
| 1460 | if (!isExtractBitsCandidateUse(User)) |
| 1461 | continue; |
| 1462 | |
| 1463 | BasicBlock *UserBB = User->getParent(); |
| 1464 | |
| 1465 | if (UserBB == DefBB) { |
| 1466 | // If the shift and truncate instruction are in the same BB. The use of |
| 1467 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1468 | // legal. In this case, we would like to sink both shift and truncate |
| 1469 | // instruction to the BB of TruncUse. |
| 1470 | // for example: |
| 1471 | // BB1: |
| 1472 | // i64 shift.result = lshr i64 opnd, imm |
| 1473 | // trunc.result = trunc shift.result to i16 |
| 1474 | // |
| 1475 | // BB2: |
| 1476 | // ----> We will have an implicit truncate here if the architecture does |
| 1477 | // not have i16 compare. |
| 1478 | // cmp i16 trunc.result, opnd2 |
| 1479 | // |
| 1480 | if (isa<TruncInst>(User) && shiftIsLegal |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 1481 | // If the type of the truncate is legal, no truncate will be |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1482 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1483 | && |
| 1484 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1485 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1486 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1487 | |
| 1488 | continue; |
| 1489 | } |
| 1490 | // If we have already inserted a shift into this block, use it. |
| 1491 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1492 | |
| 1493 | if (!InsertedShift) { |
| 1494 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1495 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1496 | |
| 1497 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1498 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1499 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1500 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1501 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1502 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1503 | |
| 1504 | MadeChange = true; |
| 1505 | } |
| 1506 | |
| 1507 | // Replace a use of the shift with a use of the new shift. |
| 1508 | TheUse = InsertedShift; |
| 1509 | } |
| 1510 | |
| 1511 | // If we removed all uses, nuke the shift. |
| 1512 | if (ShiftI->use_empty()) |
| 1513 | ShiftI->eraseFromParent(); |
| 1514 | |
| 1515 | return MadeChange; |
| 1516 | } |
| 1517 | |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1518 | /// If counting leading or trailing zeros is an expensive operation and a zero |
| 1519 | /// input is defined, add a check for zero to avoid calling the intrinsic. |
| 1520 | /// |
| 1521 | /// We want to transform: |
| 1522 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) |
| 1523 | /// |
| 1524 | /// into: |
| 1525 | /// entry: |
| 1526 | /// %cmpz = icmp eq i64 %A, 0 |
| 1527 | /// br i1 %cmpz, label %cond.end, label %cond.false |
| 1528 | /// cond.false: |
| 1529 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) |
| 1530 | /// br label %cond.end |
| 1531 | /// cond.end: |
| 1532 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] |
| 1533 | /// |
| 1534 | /// If the transform is performed, return true and set ModifiedDT to true. |
| 1535 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, |
| 1536 | const TargetLowering *TLI, |
| 1537 | const DataLayout *DL, |
| 1538 | bool &ModifiedDT) { |
| 1539 | if (!TLI || !DL) |
| 1540 | return false; |
| 1541 | |
| 1542 | // If a zero input is undefined, it doesn't make sense to despeculate that. |
| 1543 | if (match(CountZeros->getOperand(1), m_One())) |
| 1544 | return false; |
| 1545 | |
| 1546 | // If it's cheap to speculate, there's nothing to do. |
| 1547 | auto IntrinsicID = CountZeros->getIntrinsicID(); |
| 1548 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || |
| 1549 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) |
| 1550 | return false; |
| 1551 | |
| 1552 | // Only handle legal scalar cases. Anything else requires too much work. |
| 1553 | Type *Ty = CountZeros->getType(); |
| 1554 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); |
Jun Bum Lim | be11bdc | 2016-05-13 18:38:35 +0000 | [diff] [blame] | 1555 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1556 | return false; |
| 1557 | |
| 1558 | // The intrinsic will be sunk behind a compare against zero and branch. |
| 1559 | BasicBlock *StartBlock = CountZeros->getParent(); |
| 1560 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); |
| 1561 | |
| 1562 | // Create another block after the count zero intrinsic. A PHI will be added |
| 1563 | // in this block to select the result of the intrinsic or the bit-width |
| 1564 | // constant if the input to the intrinsic is zero. |
| 1565 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); |
| 1566 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); |
| 1567 | |
| 1568 | // Set up a builder to create a compare, conditional branch, and PHI. |
| 1569 | IRBuilder<> Builder(CountZeros->getContext()); |
| 1570 | Builder.SetInsertPoint(StartBlock->getTerminator()); |
| 1571 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); |
| 1572 | |
| 1573 | // Replace the unconditional branch that was created by the first split with |
| 1574 | // a compare against zero and a conditional branch. |
| 1575 | Value *Zero = Constant::getNullValue(Ty); |
| 1576 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); |
| 1577 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); |
| 1578 | StartBlock->getTerminator()->eraseFromParent(); |
| 1579 | |
| 1580 | // Create a PHI in the end block to select either the output of the intrinsic |
| 1581 | // or the bit width of the operand. |
| 1582 | Builder.SetInsertPoint(&EndBlock->front()); |
| 1583 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); |
| 1584 | CountZeros->replaceAllUsesWith(PN); |
| 1585 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); |
| 1586 | PN->addIncoming(BitWidth, StartBlock); |
| 1587 | PN->addIncoming(CountZeros, CallBlock); |
| 1588 | |
| 1589 | // We are explicitly handling the zero case, so we can set the intrinsic's |
| 1590 | // undefined zero argument to 'true'. This will also prevent reprocessing the |
| 1591 | // intrinsic; we only despeculate when a zero input is defined. |
| 1592 | CountZeros->setArgOperand(1, Builder.getTrue()); |
| 1593 | ModifiedDT = true; |
| 1594 | return true; |
| 1595 | } |
| 1596 | |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 1597 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1598 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1599 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1600 | // Lower inline assembly if we can. |
| 1601 | // If we found an inline asm expession, and if the target knows how to |
| 1602 | // lower it to normal LLVM code, do so now. |
| 1603 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 1604 | if (TLI->ExpandInlineAsm(CI)) { |
| 1605 | // Avoid invalidating the iterator. |
| 1606 | CurInstIterator = BB->begin(); |
| 1607 | // Avoid processing instructions out of order, which could cause |
| 1608 | // reuse before a value is defined. |
| 1609 | SunkAddrs.clear(); |
| 1610 | return true; |
| 1611 | } |
| 1612 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1613 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1614 | return true; |
| 1615 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1616 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1617 | // Align the pointer arguments to this call if the target thinks it's a good |
| 1618 | // idea |
| 1619 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1620 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1621 | for (auto &Arg : CI->arg_operands()) { |
| 1622 | // We want to align both objects whose address is used directly and |
| 1623 | // objects whose address is used in casts and GEPs, though it only makes |
| 1624 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 1625 | // if size - offset meets the size threshold. |
| 1626 | if (!Arg->getType()->isPointerTy()) |
| 1627 | continue; |
Elena Demikhovsky | 945b7e5 | 2018-02-14 06:58:08 +0000 | [diff] [blame] | 1628 | APInt Offset(DL->getIndexSizeInBits( |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1629 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 1630 | 0); |
| 1631 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1632 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1633 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 1634 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1635 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1636 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 1637 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1638 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1639 | // Global variables can only be aligned if they are defined in this |
| 1640 | // object (i.e. they are uniquely initialized in this object), and |
| 1641 | // over-aligning global variables that have an explicit section is |
| 1642 | // forbidden. |
| 1643 | GlobalVariable *GV; |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 1644 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && |
Tim Northover | 918f050 | 2016-07-18 18:28:52 +0000 | [diff] [blame] | 1645 | GV->getPointerAlignment(*DL) < PrefAlign && |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 1646 | DL->getTypeAllocSize(GV->getValueType()) >= |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1647 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1648 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1649 | } |
| 1650 | // If this is a memcpy (or similar) then we may be able to improve the |
| 1651 | // alignment |
| 1652 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Daniel Neilson | be58a22 | 2018-01-31 17:24:53 +0000 | [diff] [blame] | 1653 | unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL); |
| 1654 | if (DestAlign > MI->getDestAlignment()) |
| 1655 | MI->setDestAlignment(DestAlign); |
| 1656 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { |
| 1657 | unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL); |
| 1658 | if (SrcAlign > MTI->getSourceAlignment()) |
| 1659 | MTI->setSourceAlignment(SrcAlign); |
| 1660 | } |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1661 | } |
| 1662 | } |
| 1663 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 1664 | // If we have a cold call site, try to sink addressing computation into the |
| 1665 | // cold block. This interacts with our handling for loads and stores to |
| 1666 | // ensure that we can fold all uses of a potential addressing computation |
| 1667 | // into their uses. TODO: generalize this to work over profiling data |
| 1668 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 1669 | for (auto &Arg : CI->arg_operands()) { |
| 1670 | if (!Arg->getType()->isPointerTy()) |
| 1671 | continue; |
| 1672 | unsigned AS = Arg->getType()->getPointerAddressSpace(); |
| 1673 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); |
| 1674 | } |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 1675 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1676 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1677 | if (II) { |
| 1678 | switch (II->getIntrinsicID()) { |
| 1679 | default: break; |
| 1680 | case Intrinsic::objectsize: { |
| 1681 | // Lower all uses of llvm.objectsize.* |
George Burgess IV | 3f08914 | 2016-12-20 23:46:36 +0000 | [diff] [blame] | 1682 | ConstantInt *RetVal = |
| 1683 | lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1684 | // Substituting this can cause recursive simplifications, which can |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 1685 | // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case |
| 1686 | // this |
Sanjoy Das | 2cbeb00 | 2017-04-26 16:37:05 +0000 | [diff] [blame] | 1687 | // happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 1688 | Value *CurValue = &*CurInstIterator; |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 1689 | WeakTrackingVH IterHandle(CurValue); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1690 | |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 1691 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1692 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1693 | // If the iterator instruction was recursively deleted, start over at the |
| 1694 | // start of the block. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 1695 | if (IterHandle != CurValue) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1696 | CurInstIterator = BB->begin(); |
| 1697 | SunkAddrs.clear(); |
| 1698 | } |
| 1699 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 1700 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1701 | case Intrinsic::aarch64_stlxr: |
| 1702 | case Intrinsic::aarch64_stxr: { |
| 1703 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 1704 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 1705 | ExtVal->getParent() == CI->getParent()) |
| 1706 | return false; |
| 1707 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 1708 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 1709 | // Mark this instruction as "inserted by CGP", so that other |
| 1710 | // optimizations don't touch it. |
| 1711 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1712 | return true; |
| 1713 | } |
Piotr Padlewski | 5dde809 | 2018-05-03 11:03:01 +0000 | [diff] [blame] | 1714 | case Intrinsic::launder_invariant_group: |
Piotr Padlewski | 5b3db45 | 2018-07-02 04:49:30 +0000 | [diff] [blame] | 1715 | case Intrinsic::strip_invariant_group: |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 1716 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 1717 | II->eraseFromParent(); |
| 1718 | return true; |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1719 | |
| 1720 | case Intrinsic::cttz: |
| 1721 | case Intrinsic::ctlz: |
| 1722 | // If counting zeros is expensive, try to avoid it. |
| 1723 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1724 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1725 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1726 | if (TLI) { |
| 1727 | SmallVector<Value*, 2> PtrOps; |
| 1728 | Type *AccessTy; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 1729 | if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) |
| 1730 | while (!PtrOps.empty()) { |
| 1731 | Value *PtrVal = PtrOps.pop_back_val(); |
| 1732 | unsigned AS = PtrVal->getType()->getPointerAddressSpace(); |
| 1733 | if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1734 | return true; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 1735 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1736 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 1737 | } |
| 1738 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1739 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1740 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 1741 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 1742 | // Lower all default uses of _chk calls. This is very similar |
| 1743 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1744 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 1745 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1746 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1747 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 1748 | CI->replaceAllUsesWith(V); |
| 1749 | CI->eraseFromParent(); |
| 1750 | return true; |
| 1751 | } |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 1752 | |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1753 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1754 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1755 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1756 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 1757 | /// 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] | 1758 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1759 | /// bb0: |
| 1760 | /// %tmp0 = tail call i32 @f0() |
| 1761 | /// br label %return |
| 1762 | /// bb1: |
| 1763 | /// %tmp1 = tail call i32 @f1() |
| 1764 | /// br label %return |
| 1765 | /// bb2: |
| 1766 | /// %tmp2 = tail call i32 @f2() |
| 1767 | /// br label %return |
| 1768 | /// return: |
| 1769 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 1770 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1771 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1772 | /// |
| 1773 | /// => |
| 1774 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1775 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1776 | /// bb0: |
| 1777 | /// %tmp0 = tail call i32 @f0() |
| 1778 | /// ret i32 %tmp0 |
| 1779 | /// bb1: |
| 1780 | /// %tmp1 = tail call i32 @f1() |
| 1781 | /// ret i32 %tmp1 |
| 1782 | /// bb2: |
| 1783 | /// %tmp2 = tail call i32 @f2() |
| 1784 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1785 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1786 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 1787 | if (!TLI) |
| 1788 | return false; |
| 1789 | |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1790 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 1791 | if (!RetI) |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 1792 | return false; |
| 1793 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1794 | PHINode *PN = nullptr; |
| 1795 | BitCastInst *BCI = nullptr; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1796 | Value *V = RetI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1797 | if (V) { |
| 1798 | BCI = dyn_cast<BitCastInst>(V); |
| 1799 | if (BCI) |
| 1800 | V = BCI->getOperand(0); |
| 1801 | |
| 1802 | PN = dyn_cast<PHINode>(V); |
| 1803 | if (!PN) |
| 1804 | return false; |
| 1805 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1806 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1807 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1808 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1809 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1810 | // Make sure there are no instructions between the PHI and return, or that the |
| 1811 | // return is the first instruction in the block. |
| 1812 | if (PN) { |
| 1813 | BasicBlock::iterator BI = BB->begin(); |
| 1814 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1815 | if (&*BI == BCI) |
| 1816 | // Also skip over the bitcast. |
| 1817 | ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1818 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1819 | return false; |
| 1820 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1821 | BasicBlock::iterator BI = BB->begin(); |
| 1822 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1823 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1824 | return false; |
| 1825 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1826 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1827 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 1828 | /// call. |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 1829 | const Function *F = BB->getParent(); |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1830 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1831 | if (PN) { |
| 1832 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 1833 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 1834 | // Make sure the phi value is indeed produced by the tail call. |
| 1835 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 1836 | TLI->mayBeEmittedAsTailCall(CI) && |
| 1837 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1838 | TailCalls.push_back(CI); |
| 1839 | } |
| 1840 | } else { |
| 1841 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1842 | 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] | 1843 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1844 | continue; |
| 1845 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1846 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1847 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 1848 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1849 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 1850 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1851 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1852 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1853 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 1854 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && |
| 1855 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1856 | TailCalls.push_back(CI); |
| 1857 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1858 | } |
| 1859 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1860 | bool Changed = false; |
| 1861 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 1862 | CallInst *CI = TailCalls[i]; |
| 1863 | CallSite CS(CI); |
| 1864 | |
| 1865 | // Conservatively require the attributes of the call to match those of the |
| 1866 | // return. Ignore noalias because it doesn't affect the call sequence. |
Reid Kleckner | b518054 | 2017-03-21 16:57:19 +0000 | [diff] [blame] | 1867 | AttributeList CalleeAttrs = CS.getAttributes(); |
| 1868 | if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 1869 | .removeAttribute(Attribute::NoAlias) != |
| 1870 | AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 1871 | .removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1872 | continue; |
| 1873 | |
| 1874 | // Make sure the call instruction is followed by an unconditional branch to |
| 1875 | // the return block. |
| 1876 | BasicBlock *CallBB = CI->getParent(); |
| 1877 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 1878 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 1879 | continue; |
| 1880 | |
| 1881 | // Duplicate the return into CallBB. |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1882 | (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 1883 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1884 | ++NumRetsDup; |
| 1885 | } |
| 1886 | |
| 1887 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 1888 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1889 | BB->eraseFromParent(); |
| 1890 | |
| 1891 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1892 | } |
| 1893 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1894 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 1895 | // Memory Optimization |
| 1896 | //===----------------------------------------------------------------------===// |
| 1897 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1898 | namespace { |
| 1899 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1900 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1901 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 1902 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 1903 | Value *BaseReg = nullptr; |
| 1904 | Value *ScaledReg = nullptr; |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 1905 | Value *OriginalValue = nullptr; |
| 1906 | |
| 1907 | enum FieldName { |
| 1908 | NoField = 0x00, |
| 1909 | BaseRegField = 0x01, |
| 1910 | BaseGVField = 0x02, |
| 1911 | BaseOffsField = 0x04, |
| 1912 | ScaledRegField = 0x08, |
| 1913 | ScaleField = 0x10, |
| 1914 | MultipleFields = 0xff |
| 1915 | }; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 1916 | |
| 1917 | ExtAddrMode() = default; |
| 1918 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1919 | void print(raw_ostream &OS) const; |
| 1920 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 1921 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 1922 | FieldName compare(const ExtAddrMode &other) { |
| 1923 | // First check that the types are the same on each field, as differing types |
| 1924 | // is something we can't cope with later on. |
| 1925 | if (BaseReg && other.BaseReg && |
| 1926 | BaseReg->getType() != other.BaseReg->getType()) |
| 1927 | return MultipleFields; |
| 1928 | if (BaseGV && other.BaseGV && |
| 1929 | BaseGV->getType() != other.BaseGV->getType()) |
| 1930 | return MultipleFields; |
| 1931 | if (ScaledReg && other.ScaledReg && |
| 1932 | ScaledReg->getType() != other.ScaledReg->getType()) |
| 1933 | return MultipleFields; |
| 1934 | |
| 1935 | // Check each field to see if it differs. |
| 1936 | unsigned Result = NoField; |
| 1937 | if (BaseReg != other.BaseReg) |
| 1938 | Result |= BaseRegField; |
| 1939 | if (BaseGV != other.BaseGV) |
| 1940 | Result |= BaseGVField; |
| 1941 | if (BaseOffs != other.BaseOffs) |
| 1942 | Result |= BaseOffsField; |
| 1943 | if (ScaledReg != other.ScaledReg) |
| 1944 | Result |= ScaledRegField; |
| 1945 | // Don't count 0 as being a different scale, because that actually means |
| 1946 | // unscaled (which will already be counted by having no ScaledReg). |
| 1947 | if (Scale && other.Scale && Scale != other.Scale) |
| 1948 | Result |= ScaleField; |
| 1949 | |
| 1950 | if (countPopulation(Result) > 1) |
| 1951 | return MultipleFields; |
| 1952 | else |
| 1953 | return static_cast<FieldName>(Result); |
| 1954 | } |
| 1955 | |
John Brawn | 4b47648 | 2017-11-27 11:29:15 +0000 | [diff] [blame] | 1956 | // An AddrMode is trivial if it involves no calculation i.e. it is just a base |
| 1957 | // with no offset. |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 1958 | bool isTrivial() { |
John Brawn | 4b47648 | 2017-11-27 11:29:15 +0000 | [diff] [blame] | 1959 | // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is |
| 1960 | // trivial if at most one of these terms is nonzero, except that BaseGV and |
| 1961 | // BaseReg both being zero actually means a null pointer value, which we |
| 1962 | // consider to be 'non-zero' here. |
| 1963 | return !BaseOffs && !Scale && !(BaseGV && BaseReg); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 1964 | } |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 1965 | |
| 1966 | Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) { |
| 1967 | switch (Field) { |
| 1968 | default: |
| 1969 | return nullptr; |
| 1970 | case BaseRegField: |
| 1971 | return BaseReg; |
| 1972 | case BaseGVField: |
| 1973 | return BaseGV; |
| 1974 | case ScaledRegField: |
| 1975 | return ScaledReg; |
| 1976 | case BaseOffsField: |
| 1977 | return ConstantInt::get(IntPtrTy, BaseOffs); |
| 1978 | } |
| 1979 | } |
| 1980 | |
| 1981 | void SetCombinedField(FieldName Field, Value *V, |
| 1982 | const SmallVectorImpl<ExtAddrMode> &AddrModes) { |
| 1983 | switch (Field) { |
| 1984 | default: |
| 1985 | llvm_unreachable("Unhandled fields are expected to be rejected earlier"); |
| 1986 | break; |
| 1987 | case ExtAddrMode::BaseRegField: |
| 1988 | BaseReg = V; |
| 1989 | break; |
| 1990 | case ExtAddrMode::BaseGVField: |
| 1991 | // A combined BaseGV is an Instruction, not a GlobalValue, so it goes |
| 1992 | // in the BaseReg field. |
| 1993 | assert(BaseReg == nullptr); |
| 1994 | BaseReg = V; |
| 1995 | BaseGV = nullptr; |
| 1996 | break; |
| 1997 | case ExtAddrMode::ScaledRegField: |
| 1998 | ScaledReg = V; |
| 1999 | // If we have a mix of scaled and unscaled addrmodes then we want scale |
| 2000 | // to be the scale and not zero. |
| 2001 | if (!Scale) |
| 2002 | for (const ExtAddrMode &AM : AddrModes) |
| 2003 | if (AM.Scale) { |
| 2004 | Scale = AM.Scale; |
| 2005 | break; |
| 2006 | } |
| 2007 | break; |
| 2008 | case ExtAddrMode::BaseOffsField: |
| 2009 | // The offset is no longer a constant, so it goes in ScaledReg with a |
| 2010 | // scale of 1. |
| 2011 | assert(ScaledReg == nullptr); |
| 2012 | ScaledReg = V; |
| 2013 | Scale = 1; |
| 2014 | BaseOffs = 0; |
| 2015 | break; |
| 2016 | } |
| 2017 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2018 | }; |
| 2019 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2020 | } // end anonymous namespace |
| 2021 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 2022 | #ifndef NDEBUG |
| 2023 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 2024 | AM.print(OS); |
| 2025 | return OS; |
| 2026 | } |
| 2027 | #endif |
| 2028 | |
Aaron Ballman | 615eb47 | 2017-10-15 14:32:27 +0000 | [diff] [blame] | 2029 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2030 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 2031 | bool NeedPlus = false; |
| 2032 | OS << "["; |
| 2033 | if (BaseGV) { |
| 2034 | OS << (NeedPlus ? " + " : "") |
| 2035 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2036 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2037 | NeedPlus = true; |
| 2038 | } |
| 2039 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 2040 | if (BaseOffs) { |
| 2041 | OS << (NeedPlus ? " + " : "") |
| 2042 | << BaseOffs; |
| 2043 | NeedPlus = true; |
| 2044 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2045 | |
| 2046 | if (BaseReg) { |
| 2047 | OS << (NeedPlus ? " + " : "") |
| 2048 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2049 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2050 | NeedPlus = true; |
| 2051 | } |
| 2052 | if (Scale) { |
| 2053 | OS << (NeedPlus ? " + " : "") |
| 2054 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2055 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2056 | } |
| 2057 | |
| 2058 | OS << ']'; |
| 2059 | } |
| 2060 | |
Yaron Keren | eb2a254 | 2016-01-29 20:50:44 +0000 | [diff] [blame] | 2061 | LLVM_DUMP_METHOD void ExtAddrMode::dump() const { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2062 | print(dbgs()); |
| 2063 | dbgs() << '\n'; |
| 2064 | } |
| 2065 | #endif |
| 2066 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2067 | namespace { |
| 2068 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2069 | /// This class provides transaction based operation on the IR. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2070 | /// Every change made through this class is recorded in the internal state and |
| 2071 | /// can be undone (rollback) until commit is called. |
| 2072 | class TypePromotionTransaction { |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2073 | /// This represents the common interface of the individual transaction. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2074 | /// Each class implements the logic for doing one specific modification on |
| 2075 | /// the IR via the TypePromotionTransaction. |
| 2076 | class TypePromotionAction { |
| 2077 | protected: |
| 2078 | /// The Instruction modified. |
| 2079 | Instruction *Inst; |
| 2080 | |
| 2081 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2082 | /// Constructor of the action. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2083 | /// The constructor performs the related action on the IR. |
| 2084 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2085 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2086 | virtual ~TypePromotionAction() = default; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2087 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2088 | /// Undo the modification done by this action. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2089 | /// When this method is called, the IR must be in the same state as it was |
| 2090 | /// before this action was applied. |
| 2091 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2092 | /// state as it was directly after this action was applied. |
| 2093 | virtual void undo() = 0; |
| 2094 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2095 | /// Advocate every change made by this action. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2096 | /// When the results on the IR of the action are to be kept, it is important |
| 2097 | /// to call this function, otherwise hidden information may be kept forever. |
| 2098 | virtual void commit() { |
| 2099 | // Nothing to be done, this action is not doing anything. |
| 2100 | } |
| 2101 | }; |
| 2102 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2103 | /// Utility to remember the position of an instruction. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2104 | class InsertionHandler { |
| 2105 | /// Position of an instruction. |
| 2106 | /// Either an instruction: |
| 2107 | /// - Is the first in a basic block: BB is used. |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 2108 | /// - Has a previous instruction: PrevInst is used. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2109 | union { |
| 2110 | Instruction *PrevInst; |
| 2111 | BasicBlock *BB; |
| 2112 | } Point; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2113 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2114 | /// Remember whether or not the instruction had a previous instruction. |
| 2115 | bool HasPrevInstruction; |
| 2116 | |
| 2117 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2118 | /// Record the position of \p Inst. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2119 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2120 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2121 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2122 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2123 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2124 | else |
| 2125 | Point.BB = Inst->getParent(); |
| 2126 | } |
| 2127 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2128 | /// Insert \p Inst at the recorded position. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2129 | void insert(Instruction *Inst) { |
| 2130 | if (HasPrevInstruction) { |
| 2131 | if (Inst->getParent()) |
| 2132 | Inst->removeFromParent(); |
| 2133 | Inst->insertAfter(Point.PrevInst); |
| 2134 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2135 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2136 | if (Inst->getParent()) |
| 2137 | Inst->moveBefore(Position); |
| 2138 | else |
| 2139 | Inst->insertBefore(Position); |
| 2140 | } |
| 2141 | } |
| 2142 | }; |
| 2143 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2144 | /// Move an instruction before another. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2145 | class InstructionMoveBefore : public TypePromotionAction { |
| 2146 | /// Original position of the instruction. |
| 2147 | InsertionHandler Position; |
| 2148 | |
| 2149 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2150 | /// Move \p Inst before \p Before. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2151 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2152 | : TypePromotionAction(Inst), Position(Inst) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2153 | LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before |
| 2154 | << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2155 | Inst->moveBefore(Before); |
| 2156 | } |
| 2157 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2158 | /// Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2159 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2160 | LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2161 | Position.insert(Inst); |
| 2162 | } |
| 2163 | }; |
| 2164 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2165 | /// Set the operand of an instruction with a new value. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2166 | class OperandSetter : public TypePromotionAction { |
| 2167 | /// Original operand of the instruction. |
| 2168 | Value *Origin; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2169 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2170 | /// Index of the modified instruction. |
| 2171 | unsigned Idx; |
| 2172 | |
| 2173 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2174 | /// Set \p Idx operand of \p Inst with \p NewVal. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2175 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2176 | : TypePromotionAction(Inst), Idx(Idx) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2177 | LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2178 | << "for:" << *Inst << "\n" |
| 2179 | << "with:" << *NewVal << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2180 | Origin = Inst->getOperand(Idx); |
| 2181 | Inst->setOperand(Idx, NewVal); |
| 2182 | } |
| 2183 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2184 | /// Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2185 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2186 | LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2187 | << "for: " << *Inst << "\n" |
| 2188 | << "with: " << *Origin << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2189 | Inst->setOperand(Idx, Origin); |
| 2190 | } |
| 2191 | }; |
| 2192 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2193 | /// Hide the operands of an instruction. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2194 | /// Do as if this instruction was not using any of its operands. |
| 2195 | class OperandsHider : public TypePromotionAction { |
| 2196 | /// The list of original operands. |
| 2197 | SmallVector<Value *, 4> OriginalValues; |
| 2198 | |
| 2199 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2200 | /// Remove \p Inst from the uses of the operands of \p Inst. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2201 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2202 | LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2203 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2204 | OriginalValues.reserve(NumOpnds); |
| 2205 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2206 | // Save the current operand. |
| 2207 | Value *Val = Inst->getOperand(It); |
| 2208 | OriginalValues.push_back(Val); |
| 2209 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2210 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2211 | // that we are not willing to pay. |
| 2212 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2213 | } |
| 2214 | } |
| 2215 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2216 | /// Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2217 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2218 | LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2219 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2220 | Inst->setOperand(It, OriginalValues[It]); |
| 2221 | } |
| 2222 | }; |
| 2223 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2224 | /// Build a truncate instruction. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2225 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2226 | Value *Val; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2227 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2228 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2229 | /// Build a truncate instruction of \p Opnd producing a \p Ty |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2230 | /// result. |
| 2231 | /// trunc Opnd to Ty. |
| 2232 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2233 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2234 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2235 | LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2236 | } |
| 2237 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2238 | /// Get the built value. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2239 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2240 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2241 | /// Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2242 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2243 | LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2244 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2245 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2246 | } |
| 2247 | }; |
| 2248 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2249 | /// Build a sign extension instruction. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2250 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2251 | Value *Val; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2252 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2253 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2254 | /// Build a sign extension instruction of \p Opnd producing a \p Ty |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2255 | /// result. |
| 2256 | /// sext Opnd to Ty. |
| 2257 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2258 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2259 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2260 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2261 | LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2262 | } |
| 2263 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2264 | /// Get the built value. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2265 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2266 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2267 | /// Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2268 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2269 | LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2270 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2271 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2272 | } |
| 2273 | }; |
| 2274 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2275 | /// Build a zero extension instruction. |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2276 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2277 | Value *Val; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2278 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2279 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2280 | /// Build a zero extension instruction of \p Opnd producing a \p Ty |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2281 | /// result. |
| 2282 | /// zext Opnd to Ty. |
| 2283 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2284 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2285 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2286 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2287 | LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2288 | } |
| 2289 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2290 | /// Get the built value. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2291 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2292 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2293 | /// Remove the built instruction. |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2294 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2295 | LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2296 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2297 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2298 | } |
| 2299 | }; |
| 2300 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2301 | /// Mutate an instruction to another type. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2302 | class TypeMutator : public TypePromotionAction { |
| 2303 | /// Record the original type. |
| 2304 | Type *OrigTy; |
| 2305 | |
| 2306 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2307 | /// Mutate the type of \p Inst into \p NewTy. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2308 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2309 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2310 | LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2311 | << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2312 | Inst->mutateType(NewTy); |
| 2313 | } |
| 2314 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2315 | /// Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2316 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2317 | LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2318 | << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2319 | Inst->mutateType(OrigTy); |
| 2320 | } |
| 2321 | }; |
| 2322 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2323 | /// Replace the uses of an instruction by another instruction. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2324 | class UsesReplacer : public TypePromotionAction { |
| 2325 | /// Helper structure to keep track of the replaced uses. |
| 2326 | struct InstructionAndIdx { |
| 2327 | /// The instruction using the instruction. |
| 2328 | Instruction *Inst; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2329 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2330 | /// The index where this instruction is used for Inst. |
| 2331 | unsigned Idx; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2332 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2333 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2334 | : Inst(Inst), Idx(Idx) {} |
| 2335 | }; |
| 2336 | |
| 2337 | /// Keep track of the original uses (pair Instruction, Index). |
| 2338 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2339 | |
| 2340 | using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2341 | |
| 2342 | public: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2343 | /// Replace all the use of \p Inst by \p New. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2344 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2345 | LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2346 | << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2347 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2348 | for (Use &U : Inst->uses()) { |
| 2349 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2350 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2351 | } |
| 2352 | // Now, we can replace the uses. |
| 2353 | Inst->replaceAllUsesWith(New); |
| 2354 | } |
| 2355 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2356 | /// Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2357 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2358 | LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2359 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2360 | EndIt = OriginalUses.end(); |
| 2361 | UseIt != EndIt; ++UseIt) { |
| 2362 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2363 | } |
| 2364 | } |
| 2365 | }; |
| 2366 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2367 | /// Remove an instruction from the IR. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2368 | class InstructionRemover : public TypePromotionAction { |
| 2369 | /// Original position of the instruction. |
| 2370 | InsertionHandler Inserter; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2371 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2372 | /// Helper structure to hide all the link to the instruction. In other |
| 2373 | /// words, this helps to do as if the instruction was removed. |
| 2374 | OperandsHider Hider; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2375 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2376 | /// Keep track of the uses replaced, if any. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2377 | UsesReplacer *Replacer = nullptr; |
| 2378 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2379 | /// Keep track of instructions removed. |
| 2380 | SetOfInstrs &RemovedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2381 | |
| 2382 | public: |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 2383 | /// Remove all reference of \p Inst and optionally replace all its |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2384 | /// uses with New. |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2385 | /// \p RemovedInsts Keep track of the instructions removed by this Action. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2386 | /// \pre If !Inst->use_empty(), then New != nullptr |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2387 | InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts, |
| 2388 | Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2389 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2390 | RemovedInsts(RemovedInsts) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2391 | if (New) |
| 2392 | Replacer = new UsesReplacer(Inst, New); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2393 | LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2394 | RemovedInsts.insert(Inst); |
| 2395 | /// The instructions removed here will be freed after completing |
| 2396 | /// optimizeBlock() for all blocks as we need to keep track of the |
| 2397 | /// removed instructions during promotion. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2398 | Inst->removeFromParent(); |
| 2399 | } |
| 2400 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2401 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2402 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2403 | /// Resurrect the instruction and reassign it to the proper uses if |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2404 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2405 | void undo() override { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 2406 | LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2407 | Inserter.insert(Inst); |
| 2408 | if (Replacer) |
| 2409 | Replacer->undo(); |
| 2410 | Hider.undo(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2411 | RemovedInsts.erase(Inst); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2412 | } |
| 2413 | }; |
| 2414 | |
| 2415 | public: |
| 2416 | /// Restoration point. |
| 2417 | /// The restoration point is a pointer to an action instead of an iterator |
| 2418 | /// because the iterator may be invalidated but not the pointer. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2419 | using ConstRestorationPt = const TypePromotionAction *; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2420 | |
| 2421 | TypePromotionTransaction(SetOfInstrs &RemovedInsts) |
| 2422 | : RemovedInsts(RemovedInsts) {} |
| 2423 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2424 | /// Advocate every changes made in that transaction. |
| 2425 | void commit(); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2426 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2427 | /// Undo all the changes made after the given point. |
| 2428 | void rollback(ConstRestorationPt Point); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2429 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2430 | /// Get the current restoration point. |
| 2431 | ConstRestorationPt getRestorationPoint() const; |
| 2432 | |
| 2433 | /// \name API for IR modification with state keeping to support rollback. |
| 2434 | /// @{ |
| 2435 | /// Same as Instruction::setOperand. |
| 2436 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2437 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2438 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2439 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2440 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2441 | /// Same as Value::replaceAllUsesWith. |
| 2442 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2443 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2444 | /// Same as Value::mutateType. |
| 2445 | void mutateType(Instruction *Inst, Type *NewTy); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2446 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2447 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2448 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2449 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2450 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2451 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2452 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2453 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2454 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2455 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2456 | /// Same as Instruction::moveBefore. |
| 2457 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2458 | /// @} |
| 2459 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2460 | private: |
| 2461 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2462 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2463 | |
| 2464 | using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator; |
| 2465 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2466 | SetOfInstrs &RemovedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2467 | }; |
| 2468 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2469 | } // end anonymous namespace |
| 2470 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2471 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2472 | Value *NewVal) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2473 | Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>( |
| 2474 | Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2475 | } |
| 2476 | |
| 2477 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2478 | Value *NewVal) { |
| 2479 | Actions.push_back( |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2480 | llvm::make_unique<TypePromotionTransaction::InstructionRemover>( |
| 2481 | Inst, RemovedInsts, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2482 | } |
| 2483 | |
| 2484 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2485 | Value *New) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2486 | Actions.push_back( |
| 2487 | llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2488 | } |
| 2489 | |
| 2490 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2491 | Actions.push_back( |
| 2492 | llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2493 | } |
| 2494 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2495 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2496 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2497 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2498 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2499 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2500 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2501 | } |
| 2502 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2503 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2504 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2505 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2506 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2507 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2508 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2509 | } |
| 2510 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2511 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2512 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2513 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2514 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2515 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2516 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2517 | } |
| 2518 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2519 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2520 | Instruction *Before) { |
| 2521 | Actions.push_back( |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2522 | llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>( |
| 2523 | Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2524 | } |
| 2525 | |
| 2526 | TypePromotionTransaction::ConstRestorationPt |
| 2527 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2528 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2529 | } |
| 2530 | |
| 2531 | void TypePromotionTransaction::commit() { |
| 2532 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2533 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2534 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2535 | Actions.clear(); |
| 2536 | } |
| 2537 | |
| 2538 | void TypePromotionTransaction::rollback( |
| 2539 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2540 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2541 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2542 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2543 | } |
| 2544 | } |
| 2545 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2546 | namespace { |
| 2547 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2548 | /// A helper class for matching addressing modes. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2549 | /// |
| 2550 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2551 | class AddressingModeMatcher { |
| 2552 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
| 2553 | const TargetLowering &TLI; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2554 | const TargetRegisterInfo &TRI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2555 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2556 | |
| 2557 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2558 | /// the memory instruction that we're computing this address for. |
| 2559 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2560 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2561 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2562 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2563 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2564 | /// part of the return value of this addressing mode matching stuff. |
| 2565 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2566 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2567 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2568 | const SetOfInstrs &InsertedInsts; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2569 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2570 | /// A map from the instructions to their type before promotion. |
| 2571 | InstrToOrigTy &PromotedInsts; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2572 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2573 | /// The ongoing transaction where every action should be registered. |
| 2574 | TypePromotionTransaction &TPT; |
| 2575 | |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 2576 | // A GEP which has too large offset to be folded into the addressing mode. |
| 2577 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP; |
| 2578 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2579 | /// This is set to true when we should not do profitability checks. |
| 2580 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2581 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2582 | |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 2583 | AddressingModeMatcher( |
| 2584 | SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI, |
| 2585 | const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI, |
| 2586 | ExtAddrMode &AM, const SetOfInstrs &InsertedInsts, |
| 2587 | InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT, |
| 2588 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2589 | : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2590 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 2591 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 2592 | PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2593 | IgnoreProfitability = false; |
| 2594 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2595 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2596 | public: |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2597 | /// 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] | 2598 | /// give an access type of AccessTy. This returns a list of involved |
| 2599 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2600 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2601 | /// optimizations. |
| 2602 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 2603 | /// \p The ongoing transaction where every action should be registered. |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 2604 | static ExtAddrMode |
| 2605 | Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst, |
| 2606 | SmallVectorImpl<Instruction *> &AddrModeInsts, |
| 2607 | const TargetLowering &TLI, const TargetRegisterInfo &TRI, |
| 2608 | const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts, |
| 2609 | TypePromotionTransaction &TPT, |
| 2610 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2611 | ExtAddrMode Result; |
| 2612 | |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 2613 | bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2614 | MemoryInst, Result, InsertedInsts, |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 2615 | PromotedInsts, TPT, LargeOffsetGEP) |
| 2616 | .matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2617 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2618 | return Result; |
| 2619 | } |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2620 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2621 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2622 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
Fangrui Song | cb0bab8 | 2018-07-16 18:51:40 +0000 | [diff] [blame] | 2623 | bool matchAddr(Value *Addr, unsigned Depth); |
| 2624 | bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2625 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2626 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2627 | ExtAddrMode &AMBefore, |
| 2628 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2629 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 2630 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2631 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2632 | }; |
| 2633 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2634 | /// Keep track of simplification of Phi nodes. |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2635 | /// Accept the set of all phi nodes and erase phi node from this set |
| 2636 | /// if it is simplified. |
| 2637 | class SimplificationTracker { |
| 2638 | DenseMap<Value *, Value *> Storage; |
| 2639 | const SimplifyQuery &SQ; |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2640 | // Tracks newly created Phi nodes. We use a SetVector to get deterministic |
| 2641 | // order when iterating over the set in MatchPhiSet. |
| 2642 | SmallSetVector<PHINode *, 32> AllPhiNodes; |
| 2643 | // Tracks newly created Select nodes. |
| 2644 | SmallPtrSet<SelectInst *, 32> AllSelectNodes; |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2645 | |
| 2646 | public: |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2647 | SimplificationTracker(const SimplifyQuery &sq) |
| 2648 | : SQ(sq) {} |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2649 | |
| 2650 | Value *Get(Value *V) { |
| 2651 | do { |
| 2652 | auto SV = Storage.find(V); |
| 2653 | if (SV == Storage.end()) |
| 2654 | return V; |
| 2655 | V = SV->second; |
| 2656 | } while (true); |
| 2657 | } |
| 2658 | |
| 2659 | Value *Simplify(Value *Val) { |
| 2660 | SmallVector<Value *, 32> WorkList; |
| 2661 | SmallPtrSet<Value *, 32> Visited; |
| 2662 | WorkList.push_back(Val); |
| 2663 | while (!WorkList.empty()) { |
| 2664 | auto P = WorkList.pop_back_val(); |
| 2665 | if (!Visited.insert(P).second) |
| 2666 | continue; |
| 2667 | if (auto *PI = dyn_cast<Instruction>(P)) |
| 2668 | if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) { |
| 2669 | for (auto *U : PI->users()) |
| 2670 | WorkList.push_back(cast<Value>(U)); |
| 2671 | Put(PI, V); |
| 2672 | PI->replaceAllUsesWith(V); |
| 2673 | if (auto *PHI = dyn_cast<PHINode>(PI)) |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2674 | AllPhiNodes.remove(PHI); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2675 | if (auto *Select = dyn_cast<SelectInst>(PI)) |
| 2676 | AllSelectNodes.erase(Select); |
| 2677 | PI->eraseFromParent(); |
| 2678 | } |
| 2679 | } |
| 2680 | return Get(Val); |
| 2681 | } |
| 2682 | |
| 2683 | void Put(Value *From, Value *To) { |
| 2684 | Storage.insert({ From, To }); |
| 2685 | } |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2686 | |
| 2687 | void ReplacePhi(PHINode *From, PHINode *To) { |
| 2688 | Value* OldReplacement = Get(From); |
| 2689 | while (OldReplacement != From) { |
| 2690 | From = To; |
| 2691 | To = dyn_cast<PHINode>(OldReplacement); |
| 2692 | OldReplacement = Get(From); |
| 2693 | } |
| 2694 | assert(Get(To) == To && "Replacement PHI node is already replaced."); |
| 2695 | Put(From, To); |
| 2696 | From->replaceAllUsesWith(To); |
| 2697 | AllPhiNodes.remove(From); |
| 2698 | From->eraseFromParent(); |
| 2699 | } |
| 2700 | |
| 2701 | SmallSetVector<PHINode *, 32>& newPhiNodes() { return AllPhiNodes; } |
| 2702 | |
| 2703 | void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); } |
| 2704 | |
| 2705 | void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); } |
| 2706 | |
| 2707 | unsigned countNewPhiNodes() const { return AllPhiNodes.size(); } |
| 2708 | |
| 2709 | unsigned countNewSelectNodes() const { return AllSelectNodes.size(); } |
| 2710 | |
| 2711 | void destroyNewNodes(Type *CommonType) { |
| 2712 | // For safe erasing, replace the uses with dummy value first. |
| 2713 | auto Dummy = UndefValue::get(CommonType); |
| 2714 | for (auto I : AllPhiNodes) { |
| 2715 | I->replaceAllUsesWith(Dummy); |
| 2716 | I->eraseFromParent(); |
| 2717 | } |
| 2718 | AllPhiNodes.clear(); |
| 2719 | for (auto I : AllSelectNodes) { |
| 2720 | I->replaceAllUsesWith(Dummy); |
| 2721 | I->eraseFromParent(); |
| 2722 | } |
| 2723 | AllSelectNodes.clear(); |
| 2724 | } |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2725 | }; |
| 2726 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2727 | /// A helper class for combining addressing modes. |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2728 | class AddressingModeCombiner { |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2729 | typedef std::pair<Value *, BasicBlock *> ValueInBB; |
| 2730 | typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping; |
| 2731 | typedef std::pair<PHINode *, PHINode *> PHIPair; |
| 2732 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2733 | private: |
| 2734 | /// The addressing modes we've collected. |
| 2735 | SmallVector<ExtAddrMode, 16> AddrModes; |
| 2736 | |
| 2737 | /// The field in which the AddrModes differ, when we have more than one. |
| 2738 | ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField; |
| 2739 | |
| 2740 | /// Are the AddrModes that we have all just equal to their original values? |
| 2741 | bool AllAddrModesTrivial = true; |
| 2742 | |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2743 | /// Common Type for all different fields in addressing modes. |
| 2744 | Type *CommonType; |
| 2745 | |
| 2746 | /// SimplifyQuery for simplifyInstruction utility. |
| 2747 | const SimplifyQuery &SQ; |
| 2748 | |
| 2749 | /// Original Address. |
| 2750 | ValueInBB Original; |
| 2751 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2752 | public: |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2753 | AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue) |
| 2754 | : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {} |
| 2755 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2756 | /// Get the combined AddrMode |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2757 | const ExtAddrMode &getAddrMode() const { |
| 2758 | return AddrModes[0]; |
| 2759 | } |
| 2760 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2761 | /// Add a new AddrMode if it's compatible with the AddrModes we already |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2762 | /// have. |
| 2763 | /// \return True iff we succeeded in doing so. |
| 2764 | bool addNewAddrMode(ExtAddrMode &NewAddrMode) { |
| 2765 | // Take note of if we have any non-trivial AddrModes, as we need to detect |
| 2766 | // when all AddrModes are trivial as then we would introduce a phi or select |
| 2767 | // which just duplicates what's already there. |
| 2768 | AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial(); |
| 2769 | |
| 2770 | // If this is the first addrmode then everything is fine. |
| 2771 | if (AddrModes.empty()) { |
| 2772 | AddrModes.emplace_back(NewAddrMode); |
| 2773 | return true; |
| 2774 | } |
| 2775 | |
| 2776 | // Figure out how different this is from the other address modes, which we |
| 2777 | // can do just by comparing against the first one given that we only care |
| 2778 | // about the cumulative difference. |
| 2779 | ExtAddrMode::FieldName ThisDifferentField = |
| 2780 | AddrModes[0].compare(NewAddrMode); |
| 2781 | if (DifferentField == ExtAddrMode::NoField) |
| 2782 | DifferentField = ThisDifferentField; |
| 2783 | else if (DifferentField != ThisDifferentField) |
| 2784 | DifferentField = ExtAddrMode::MultipleFields; |
| 2785 | |
Serguei Katkov | 17e5794 | 2018-01-23 12:07:49 +0000 | [diff] [blame] | 2786 | // If NewAddrMode differs in more than one dimension we cannot handle it. |
| 2787 | bool CanHandle = DifferentField != ExtAddrMode::MultipleFields; |
| 2788 | |
| 2789 | // If Scale Field is different then we reject. |
| 2790 | CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField; |
| 2791 | |
Serguei Katkov | 4d1dd6b | 2018-01-09 04:37:06 +0000 | [diff] [blame] | 2792 | // We also must reject the case when base offset is different and |
| 2793 | // scale reg is not null, we cannot handle this case due to merge of |
| 2794 | // different offsets will be used as ScaleReg. |
Serguei Katkov | 17e5794 | 2018-01-23 12:07:49 +0000 | [diff] [blame] | 2795 | CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField || |
| 2796 | !NewAddrMode.ScaledReg); |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2797 | |
Serguei Katkov | 17e5794 | 2018-01-23 12:07:49 +0000 | [diff] [blame] | 2798 | // We also must reject the case when GV is different and BaseReg installed |
| 2799 | // due to we want to use base reg as a merge of GV values. |
| 2800 | CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField || |
| 2801 | !NewAddrMode.HasBaseReg); |
| 2802 | |
| 2803 | // Even if NewAddMode is the same we still need to collect it due to |
| 2804 | // original value is different. And later we will need all original values |
| 2805 | // as anchors during finding the common Phi node. |
| 2806 | if (CanHandle) |
| 2807 | AddrModes.emplace_back(NewAddrMode); |
| 2808 | else |
| 2809 | AddrModes.clear(); |
| 2810 | |
| 2811 | return CanHandle; |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2812 | } |
| 2813 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2814 | /// Combine the addressing modes we've collected into a single |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2815 | /// addressing mode. |
| 2816 | /// \return True iff we successfully combined them or we only had one so |
| 2817 | /// didn't need to combine them anyway. |
| 2818 | bool combineAddrModes() { |
| 2819 | // If we have no AddrModes then they can't be combined. |
| 2820 | if (AddrModes.size() == 0) |
| 2821 | return false; |
| 2822 | |
| 2823 | // A single AddrMode can trivially be combined. |
Serguei Katkov | 505359f | 2017-11-20 05:42:36 +0000 | [diff] [blame] | 2824 | if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField) |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2825 | return true; |
| 2826 | |
| 2827 | // If the AddrModes we collected are all just equal to the value they are |
| 2828 | // derived from then combining them wouldn't do anything useful. |
| 2829 | if (AllAddrModesTrivial) |
| 2830 | return false; |
| 2831 | |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2832 | if (!addrModeCombiningAllowed()) |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2833 | return false; |
| 2834 | |
| 2835 | // Build a map between <original value, basic block where we saw it> to |
| 2836 | // value of base register. |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2837 | // Bail out if there is no common type. |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2838 | FoldAddrToValueMapping Map; |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2839 | if (!initializeMap(Map)) |
| 2840 | return false; |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2841 | |
| 2842 | Value *CommonValue = findCommon(Map); |
| 2843 | if (CommonValue) |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2844 | AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2845 | return CommonValue != nullptr; |
| 2846 | } |
| 2847 | |
| 2848 | private: |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2849 | /// Initialize Map with anchor values. For address seen in some BB |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2850 | /// we set the value of different field saw in this address. |
| 2851 | /// If address is not an instruction than basic block is set to null. |
| 2852 | /// At the same time we find a common type for different field we will |
| 2853 | /// use to create new Phi/Select nodes. Keep it in CommonType field. |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2854 | /// Return false if there is no common type found. |
| 2855 | bool initializeMap(FoldAddrToValueMapping &Map) { |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2856 | // Keep track of keys where the value is null. We will need to replace it |
| 2857 | // with constant null when we know the common type. |
| 2858 | SmallVector<ValueInBB, 2> NullValue; |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2859 | Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType()); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2860 | for (auto &AM : AddrModes) { |
| 2861 | BasicBlock *BB = nullptr; |
| 2862 | if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue)) |
| 2863 | BB = I->getParent(); |
| 2864 | |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2865 | Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2866 | if (DV) { |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2867 | auto *Type = DV->getType(); |
| 2868 | if (CommonType && CommonType != Type) |
| 2869 | return false; |
| 2870 | CommonType = Type; |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2871 | Map[{ AM.OriginalValue, BB }] = DV; |
| 2872 | } else { |
| 2873 | NullValue.push_back({ AM.OriginalValue, BB }); |
| 2874 | } |
| 2875 | } |
| 2876 | assert(CommonType && "At least one non-null value must be!"); |
| 2877 | for (auto VIBB : NullValue) |
| 2878 | Map[VIBB] = Constant::getNullValue(CommonType); |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2879 | return true; |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2880 | } |
| 2881 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2882 | /// We have mapping between value A and basic block where value A |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2883 | /// seen to other value B where B was a field in addressing mode represented |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 2884 | /// by A. Also we have an original value C representing an address in some |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2885 | /// basic block. Traversing from C through phi and selects we ended up with |
| 2886 | /// A's in a map. This utility function tries to find a value V which is a |
| 2887 | /// field in addressing mode C and traversing through phi nodes and selects |
| 2888 | /// we will end up in corresponded values B in a map. |
| 2889 | /// The utility will create a new Phi/Selects if needed. |
| 2890 | // The simple example looks as follows: |
| 2891 | // BB1: |
| 2892 | // p1 = b1 + 40 |
| 2893 | // br cond BB2, BB3 |
| 2894 | // BB2: |
| 2895 | // p2 = b2 + 40 |
| 2896 | // br BB3 |
| 2897 | // BB3: |
| 2898 | // p = phi [p1, BB1], [p2, BB2] |
| 2899 | // v = load p |
| 2900 | // Map is |
| 2901 | // <p1, BB1> -> b1 |
| 2902 | // <p2, BB2> -> b2 |
| 2903 | // Request is |
| 2904 | // <p, BB3> -> ? |
| 2905 | // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3 |
| 2906 | Value *findCommon(FoldAddrToValueMapping &Map) { |
Eric Christopher | d72f78e | 2018-01-09 23:25:38 +0000 | [diff] [blame] | 2907 | // Tracks the simplification of newly created phi nodes. The reason we use |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2908 | // this mapping is because we will add new created Phi nodes in AddrToBase. |
| 2909 | // Simplification of Phi nodes is recursive, so some Phi node may |
| 2910 | // be simplified after we added it to AddrToBase. |
| 2911 | // Using this mapping we can find the current value in AddrToBase. |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2912 | SimplificationTracker ST(SQ); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2913 | |
| 2914 | // First step, DFS to create PHI nodes for all intermediate blocks. |
| 2915 | // Also fill traverse order for the second step. |
| 2916 | SmallVector<ValueInBB, 32> TraverseOrder; |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2917 | InsertPlaceholders(Map, TraverseOrder, ST); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2918 | |
| 2919 | // Second Step, fill new nodes by merged values and simplify if possible. |
| 2920 | FillPlaceholders(Map, TraverseOrder, ST); |
| 2921 | |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2922 | if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) { |
| 2923 | ST.destroyNewNodes(CommonType); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2924 | return nullptr; |
| 2925 | } |
| 2926 | |
| 2927 | // Now we'd like to match New Phi nodes to existed ones. |
| 2928 | unsigned PhiNotMatchedCount = 0; |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2929 | if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) { |
| 2930 | ST.destroyNewNodes(CommonType); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2931 | return nullptr; |
| 2932 | } |
| 2933 | |
| 2934 | auto *Result = ST.Get(Map.find(Original)->second); |
| 2935 | if (Result) { |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2936 | NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount; |
| 2937 | NumMemoryInstsSelectCreated += ST.countNewSelectNodes(); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2938 | } |
| 2939 | return Result; |
| 2940 | } |
| 2941 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2942 | /// Try to match PHI node to Candidate. |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2943 | /// Matcher tracks the matched Phi nodes. |
| 2944 | bool MatchPhiNode(PHINode *PHI, PHINode *Candidate, |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2945 | SmallSetVector<PHIPair, 8> &Matcher, |
| 2946 | SmallSetVector<PHINode *, 32> &PhiNodesToMatch) { |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2947 | SmallVector<PHIPair, 8> WorkList; |
| 2948 | Matcher.insert({ PHI, Candidate }); |
| 2949 | WorkList.push_back({ PHI, Candidate }); |
| 2950 | SmallSet<PHIPair, 8> Visited; |
| 2951 | while (!WorkList.empty()) { |
| 2952 | auto Item = WorkList.pop_back_val(); |
| 2953 | if (!Visited.insert(Item).second) |
| 2954 | continue; |
| 2955 | // We iterate over all incoming values to Phi to compare them. |
| 2956 | // If values are different and both of them Phi and the first one is a |
| 2957 | // Phi we added (subject to match) and both of them is in the same basic |
| 2958 | // block then we can match our pair if values match. So we state that |
| 2959 | // these values match and add it to work list to verify that. |
| 2960 | for (auto B : Item.first->blocks()) { |
| 2961 | Value *FirstValue = Item.first->getIncomingValueForBlock(B); |
| 2962 | Value *SecondValue = Item.second->getIncomingValueForBlock(B); |
| 2963 | if (FirstValue == SecondValue) |
| 2964 | continue; |
| 2965 | |
| 2966 | PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue); |
| 2967 | PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue); |
| 2968 | |
| 2969 | // One of them is not Phi or |
| 2970 | // The first one is not Phi node from the set we'd like to match or |
| 2971 | // Phi nodes from different basic blocks then |
| 2972 | // we will not be able to match. |
| 2973 | if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) || |
| 2974 | FirstPhi->getParent() != SecondPhi->getParent()) |
| 2975 | return false; |
| 2976 | |
| 2977 | // If we already matched them then continue. |
| 2978 | if (Matcher.count({ FirstPhi, SecondPhi })) |
| 2979 | continue; |
| 2980 | // So the values are different and does not match. So we need them to |
| 2981 | // match. |
| 2982 | Matcher.insert({ FirstPhi, SecondPhi }); |
| 2983 | // But me must check it. |
| 2984 | WorkList.push_back({ FirstPhi, SecondPhi }); |
| 2985 | } |
| 2986 | } |
| 2987 | return true; |
| 2988 | } |
| 2989 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 2990 | /// For the given set of PHI nodes (in the SimplificationTracker) try |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2991 | /// to find their equivalents. |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2992 | /// Returns false if this matching fails and creation of new Phi is disabled. |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2993 | bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes, |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2994 | unsigned &PhiNotMatchedCount) { |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2995 | // Use a SetVector for Matched to make sure we do replacements (ReplacePhi) |
| 2996 | // in a deterministic order below. |
| 2997 | SmallSetVector<PHIPair, 8> Matched; |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2998 | SmallPtrSet<PHINode *, 8> WillNotMatch; |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 2999 | SmallSetVector<PHINode *, 32> &PhiNodesToMatch = ST.newPhiNodes(); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3000 | while (PhiNodesToMatch.size()) { |
| 3001 | PHINode *PHI = *PhiNodesToMatch.begin(); |
| 3002 | |
| 3003 | // Add us, if no Phi nodes in the basic block we do not match. |
| 3004 | WillNotMatch.clear(); |
| 3005 | WillNotMatch.insert(PHI); |
| 3006 | |
| 3007 | // Traverse all Phis until we found equivalent or fail to do that. |
| 3008 | bool IsMatched = false; |
| 3009 | for (auto &P : PHI->getParent()->phis()) { |
| 3010 | if (&P == PHI) |
| 3011 | continue; |
| 3012 | if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch))) |
| 3013 | break; |
| 3014 | // If it does not match, collect all Phi nodes from matcher. |
| 3015 | // if we end up with no match, them all these Phi nodes will not match |
| 3016 | // later. |
| 3017 | for (auto M : Matched) |
| 3018 | WillNotMatch.insert(M.first); |
| 3019 | Matched.clear(); |
| 3020 | } |
| 3021 | if (IsMatched) { |
Serguei Katkov | a20e05b | 2018-03-12 03:50:07 +0000 | [diff] [blame] | 3022 | // Replace all matched values and erase them. |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 3023 | for (auto MV : Matched) |
| 3024 | ST.ReplacePhi(MV.first, MV.second); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3025 | Matched.clear(); |
| 3026 | continue; |
| 3027 | } |
| 3028 | // If we are not allowed to create new nodes then bail out. |
| 3029 | if (!AllowNewPhiNodes) |
| 3030 | return false; |
| 3031 | // Just remove all seen values in matcher. They will not match anything. |
| 3032 | PhiNotMatchedCount += WillNotMatch.size(); |
| 3033 | for (auto *P : WillNotMatch) |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 3034 | PhiNodesToMatch.remove(P); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3035 | } |
| 3036 | return true; |
| 3037 | } |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 3038 | /// Fill the placeholder with values from predecessors and simplify it. |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3039 | void FillPlaceholders(FoldAddrToValueMapping &Map, |
| 3040 | SmallVectorImpl<ValueInBB> &TraverseOrder, |
| 3041 | SimplificationTracker &ST) { |
| 3042 | while (!TraverseOrder.empty()) { |
| 3043 | auto Current = TraverseOrder.pop_back_val(); |
| 3044 | assert(Map.find(Current) != Map.end() && "No node to fill!!!"); |
| 3045 | Value *CurrentValue = Current.first; |
| 3046 | BasicBlock *CurrentBlock = Current.second; |
| 3047 | Value *V = Map[Current]; |
| 3048 | |
| 3049 | if (SelectInst *Select = dyn_cast<SelectInst>(V)) { |
| 3050 | // CurrentValue also must be Select. |
| 3051 | auto *CurrentSelect = cast<SelectInst>(CurrentValue); |
| 3052 | auto *TrueValue = CurrentSelect->getTrueValue(); |
| 3053 | ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue) |
| 3054 | ? CurrentBlock |
| 3055 | : nullptr }; |
| 3056 | assert(Map.find(TrueItem) != Map.end() && "No True Value!"); |
Serguei Katkov | b0b67a8 | 2017-12-18 04:25:07 +0000 | [diff] [blame] | 3057 | Select->setTrueValue(ST.Get(Map[TrueItem])); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3058 | auto *FalseValue = CurrentSelect->getFalseValue(); |
| 3059 | ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue) |
| 3060 | ? CurrentBlock |
| 3061 | : nullptr }; |
| 3062 | assert(Map.find(FalseItem) != Map.end() && "No False Value!"); |
Serguei Katkov | b0b67a8 | 2017-12-18 04:25:07 +0000 | [diff] [blame] | 3063 | Select->setFalseValue(ST.Get(Map[FalseItem])); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3064 | } else { |
| 3065 | // Must be a Phi node then. |
| 3066 | PHINode *PHI = cast<PHINode>(V); |
| 3067 | // Fill the Phi node with values from predecessors. |
| 3068 | bool IsDefinedInThisBB = |
| 3069 | cast<Instruction>(CurrentValue)->getParent() == CurrentBlock; |
| 3070 | auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue); |
| 3071 | for (auto B : predecessors(CurrentBlock)) { |
| 3072 | Value *PV = IsDefinedInThisBB |
| 3073 | ? CurrentPhi->getIncomingValueForBlock(B) |
| 3074 | : CurrentValue; |
| 3075 | ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr }; |
| 3076 | assert(Map.find(item) != Map.end() && "No predecessor Value!"); |
| 3077 | PHI->addIncoming(ST.Get(Map[item]), B); |
| 3078 | } |
| 3079 | } |
| 3080 | // Simplify if possible. |
| 3081 | Map[Current] = ST.Simplify(V); |
| 3082 | } |
| 3083 | } |
| 3084 | |
| 3085 | /// Starting from value recursively iterates over predecessors up to known |
| 3086 | /// ending values represented in a map. For each traversed block inserts |
| 3087 | /// a placeholder Phi or Select. |
| 3088 | /// Reports all new created Phi/Select nodes by adding them to set. |
| 3089 | /// Also reports and order in what basic blocks have been traversed. |
| 3090 | void InsertPlaceholders(FoldAddrToValueMapping &Map, |
| 3091 | SmallVectorImpl<ValueInBB> &TraverseOrder, |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 3092 | SimplificationTracker &ST) { |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3093 | SmallVector<ValueInBB, 32> Worklist; |
| 3094 | assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) && |
| 3095 | "Address must be a Phi or Select node"); |
| 3096 | auto *Dummy = UndefValue::get(CommonType); |
| 3097 | Worklist.push_back(Original); |
| 3098 | while (!Worklist.empty()) { |
| 3099 | auto Current = Worklist.pop_back_val(); |
| 3100 | // If value is not an instruction it is something global, constant, |
| 3101 | // parameter and we can say that this value is observable in any block. |
| 3102 | // Set block to null to denote it. |
| 3103 | // Also please take into account that it is how we build anchors. |
| 3104 | if (!isa<Instruction>(Current.first)) |
| 3105 | Current.second = nullptr; |
| 3106 | // if it is already visited or it is an ending value then skip it. |
| 3107 | if (Map.find(Current) != Map.end()) |
| 3108 | continue; |
| 3109 | TraverseOrder.push_back(Current); |
| 3110 | |
| 3111 | Value *CurrentValue = Current.first; |
| 3112 | BasicBlock *CurrentBlock = Current.second; |
| 3113 | // CurrentValue must be a Phi node or select. All others must be covered |
| 3114 | // by anchors. |
| 3115 | Instruction *CurrentI = cast<Instruction>(CurrentValue); |
| 3116 | bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock; |
| 3117 | |
Vedant Kumar | e0b5f86 | 2018-05-10 23:01:54 +0000 | [diff] [blame] | 3118 | unsigned PredCount = pred_size(CurrentBlock); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3119 | // if Current Value is not defined in this basic block we are interested |
| 3120 | // in values in predecessors. |
| 3121 | if (!IsDefinedInThisBB) { |
| 3122 | assert(PredCount && "Unreachable block?!"); |
| 3123 | PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi", |
| 3124 | &CurrentBlock->front()); |
| 3125 | Map[Current] = PHI; |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 3126 | ST.insertNewPhi(PHI); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3127 | // Add all predecessors in work list. |
| 3128 | for (auto B : predecessors(CurrentBlock)) |
| 3129 | Worklist.push_back({ CurrentValue, B }); |
| 3130 | continue; |
| 3131 | } |
| 3132 | // Value is defined in this basic block. |
| 3133 | if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) { |
| 3134 | // Is it OK to get metadata from OrigSelect?! |
| 3135 | // Create a Select placeholder with dummy value. |
| 3136 | SelectInst *Select = |
| 3137 | SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy, |
| 3138 | OrigSelect->getName(), OrigSelect, OrigSelect); |
| 3139 | Map[Current] = Select; |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 3140 | ST.insertNewSelect(Select); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3141 | // We are interested in True and False value in this basic block. |
| 3142 | Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock }); |
| 3143 | Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock }); |
| 3144 | } else { |
| 3145 | // It must be a Phi node then. |
| 3146 | auto *CurrentPhi = cast<PHINode>(CurrentI); |
| 3147 | // Create new Phi node for merge of bases. |
| 3148 | assert(PredCount && "Unreachable block?!"); |
| 3149 | PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi", |
| 3150 | &CurrentBlock->front()); |
| 3151 | Map[Current] = PHI; |
Bjorn Pettersson | bf3213e | 2018-03-20 09:06:37 +0000 | [diff] [blame] | 3152 | ST.insertNewPhi(PHI); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 3153 | |
| 3154 | // Add all predecessors in work list. |
| 3155 | for (auto B : predecessors(CurrentBlock)) |
| 3156 | Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B }); |
| 3157 | } |
| 3158 | } |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 3159 | } |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 3160 | |
| 3161 | bool addrModeCombiningAllowed() { |
| 3162 | if (DisableComplexAddrModes) |
| 3163 | return false; |
| 3164 | switch (DifferentField) { |
| 3165 | default: |
| 3166 | return false; |
| 3167 | case ExtAddrMode::BaseRegField: |
| 3168 | return AddrSinkCombineBaseReg; |
| 3169 | case ExtAddrMode::BaseGVField: |
| 3170 | return AddrSinkCombineBaseGV; |
| 3171 | case ExtAddrMode::BaseOffsField: |
| 3172 | return AddrSinkCombineBaseOffs; |
| 3173 | case ExtAddrMode::ScaledRegField: |
| 3174 | return AddrSinkCombineScaledReg; |
| 3175 | } |
| 3176 | } |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 3177 | }; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3178 | } // end anonymous namespace |
| 3179 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3180 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3181 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 3182 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3183 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3184 | unsigned Depth) { |
| 3185 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 3186 | // mode. Just process that directly. |
| 3187 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3188 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3189 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3190 | // If the scale is 0, it takes nothing to add this. |
| 3191 | if (Scale == 0) |
| 3192 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3193 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3194 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 3195 | // need an available scale field. |
| 3196 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 3197 | return false; |
| 3198 | |
| 3199 | ExtAddrMode TestAddrMode = AddrMode; |
| 3200 | |
| 3201 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 3202 | // [A+B + A*7] -> [B+A*8]. |
| 3203 | TestAddrMode.Scale += Scale; |
| 3204 | TestAddrMode.ScaledReg = ScaleReg; |
| 3205 | |
| 3206 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3207 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3208 | return false; |
| 3209 | |
| 3210 | // It was legal, so commit it. |
| 3211 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3212 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3213 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 3214 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 3215 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3216 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3217 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 3218 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 3219 | TestAddrMode.ScaledReg = AddLHS; |
| 3220 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3221 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3222 | // If this addressing mode is legal, commit it and remember that we folded |
| 3223 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3224 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3225 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 3226 | AddrMode = TestAddrMode; |
| 3227 | return true; |
| 3228 | } |
| 3229 | } |
| 3230 | |
| 3231 | // Otherwise, not (x+c)*scale, just return what we have. |
| 3232 | return true; |
| 3233 | } |
| 3234 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3235 | /// This is a little filter, which returns true if an addressing computation |
| 3236 | /// involving I might be folded into a load/store accessing it. |
| 3237 | /// 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] | 3238 | /// the set of instructions that MatchOperationAddr can. |
| 3239 | static bool MightBeFoldableInst(Instruction *I) { |
| 3240 | switch (I->getOpcode()) { |
| 3241 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 3242 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3243 | // Don't touch identity bitcasts. |
| 3244 | if (I->getType() == I->getOperand(0)->getType()) |
| 3245 | return false; |
Vedant Kumar | b3091da | 2018-07-06 20:17:42 +0000 | [diff] [blame] | 3246 | return I->getType()->isIntOrPtrTy(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3247 | case Instruction::PtrToInt: |
| 3248 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 3249 | return true; |
| 3250 | case Instruction::IntToPtr: |
| 3251 | // We know the input is intptr_t, so this is foldable. |
| 3252 | return true; |
| 3253 | case Instruction::Add: |
| 3254 | return true; |
| 3255 | case Instruction::Mul: |
| 3256 | case Instruction::Shl: |
| 3257 | // Can only handle X*C and X << C. |
| 3258 | return isa<ConstantInt>(I->getOperand(1)); |
| 3259 | case Instruction::GetElementPtr: |
| 3260 | return true; |
| 3261 | default: |
| 3262 | return false; |
| 3263 | } |
| 3264 | } |
| 3265 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 3266 | /// Check whether or not \p Val is a legal instruction for \p TLI. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3267 | /// \note \p Val is assumed to be the product of some type promotion. |
| 3268 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 3269 | /// 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] | 3270 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 3271 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3272 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 3273 | if (!PromotedInst) |
| 3274 | return false; |
| 3275 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 3276 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 3277 | if (!ISDOpcode) |
| 3278 | return true; |
| 3279 | // Otherwise, check if the promoted instruction is legal or not. |
| 3280 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3281 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3282 | } |
| 3283 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3284 | namespace { |
| 3285 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 3286 | /// Hepler class to perform type promotion. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3287 | class TypePromotionHelper { |
Guozhi Wei | 8c17f9a | 2018-08-15 22:08:26 +0000 | [diff] [blame] | 3288 | /// Utility function to add a promoted instruction \p ExtOpnd to |
| 3289 | /// \p PromotedInsts and record the type of extension we have seen. |
| 3290 | static void addPromotedInst(InstrToOrigTy &PromotedInsts, |
| 3291 | Instruction *ExtOpnd, |
| 3292 | bool IsSExt) { |
| 3293 | ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; |
| 3294 | InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd); |
| 3295 | if (It != PromotedInsts.end()) { |
| 3296 | // If the new extension is same as original, the information in |
| 3297 | // PromotedInsts[ExtOpnd] is still correct. |
| 3298 | if (It->second.getInt() == ExtTy) |
| 3299 | return; |
| 3300 | |
| 3301 | // Now the new extension is different from old extension, we make |
| 3302 | // the type information invalid by setting extension type to |
| 3303 | // BothExtension. |
| 3304 | ExtTy = BothExtension; |
| 3305 | } |
| 3306 | PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy); |
| 3307 | } |
| 3308 | |
| 3309 | /// Utility function to query the original type of instruction \p Opnd |
| 3310 | /// with a matched extension type. If the extension doesn't match, we |
| 3311 | /// cannot use the information we had on the original type. |
| 3312 | /// BothExtension doesn't match any extension type. |
| 3313 | static const Type *getOrigType(const InstrToOrigTy &PromotedInsts, |
| 3314 | Instruction *Opnd, |
| 3315 | bool IsSExt) { |
| 3316 | ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension; |
| 3317 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
| 3318 | if (It != PromotedInsts.end() && It->second.getInt() == ExtTy) |
| 3319 | return It->second.getPointer(); |
| 3320 | return nullptr; |
| 3321 | } |
| 3322 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 3323 | /// Utility function to check whether or not a sign or zero extension |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3324 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 3325 | /// either using the operands of \p Inst or promoting \p Inst. |
| 3326 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3327 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3328 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3329 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3330 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3331 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3332 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3333 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3334 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 3335 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3336 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 3337 | /// Utility function to determine if \p OpIdx should be promoted when |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3338 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3339 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3340 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3341 | } |
| 3342 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 3343 | /// Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3344 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3345 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3346 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3347 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3348 | /// Newly added extensions are inserted in \p Exts. |
| 3349 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3350 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3351 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3352 | static Value *promoteOperandForTruncAndAnyExt( |
| 3353 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3354 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3355 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3356 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3357 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 3358 | /// Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3359 | /// operand is promotable and is not a supported trunc or sext. |
| 3360 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3361 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3362 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3363 | /// Newly added extensions are inserted in \p Exts. |
| 3364 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3365 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3366 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3367 | static Value *promoteOperandForOther(Instruction *Ext, |
| 3368 | TypePromotionTransaction &TPT, |
| 3369 | InstrToOrigTy &PromotedInsts, |
| 3370 | unsigned &CreatedInstsCost, |
| 3371 | SmallVectorImpl<Instruction *> *Exts, |
| 3372 | SmallVectorImpl<Instruction *> *Truncs, |
| 3373 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3374 | |
| 3375 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3376 | static Value *signExtendOperandForOther( |
| 3377 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3378 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3379 | SmallVectorImpl<Instruction *> *Exts, |
| 3380 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3381 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3382 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3383 | } |
| 3384 | |
| 3385 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3386 | static Value *zeroExtendOperandForOther( |
| 3387 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3388 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3389 | SmallVectorImpl<Instruction *> *Exts, |
| 3390 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3391 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3392 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3393 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3394 | |
| 3395 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3396 | /// Type for the utility function that promotes the operand of Ext. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3397 | using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT, |
| 3398 | InstrToOrigTy &PromotedInsts, |
| 3399 | unsigned &CreatedInstsCost, |
| 3400 | SmallVectorImpl<Instruction *> *Exts, |
| 3401 | SmallVectorImpl<Instruction *> *Truncs, |
| 3402 | const TargetLowering &TLI); |
| 3403 | |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 3404 | /// Given a sign/zero extend instruction \p Ext, return the appropriate |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3405 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3406 | /// \return NULL if no promotable action is possible with the current |
| 3407 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3408 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 3409 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3410 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 3411 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 3412 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3413 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3414 | const TargetLowering &TLI, |
| 3415 | const InstrToOrigTy &PromotedInsts); |
| 3416 | }; |
| 3417 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3418 | } // end anonymous namespace |
| 3419 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3420 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3421 | Type *ConsideredExtType, |
| 3422 | const InstrToOrigTy &PromotedInsts, |
| 3423 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3424 | // The promotion helper does not know how to deal with vector types yet. |
| 3425 | // To be able to fix that, we would need to fix the places where we |
| 3426 | // statically extend, e.g., constants and such. |
| 3427 | if (Inst->getType()->isVectorTy()) |
| 3428 | return false; |
| 3429 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3430 | // We can always get through zext. |
| 3431 | if (isa<ZExtInst>(Inst)) |
| 3432 | return true; |
| 3433 | |
| 3434 | // sext(sext) is ok too. |
| 3435 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3436 | return true; |
| 3437 | |
| 3438 | // We can get through binary operator, if it is legal. In other words, the |
| 3439 | // binary operator must have a nuw or nsw flag. |
| 3440 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 3441 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3442 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 3443 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3444 | return true; |
| 3445 | |
Guozhi Wei | c4c6b54 | 2018-06-05 21:03:52 +0000 | [diff] [blame] | 3446 | // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst)) |
| 3447 | if ((Inst->getOpcode() == Instruction::And || |
| 3448 | Inst->getOpcode() == Instruction::Or)) |
| 3449 | return true; |
| 3450 | |
| 3451 | // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst)) |
| 3452 | if (Inst->getOpcode() == Instruction::Xor) { |
| 3453 | const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)); |
| 3454 | // Make sure it is not a NOT. |
| 3455 | if (Cst && !Cst->getValue().isAllOnesValue()) |
| 3456 | return true; |
| 3457 | } |
| 3458 | |
| 3459 | // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst)) |
| 3460 | // It may change a poisoned value into a regular value, like |
| 3461 | // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12 |
| 3462 | // poisoned value regular value |
| 3463 | // It should be OK since undef covers valid value. |
| 3464 | if (Inst->getOpcode() == Instruction::LShr && !IsSExt) |
| 3465 | return true; |
| 3466 | |
| 3467 | // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst) |
| 3468 | // It may change a poisoned value into a regular value, like |
| 3469 | // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12 |
| 3470 | // poisoned value regular value |
| 3471 | // It should be OK since undef covers valid value. |
| 3472 | if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) { |
| 3473 | const Instruction *ExtInst = |
| 3474 | dyn_cast<const Instruction>(*Inst->user_begin()); |
| 3475 | if (ExtInst->hasOneUse()) { |
| 3476 | const Instruction *AndInst = |
| 3477 | dyn_cast<const Instruction>(*ExtInst->user_begin()); |
| 3478 | if (AndInst && AndInst->getOpcode() == Instruction::And) { |
| 3479 | const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1)); |
| 3480 | if (Cst && |
| 3481 | Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth())) |
| 3482 | return true; |
| 3483 | } |
| 3484 | } |
| 3485 | } |
| 3486 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3487 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3488 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3489 | if (!isa<TruncInst>(Inst)) |
| 3490 | return false; |
| 3491 | |
| 3492 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3493 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3494 | // 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] | 3495 | if (!OpndVal->getType()->isIntegerTy() || |
| 3496 | OpndVal->getType()->getIntegerBitWidth() > |
| 3497 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3498 | return false; |
| 3499 | |
| 3500 | // If the operand of the truncate is not an instruction, we will not have |
| 3501 | // any information on the dropped bits. |
| 3502 | // (Actually we could for constant but it is not worth the extra logic). |
| 3503 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 3504 | if (!Opnd) |
| 3505 | return false; |
| 3506 | |
| 3507 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3508 | // I.e., check that trunc just drops extended bits of the same kind of |
| 3509 | // the extension. |
| 3510 | // #1 get the type of the operand and check the kind of the extended bits. |
Guozhi Wei | 8c17f9a | 2018-08-15 22:08:26 +0000 | [diff] [blame] | 3511 | const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt); |
| 3512 | if (OpndType) |
| 3513 | ; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3514 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 3515 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3516 | else |
| 3517 | return false; |
| 3518 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3519 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3520 | return Inst->getType()->getIntegerBitWidth() >= |
| 3521 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3522 | } |
| 3523 | |
| 3524 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3525 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3526 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3527 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 3528 | "Unexpected instruction type"); |
| 3529 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 3530 | Type *ExtTy = Ext->getType(); |
| 3531 | bool IsSExt = isa<SExtInst>(Ext); |
| 3532 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3533 | // get through. |
| 3534 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3535 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3536 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3537 | |
| 3538 | // Do not promote if the operand has been added by codegenprepare. |
| 3539 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 3540 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3541 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3542 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3543 | |
| 3544 | // SExt or Trunc instructions. |
| 3545 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3546 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 3547 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3548 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3549 | |
| 3550 | // Regular instruction. |
| 3551 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3552 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3553 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3554 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3555 | } |
| 3556 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3557 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3558 | Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3559 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3560 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3561 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3562 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 3563 | // get through it and this method should not be called. |
| 3564 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3565 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3566 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3567 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3568 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3569 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3570 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3571 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3572 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 3573 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 3574 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3575 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3576 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3577 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 3578 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3579 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 3580 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3581 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3582 | |
| 3583 | // Remove dead code. |
| 3584 | if (SExtOpnd->use_empty()) |
| 3585 | TPT.eraseInstruction(SExtOpnd); |
| 3586 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3587 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3588 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3589 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3590 | if (ExtInst) { |
| 3591 | if (Exts) |
| 3592 | Exts->push_back(ExtInst); |
| 3593 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 3594 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3595 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3596 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3597 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3598 | // At this point we have: ext ty opnd to ty. |
| 3599 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 3600 | Value *NextVal = ExtInst->getOperand(0); |
| 3601 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3602 | return NextVal; |
| 3603 | } |
| 3604 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3605 | Value *TypePromotionHelper::promoteOperandForOther( |
| 3606 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3607 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3608 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3609 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 3610 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3611 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3612 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3613 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3614 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3615 | if (!ExtOpnd->hasOneUse()) { |
| 3616 | // ExtOpnd will be promoted. |
| 3617 | // 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] | 3618 | // promoted version. |
| 3619 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3620 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3621 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3622 | // Insert it just after the definition. |
Sanjay Patel | 674d2c2 | 2017-08-29 14:07:48 +0000 | [diff] [blame] | 3623 | ITrunc->moveAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3624 | if (Truncs) |
| 3625 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3626 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3627 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3628 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3629 | // 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] | 3630 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3631 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3632 | } |
| 3633 | |
| 3634 | // Get through the Instruction: |
| 3635 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3636 | // 2. Replace the uses of Ext by Inst. |
| 3637 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3638 | |
| 3639 | // Remember the original type of the instruction before promotion. |
| 3640 | // This is useful to know that the high bits are sign extended bits. |
Guozhi Wei | 8c17f9a | 2018-08-15 22:08:26 +0000 | [diff] [blame] | 3641 | addPromotedInst(PromotedInsts, ExtOpnd, IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3642 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3643 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3644 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3645 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3646 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3647 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3648 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3649 | LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n"); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3650 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3651 | ++OpIdx) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3652 | LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3653 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 3654 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3655 | LLVM_DEBUG(dbgs() << "No need to propagate\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3656 | continue; |
| 3657 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3658 | // Check if we can statically extend the operand. |
| 3659 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3660 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3661 | LLVM_DEBUG(dbgs() << "Statically extend\n"); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3662 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 3663 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 3664 | : Cst->getValue().zext(BitWidth); |
| 3665 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3666 | continue; |
| 3667 | } |
| 3668 | // UndefValue are typed, so we have to statically sign extend them. |
| 3669 | if (isa<UndefValue>(Opnd)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3670 | LLVM_DEBUG(dbgs() << "Statically extend\n"); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3671 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3672 | continue; |
| 3673 | } |
| 3674 | |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 3675 | // Otherwise we have to explicitly sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3676 | // Check if Ext was reused to extend an operand. |
| 3677 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3678 | // If yes, create a new one. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3679 | LLVM_DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 3680 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 3681 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 3682 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 3683 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 3684 | continue; |
| 3685 | } |
| 3686 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3687 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3688 | if (Exts) |
| 3689 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3690 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3691 | |
| 3692 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3693 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 3694 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3695 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3696 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3697 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3698 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3699 | if (ExtForOpnd == Ext) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3700 | LLVM_DEBUG(dbgs() << "Extension is useless now\n"); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3701 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3702 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3703 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3704 | } |
| 3705 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3706 | /// 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] | 3707 | /// \p NewCost gives the cost of extension instructions created by the |
| 3708 | /// promotion. |
| 3709 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 3710 | /// plus the number of instructions that have been |
| 3711 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3712 | /// \p PromotedOperand is the value that has been promoted. |
| 3713 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3714 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3715 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3716 | LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost |
| 3717 | << '\n'); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3718 | // The cost of the new extensions is greater than the cost of the |
| 3719 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3720 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3721 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3722 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3723 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3724 | return true; |
| 3725 | // The promotion is neutral but it may help folding the sign extension in |
| 3726 | // loads for instance. |
| 3727 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3728 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3729 | } |
| 3730 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3731 | /// 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] | 3732 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3733 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3734 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 3735 | /// not AddrInst has to be folded into the addressing mode on success. |
| 3736 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 3737 | /// because it has been moved away. |
| 3738 | /// Thus AddrInst must not be added in the matched instructions. |
| 3739 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 3740 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 3741 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3742 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3743 | unsigned Depth, |
| 3744 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3745 | // Avoid exponential behavior on extremely deep expression trees. |
| 3746 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3747 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3748 | // By default, all matched instructions stay in place. |
| 3749 | if (MovedAway) |
| 3750 | *MovedAway = false; |
| 3751 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3752 | switch (Opcode) { |
| 3753 | case Instruction::PtrToInt: |
| 3754 | // 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] | 3755 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3756 | case Instruction::IntToPtr: { |
| 3757 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3758 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3759 | // 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] | 3760 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3761 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3762 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3763 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3764 | case Instruction::BitCast: |
| 3765 | // BitCast is always a noop, and we can handle it as long as it is |
| 3766 | // int->int or pointer->pointer (we don't want int<->fp or something). |
Vedant Kumar | b3091da | 2018-07-06 20:17:42 +0000 | [diff] [blame] | 3767 | if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() && |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3768 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3769 | // and we don't want to mess around with them. Assume it knows what it |
| 3770 | // is doing. |
| 3771 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3772 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3773 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3774 | case Instruction::AddrSpaceCast: { |
| 3775 | unsigned SrcAS |
| 3776 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3777 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3778 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3779 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3780 | return false; |
| 3781 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3782 | case Instruction::Add: { |
| 3783 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3784 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3785 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3786 | // Start a transaction at this point. |
| 3787 | // The LHS may match but not the RHS. |
| 3788 | // Therefore, we need a higher level restoration point to undo partially |
| 3789 | // matched operation. |
| 3790 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3791 | TPT.getRestorationPoint(); |
| 3792 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3793 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3794 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3795 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3796 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3797 | // Restore the old addr mode info. |
| 3798 | AddrMode = BackupAddrMode; |
| 3799 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3800 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3801 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3802 | // 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] | 3803 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3804 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3805 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3806 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3807 | // Otherwise we definitely can't merge the ADD in. |
| 3808 | AddrMode = BackupAddrMode; |
| 3809 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3810 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3811 | break; |
| 3812 | } |
| 3813 | //case Instruction::Or: |
| 3814 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3815 | //break; |
| 3816 | case Instruction::Mul: |
| 3817 | case Instruction::Shl: { |
| 3818 | // Can only handle X*C and X << C. |
| 3819 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Philip Reames | 9c3cbee | 2017-10-30 23:59:51 +0000 | [diff] [blame] | 3820 | if (!RHS || RHS->getBitWidth() > 64) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3821 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3822 | int64_t Scale = RHS->getSExtValue(); |
| 3823 | if (Opcode == Instruction::Shl) |
| 3824 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3825 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3826 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3827 | } |
| 3828 | case Instruction::GetElementPtr: { |
| 3829 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3830 | // one variable offset. |
| 3831 | int VariableOperand = -1; |
| 3832 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3833 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3834 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3835 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3836 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 3837 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3838 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3839 | unsigned Idx = |
| 3840 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3841 | ConstantOffset += SL->getElementOffset(Idx); |
| 3842 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3843 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3844 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
Simon Pilgrim | ee82a79 | 2018-08-13 12:10:09 +0000 | [diff] [blame] | 3845 | const APInt &CVal = CI->getValue(); |
| 3846 | if (CVal.getMinSignedBits() <= 64) { |
| 3847 | ConstantOffset += CVal.getSExtValue() * TypeSize; |
| 3848 | continue; |
| 3849 | } |
| 3850 | } |
| 3851 | if (TypeSize) { // Scales of zero don't do anything. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3852 | // We only allow one variable index at the moment. |
| 3853 | if (VariableOperand != -1) |
| 3854 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3855 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3856 | // Remember the variable index. |
| 3857 | VariableOperand = i; |
| 3858 | VariableScale = TypeSize; |
| 3859 | } |
| 3860 | } |
| 3861 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3862 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3863 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3864 | // just add it to the disp field and check validity. |
| 3865 | if (VariableOperand == -1) { |
| 3866 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3867 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3868 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3869 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3870 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3871 | return true; |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 3872 | } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) && |
| 3873 | TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 && |
| 3874 | ConstantOffset > 0) { |
| 3875 | // Record GEPs with non-zero offsets as candidates for splitting in the |
| 3876 | // event that the offset cannot fit into the r+i addressing mode. |
| 3877 | // Simple and common case that only one GEP is used in calculating the |
| 3878 | // address for the memory access. |
| 3879 | Value *Base = AddrInst->getOperand(0); |
| 3880 | auto *BaseI = dyn_cast<Instruction>(Base); |
| 3881 | auto *GEP = cast<GetElementPtrInst>(AddrInst); |
| 3882 | if (isa<Argument>(Base) || isa<GlobalValue>(Base) || |
| 3883 | (BaseI && !isa<CastInst>(BaseI) && |
| 3884 | !isa<GetElementPtrInst>(BaseI))) { |
| 3885 | // If the base is an instruction, make sure the GEP is not in the same |
| 3886 | // basic block as the base. If the base is an argument or global |
| 3887 | // value, make sure the GEP is not in the entry block. Otherwise, |
| 3888 | // instruction selection can undo the split. Also make sure the |
| 3889 | // parent block allows inserting non-PHI instructions before the |
| 3890 | // terminator. |
| 3891 | BasicBlock *Parent = |
| 3892 | BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock(); |
| 3893 | if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad()) |
| 3894 | LargeOffsetGEP = std::make_pair(GEP, ConstantOffset); |
| 3895 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3896 | } |
| 3897 | AddrMode.BaseOffs -= ConstantOffset; |
| 3898 | return false; |
| 3899 | } |
| 3900 | |
| 3901 | // Save the valid addressing mode in case we can't match. |
| 3902 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3903 | unsigned OldSize = AddrModeInsts.size(); |
| 3904 | |
| 3905 | // See if the scale and offset amount is valid for this target. |
| 3906 | AddrMode.BaseOffs += ConstantOffset; |
| 3907 | |
| 3908 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3909 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3910 | // If it couldn't be matched, just stuff the value in a register. |
| 3911 | if (AddrMode.HasBaseReg) { |
| 3912 | AddrMode = BackupAddrMode; |
| 3913 | AddrModeInsts.resize(OldSize); |
| 3914 | return false; |
| 3915 | } |
| 3916 | AddrMode.HasBaseReg = true; |
| 3917 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3918 | } |
| 3919 | |
| 3920 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3921 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3922 | Depth)) { |
| 3923 | // If it couldn't be matched, try stuffing the base into a register |
| 3924 | // instead of matching it, and retrying the match of the scale. |
| 3925 | AddrMode = BackupAddrMode; |
| 3926 | AddrModeInsts.resize(OldSize); |
| 3927 | if (AddrMode.HasBaseReg) |
| 3928 | return false; |
| 3929 | AddrMode.HasBaseReg = true; |
| 3930 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3931 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3932 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3933 | VariableScale, Depth)) { |
| 3934 | // If even that didn't work, bail. |
| 3935 | AddrMode = BackupAddrMode; |
| 3936 | AddrModeInsts.resize(OldSize); |
| 3937 | return false; |
| 3938 | } |
| 3939 | } |
| 3940 | |
| 3941 | return true; |
| 3942 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3943 | case Instruction::SExt: |
| 3944 | case Instruction::ZExt: { |
| 3945 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3946 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3947 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3948 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3949 | // 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] | 3950 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3951 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3952 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3953 | if (!TPH) |
| 3954 | return false; |
| 3955 | |
| 3956 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3957 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3958 | unsigned CreatedInstsCost = 0; |
| 3959 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3960 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3961 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3962 | // SExt has been moved away. |
| 3963 | // Thus either it will be rematched later in the recursive calls or it is |
| 3964 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3965 | // E.g., |
| 3966 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3967 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3968 | // addr = gep base, idx |
| 3969 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3970 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3971 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3972 | // addr = gep base, op <- match |
| 3973 | if (MovedAway) |
| 3974 | *MovedAway = true; |
| 3975 | |
| 3976 | assert(PromotedOperand && |
| 3977 | "TypePromotionHelper should have filtered out those cases"); |
| 3978 | |
| 3979 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3980 | unsigned OldSize = AddrModeInsts.size(); |
| 3981 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3982 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3983 | // 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] | 3984 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3985 | // 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] | 3986 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3987 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3988 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3989 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3990 | AddrMode = BackupAddrMode; |
| 3991 | AddrModeInsts.resize(OldSize); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 3992 | LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3993 | TPT.rollback(LastKnownGood); |
| 3994 | return false; |
| 3995 | } |
| 3996 | return true; |
| 3997 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3998 | } |
| 3999 | return false; |
| 4000 | } |
| 4001 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4002 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 4003 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 4004 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 4005 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4006 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4007 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4008 | // Start a transaction at this point that we will rollback if the matching |
| 4009 | // fails. |
| 4010 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4011 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4012 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 4013 | // Fold in immediates if legal for the target. |
| 4014 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 4015 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4016 | return true; |
| 4017 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 4018 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 4019 | // 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] | 4020 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4021 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 4022 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4023 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4024 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4025 | } |
| 4026 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 4027 | ExtAddrMode BackupAddrMode = AddrMode; |
| 4028 | unsigned OldSize = AddrModeInsts.size(); |
| 4029 | |
| 4030 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4031 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4032 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 4033 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4034 | // to check here. |
| 4035 | if (MovedAway) |
| 4036 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4037 | // Okay, it's possible to fold this. Check to see if it is actually |
| 4038 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 4039 | // register pressure too much. |
| 4040 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4041 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4042 | AddrModeInsts.push_back(I); |
| 4043 | return true; |
| 4044 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4045 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4046 | // It isn't profitable to do this, roll back. |
| 4047 | //cerr << "NOT FOLDING: " << *I; |
| 4048 | AddrMode = BackupAddrMode; |
| 4049 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4050 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4051 | } |
| 4052 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4053 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4054 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4055 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4056 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 4057 | // Null pointer gets folded without affecting the addressing mode. |
| 4058 | return true; |
| 4059 | } |
| 4060 | |
| 4061 | // Worse case, the target should support [reg] addressing modes. :) |
| 4062 | if (!AddrMode.HasBaseReg) { |
| 4063 | AddrMode.HasBaseReg = true; |
| 4064 | AddrMode.BaseReg = Addr; |
| 4065 | // 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] | 4066 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4067 | return true; |
| 4068 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4069 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4070 | } |
| 4071 | |
| 4072 | // If the base register is already taken, see if we can do [r+r]. |
| 4073 | if (AddrMode.Scale == 0) { |
| 4074 | AddrMode.Scale = 1; |
| 4075 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 4076 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4077 | return true; |
| 4078 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4079 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4080 | } |
| 4081 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4082 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4083 | return false; |
| 4084 | } |
| 4085 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4086 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 4087 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4088 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4089 | const TargetLowering &TLI, |
| 4090 | const TargetRegisterInfo &TRI) { |
Sanjay Patel | 4137d51 | 2017-06-07 14:29:52 +0000 | [diff] [blame] | 4091 | const Function *F = CI->getFunction(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 4092 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4093 | TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4094 | ImmutableCallSite(CI)); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4095 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4096 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4097 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4098 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4099 | // Compute the constraint code and ConstraintType to use. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4100 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4101 | |
| 4102 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 4103 | // operand, we can't fold it! |
| 4104 | if (OpInfo.CallOperandVal == OpVal && |
| 4105 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 4106 | !OpInfo.isIndirect)) |
| 4107 | return false; |
| 4108 | } |
| 4109 | |
| 4110 | return true; |
| 4111 | } |
| 4112 | |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4113 | // Max number of memory uses to look at before aborting the search to conserve |
| 4114 | // compile time. |
| 4115 | static constexpr int MaxMemoryUsesToScan = 20; |
| 4116 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4117 | /// Recursively walk all the uses of I until we find a memory use. |
| 4118 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4119 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4120 | static bool FindAllMemoryUses( |
| 4121 | Instruction *I, |
| 4122 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4123 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI, |
| 4124 | const TargetRegisterInfo &TRI, int SeenInsts = 0) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4125 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4126 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4127 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4128 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4129 | // If this is an obviously unfoldable instruction, bail out. |
| 4130 | if (!MightBeFoldableInst(I)) |
| 4131 | return true; |
| 4132 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4133 | const bool OptSize = I->getFunction()->optForSize(); |
| 4134 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4135 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4136 | for (Use &U : I->uses()) { |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4137 | // Conservatively return true if we're seeing a large number or a deep chain |
| 4138 | // of users. This avoids excessive compilation times in pathological cases. |
| 4139 | if (SeenInsts++ >= MaxMemoryUsesToScan) |
| 4140 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4141 | |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4142 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4143 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 4144 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4145 | continue; |
| 4146 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4147 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4148 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 4149 | unsigned opNo = U.getOperandNo(); |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 4150 | if (opNo != StoreInst::getPointerOperandIndex()) |
| 4151 | return true; // Storing addr, not into addr. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4152 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 4153 | continue; |
| 4154 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4155 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 4156 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { |
| 4157 | unsigned opNo = U.getOperandNo(); |
| 4158 | if (opNo != AtomicRMWInst::getPointerOperandIndex()) |
| 4159 | return true; // Storing addr, not into addr. |
| 4160 | MemoryUses.push_back(std::make_pair(RMW, opNo)); |
| 4161 | continue; |
| 4162 | } |
| 4163 | |
| 4164 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { |
| 4165 | unsigned opNo = U.getOperandNo(); |
| 4166 | if (opNo != AtomicCmpXchgInst::getPointerOperandIndex()) |
| 4167 | return true; // Storing addr, not into addr. |
| 4168 | MemoryUses.push_back(std::make_pair(CmpX, opNo)); |
| 4169 | continue; |
| 4170 | } |
| 4171 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4172 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4173 | // If this is a cold call, we can sink the addressing calculation into |
| 4174 | // the cold path. See optimizeCallInst |
| 4175 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 4176 | continue; |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 4177 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4178 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 4179 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4180 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4181 | // If this is a memory operand, we're cool, otherwise bail out. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4182 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4183 | return true; |
| 4184 | continue; |
| 4185 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4186 | |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4187 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, |
| 4188 | SeenInsts)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4189 | return true; |
| 4190 | } |
| 4191 | |
| 4192 | return false; |
| 4193 | } |
| 4194 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 4195 | /// Return true if Val is already known to be live at the use site that we're |
| 4196 | /// folding it into. If so, there is no cost to include it in the addressing |
| 4197 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 4198 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4199 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4200 | Value *KnownLive2) { |
| 4201 | // 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] | 4202 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4203 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4204 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4205 | // All values other than instructions and arguments (e.g. constants) are live. |
| 4206 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4207 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4208 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 4209 | // true because it is just a reference to the stack/frame pointer, which is |
| 4210 | // live for the whole function. |
| 4211 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 4212 | if (AI->isStaticAlloca()) |
| 4213 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4214 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4215 | // Check to see if this value is already used in the memory instruction's |
| 4216 | // block. If so, it's already live into the block at the very least, so we |
| 4217 | // can reasonably fold it. |
| 4218 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 4219 | } |
| 4220 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4221 | /// It is possible for the addressing mode of the machine to fold the specified |
| 4222 | /// instruction into a load or store that ultimately uses it. |
| 4223 | /// However, the specified instruction has multiple uses. |
| 4224 | /// Given this, it may actually increase register pressure to fold it |
| 4225 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4226 | /// |
| 4227 | /// X = ... |
| 4228 | /// Y = X+1 |
| 4229 | /// use(Y) -> nonload/store |
| 4230 | /// Z = Y+1 |
| 4231 | /// load Z |
| 4232 | /// |
| 4233 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 4234 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 4235 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 4236 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 4237 | /// number of computations either. |
| 4238 | /// |
| 4239 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 4240 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 4241 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 4242 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4243 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4244 | ExtAddrMode &AMAfter) { |
| 4245 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4246 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4247 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 4248 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 4249 | // the set of registers referenced by AMAfter and subtract out those |
| 4250 | // referenced by AMBefore: this is the set of values which folding in this |
| 4251 | // address extends the lifetime of. |
| 4252 | // |
| 4253 | // Note that there are only two potential values being referenced here, |
| 4254 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 4255 | // folded immediates). |
| 4256 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4257 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4258 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 4259 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4260 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4261 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4262 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4263 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4264 | |
| 4265 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 4266 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4267 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4268 | return true; |
| 4269 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4270 | // If all uses of this instruction can have the address mode sunk into them, |
| 4271 | // we can remove the addressing mode and effectively trade one live register |
| 4272 | // for another (at worst.) In this context, folding an addressing mode into |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 4273 | // the use is just a particularly nice way of sinking it. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4274 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 4275 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4276 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4277 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4278 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4279 | // Now that we know that all uses of this instruction are part of a chain of |
| 4280 | // computation involving only operations that could theoretically be folded |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4281 | // into a memory use, loop over each of these memory operation uses and see |
| 4282 | // if they could *actually* fold the instruction. The assumption is that |
| 4283 | // addressing modes are cheap and that duplicating the computation involved |
| 4284 | // many times is worthwhile, even on a fastpath. For sinking candidates |
| 4285 | // (i.e. cold call sites), this serves as a way to prevent excessive code |
| 4286 | // growth since most architectures have some reasonable small and fast way to |
| 4287 | // compute an effective address. (i.e LEA on x86) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4288 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 4289 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 4290 | Instruction *User = MemoryUses[i].first; |
| 4291 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4292 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4293 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 4294 | // know what it accesses. |
| 4295 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4296 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 4297 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4298 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4299 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 4300 | unsigned AS = AddrTy->getAddressSpace(); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4301 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4302 | // Do a match against the root of this address, ignoring profitability. This |
| 4303 | // will tell us if the addressing mode for the memory operation will |
| 4304 | // *actually* cover the shared instruction. |
| 4305 | ExtAddrMode Result; |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 4306 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, |
| 4307 | 0); |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4308 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4309 | TPT.getRestorationPoint(); |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 4310 | AddressingModeMatcher Matcher( |
| 4311 | MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result, |
| 4312 | InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4313 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4314 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4315 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 4316 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4317 | // The match was to check the profitability, the changes made are not |
| 4318 | // part of the original matcher. Therefore, they should be dropped |
| 4319 | // otherwise the original matcher will not present the right state. |
| 4320 | TPT.rollback(LastKnownGood); |
| 4321 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4322 | // 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] | 4323 | if (!is_contained(MatchedAddrModeInsts, I)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4324 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4325 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4326 | MatchedAddrModeInsts.clear(); |
| 4327 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4328 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4329 | return true; |
| 4330 | } |
| 4331 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4332 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4333 | /// different basic block than BB. |
| 4334 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 4335 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4336 | return I->getParent() != BB; |
| 4337 | return false; |
| 4338 | } |
| 4339 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4340 | /// Sink addressing mode computation immediate before MemoryInst if doing so |
| 4341 | /// can be done without increasing register pressure. The need for the |
| 4342 | /// register pressure constraint means this can end up being an all or nothing |
| 4343 | /// decision for all uses of the same addressing computation. |
| 4344 | /// |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4345 | /// Load and Store Instructions often have addressing modes that can do |
| 4346 | /// significant amounts of computation. As such, instruction selection will try |
| 4347 | /// to get the load or store to do as much computation as possible for the |
| 4348 | /// program. The problem is that isel can only see within a single block. As |
| 4349 | /// 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] | 4350 | /// |
| 4351 | /// 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] | 4352 | /// operands. It's also used to sink addressing computations feeding into cold |
| 4353 | /// call sites into their (cold) basic block. |
| 4354 | /// |
| 4355 | /// The motivation for handling sinking into cold blocks is that doing so can |
| 4356 | /// both enable other address mode sinking (by satisfying the register pressure |
| 4357 | /// constraint above), and reduce register pressure globally (by removing the |
| 4358 | /// addressing mode computation from the fast path entirely.). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4359 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4360 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4361 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4362 | |
| 4363 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4364 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 4365 | SmallVector<Value*, 8> worklist; |
| 4366 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4367 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4368 | |
John Brawn | eb83c75 | 2017-10-03 13:04:15 +0000 | [diff] [blame] | 4369 | // Use a worklist to iteratively look through PHI and select nodes, and |
| 4370 | // ensure that the addressing mode obtained from the non-PHI/select roots of |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 4371 | // the graph are compatible. |
John Brawn | eb83c75 | 2017-10-03 13:04:15 +0000 | [diff] [blame] | 4372 | bool PhiOrSelectSeen = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4373 | SmallVector<Instruction*, 16> AddrModeInsts; |
Serguei Katkov | aee6375 | 2017-11-05 07:59:02 +0000 | [diff] [blame] | 4374 | const SimplifyQuery SQ(*DL, TLInfo); |
| 4375 | AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() }); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4376 | TypePromotionTransaction TPT(RemovedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4377 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4378 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4379 | while (!worklist.empty()) { |
| 4380 | Value *V = worklist.back(); |
| 4381 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4382 | |
Serguei Katkov | 4ea855e | 2017-07-19 04:49:17 +0000 | [diff] [blame] | 4383 | // We allow traversing cyclic Phi nodes. |
| 4384 | // In case of success after this loop we ensure that traversing through |
| 4385 | // Phi nodes ends up with all cases to compute address of the form |
| 4386 | // BaseGV + Base + Scale * Index + Offset |
| 4387 | // where Scale and Offset are constans and BaseGV, Base and Index |
| 4388 | // are exactly the same Values in all cases. |
| 4389 | // It means that BaseGV, Scale and Offset dominate our memory instruction |
| 4390 | // and have the same value as they had in address computation represented |
| 4391 | // as Phi. So we can safely sink address computation to memory instruction. |
| 4392 | if (!Visited.insert(V).second) |
| 4393 | continue; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4394 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4395 | // For a PHI node, push all of its incoming values. |
| 4396 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 4397 | for (Value *IncValue : P->incoming_values()) |
| 4398 | worklist.push_back(IncValue); |
John Brawn | eb83c75 | 2017-10-03 13:04:15 +0000 | [diff] [blame] | 4399 | PhiOrSelectSeen = true; |
| 4400 | continue; |
| 4401 | } |
| 4402 | // Similar for select. |
| 4403 | if (SelectInst *SI = dyn_cast<SelectInst>(V)) { |
| 4404 | worklist.push_back(SI->getFalseValue()); |
| 4405 | worklist.push_back(SI->getTrueValue()); |
| 4406 | PhiOrSelectSeen = true; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4407 | continue; |
| 4408 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4409 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4410 | // For non-PHIs, determine the addressing mode being computed. Note that |
| 4411 | // the result may differ depending on what other uses our candidate |
| 4412 | // addressing instructions might have. |
Serguei Katkov | a6fba3d | 2017-07-18 05:16:38 +0000 | [diff] [blame] | 4413 | AddrModeInsts.clear(); |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 4414 | std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr, |
| 4415 | 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4416 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Serguei Katkov | a6fba3d | 2017-07-18 05:16:38 +0000 | [diff] [blame] | 4417 | V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI, |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 4418 | InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP); |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 4419 | |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 4420 | GetElementPtrInst *GEP = LargeOffsetGEP.first; |
| 4421 | if (GEP && GEP->getParent() != MemoryInst->getParent() && |
| 4422 | !NewGEPBases.count(GEP)) { |
| 4423 | // If splitting the underlying data structure can reduce the offset of a |
| 4424 | // GEP, collect the GEP. Skip the GEPs that are the new bases of |
| 4425 | // previously split data structures. |
| 4426 | LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP); |
| 4427 | if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end()) |
| 4428 | LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size(); |
| 4429 | } |
| 4430 | |
| 4431 | NewAddrMode.OriginalValue = V; |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 4432 | if (!AddrModes.addNewAddrMode(NewAddrMode)) |
| 4433 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4434 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4435 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 4436 | // Try to combine the AddrModes we've collected. If we couldn't collect any, |
| 4437 | // or we have multiple but either couldn't combine them or combining them |
| 4438 | // wouldn't do anything useful, bail out now. |
| 4439 | if (!AddrModes.combineAddrModes()) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4440 | TPT.rollback(LastKnownGood); |
| 4441 | return false; |
| 4442 | } |
| 4443 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4444 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 4445 | // Get the combined AddrMode (or the only AddrMode, if we only had one). |
| 4446 | ExtAddrMode AddrMode = AddrModes.getAddrMode(); |
| 4447 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4448 | // If all the instructions matched are already in this BB, don't do anything. |
John Brawn | eb83c75 | 2017-10-03 13:04:15 +0000 | [diff] [blame] | 4449 | // If we saw a Phi node then it is not local definitely, and if we saw a select |
| 4450 | // then we want to push the address calculation past it even if it's already |
| 4451 | // in this BB. |
| 4452 | if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) { |
Justin Lebar | 838c7f5 | 2016-11-21 22:49:11 +0000 | [diff] [blame] | 4453 | return IsNonLocalValue(V, MemoryInst->getParent()); |
Serguei Katkov | 0b7b59a | 2017-07-11 06:24:44 +0000 | [diff] [blame] | 4454 | })) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 4455 | LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode |
| 4456 | << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4457 | return false; |
| 4458 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4459 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4460 | // Insert this computation right after this user. Since our caller is |
| 4461 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 4462 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4463 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4464 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4465 | // Now that we determined the addressing expression we want to use and know |
| 4466 | // that we have to sink it into this block. Check to see if we have already |
Simon Dardis | 230f453 | 2017-11-24 16:45:28 +0000 | [diff] [blame] | 4467 | // done this for some other load/store instr in this block. If so, reuse |
| 4468 | // the computation. Before attempting reuse, check if the address is valid |
| 4469 | // as it may have been erased. |
| 4470 | |
| 4471 | WeakTrackingVH SunkAddrVH = SunkAddrs[Addr]; |
| 4472 | |
| 4473 | Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4474 | if (SunkAddr) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 4475 | LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode |
| 4476 | << " for " << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4477 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4478 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 4479 | } else if (AddrSinkUsingGEPs || |
David Blaikie | 8ad9a97 | 2018-03-28 22:28:50 +0000 | [diff] [blame] | 4480 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4481 | // By default, we use the GEP-based method when AA is used later. This |
| 4482 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 4483 | LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode |
| 4484 | << " for " << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4485 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4486 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4487 | |
| 4488 | // First, find the pointer. |
| 4489 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 4490 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4491 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4492 | } |
| 4493 | |
| 4494 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 4495 | // We can't add more than one pointer together, nor can we scale a |
| 4496 | // pointer (both of which seem meaningless). |
| 4497 | if (ResultPtr || AddrMode.Scale != 1) |
| 4498 | return false; |
| 4499 | |
| 4500 | ResultPtr = AddrMode.ScaledReg; |
| 4501 | AddrMode.Scale = 0; |
| 4502 | } |
| 4503 | |
Eli Friedman | 6f7c9ad | 2017-07-12 23:30:02 +0000 | [diff] [blame] | 4504 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4505 | // required to create it did not overflow before we extend it. Since |
| 4506 | // the original IR value was tossed in favor of a constant back when |
| 4507 | // the AddrMode was created we need to bail out gracefully if widths |
| 4508 | // do not match instead of extending it. |
| 4509 | // |
| 4510 | // (See below for code to add the scale.) |
| 4511 | if (AddrMode.Scale) { |
| 4512 | Type *ScaledRegTy = AddrMode.ScaledReg->getType(); |
| 4513 | if (cast<IntegerType>(IntPtrTy)->getBitWidth() > |
| 4514 | cast<IntegerType>(ScaledRegTy)->getBitWidth()) |
| 4515 | return false; |
| 4516 | } |
| 4517 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4518 | if (AddrMode.BaseGV) { |
| 4519 | if (ResultPtr) |
| 4520 | return false; |
| 4521 | |
| 4522 | ResultPtr = AddrMode.BaseGV; |
| 4523 | } |
| 4524 | |
| 4525 | // If the real base value actually came from an inttoptr, then the matcher |
| 4526 | // will look through it and provide only the integer value. In that case, |
| 4527 | // use it here. |
Keno Fischer | 05e4ac2 | 2017-06-29 20:28:59 +0000 | [diff] [blame] | 4528 | if (!DL->isNonIntegralPointerType(Addr->getType())) { |
| 4529 | if (!ResultPtr && AddrMode.BaseReg) { |
| 4530 | ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), |
| 4531 | "sunkaddr"); |
| 4532 | AddrMode.BaseReg = nullptr; |
| 4533 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 4534 | ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), |
| 4535 | "sunkaddr"); |
| 4536 | AddrMode.Scale = 0; |
| 4537 | } |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4538 | } |
| 4539 | |
| 4540 | if (!ResultPtr && |
| 4541 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 4542 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 4543 | } else if (!ResultPtr) { |
| 4544 | return false; |
| 4545 | } else { |
| 4546 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4547 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 4548 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4549 | |
| 4550 | // Start with the base register. Do this first so that subsequent address |
| 4551 | // matching finds it last, which will prevent it from trying to match it |
| 4552 | // as the scaled value in case it happens to be a mul. That would be |
| 4553 | // problematic if we've sunk a different mul for the scale, because then |
| 4554 | // we'd end up sinking both muls. |
| 4555 | if (AddrMode.BaseReg) { |
| 4556 | Value *V = AddrMode.BaseReg; |
| 4557 | if (V->getType() != IntPtrTy) |
| 4558 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 4559 | |
| 4560 | ResultIndex = V; |
| 4561 | } |
| 4562 | |
| 4563 | // Add the scale value. |
| 4564 | if (AddrMode.Scale) { |
| 4565 | Value *V = AddrMode.ScaledReg; |
| 4566 | if (V->getType() == IntPtrTy) { |
| 4567 | // done. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4568 | } else { |
Eli Friedman | 6f7c9ad | 2017-07-12 23:30:02 +0000 | [diff] [blame] | 4569 | assert(cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4570 | cast<IntegerType>(V->getType())->getBitWidth() && |
| 4571 | "We can't transform if ScaledReg is too narrow"); |
| 4572 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4573 | } |
| 4574 | |
| 4575 | if (AddrMode.Scale != 1) |
| 4576 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4577 | "sunkaddr"); |
| 4578 | if (ResultIndex) |
| 4579 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 4580 | else |
| 4581 | ResultIndex = V; |
| 4582 | } |
| 4583 | |
| 4584 | // Add in the Base Offset if present. |
| 4585 | if (AddrMode.BaseOffs) { |
| 4586 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 4587 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 4588 | // We need to add this separately from the scale above to help with |
| 4589 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4590 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4591 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4592 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4593 | } |
| 4594 | |
| 4595 | ResultIndex = V; |
| 4596 | } |
| 4597 | |
| 4598 | if (!ResultIndex) { |
| 4599 | SunkAddr = ResultPtr; |
| 4600 | } else { |
| 4601 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4602 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4603 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4604 | } |
| 4605 | |
| 4606 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4607 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4608 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4609 | } else { |
Keno Fischer | 05e4ac2 | 2017-06-29 20:28:59 +0000 | [diff] [blame] | 4610 | // We'd require a ptrtoint/inttoptr down the line, which we can't do for |
| 4611 | // non-integral pointers, so in that case bail out now. |
| 4612 | Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr; |
| 4613 | Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr; |
| 4614 | PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy); |
| 4615 | PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy); |
| 4616 | if (DL->isNonIntegralPointerType(Addr->getType()) || |
| 4617 | (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) || |
| 4618 | (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) || |
| 4619 | (AddrMode.BaseGV && |
| 4620 | DL->isNonIntegralPointerType(AddrMode.BaseGV->getType()))) |
| 4621 | return false; |
| 4622 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 4623 | LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode |
| 4624 | << " for " << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4625 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4626 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4627 | |
| 4628 | // Start with the base register. Do this first so that subsequent address |
| 4629 | // matching finds it last, which will prevent it from trying to match it |
| 4630 | // as the scaled value in case it happens to be a mul. That would be |
| 4631 | // problematic if we've sunk a different mul for the scale, because then |
| 4632 | // we'd end up sinking both muls. |
| 4633 | if (AddrMode.BaseReg) { |
| 4634 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4635 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4636 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4637 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4638 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4639 | Result = V; |
| 4640 | } |
| 4641 | |
| 4642 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4643 | if (AddrMode.Scale) { |
| 4644 | Value *V = AddrMode.ScaledReg; |
| 4645 | if (V->getType() == IntPtrTy) { |
| 4646 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4647 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4648 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4649 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4650 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4651 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4652 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4653 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4654 | // required to create it did not overflow before we extend it. Since |
| 4655 | // the original IR value was tossed in favor of a constant back when |
| 4656 | // the AddrMode was created we need to bail out gracefully if widths |
| 4657 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 4658 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 4659 | if (I && (Result != AddrMode.BaseReg)) |
| 4660 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4661 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4662 | } |
| 4663 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4664 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4665 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4666 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4667 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4668 | else |
| 4669 | Result = V; |
| 4670 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4671 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4672 | // Add in the BaseGV if present. |
| 4673 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4674 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4675 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4676 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4677 | else |
| 4678 | Result = V; |
| 4679 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4680 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4681 | // Add in the Base Offset if present. |
| 4682 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4683 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4684 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4685 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4686 | else |
| 4687 | Result = V; |
| 4688 | } |
| 4689 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4690 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 4691 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4692 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4693 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4694 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4695 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4696 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Simon Dardis | 230f453 | 2017-11-24 16:45:28 +0000 | [diff] [blame] | 4697 | // Store the newly computed address into the cache. In the case we reused a |
| 4698 | // value, this should be idempotent. |
| 4699 | SunkAddrs[Addr] = WeakTrackingVH(SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4700 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4701 | // If we have no uses, recursively delete the value and all dead instructions |
| 4702 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4703 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4704 | // This can cause recursive deletion, which can invalidate our iterator. |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 4705 | // Use a WeakTrackingVH to hold onto it in case this happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4706 | Value *CurValue = &*CurInstIterator; |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 4707 | WeakTrackingVH IterHandle(CurValue); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4708 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4709 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 4710 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4711 | |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4712 | if (IterHandle != CurValue) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4713 | // If the iterator instruction was recursively deleted, start over at the |
| 4714 | // start of the block. |
| 4715 | CurInstIterator = BB->begin(); |
| 4716 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4717 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 4718 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4719 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4720 | return true; |
| 4721 | } |
| 4722 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4723 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 4724 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4725 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4726 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4727 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4728 | const TargetRegisterInfo *TRI = |
Sanjay Patel | 4137d51 | 2017-06-07 14:29:52 +0000 | [diff] [blame] | 4729 | TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4730 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 4731 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4732 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 4733 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4734 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4735 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4736 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 4737 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4738 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 4739 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 4740 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4741 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4742 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4743 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 4744 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4745 | } |
| 4746 | |
| 4747 | return MadeChange; |
| 4748 | } |
| 4749 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 4750 | /// 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] | 4751 | /// sign extensions. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4752 | static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { |
| 4753 | assert(!Val->use_empty() && "Input must have at least one use"); |
| 4754 | const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4755 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 4756 | Type *ExtTy = FirstUser->getType(); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4757 | for (const User *U : Val->users()) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4758 | const Instruction *UI = cast<Instruction>(U); |
| 4759 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 4760 | return false; |
| 4761 | Type *CurTy = UI->getType(); |
| 4762 | // Same input and output types: Same instruction after CSE. |
| 4763 | if (CurTy == ExtTy) |
| 4764 | continue; |
| 4765 | |
| 4766 | // If IsSExt is true, we are in this situation: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4767 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4768 | // b = sext ty1 a to ty2 |
| 4769 | // c = sext ty1 a to ty3 |
| 4770 | // Assuming ty2 is shorter than ty3, this could be turned into: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4771 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4772 | // b = sext ty1 a to ty2 |
| 4773 | // c = sext ty2 b to ty3 |
| 4774 | // However, the last sext is not free. |
| 4775 | if (IsSExt) |
| 4776 | return false; |
| 4777 | |
| 4778 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 4779 | // In that case, we would not account for a different use. |
| 4780 | Type *NarrowTy; |
| 4781 | Type *LargeTy; |
| 4782 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 4783 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 4784 | NarrowTy = CurTy; |
| 4785 | LargeTy = ExtTy; |
| 4786 | } else { |
| 4787 | NarrowTy = ExtTy; |
| 4788 | LargeTy = CurTy; |
| 4789 | } |
| 4790 | |
| 4791 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 4792 | return false; |
| 4793 | } |
| 4794 | // All uses are the same or can be derived from one another for free. |
| 4795 | return true; |
| 4796 | } |
| 4797 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 4798 | /// Try to speculatively promote extensions in \p Exts and continue |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4799 | /// promoting through newly promoted operands recursively as far as doing so is |
| 4800 | /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. |
| 4801 | /// When some promotion happened, \p TPT contains the proper state to revert |
| 4802 | /// them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4803 | /// |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4804 | /// \return true if some promotion happened, false otherwise. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4805 | bool CodeGenPrepare::tryToPromoteExts( |
| 4806 | TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, |
| 4807 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 4808 | unsigned CreatedInstsCost) { |
| 4809 | bool Promoted = false; |
| 4810 | |
| 4811 | // Iterate over all the extensions to try to promote them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4812 | for (auto I : Exts) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4813 | // Early check if we directly have ext(load). |
| 4814 | if (isa<LoadInst>(I->getOperand(0))) { |
| 4815 | ProfitablyMovedExts.push_back(I); |
| 4816 | continue; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4817 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4818 | |
| 4819 | // Check whether or not we want to do any promotion. The reason we have |
| 4820 | // this check inside the for loop is to catch the case where an extension |
| 4821 | // is directly fed by a load because in such case the extension can be moved |
| 4822 | // up without any promotion on its operands. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4823 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4824 | return false; |
| 4825 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4826 | // Get the action to perform the promotion. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4827 | TypePromotionHelper::Action TPH = |
| 4828 | TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4829 | // Check if we can promote. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4830 | if (!TPH) { |
| 4831 | // Save the current extension as we cannot move up through its operand. |
| 4832 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4833 | continue; |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4834 | } |
| 4835 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4836 | // Save the current state. |
| 4837 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4838 | TPT.getRestorationPoint(); |
| 4839 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4840 | unsigned NewCreatedInstsCost = 0; |
| 4841 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4842 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4843 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 4844 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4845 | assert(PromotedVal && |
| 4846 | "TypePromotionHelper should have filtered out those cases"); |
| 4847 | |
| 4848 | // We would be able to merge only one extension in a load. |
| 4849 | // Therefore, if we have more than 1 new extension we heuristically |
| 4850 | // cut this search path, because it means we degrade the code quality. |
| 4851 | // With exactly 2, the transformation is neutral, because we will merge |
| 4852 | // one extension but leave one. However, we optimistically keep going, |
| 4853 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4854 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4855 | // 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] | 4856 | // conservatively ceiling it to 0. |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4857 | TotalCreatedInstsCost = |
| 4858 | std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4859 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4860 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4861 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4862 | // This promotion is not profitable, rollback to the previous state, and |
| 4863 | // save the current extension in ProfitablyMovedExts as the latest |
| 4864 | // speculative promotion turned out to be unprofitable. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4865 | TPT.rollback(LastKnownGood); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4866 | ProfitablyMovedExts.push_back(I); |
| 4867 | continue; |
| 4868 | } |
| 4869 | // Continue promoting NewExts as far as doing so is profitable. |
| 4870 | SmallVector<Instruction *, 2> NewlyMovedExts; |
| 4871 | (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); |
| 4872 | bool NewPromoted = false; |
| 4873 | for (auto ExtInst : NewlyMovedExts) { |
| 4874 | Instruction *MovedExt = cast<Instruction>(ExtInst); |
| 4875 | Value *ExtOperand = MovedExt->getOperand(0); |
| 4876 | // If we have reached to a load, we need this extra profitability check |
| 4877 | // as it could potentially be merged into an ext(load). |
| 4878 | if (isa<LoadInst>(ExtOperand) && |
| 4879 | !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
| 4880 | (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) |
| 4881 | continue; |
| 4882 | |
| 4883 | ProfitablyMovedExts.push_back(MovedExt); |
| 4884 | NewPromoted = true; |
| 4885 | } |
| 4886 | |
| 4887 | // If none of speculative promotions for NewExts is profitable, rollback |
| 4888 | // and save the current extension (I) as the last profitable extension. |
| 4889 | if (!NewPromoted) { |
| 4890 | TPT.rollback(LastKnownGood); |
| 4891 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4892 | continue; |
| 4893 | } |
| 4894 | // The promotion is profitable. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4895 | Promoted = true; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4896 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4897 | return Promoted; |
| 4898 | } |
| 4899 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4900 | /// Merging redundant sexts when one is dominating the other. |
| 4901 | bool CodeGenPrepare::mergeSExts(Function &F) { |
| 4902 | DominatorTree DT(F); |
| 4903 | bool Changed = false; |
| 4904 | for (auto &Entry : ValToSExtendedUses) { |
| 4905 | SExts &Insts = Entry.second; |
| 4906 | SExts CurPts; |
| 4907 | for (Instruction *Inst : Insts) { |
| 4908 | if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) || |
| 4909 | Inst->getOperand(0) != Entry.first) |
| 4910 | continue; |
| 4911 | bool inserted = false; |
| 4912 | for (auto &Pt : CurPts) { |
| 4913 | if (DT.dominates(Inst, Pt)) { |
| 4914 | Pt->replaceAllUsesWith(Inst); |
| 4915 | RemovedInsts.insert(Pt); |
| 4916 | Pt->removeFromParent(); |
| 4917 | Pt = Inst; |
| 4918 | inserted = true; |
| 4919 | Changed = true; |
| 4920 | break; |
| 4921 | } |
| 4922 | if (!DT.dominates(Pt, Inst)) |
| 4923 | // Give up if we need to merge in a common dominator as the |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 4924 | // experiments show it is not profitable. |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4925 | continue; |
| 4926 | Inst->replaceAllUsesWith(Pt); |
| 4927 | RemovedInsts.insert(Inst); |
| 4928 | Inst->removeFromParent(); |
| 4929 | inserted = true; |
| 4930 | Changed = true; |
| 4931 | break; |
| 4932 | } |
| 4933 | if (!inserted) |
| 4934 | CurPts.push_back(Inst); |
| 4935 | } |
| 4936 | } |
| 4937 | return Changed; |
| 4938 | } |
| 4939 | |
Haicheng Wu | 0aae2bc | 2018-05-10 18:27:36 +0000 | [diff] [blame] | 4940 | // Spliting large data structures so that the GEPs accessing them can have |
| 4941 | // smaller offsets so that they can be sunk to the same blocks as their users. |
| 4942 | // For example, a large struct starting from %base is splitted into two parts |
| 4943 | // where the second part starts from %new_base. |
| 4944 | // |
| 4945 | // Before: |
| 4946 | // BB0: |
| 4947 | // %base = |
| 4948 | // |
| 4949 | // BB1: |
| 4950 | // %gep0 = gep %base, off0 |
| 4951 | // %gep1 = gep %base, off1 |
| 4952 | // %gep2 = gep %base, off2 |
| 4953 | // |
| 4954 | // BB2: |
| 4955 | // %load1 = load %gep0 |
| 4956 | // %load2 = load %gep1 |
| 4957 | // %load3 = load %gep2 |
| 4958 | // |
| 4959 | // After: |
| 4960 | // BB0: |
| 4961 | // %base = |
| 4962 | // %new_base = gep %base, off0 |
| 4963 | // |
| 4964 | // BB1: |
| 4965 | // %new_gep0 = %new_base |
| 4966 | // %new_gep1 = gep %new_base, off1 - off0 |
| 4967 | // %new_gep2 = gep %new_base, off2 - off0 |
| 4968 | // |
| 4969 | // BB2: |
| 4970 | // %load1 = load i32, i32* %new_gep0 |
| 4971 | // %load2 = load i32, i32* %new_gep1 |
| 4972 | // %load3 = load i32, i32* %new_gep2 |
| 4973 | // |
| 4974 | // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because |
| 4975 | // their offsets are smaller enough to fit into the addressing mode. |
| 4976 | bool CodeGenPrepare::splitLargeGEPOffsets() { |
| 4977 | bool Changed = false; |
| 4978 | for (auto &Entry : LargeOffsetGEPMap) { |
| 4979 | Value *OldBase = Entry.first; |
| 4980 | SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>> |
| 4981 | &LargeOffsetGEPs = Entry.second; |
| 4982 | auto compareGEPOffset = |
| 4983 | [&](const std::pair<GetElementPtrInst *, int64_t> &LHS, |
| 4984 | const std::pair<GetElementPtrInst *, int64_t> &RHS) { |
| 4985 | if (LHS.first == RHS.first) |
| 4986 | return false; |
| 4987 | if (LHS.second != RHS.second) |
| 4988 | return LHS.second < RHS.second; |
| 4989 | return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first]; |
| 4990 | }; |
| 4991 | // Sorting all the GEPs of the same data structures based on the offsets. |
| 4992 | llvm::sort(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end(), |
| 4993 | compareGEPOffset); |
| 4994 | LargeOffsetGEPs.erase( |
| 4995 | std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()), |
| 4996 | LargeOffsetGEPs.end()); |
| 4997 | // Skip if all the GEPs have the same offsets. |
| 4998 | if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second) |
| 4999 | continue; |
| 5000 | GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first; |
| 5001 | int64_t BaseOffset = LargeOffsetGEPs.begin()->second; |
| 5002 | Value *NewBaseGEP = nullptr; |
| 5003 | |
| 5004 | auto LargeOffsetGEP = LargeOffsetGEPs.begin(); |
| 5005 | while (LargeOffsetGEP != LargeOffsetGEPs.end()) { |
| 5006 | GetElementPtrInst *GEP = LargeOffsetGEP->first; |
| 5007 | int64_t Offset = LargeOffsetGEP->second; |
| 5008 | if (Offset != BaseOffset) { |
| 5009 | TargetLowering::AddrMode AddrMode; |
| 5010 | AddrMode.BaseOffs = Offset - BaseOffset; |
| 5011 | // The result type of the GEP might not be the type of the memory |
| 5012 | // access. |
| 5013 | if (!TLI->isLegalAddressingMode(*DL, AddrMode, |
| 5014 | GEP->getResultElementType(), |
| 5015 | GEP->getAddressSpace())) { |
| 5016 | // We need to create a new base if the offset to the current base is |
| 5017 | // too large to fit into the addressing mode. So, a very large struct |
| 5018 | // may be splitted into several parts. |
| 5019 | BaseGEP = GEP; |
| 5020 | BaseOffset = Offset; |
| 5021 | NewBaseGEP = nullptr; |
| 5022 | } |
| 5023 | } |
| 5024 | |
| 5025 | // Generate a new GEP to replace the current one. |
| 5026 | IRBuilder<> Builder(GEP); |
| 5027 | Type *IntPtrTy = DL->getIntPtrType(GEP->getType()); |
| 5028 | Type *I8PtrTy = |
| 5029 | Builder.getInt8PtrTy(GEP->getType()->getPointerAddressSpace()); |
| 5030 | Type *I8Ty = Builder.getInt8Ty(); |
| 5031 | |
| 5032 | if (!NewBaseGEP) { |
| 5033 | // Create a new base if we don't have one yet. Find the insertion |
| 5034 | // pointer for the new base first. |
| 5035 | BasicBlock::iterator NewBaseInsertPt; |
| 5036 | BasicBlock *NewBaseInsertBB; |
| 5037 | if (auto *BaseI = dyn_cast<Instruction>(OldBase)) { |
| 5038 | // If the base of the struct is an instruction, the new base will be |
| 5039 | // inserted close to it. |
| 5040 | NewBaseInsertBB = BaseI->getParent(); |
| 5041 | if (isa<PHINode>(BaseI)) |
| 5042 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); |
| 5043 | else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) { |
| 5044 | NewBaseInsertBB = |
| 5045 | SplitEdge(NewBaseInsertBB, Invoke->getNormalDest()); |
| 5046 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); |
| 5047 | } else |
| 5048 | NewBaseInsertPt = std::next(BaseI->getIterator()); |
| 5049 | } else { |
| 5050 | // If the current base is an argument or global value, the new base |
| 5051 | // will be inserted to the entry block. |
| 5052 | NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock(); |
| 5053 | NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt(); |
| 5054 | } |
| 5055 | IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt); |
| 5056 | // Create a new base. |
| 5057 | Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset); |
| 5058 | NewBaseGEP = OldBase; |
| 5059 | if (NewBaseGEP->getType() != I8PtrTy) |
| 5060 | NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy); |
| 5061 | NewBaseGEP = |
| 5062 | NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep"); |
| 5063 | NewGEPBases.insert(NewBaseGEP); |
| 5064 | } |
| 5065 | |
| 5066 | Value *NewGEP = NewBaseGEP; |
| 5067 | if (Offset == BaseOffset) { |
| 5068 | if (GEP->getType() != I8PtrTy) |
| 5069 | NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); |
| 5070 | } else { |
| 5071 | // Calculate the new offset for the new GEP. |
| 5072 | Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset); |
| 5073 | NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index); |
| 5074 | |
| 5075 | if (GEP->getType() != I8PtrTy) |
| 5076 | NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType()); |
| 5077 | } |
| 5078 | GEP->replaceAllUsesWith(NewGEP); |
| 5079 | LargeOffsetGEPID.erase(GEP); |
| 5080 | LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP); |
| 5081 | GEP->eraseFromParent(); |
| 5082 | Changed = true; |
| 5083 | } |
| 5084 | } |
| 5085 | return Changed; |
| 5086 | } |
| 5087 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 5088 | /// Return true, if an ext(load) can be formed from an extension in |
| 5089 | /// \p MovedExts. |
| 5090 | bool CodeGenPrepare::canFormExtLd( |
| 5091 | const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, |
| 5092 | Instruction *&Inst, bool HasPromoted) { |
| 5093 | for (auto *MovedExtInst : MovedExts) { |
| 5094 | if (isa<LoadInst>(MovedExtInst->getOperand(0))) { |
| 5095 | LI = cast<LoadInst>(MovedExtInst->getOperand(0)); |
| 5096 | Inst = MovedExtInst; |
| 5097 | break; |
| 5098 | } |
| 5099 | } |
| 5100 | if (!LI) |
| 5101 | return false; |
| 5102 | |
| 5103 | // If they're already in the same block, there's nothing to do. |
| 5104 | // Make the cheap checks first if we did not promote. |
| 5105 | // If we promoted, we need to check if it is indeed profitable. |
| 5106 | if (!HasPromoted && LI->getParent() == Inst->getParent()) |
| 5107 | return false; |
| 5108 | |
Haicheng Wu | abdef9e | 2017-07-15 02:12:16 +0000 | [diff] [blame] | 5109 | return TLI->isExtLoad(LI, Inst, *DL); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 5110 | } |
| 5111 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 5112 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 5113 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 5114 | /// extend into the load. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 5115 | /// |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5116 | /// E.g., |
| 5117 | /// \code |
| 5118 | /// %ld = load i32* %addr |
| 5119 | /// %add = add nuw i32 %ld, 4 |
| 5120 | /// %zext = zext i32 %add to i64 |
| 5121 | // \endcode |
| 5122 | /// => |
| 5123 | /// \code |
| 5124 | /// %ld = load i32* %addr |
| 5125 | /// %zext = zext i32 %ld to i64 |
| 5126 | /// %add = add nuw i64 %zext, 4 |
| 5127 | /// \encode |
| 5128 | /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which |
| 5129 | /// allow us to match zext(load i32*) to i64. |
| 5130 | /// |
| 5131 | /// Also, try to promote the computations used to obtain a sign extended |
| 5132 | /// value used into memory accesses. |
| 5133 | /// E.g., |
| 5134 | /// \code |
| 5135 | /// a = add nsw i32 b, 3 |
| 5136 | /// d = sext i32 a to i64 |
| 5137 | /// e = getelementptr ..., i64 d |
| 5138 | /// \endcode |
| 5139 | /// => |
| 5140 | /// \code |
| 5141 | /// f = sext i32 b to i64 |
| 5142 | /// a = add nsw i64 f, 3 |
| 5143 | /// e = getelementptr ..., i64 a |
| 5144 | /// \endcode |
| 5145 | /// |
| 5146 | /// \p Inst[in/out] the extension may be modified during the process if some |
| 5147 | /// promotions apply. |
| 5148 | bool CodeGenPrepare::optimizeExt(Instruction *&Inst) { |
| 5149 | // ExtLoad formation and address type promotion infrastructure requires TLI to |
| 5150 | // be effective. |
Chandler Carruth | 0f139b4 | 2016-11-04 06:54:00 +0000 | [diff] [blame] | 5151 | if (!TLI) |
| 5152 | return false; |
| 5153 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5154 | bool AllowPromotionWithoutCommonHeader = false; |
| 5155 | /// See if it is an interesting sext operations for the address type |
| 5156 | /// promotion before trying to promote it, e.g., the ones with the right |
| 5157 | /// type and used in memory accesses. |
| 5158 | bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion( |
| 5159 | *Inst, AllowPromotionWithoutCommonHeader); |
| 5160 | TypePromotionTransaction TPT(RemovedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 5161 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 5162 | TPT.getRestorationPoint(); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 5163 | SmallVector<Instruction *, 1> Exts; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5164 | SmallVector<Instruction *, 2> SpeculativelyMovedExts; |
| 5165 | Exts.push_back(Inst); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 5166 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5167 | bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 5168 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 5169 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 5170 | LoadInst *LI = nullptr; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5171 | Instruction *ExtFedByLoad; |
| 5172 | |
| 5173 | // Try to promote a chain of computation if it allows to form an extended |
| 5174 | // load. |
| 5175 | if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) { |
| 5176 | assert(LI && ExtFedByLoad && "Expect a valid load and extension"); |
| 5177 | TPT.commit(); |
| 5178 | // Move the extend into the same block as the load |
Sanjay Patel | 674d2c2 | 2017-08-29 14:07:48 +0000 | [diff] [blame] | 5179 | ExtFedByLoad->moveAfter(LI); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5180 | // CGP does not check if the zext would be speculatively executed when moved |
| 5181 | // to the same basic block as the load. Preserving its original location |
| 5182 | // would pessimize the debugging experience, as well as negatively impact |
| 5183 | // the quality of sample pgo. We don't want to use "line 0" as that has a |
| 5184 | // size cost in the line-table section and logically the zext can be seen as |
| 5185 | // part of the load. Therefore we conservatively reuse the same debug |
| 5186 | // location for the load and the zext. |
| 5187 | ExtFedByLoad->setDebugLoc(LI->getDebugLoc()); |
| 5188 | ++NumExtsMoved; |
| 5189 | Inst = ExtFedByLoad; |
| 5190 | return true; |
| 5191 | } |
| 5192 | |
| 5193 | // Continue promoting SExts if known as considerable depending on targets. |
| 5194 | if (ATPConsiderable && |
| 5195 | performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader, |
| 5196 | HasPromoted, TPT, SpeculativelyMovedExts)) |
| 5197 | return true; |
| 5198 | |
| 5199 | TPT.rollback(LastKnownGood); |
| 5200 | return false; |
| 5201 | } |
| 5202 | |
| 5203 | // Perform address type promotion if doing so is profitable. |
| 5204 | // If AllowPromotionWithoutCommonHeader == false, we should find other sext |
| 5205 | // instructions that sign extended the same initial value. However, if |
| 5206 | // AllowPromotionWithoutCommonHeader == true, we expect promoting the |
| 5207 | // extension is just profitable. |
| 5208 | bool CodeGenPrepare::performAddressTypePromotion( |
| 5209 | Instruction *&Inst, bool AllowPromotionWithoutCommonHeader, |
| 5210 | bool HasPromoted, TypePromotionTransaction &TPT, |
| 5211 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) { |
| 5212 | bool Promoted = false; |
| 5213 | SmallPtrSet<Instruction *, 1> UnhandledExts; |
| 5214 | bool AllSeenFirst = true; |
| 5215 | for (auto I : SpeculativelyMovedExts) { |
| 5216 | Value *HeadOfChain = I->getOperand(0); |
| 5217 | DenseMap<Value *, Instruction *>::iterator AlreadySeen = |
| 5218 | SeenChainsForSExt.find(HeadOfChain); |
| 5219 | // If there is an unhandled SExt which has the same header, try to promote |
| 5220 | // it as well. |
| 5221 | if (AlreadySeen != SeenChainsForSExt.end()) { |
| 5222 | if (AlreadySeen->second != nullptr) |
| 5223 | UnhandledExts.insert(AlreadySeen->second); |
| 5224 | AllSeenFirst = false; |
| 5225 | } |
| 5226 | } |
| 5227 | |
| 5228 | if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader && |
| 5229 | SpeculativelyMovedExts.size() == 1)) { |
| 5230 | TPT.commit(); |
| 5231 | if (HasPromoted) |
| 5232 | Promoted = true; |
| 5233 | for (auto I : SpeculativelyMovedExts) { |
| 5234 | Value *HeadOfChain = I->getOperand(0); |
| 5235 | SeenChainsForSExt[HeadOfChain] = nullptr; |
| 5236 | ValToSExtendedUses[HeadOfChain].push_back(I); |
| 5237 | } |
| 5238 | // Update Inst as promotion happen. |
| 5239 | Inst = SpeculativelyMovedExts.pop_back_val(); |
| 5240 | } else { |
| 5241 | // This is the first chain visited from the header, keep the current chain |
| 5242 | // as unhandled. Defer to promote this until we encounter another SExt |
| 5243 | // chain derived from the same header. |
| 5244 | for (auto I : SpeculativelyMovedExts) { |
| 5245 | Value *HeadOfChain = I->getOperand(0); |
| 5246 | SeenChainsForSExt[HeadOfChain] = Inst; |
| 5247 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 5248 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 5249 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 5250 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5251 | if (!AllSeenFirst && !UnhandledExts.empty()) |
| 5252 | for (auto VisitedSExt : UnhandledExts) { |
| 5253 | if (RemovedInsts.count(VisitedSExt)) |
| 5254 | continue; |
| 5255 | TypePromotionTransaction TPT(RemovedInsts); |
| 5256 | SmallVector<Instruction *, 1> Exts; |
| 5257 | SmallVector<Instruction *, 2> Chains; |
| 5258 | Exts.push_back(VisitedSExt); |
| 5259 | bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains); |
| 5260 | TPT.commit(); |
| 5261 | if (HasPromoted) |
| 5262 | Promoted = true; |
| 5263 | for (auto I : Chains) { |
| 5264 | Value *HeadOfChain = I->getOperand(0); |
| 5265 | // Mark this as handled. |
| 5266 | SeenChainsForSExt[HeadOfChain] = nullptr; |
| 5267 | ValToSExtendedUses[HeadOfChain].push_back(I); |
| 5268 | } |
| 5269 | } |
| 5270 | return Promoted; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 5271 | } |
| 5272 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5273 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5274 | BasicBlock *DefBB = I->getParent(); |
| 5275 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 5276 | // 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] | 5277 | // other uses of the source with result of extension. |
| 5278 | Value *Src = I->getOperand(0); |
| 5279 | if (Src->hasOneUse()) |
| 5280 | return false; |
| 5281 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 5282 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 5283 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 5284 | return false; |
| 5285 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 5286 | // 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] | 5287 | // this block. |
| 5288 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 5289 | return false; |
| 5290 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5291 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5292 | for (User *U : I->users()) { |
| 5293 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5294 | |
| 5295 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5296 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5297 | if (UserBB == DefBB) continue; |
| 5298 | DefIsLiveOut = true; |
| 5299 | break; |
| 5300 | } |
| 5301 | if (!DefIsLiveOut) |
| 5302 | return false; |
| 5303 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 5304 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5305 | for (User *U : Src->users()) { |
| 5306 | Instruction *UI = cast<Instruction>(U); |
| 5307 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 5308 | if (UserBB == DefBB) continue; |
| 5309 | // Be conservative. We don't want this xform to end up introducing |
| 5310 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5311 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 5312 | return false; |
| 5313 | } |
| 5314 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5315 | // InsertedTruncs - Only insert one trunc in each block once. |
| 5316 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 5317 | |
| 5318 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5319 | for (Use &U : Src->uses()) { |
| 5320 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5321 | |
| 5322 | // Figure out which BB this ext is used in. |
| 5323 | BasicBlock *UserBB = User->getParent(); |
| 5324 | if (UserBB == DefBB) continue; |
| 5325 | |
| 5326 | // Both src and def are live in this block. Rewrite the use. |
| 5327 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 5328 | |
| 5329 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 5330 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5331 | assert(InsertPt != UserBB->end()); |
| 5332 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 5333 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5334 | } |
| 5335 | |
| 5336 | // 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] | 5337 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 5338 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5339 | MadeChange = true; |
| 5340 | } |
| 5341 | |
| 5342 | return MadeChange; |
| 5343 | } |
| 5344 | |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5345 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" |
| 5346 | // just after the load if the target can fold this into one extload instruction, |
| 5347 | // with the hope of eliminating some of the other later "and" instructions using |
| 5348 | // the loaded value. "and"s that are made trivially redundant by the insertion |
| 5349 | // of the new "and" are removed by this function, while others (e.g. those whose |
| 5350 | // path from the load goes through a phi) are left for isel to potentially |
| 5351 | // remove. |
| 5352 | // |
| 5353 | // For example: |
| 5354 | // |
| 5355 | // b0: |
| 5356 | // x = load i32 |
| 5357 | // ... |
| 5358 | // b1: |
| 5359 | // y = and x, 0xff |
| 5360 | // z = use y |
| 5361 | // |
| 5362 | // becomes: |
| 5363 | // |
| 5364 | // b0: |
| 5365 | // x = load i32 |
| 5366 | // x' = and x, 0xff |
| 5367 | // ... |
| 5368 | // b1: |
| 5369 | // z = use x' |
| 5370 | // |
| 5371 | // whereas: |
| 5372 | // |
| 5373 | // b0: |
| 5374 | // x1 = load i32 |
| 5375 | // ... |
| 5376 | // b1: |
| 5377 | // x2 = load i32 |
| 5378 | // ... |
| 5379 | // b2: |
| 5380 | // x = phi x1, x2 |
| 5381 | // y = and x, 0xff |
| 5382 | // |
| 5383 | // becomes (after a call to optimizeLoadExt for each load): |
| 5384 | // |
| 5385 | // b0: |
| 5386 | // x1 = load i32 |
| 5387 | // x1' = and x1, 0xff |
| 5388 | // ... |
| 5389 | // b1: |
| 5390 | // x2 = load i32 |
| 5391 | // x2' = and x2, 0xff |
| 5392 | // ... |
| 5393 | // b2: |
| 5394 | // x = phi x1', x2' |
| 5395 | // y = and x, 0xff |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5396 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { |
Vedant Kumar | b3091da | 2018-07-06 20:17:42 +0000 | [diff] [blame] | 5397 | if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy()) |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5398 | return false; |
| 5399 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5400 | // Skip loads we've already transformed. |
| 5401 | if (Load->hasOneUse() && |
| 5402 | InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) |
| 5403 | return false; |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5404 | |
| 5405 | // Look at all uses of Load, looking through phis, to determine how many bits |
| 5406 | // of the loaded value are needed. |
| 5407 | SmallVector<Instruction *, 8> WorkList; |
| 5408 | SmallPtrSet<Instruction *, 16> Visited; |
| 5409 | SmallVector<Instruction *, 8> AndsToMaybeRemove; |
| 5410 | for (auto *U : Load->users()) |
| 5411 | WorkList.push_back(cast<Instruction>(U)); |
| 5412 | |
| 5413 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); |
| 5414 | unsigned BitWidth = LoadResultVT.getSizeInBits(); |
| 5415 | APInt DemandBits(BitWidth, 0); |
| 5416 | APInt WidestAndBits(BitWidth, 0); |
| 5417 | |
| 5418 | while (!WorkList.empty()) { |
| 5419 | Instruction *I = WorkList.back(); |
| 5420 | WorkList.pop_back(); |
| 5421 | |
| 5422 | // Break use-def graph loops. |
| 5423 | if (!Visited.insert(I).second) |
| 5424 | continue; |
| 5425 | |
| 5426 | // For a PHI node, push all of its users. |
| 5427 | if (auto *Phi = dyn_cast<PHINode>(I)) { |
| 5428 | for (auto *U : Phi->users()) |
| 5429 | WorkList.push_back(cast<Instruction>(U)); |
| 5430 | continue; |
| 5431 | } |
| 5432 | |
| 5433 | switch (I->getOpcode()) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5434 | case Instruction::And: { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5435 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 5436 | if (!AndC) |
| 5437 | return false; |
| 5438 | APInt AndBits = AndC->getValue(); |
| 5439 | DemandBits |= AndBits; |
| 5440 | // Keep track of the widest and mask we see. |
| 5441 | if (AndBits.ugt(WidestAndBits)) |
| 5442 | WidestAndBits = AndBits; |
| 5443 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) |
| 5444 | AndsToMaybeRemove.push_back(I); |
| 5445 | break; |
| 5446 | } |
| 5447 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5448 | case Instruction::Shl: { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5449 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 5450 | if (!ShlC) |
| 5451 | return false; |
| 5452 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); |
Craig Topper | fc947bc | 2017-04-18 17:14:21 +0000 | [diff] [blame] | 5453 | DemandBits.setLowBits(BitWidth - ShiftAmt); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5454 | break; |
| 5455 | } |
| 5456 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5457 | case Instruction::Trunc: { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5458 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); |
| 5459 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); |
Craig Topper | fc947bc | 2017-04-18 17:14:21 +0000 | [diff] [blame] | 5460 | DemandBits.setLowBits(TruncBitWidth); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5461 | break; |
| 5462 | } |
| 5463 | |
| 5464 | default: |
| 5465 | return false; |
| 5466 | } |
| 5467 | } |
| 5468 | |
| 5469 | uint32_t ActiveBits = DemandBits.getActiveBits(); |
| 5470 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the |
| 5471 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, |
| 5472 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but |
| 5473 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR |
| 5474 | // followed by an AND. |
| 5475 | // TODO: Look into removing this restriction by fixing backends to either |
| 5476 | // return false for isLoadExtLegal for i1 or have them select this pattern to |
| 5477 | // a single instruction. |
| 5478 | // |
| 5479 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits |
| 5480 | // 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] | 5481 | if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) || |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5482 | WidestAndBits != DemandBits) |
| 5483 | return false; |
| 5484 | |
| 5485 | LLVMContext &Ctx = Load->getType()->getContext(); |
| 5486 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); |
| 5487 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); |
| 5488 | |
| 5489 | // Reject cases that won't be matched as extloads. |
| 5490 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || |
| 5491 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) |
| 5492 | return false; |
| 5493 | |
| 5494 | IRBuilder<> Builder(Load->getNextNode()); |
| 5495 | auto *NewAnd = dyn_cast<Instruction>( |
| 5496 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5497 | // Mark this instruction as "inserted by CGP", so that other |
| 5498 | // optimizations don't touch it. |
| 5499 | InsertedInsts.insert(NewAnd); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5500 | |
| 5501 | // Replace all uses of load with new and (except for the use of load in the |
| 5502 | // new and itself). |
| 5503 | Load->replaceAllUsesWith(NewAnd); |
| 5504 | NewAnd->setOperand(0, Load); |
| 5505 | |
| 5506 | // Remove any and instructions that are now redundant. |
| 5507 | for (auto *And : AndsToMaybeRemove) |
| 5508 | // Check that the and mask is the same as the one we decided to put on the |
| 5509 | // new and. |
| 5510 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { |
| 5511 | And->replaceAllUsesWith(NewAnd); |
| 5512 | if (&*CurInstIterator == And) |
| 5513 | CurInstIterator = std::next(And->getIterator()); |
| 5514 | And->eraseFromParent(); |
| 5515 | ++NumAndUses; |
| 5516 | } |
| 5517 | |
| 5518 | ++NumAndsAdded; |
| 5519 | return true; |
| 5520 | } |
| 5521 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5522 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 5523 | /// that is only used once. |
| 5524 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 5525 | auto *I = dyn_cast<Instruction>(V); |
| 5526 | // If it's safe to speculatively execute, then it should not have side |
| 5527 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 5528 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 5529 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5530 | } |
| 5531 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 5532 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5533 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5534 | const TargetLowering *TLI, |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5535 | SelectInst *SI) { |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5536 | // If even a predictable select is cheap, then a branch can't be cheaper. |
| 5537 | if (!TLI->isPredictableSelectExpensive()) |
| 5538 | return false; |
| 5539 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5540 | // FIXME: This should use the same heuristics as IfConversion to determine |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5541 | // whether a select is better represented as a branch. |
| 5542 | |
| 5543 | // If metadata tells us that the select condition is obviously predictable, |
| 5544 | // then we want to replace the select with a branch. |
| 5545 | uint64_t TrueWeight, FalseWeight; |
| 5546 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { |
| 5547 | uint64_t Max = std::max(TrueWeight, FalseWeight); |
| 5548 | uint64_t Sum = TrueWeight + FalseWeight; |
Sanjay Patel | c7b91e6 | 2016-05-09 17:31:55 +0000 | [diff] [blame] | 5549 | if (Sum != 0) { |
| 5550 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); |
| 5551 | if (Probability > TLI->getPredictableBranchThreshold()) |
| 5552 | return true; |
| 5553 | } |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5554 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5555 | |
| 5556 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 5557 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 5558 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 5559 | // comparison condition. If the compare has more than one use, there's |
| 5560 | // 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] | 5561 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5562 | return false; |
| 5563 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5564 | // If either operand of the select is expensive and only needed on one side |
| 5565 | // of the select, we should form a branch. |
| 5566 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 5567 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 5568 | return true; |
| 5569 | |
| 5570 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5571 | } |
| 5572 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5573 | /// If \p isTrue is true, return the true value of \p SI, otherwise return |
| 5574 | /// false value of \p SI. If the true/false value of \p SI is defined by any |
| 5575 | /// select instructions in \p Selects, look through the defining select |
| 5576 | /// instruction until the true/false value is not defined in \p Selects. |
| 5577 | static Value *getTrueOrFalseValue( |
| 5578 | SelectInst *SI, bool isTrue, |
| 5579 | const SmallPtrSet<const Instruction *, 2> &Selects) { |
| 5580 | Value *V; |
| 5581 | |
| 5582 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); |
| 5583 | DefSI = dyn_cast<SelectInst>(V)) { |
Dehao Chen | c32d712 | 2016-09-12 20:29:54 +0000 | [diff] [blame] | 5584 | assert(DefSI->getCondition() == SI->getCondition() && |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5585 | "The condition of DefSI does not match with SI"); |
| 5586 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); |
| 5587 | } |
| 5588 | return V; |
| 5589 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5590 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5591 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 5592 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5593 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Vedant Kumar | fbc3873 | 2018-08-21 23:42:23 +0000 | [diff] [blame] | 5594 | // If branch conversion isn't desirable, exit early. |
| 5595 | if (DisableSelectToBranch || OptSize || !TLI) |
| 5596 | return false; |
| 5597 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5598 | // Find all consecutive select instructions that share the same condition. |
| 5599 | SmallVector<SelectInst *, 2> ASI; |
| 5600 | ASI.push_back(SI); |
Vedant Kumar | 00e7558 | 2018-08-21 23:42:38 +0000 | [diff] [blame] | 5601 | for (Instruction *NextInst = SI->getNextNonDebugInstruction(); |
| 5602 | NextInst != SI->getParent()->getTerminator(); |
| 5603 | NextInst = NextInst->getNextNonDebugInstruction()) { |
| 5604 | SelectInst *I = dyn_cast<SelectInst>(NextInst); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5605 | if (I && SI->getCondition() == I->getCondition()) { |
| 5606 | ASI.push_back(I); |
| 5607 | } else { |
| 5608 | break; |
| 5609 | } |
| 5610 | } |
| 5611 | |
| 5612 | SelectInst *LastSI = ASI.back(); |
| 5613 | // Increment the current iterator to skip all the rest of select instructions |
| 5614 | // because they will be either "not lowered" or "all lowered" to branch. |
| 5615 | CurInstIterator = std::next(LastSI->getIterator()); |
| 5616 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5617 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 5618 | |
| 5619 | // Can we convert the 'select' to CF ? |
Vedant Kumar | fbc3873 | 2018-08-21 23:42:23 +0000 | [diff] [blame] | 5620 | if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable)) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5621 | return false; |
| 5622 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5623 | TargetLowering::SelectSupportKind SelectKind; |
| 5624 | if (VectorCond) |
| 5625 | SelectKind = TargetLowering::VectorMaskSelect; |
| 5626 | else if (SI->getType()->isVectorTy()) |
| 5627 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 5628 | else |
| 5629 | SelectKind = TargetLowering::ScalarValSelect; |
| 5630 | |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5631 | if (TLI->isSelectSupported(SelectKind) && |
| 5632 | !isFormingBranchFromSelectProfitable(TTI, TLI, SI)) |
| 5633 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5634 | |
| 5635 | ModifiedDT = true; |
| 5636 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5637 | // Transform a sequence like this: |
| 5638 | // start: |
| 5639 | // %cmp = cmp uge i32 %a, %b |
| 5640 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 5641 | // |
| 5642 | // Into: |
| 5643 | // start: |
| 5644 | // %cmp = cmp uge i32 %a, %b |
| 5645 | // br i1 %cmp, label %select.true, label %select.false |
| 5646 | // select.true: |
| 5647 | // br label %select.end |
| 5648 | // select.false: |
| 5649 | // br label %select.end |
| 5650 | // select.end: |
| 5651 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 5652 | // |
| 5653 | // In addition, we may sink instructions that produce %c or %d from |
| 5654 | // the entry block into the destination(s) of the new branch. |
| 5655 | // If the true or false blocks do not contain a sunken instruction, that |
| 5656 | // block and its branch may be optimized away. In that case, one side of the |
| 5657 | // first branch will point directly to select.end, and the corresponding PHI |
| 5658 | // predecessor block will be the start block. |
| 5659 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5660 | // First, we split the block containing the select into 2 blocks. |
| 5661 | BasicBlock *StartBlock = SI->getParent(); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5662 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5663 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5664 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5665 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5666 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5667 | |
| 5668 | // These are the new basic blocks for the conditional branch. |
| 5669 | // At least one will become an actual new basic block. |
| 5670 | BasicBlock *TrueBlock = nullptr; |
| 5671 | BasicBlock *FalseBlock = nullptr; |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5672 | BranchInst *TrueBranch = nullptr; |
| 5673 | BranchInst *FalseBranch = nullptr; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5674 | |
| 5675 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 5676 | // them speculatively. |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5677 | for (SelectInst *SI : ASI) { |
| 5678 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 5679 | if (TrueBlock == nullptr) { |
| 5680 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 5681 | EndBlock->getParent(), EndBlock); |
| 5682 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
Vedant Kumar | 1e8a2c9 | 2018-08-22 00:10:37 +0000 | [diff] [blame^] | 5683 | TrueBranch->setDebugLoc(SI->getDebugLoc()); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5684 | } |
| 5685 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 5686 | TrueInst->moveBefore(TrueBranch); |
| 5687 | } |
| 5688 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 5689 | if (FalseBlock == nullptr) { |
| 5690 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 5691 | EndBlock->getParent(), EndBlock); |
| 5692 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
Vedant Kumar | 1e8a2c9 | 2018-08-22 00:10:37 +0000 | [diff] [blame^] | 5693 | FalseBranch->setDebugLoc(SI->getDebugLoc()); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5694 | } |
| 5695 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 5696 | FalseInst->moveBefore(FalseBranch); |
| 5697 | } |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5698 | } |
| 5699 | |
| 5700 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 5701 | // for a new input value to the PHI. |
| 5702 | if (TrueBlock == FalseBlock) { |
| 5703 | assert(TrueBlock == nullptr && |
| 5704 | "Unexpected basic block transform while optimizing select"); |
| 5705 | |
| 5706 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 5707 | EndBlock->getParent(), EndBlock); |
Vedant Kumar | 1e8a2c9 | 2018-08-22 00:10:37 +0000 | [diff] [blame^] | 5708 | auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 5709 | FalseBranch->setDebugLoc(SI->getDebugLoc()); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5710 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5711 | |
| 5712 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5713 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 5714 | // of the condition, it means that side of the branch goes to the end block |
| 5715 | // directly and the path originates from the start block from the point of |
| 5716 | // view of the new PHI. |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5717 | BasicBlock *TT, *FT; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5718 | if (TrueBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5719 | TT = EndBlock; |
| 5720 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5721 | TrueBlock = StartBlock; |
| 5722 | } else if (FalseBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5723 | TT = TrueBlock; |
| 5724 | FT = EndBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5725 | FalseBlock = StartBlock; |
| 5726 | } else { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5727 | TT = TrueBlock; |
| 5728 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5729 | } |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5730 | IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5731 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5732 | SmallPtrSet<const Instruction *, 2> INS; |
| 5733 | INS.insert(ASI.begin(), ASI.end()); |
| 5734 | // Use reverse iterator because later select may use the value of the |
| 5735 | // earlier select, and we need to propagate value through earlier select |
| 5736 | // to get the PHI operand. |
| 5737 | for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { |
| 5738 | SelectInst *SI = *It; |
| 5739 | // The select itself is replaced with a PHI Node. |
| 5740 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
| 5741 | PN->takeName(SI); |
| 5742 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); |
| 5743 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); |
Vedant Kumar | 1e8a2c9 | 2018-08-22 00:10:37 +0000 | [diff] [blame^] | 5744 | PN->setDebugLoc(SI->getDebugLoc()); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5745 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5746 | SI->replaceAllUsesWith(PN); |
| 5747 | SI->eraseFromParent(); |
| 5748 | INS.erase(SI); |
| 5749 | ++NumSelectsExpanded; |
| 5750 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5751 | |
| 5752 | // Instruct OptimizeBlock to skip to the next block. |
| 5753 | CurInstIterator = StartBlock->end(); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5754 | return true; |
| 5755 | } |
| 5756 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 5757 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5758 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 5759 | int SplatElem = -1; |
| 5760 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 5761 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 5762 | return false; |
| 5763 | SplatElem = Mask[i]; |
| 5764 | } |
| 5765 | |
| 5766 | return true; |
| 5767 | } |
| 5768 | |
| 5769 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 5770 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 5771 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 5772 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5773 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5774 | BasicBlock *DefBB = SVI->getParent(); |
| 5775 | |
| 5776 | // Only do this xform if variable vector shifts are particularly expensive. |
| 5777 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 5778 | return false; |
| 5779 | |
| 5780 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 5781 | // constant splat. |
| 5782 | if (!isBroadcastShuffle(SVI)) |
| 5783 | return false; |
| 5784 | |
| 5785 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 5786 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 5787 | |
| 5788 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5789 | for (User *U : SVI->users()) { |
| 5790 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5791 | |
| 5792 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5793 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5794 | if (UserBB == DefBB) continue; |
| 5795 | |
| 5796 | // 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] | 5797 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5798 | |
| 5799 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 5800 | // already have a copy. |
| 5801 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 5802 | |
| 5803 | if (!InsertedShuffle) { |
| 5804 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5805 | assert(InsertPt != UserBB->end()); |
| 5806 | InsertedShuffle = |
| 5807 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 5808 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5809 | } |
| 5810 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5811 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5812 | MadeChange = true; |
| 5813 | } |
| 5814 | |
| 5815 | // If we removed all uses, nuke the shuffle. |
| 5816 | if (SVI->use_empty()) { |
| 5817 | SVI->eraseFromParent(); |
| 5818 | MadeChange = true; |
| 5819 | } |
| 5820 | |
| 5821 | return MadeChange; |
| 5822 | } |
| 5823 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5824 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 5825 | if (!TLI || !DL) |
| 5826 | return false; |
| 5827 | |
| 5828 | Value *Cond = SI->getCondition(); |
| 5829 | Type *OldType = Cond->getType(); |
| 5830 | LLVMContext &Context = Cond->getContext(); |
| 5831 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 5832 | unsigned RegWidth = RegType.getSizeInBits(); |
| 5833 | |
| 5834 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 5835 | return false; |
| 5836 | |
| 5837 | // If the register width is greater than the type width, expand the condition |
| 5838 | // of the switch instruction and each case constant to the width of the |
| 5839 | // register. By widening the type of the switch condition, subsequent |
| 5840 | // comparisons (for case comparisons) will not need to be extended to the |
| 5841 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 5842 | // where N is the number of cases in the switch. |
| 5843 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 5844 | |
| 5845 | // Zero-extend the switch condition and case constants unless the switch |
| 5846 | // condition is a function argument that is already being sign-extended. |
| 5847 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 5848 | // everything instead. |
| 5849 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 5850 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 5851 | if (Arg->hasSExtAttr()) |
| 5852 | ExtType = Instruction::SExt; |
| 5853 | |
| 5854 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 5855 | ExtInst->insertBefore(SI); |
| 5856 | SI->setCondition(ExtInst); |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 5857 | for (auto Case : SI->cases()) { |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5858 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 5859 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 5860 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 5861 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 5862 | } |
| 5863 | |
| 5864 | return true; |
| 5865 | } |
| 5866 | |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 5867 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5868 | namespace { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5869 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 5870 | /// Helper class to promote a scalar operation to a vector one. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5871 | /// This class is used to move downward extractelement transition. |
| 5872 | /// E.g., |
| 5873 | /// a = vector_op <2 x i32> |
| 5874 | /// b = extractelement <2 x i32> a, i32 0 |
| 5875 | /// c = scalar_op b |
| 5876 | /// store c |
| 5877 | /// |
| 5878 | /// => |
| 5879 | /// a = vector_op <2 x i32> |
| 5880 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 5881 | /// * d = extractelement <2 x i32> c, i32 0 |
| 5882 | /// * store d |
| 5883 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 5884 | /// transition. |
| 5885 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5886 | /// DataLayout associated with the current module. |
| 5887 | const DataLayout &DL; |
| 5888 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5889 | /// Used to perform some checks on the legality of vector operations. |
| 5890 | const TargetLowering &TLI; |
| 5891 | |
| 5892 | /// Used to estimated the cost of the promoted chain. |
| 5893 | const TargetTransformInfo &TTI; |
| 5894 | |
| 5895 | /// The transition being moved downwards. |
| 5896 | Instruction *Transition; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5897 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5898 | /// The sequence of instructions to be promoted. |
| 5899 | SmallVector<Instruction *, 4> InstsToBePromoted; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5900 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5901 | /// Cost of combining a store and an extract. |
| 5902 | unsigned StoreExtractCombineCost; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5903 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5904 | /// Instruction that will be combined with the transition. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5905 | Instruction *CombineInst = nullptr; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5906 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 5907 | /// The instruction that represents the current end of the transition. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5908 | /// Since we are faking the promotion until we reach the end of the chain |
| 5909 | /// of computation, we need a way to get the current end of the transition. |
| 5910 | Instruction *getEndOfTransition() const { |
| 5911 | if (InstsToBePromoted.empty()) |
| 5912 | return Transition; |
| 5913 | return InstsToBePromoted.back(); |
| 5914 | } |
| 5915 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 5916 | /// Return the index of the original value in the transition. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5917 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 5918 | /// c, is at index 0. |
| 5919 | unsigned getTransitionOriginalValueIdx() const { |
| 5920 | assert(isa<ExtractElementInst>(Transition) && |
| 5921 | "Other kind of transitions are not supported yet"); |
| 5922 | return 0; |
| 5923 | } |
| 5924 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 5925 | /// Return the index of the index in the transition. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5926 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 5927 | /// is at index 1. |
| 5928 | unsigned getTransitionIdx() const { |
| 5929 | assert(isa<ExtractElementInst>(Transition) && |
| 5930 | "Other kind of transitions are not supported yet"); |
| 5931 | return 1; |
| 5932 | } |
| 5933 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 5934 | /// Get the type of the transition. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5935 | /// This is the type of the original value. |
| 5936 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 5937 | /// transition is <2 x i32>. |
| 5938 | Type *getTransitionType() const { |
| 5939 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 5940 | } |
| 5941 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 5942 | /// Promote \p ToBePromoted by moving \p Def downward through. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5943 | /// I.e., we have the following sequence: |
| 5944 | /// Def = Transition <ty1> a to <ty2> |
| 5945 | /// b = ToBePromoted <ty2> Def, ... |
| 5946 | /// => |
| 5947 | /// b = ToBePromoted <ty1> a, ... |
| 5948 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 5949 | void promoteImpl(Instruction *ToBePromoted); |
| 5950 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 5951 | /// Check whether or not it is profitable to promote all the |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5952 | /// instructions enqueued to be promoted. |
| 5953 | bool isProfitableToPromote() { |
| 5954 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5955 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 5956 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 5957 | : -1; |
| 5958 | Type *PromotedType = getTransitionType(); |
| 5959 | |
| 5960 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 5961 | unsigned AS = ST->getPointerAddressSpace(); |
| 5962 | unsigned Align = ST->getAlignment(); |
| 5963 | // Check if this store is supported. |
| 5964 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5965 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 5966 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5967 | // If this is not supported, there is no way we can combine |
| 5968 | // the extract with the store. |
| 5969 | return false; |
| 5970 | } |
| 5971 | |
| 5972 | // The scalar chain of computation has to pay for the transition |
| 5973 | // scalar to vector. |
| 5974 | // The vector chain has to account for the combining cost. |
| 5975 | uint64_t ScalarCost = |
| 5976 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 5977 | uint64_t VectorCost = StoreExtractCombineCost; |
| 5978 | for (const auto &Inst : InstsToBePromoted) { |
| 5979 | // Compute the cost. |
| 5980 | // By construction, all instructions being promoted are arithmetic ones. |
| 5981 | // Moreover, one argument is a constant that can be viewed as a splat |
| 5982 | // constant. |
| 5983 | Value *Arg0 = Inst->getOperand(0); |
| 5984 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 5985 | isa<ConstantFP>(Arg0); |
| 5986 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 5987 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5988 | : TargetTransformInfo::OK_AnyValue; |
| 5989 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 5990 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5991 | : TargetTransformInfo::OK_AnyValue; |
| 5992 | ScalarCost += TTI.getArithmeticInstrCost( |
| 5993 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 5994 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 5995 | Arg0OVK, Arg1OVK); |
| 5996 | } |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 5997 | LLVM_DEBUG( |
| 5998 | dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 5999 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6000 | return ScalarCost > VectorCost; |
| 6001 | } |
| 6002 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6003 | /// Generate a constant vector with \p Val with the same |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6004 | /// number of elements as the transition. |
| 6005 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 6006 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6007 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 6008 | /// otherwise we generate a vector with as many undef as possible: |
| 6009 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 6010 | /// used at the index of the extract. |
| 6011 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 6012 | unsigned ExtractIdx = std::numeric_limits<unsigned>::max(); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6013 | if (!UseSplat) { |
| 6014 | // If we cannot determine where the constant must be, we have to |
| 6015 | // use a splat constant. |
| 6016 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 6017 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 6018 | ExtractIdx = CstVal->getSExtValue(); |
| 6019 | else |
| 6020 | UseSplat = true; |
| 6021 | } |
| 6022 | |
| 6023 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 6024 | if (UseSplat) |
| 6025 | return ConstantVector::getSplat(End, Val); |
| 6026 | |
| 6027 | SmallVector<Constant *, 4> ConstVec; |
| 6028 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 6029 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 6030 | if (Idx == ExtractIdx) |
| 6031 | ConstVec.push_back(Val); |
| 6032 | else |
| 6033 | ConstVec.push_back(UndefVal); |
| 6034 | } |
| 6035 | return ConstantVector::get(ConstVec); |
| 6036 | } |
| 6037 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6038 | /// Check if promoting to a vector type an operand at \p OperandIdx |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6039 | /// in \p Use can trigger undefined behavior. |
| 6040 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 6041 | unsigned OperandIdx) { |
| 6042 | // This is not safe to introduce undef when the operand is on |
| 6043 | // the right hand side of a division-like instruction. |
| 6044 | if (OperandIdx != 1) |
| 6045 | return false; |
| 6046 | switch (Use->getOpcode()) { |
| 6047 | default: |
| 6048 | return false; |
| 6049 | case Instruction::SDiv: |
| 6050 | case Instruction::UDiv: |
| 6051 | case Instruction::SRem: |
| 6052 | case Instruction::URem: |
| 6053 | return true; |
| 6054 | case Instruction::FDiv: |
| 6055 | case Instruction::FRem: |
| 6056 | return !Use->hasNoNaNs(); |
| 6057 | } |
| 6058 | llvm_unreachable(nullptr); |
| 6059 | } |
| 6060 | |
| 6061 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6062 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 6063 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 6064 | unsigned CombineCost) |
| 6065 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 6066 | StoreExtractCombineCost(CombineCost) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6067 | assert(Transition && "Do not know how to promote null"); |
| 6068 | } |
| 6069 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6070 | /// Check if we can promote \p ToBePromoted to \p Type. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6071 | bool canPromote(const Instruction *ToBePromoted) const { |
| 6072 | // We could support CastInst too. |
| 6073 | return isa<BinaryOperator>(ToBePromoted); |
| 6074 | } |
| 6075 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6076 | /// Check if it is profitable to promote \p ToBePromoted |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6077 | /// by moving downward the transition through. |
| 6078 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 6079 | // Promote only if all the operands can be statically expanded. |
| 6080 | // Indeed, we do not want to introduce any new kind of transitions. |
| 6081 | for (const Use &U : ToBePromoted->operands()) { |
| 6082 | const Value *Val = U.get(); |
| 6083 | if (Val == getEndOfTransition()) { |
| 6084 | // If the use is a division and the transition is on the rhs, |
| 6085 | // we cannot promote the operation, otherwise we may create a |
| 6086 | // division by zero. |
| 6087 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 6088 | return false; |
| 6089 | continue; |
| 6090 | } |
| 6091 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 6092 | !isa<ConstantFP>(Val)) |
| 6093 | return false; |
| 6094 | } |
| 6095 | // Check that the resulting operation is legal. |
| 6096 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 6097 | if (!ISDOpcode) |
| 6098 | return false; |
| 6099 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 6100 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6101 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6102 | } |
| 6103 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6104 | /// Check whether or not \p Use can be combined |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6105 | /// with the transition. |
| 6106 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 6107 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 6108 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6109 | /// Record \p ToBePromoted as part of the chain to be promoted. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6110 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 6111 | InstsToBePromoted.push_back(ToBePromoted); |
| 6112 | } |
| 6113 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6114 | /// Set the instruction that will be combined with the transition. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6115 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 6116 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 6117 | CombineInst = ToBeCombined; |
| 6118 | } |
| 6119 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6120 | /// Promote all the instructions enqueued for promotion if it is |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6121 | /// is profitable. |
| 6122 | /// \return True if the promotion happened, false otherwise. |
| 6123 | bool promote() { |
| 6124 | // Check if there is something to promote. |
| 6125 | // Right now, if we do not have anything to combine with, |
| 6126 | // we assume the promotion is not profitable. |
| 6127 | if (InstsToBePromoted.empty() || !CombineInst) |
| 6128 | return false; |
| 6129 | |
| 6130 | // Check cost. |
| 6131 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 6132 | return false; |
| 6133 | |
| 6134 | // Promote. |
| 6135 | for (auto &ToBePromoted : InstsToBePromoted) |
| 6136 | promoteImpl(ToBePromoted); |
| 6137 | InstsToBePromoted.clear(); |
| 6138 | return true; |
| 6139 | } |
| 6140 | }; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 6141 | |
| 6142 | } // end anonymous namespace |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6143 | |
| 6144 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 6145 | // At this point, we know that all the operands of ToBePromoted but Def |
| 6146 | // can be statically promoted. |
| 6147 | // For Def, we need to use its parameter in ToBePromoted: |
| 6148 | // b = ToBePromoted ty1 a |
| 6149 | // Def = Transition ty1 b to ty2 |
| 6150 | // Move the transition down. |
| 6151 | // 1. Replace all uses of the promoted operation by the transition. |
| 6152 | // = ... b => = ... Def. |
| 6153 | assert(ToBePromoted->getType() == Transition->getType() && |
| 6154 | "The type of the result of the transition does not match " |
| 6155 | "the final type"); |
| 6156 | ToBePromoted->replaceAllUsesWith(Transition); |
| 6157 | // 2. Update the type of the uses. |
| 6158 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 6159 | Type *TransitionTy = getTransitionType(); |
| 6160 | ToBePromoted->mutateType(TransitionTy); |
| 6161 | // 3. Update all the operands of the promoted operation with promoted |
| 6162 | // operands. |
| 6163 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 6164 | for (Use &U : ToBePromoted->operands()) { |
| 6165 | Value *Val = U.get(); |
| 6166 | Value *NewVal = nullptr; |
| 6167 | if (Val == Transition) |
| 6168 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 6169 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 6170 | isa<ConstantFP>(Val)) { |
| 6171 | // Use a splat constant if it is not safe to use undef. |
| 6172 | NewVal = getConstantVector( |
| 6173 | cast<Constant>(Val), |
| 6174 | isa<UndefValue>(Val) || |
| 6175 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 6176 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 6177 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 6178 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6179 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 6180 | } |
Sanjay Patel | 674d2c2 | 2017-08-29 14:07:48 +0000 | [diff] [blame] | 6181 | Transition->moveAfter(ToBePromoted); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6182 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 6183 | } |
| 6184 | |
| 6185 | /// Some targets can do store(extractelement) with one instruction. |
| 6186 | /// Try to push the extractelement towards the stores when the target |
| 6187 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6188 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 6189 | unsigned CombineCost = std::numeric_limits<unsigned>::max(); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6190 | if (DisableStoreExtract || !TLI || |
| 6191 | (!StressStoreExtract && |
| 6192 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 6193 | Inst->getOperand(1), CombineCost))) |
| 6194 | return false; |
| 6195 | |
| 6196 | // At this point we know that Inst is a vector to scalar transition. |
| 6197 | // Try to move it down the def-use chain, until: |
| 6198 | // - We can combine the transition with its single use |
| 6199 | // => we got rid of the transition. |
| 6200 | // - We escape the current basic block |
| 6201 | // => we would need to check that we are moving it at a cheaper place and |
| 6202 | // we do not do that for now. |
| 6203 | BasicBlock *Parent = Inst->getParent(); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6204 | LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6205 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6206 | // If the transition has more than one use, assume this is not going to be |
| 6207 | // beneficial. |
| 6208 | while (Inst->hasOneUse()) { |
| 6209 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6210 | LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6211 | |
| 6212 | if (ToBePromoted->getParent() != Parent) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6213 | LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 6214 | << ToBePromoted->getParent()->getName() |
| 6215 | << ") than the transition (" << Parent->getName() |
| 6216 | << ").\n"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6217 | return false; |
| 6218 | } |
| 6219 | |
| 6220 | if (VPH.canCombine(ToBePromoted)) { |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6221 | LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 6222 | << "will be combined with: " << *ToBePromoted << '\n'); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6223 | VPH.recordCombineInstruction(ToBePromoted); |
| 6224 | bool Changed = VPH.promote(); |
| 6225 | NumStoreExtractExposed += Changed; |
| 6226 | return Changed; |
| 6227 | } |
| 6228 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6229 | LLVM_DEBUG(dbgs() << "Try promoting.\n"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6230 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 6231 | return false; |
| 6232 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6233 | LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6234 | |
| 6235 | VPH.enqueueForPromotion(ToBePromoted); |
| 6236 | Inst = ToBePromoted; |
| 6237 | } |
| 6238 | return false; |
| 6239 | } |
| 6240 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6241 | /// For the instruction sequence of store below, F and I values |
| 6242 | /// are bundled together as an i64 value before being stored into memory. |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 6243 | /// Sometimes it is more efficient to generate separate stores for F and I, |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6244 | /// which can remove the bitwise instructions or sink them to colder places. |
| 6245 | /// |
| 6246 | /// (store (or (zext (bitcast F to i32) to i64), |
| 6247 | /// (shl (zext I to i64), 32)), addr) --> |
| 6248 | /// (store F, addr) and (store I, addr+4) |
| 6249 | /// |
| 6250 | /// Similarly, splitting for other merged store can also be beneficial, like: |
| 6251 | /// For pair of {i32, i32}, i64 store --> two i32 stores. |
| 6252 | /// For pair of {i32, i16}, i64 store --> two i32 stores. |
| 6253 | /// For pair of {i16, i16}, i32 store --> two i16 stores. |
| 6254 | /// For pair of {i16, i8}, i32 store --> two i16 stores. |
| 6255 | /// For pair of {i8, i8}, i16 store --> two i8 stores. |
| 6256 | /// |
| 6257 | /// We allow each target to determine specifically which kind of splitting is |
| 6258 | /// supported. |
| 6259 | /// |
| 6260 | /// The store patterns are commonly seen from the simple code snippet below |
| 6261 | /// if only std::make_pair(...) is sroa transformed before inlined into hoo. |
| 6262 | /// void goo(const std::pair<int, float> &); |
| 6263 | /// hoo() { |
| 6264 | /// ... |
| 6265 | /// goo(std::make_pair(tmp, ftmp)); |
| 6266 | /// ... |
| 6267 | /// } |
| 6268 | /// |
| 6269 | /// Although we already have similar splitting in DAG Combine, we duplicate |
| 6270 | /// it in CodeGenPrepare to catch the case in which pattern is across |
| 6271 | /// multiple BBs. The logic in DAG Combine is kept to catch case generated |
| 6272 | /// during code expansion. |
| 6273 | static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, |
| 6274 | const TargetLowering &TLI) { |
| 6275 | // Handle simple but common cases only. |
| 6276 | Type *StoreType = SI.getValueOperand()->getType(); |
| 6277 | if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) || |
| 6278 | DL.getTypeSizeInBits(StoreType) == 0) |
| 6279 | return false; |
| 6280 | |
| 6281 | unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; |
| 6282 | Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); |
| 6283 | if (DL.getTypeStoreSizeInBits(SplitStoreType) != |
| 6284 | DL.getTypeSizeInBits(SplitStoreType)) |
| 6285 | return false; |
| 6286 | |
| 6287 | // Match the following patterns: |
| 6288 | // (store (or (zext LValue to i64), |
| 6289 | // (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 6290 | // or |
| 6291 | // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 6292 | // (zext LValue to i64), |
| 6293 | // Expect both operands of OR and the first operand of SHL have only |
| 6294 | // one use. |
| 6295 | Value *LValue, *HValue; |
| 6296 | if (!match(SI.getValueOperand(), |
| 6297 | m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), |
| 6298 | m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), |
| 6299 | m_SpecificInt(HalfValBitSize)))))) |
| 6300 | return false; |
| 6301 | |
| 6302 | // Check LValue and HValue are int with size less or equal than 32. |
| 6303 | if (!LValue->getType()->isIntegerTy() || |
| 6304 | DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || |
| 6305 | !HValue->getType()->isIntegerTy() || |
| 6306 | DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) |
| 6307 | return false; |
| 6308 | |
| 6309 | // If LValue/HValue is a bitcast instruction, use the EVT before bitcast |
| 6310 | // as the input of target query. |
| 6311 | auto *LBC = dyn_cast<BitCastInst>(LValue); |
| 6312 | auto *HBC = dyn_cast<BitCastInst>(HValue); |
| 6313 | EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) |
| 6314 | : EVT::getEVT(LValue->getType()); |
| 6315 | EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) |
| 6316 | : EVT::getEVT(HValue->getType()); |
| 6317 | if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) |
| 6318 | return false; |
| 6319 | |
| 6320 | // Start to split store. |
| 6321 | IRBuilder<> Builder(SI.getContext()); |
| 6322 | Builder.SetInsertPoint(&SI); |
| 6323 | |
| 6324 | // If LValue/HValue is a bitcast in another BB, create a new one in current |
| 6325 | // BB so it may be merged with the splitted stores by dag combiner. |
| 6326 | if (LBC && LBC->getParent() != SI.getParent()) |
| 6327 | LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); |
| 6328 | if (HBC && HBC->getParent() != SI.getParent()) |
| 6329 | HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); |
| 6330 | |
Jonas Paulsson | 5612bb2 | 2018-03-13 08:36:20 +0000 | [diff] [blame] | 6331 | bool IsLE = SI.getModule()->getDataLayout().isLittleEndian(); |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6332 | auto CreateSplitStore = [&](Value *V, bool Upper) { |
| 6333 | V = Builder.CreateZExtOrBitCast(V, SplitStoreType); |
| 6334 | Value *Addr = Builder.CreateBitCast( |
| 6335 | SI.getOperand(1), |
| 6336 | SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); |
Jonas Paulsson | 5612bb2 | 2018-03-13 08:36:20 +0000 | [diff] [blame] | 6337 | if ((IsLE && Upper) || (!IsLE && !Upper)) |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6338 | Addr = Builder.CreateGEP( |
| 6339 | SplitStoreType, Addr, |
| 6340 | ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); |
| 6341 | Builder.CreateAlignedStore( |
| 6342 | V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment()); |
| 6343 | }; |
| 6344 | |
| 6345 | CreateSplitStore(LValue, false); |
| 6346 | CreateSplitStore(HValue, true); |
| 6347 | |
| 6348 | // Delete the old store. |
| 6349 | SI.eraseFromParent(); |
| 6350 | return true; |
| 6351 | } |
| 6352 | |
Hiroshi Yamauchi | 9364432 | 2017-09-11 17:52:08 +0000 | [diff] [blame] | 6353 | // Return true if the GEP has two operands, the first operand is of a sequential |
| 6354 | // type, and the second operand is a constant. |
| 6355 | static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) { |
| 6356 | gep_type_iterator I = gep_type_begin(*GEP); |
| 6357 | return GEP->getNumOperands() == 2 && |
| 6358 | I.isSequential() && |
| 6359 | isa<ConstantInt>(GEP->getOperand(1)); |
| 6360 | } |
| 6361 | |
| 6362 | // Try unmerging GEPs to reduce liveness interference (register pressure) across |
| 6363 | // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks, |
| 6364 | // reducing liveness interference across those edges benefits global register |
| 6365 | // allocation. Currently handles only certain cases. |
| 6366 | // |
| 6367 | // For example, unmerge %GEPI and %UGEPI as below. |
| 6368 | // |
| 6369 | // ---------- BEFORE ---------- |
| 6370 | // SrcBlock: |
| 6371 | // ... |
| 6372 | // %GEPIOp = ... |
| 6373 | // ... |
| 6374 | // %GEPI = gep %GEPIOp, Idx |
| 6375 | // ... |
| 6376 | // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ] |
| 6377 | // (* %GEPI is alive on the indirectbr edges due to other uses ahead) |
| 6378 | // (* %GEPIOp is alive on the indirectbr edges only because of it's used by |
| 6379 | // %UGEPI) |
| 6380 | // |
| 6381 | // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged) |
| 6382 | // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged) |
| 6383 | // ... |
| 6384 | // |
| 6385 | // DstBi: |
| 6386 | // ... |
| 6387 | // %UGEPI = gep %GEPIOp, UIdx |
| 6388 | // ... |
| 6389 | // --------------------------- |
| 6390 | // |
| 6391 | // ---------- AFTER ---------- |
| 6392 | // SrcBlock: |
| 6393 | // ... (same as above) |
| 6394 | // (* %GEPI is still alive on the indirectbr edges) |
| 6395 | // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the |
| 6396 | // unmerging) |
| 6397 | // ... |
| 6398 | // |
| 6399 | // DstBi: |
| 6400 | // ... |
| 6401 | // %UGEPI = gep %GEPI, (UIdx-Idx) |
| 6402 | // ... |
| 6403 | // --------------------------- |
| 6404 | // |
| 6405 | // The register pressure on the IndirectBr edges is reduced because %GEPIOp is |
| 6406 | // no longer alive on them. |
| 6407 | // |
| 6408 | // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging |
| 6409 | // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as |
| 6410 | // not to disable further simplications and optimizations as a result of GEP |
| 6411 | // merging. |
| 6412 | // |
| 6413 | // Note this unmerging may increase the length of the data flow critical path |
| 6414 | // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff |
| 6415 | // between the register pressure and the length of data-flow critical |
| 6416 | // path. Restricting this to the uncommon IndirectBr case would minimize the |
| 6417 | // impact of potentially longer critical path, if any, and the impact on compile |
| 6418 | // time. |
| 6419 | static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, |
| 6420 | const TargetTransformInfo *TTI) { |
| 6421 | BasicBlock *SrcBlock = GEPI->getParent(); |
| 6422 | // Check that SrcBlock ends with an IndirectBr. If not, give up. The common |
| 6423 | // (non-IndirectBr) cases exit early here. |
| 6424 | if (!isa<IndirectBrInst>(SrcBlock->getTerminator())) |
| 6425 | return false; |
| 6426 | // Check that GEPI is a simple gep with a single constant index. |
| 6427 | if (!GEPSequentialConstIndexed(GEPI)) |
| 6428 | return false; |
| 6429 | ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1)); |
| 6430 | // Check that GEPI is a cheap one. |
| 6431 | if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType()) |
| 6432 | > TargetTransformInfo::TCC_Basic) |
| 6433 | return false; |
| 6434 | Value *GEPIOp = GEPI->getOperand(0); |
| 6435 | // Check that GEPIOp is an instruction that's also defined in SrcBlock. |
| 6436 | if (!isa<Instruction>(GEPIOp)) |
| 6437 | return false; |
| 6438 | auto *GEPIOpI = cast<Instruction>(GEPIOp); |
| 6439 | if (GEPIOpI->getParent() != SrcBlock) |
| 6440 | return false; |
| 6441 | // Check that GEP is used outside the block, meaning it's alive on the |
| 6442 | // IndirectBr edge(s). |
| 6443 | if (find_if(GEPI->users(), [&](User *Usr) { |
| 6444 | if (auto *I = dyn_cast<Instruction>(Usr)) { |
| 6445 | if (I->getParent() != SrcBlock) { |
| 6446 | return true; |
| 6447 | } |
| 6448 | } |
| 6449 | return false; |
| 6450 | }) == GEPI->users().end()) |
| 6451 | return false; |
| 6452 | // The second elements of the GEP chains to be unmerged. |
| 6453 | std::vector<GetElementPtrInst *> UGEPIs; |
| 6454 | // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive |
| 6455 | // on IndirectBr edges. |
| 6456 | for (User *Usr : GEPIOp->users()) { |
| 6457 | if (Usr == GEPI) continue; |
| 6458 | // Check if Usr is an Instruction. If not, give up. |
| 6459 | if (!isa<Instruction>(Usr)) |
| 6460 | return false; |
| 6461 | auto *UI = cast<Instruction>(Usr); |
| 6462 | // Check if Usr in the same block as GEPIOp, which is fine, skip. |
| 6463 | if (UI->getParent() == SrcBlock) |
| 6464 | continue; |
| 6465 | // Check if Usr is a GEP. If not, give up. |
| 6466 | if (!isa<GetElementPtrInst>(Usr)) |
| 6467 | return false; |
| 6468 | auto *UGEPI = cast<GetElementPtrInst>(Usr); |
| 6469 | // Check if UGEPI is a simple gep with a single constant index and GEPIOp is |
| 6470 | // the pointer operand to it. If so, record it in the vector. If not, give |
| 6471 | // up. |
| 6472 | if (!GEPSequentialConstIndexed(UGEPI)) |
| 6473 | return false; |
| 6474 | if (UGEPI->getOperand(0) != GEPIOp) |
| 6475 | return false; |
| 6476 | if (GEPIIdx->getType() != |
| 6477 | cast<ConstantInt>(UGEPI->getOperand(1))->getType()) |
| 6478 | return false; |
| 6479 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); |
| 6480 | if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType()) |
| 6481 | > TargetTransformInfo::TCC_Basic) |
| 6482 | return false; |
| 6483 | UGEPIs.push_back(UGEPI); |
| 6484 | } |
| 6485 | if (UGEPIs.size() == 0) |
| 6486 | return false; |
| 6487 | // Check the materializing cost of (Uidx-Idx). |
| 6488 | for (GetElementPtrInst *UGEPI : UGEPIs) { |
| 6489 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); |
| 6490 | APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue(); |
| 6491 | unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType()); |
| 6492 | if (ImmCost > TargetTransformInfo::TCC_Basic) |
| 6493 | return false; |
| 6494 | } |
| 6495 | // Now unmerge between GEPI and UGEPIs. |
| 6496 | for (GetElementPtrInst *UGEPI : UGEPIs) { |
| 6497 | UGEPI->setOperand(0, GEPI); |
| 6498 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); |
| 6499 | Constant *NewUGEPIIdx = |
| 6500 | ConstantInt::get(GEPIIdx->getType(), |
| 6501 | UGEPIIdx->getValue() - GEPIIdx->getValue()); |
| 6502 | UGEPI->setOperand(1, NewUGEPIIdx); |
| 6503 | // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not |
| 6504 | // inbounds to avoid UB. |
| 6505 | if (!GEPI->isInBounds()) { |
| 6506 | UGEPI->setIsInBounds(false); |
| 6507 | } |
| 6508 | } |
| 6509 | // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not |
| 6510 | // alive on IndirectBr edges). |
| 6511 | assert(find_if(GEPIOp->users(), [&](User *Usr) { |
| 6512 | return cast<Instruction>(Usr)->getParent() != SrcBlock; |
| 6513 | }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock"); |
| 6514 | return true; |
| 6515 | } |
| 6516 | |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 6517 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 6518 | // Bail out if we inserted the instruction to prevent optimizations from |
| 6519 | // stepping on each other's toes. |
| 6520 | if (InsertedInsts.count(I)) |
| 6521 | return false; |
| 6522 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6523 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 6524 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 6525 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 6526 | // trivial PHI, go ahead and zap it here. |
Daniel Berlin | 4d0fe64 | 2017-04-28 19:55:38 +0000 | [diff] [blame] | 6527 | if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6528 | P->replaceAllUsesWith(V); |
| 6529 | P->eraseFromParent(); |
| 6530 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6531 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6532 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6533 | return false; |
| 6534 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6535 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6536 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6537 | // If the source of the cast is a constant, then this should have |
| 6538 | // already been constant folded. The only reason NOT to constant fold |
| 6539 | // it is if something (e.g. LSR) was careful to place the constant |
| 6540 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 6541 | // the address of globals out of a loop). If this is the case, we don't |
| 6542 | // want to forward-subst the cast. |
| 6543 | if (isa<Constant>(CI->getOperand(0))) |
| 6544 | return false; |
| 6545 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6546 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6547 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6548 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6549 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6550 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 6551 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6552 | if (TLI && |
| 6553 | TLI->getTypeAction(CI->getContext(), |
| 6554 | TLI->getValueType(*DL, CI->getType())) == |
| 6555 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6556 | return SinkCast(CI); |
| 6557 | } else { |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 6558 | bool MadeChange = optimizeExt(I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6559 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6560 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6561 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6562 | return false; |
| 6563 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6564 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6565 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 6566 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 6567 | return OptimizeCmpExpression(CI, TLI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6568 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6569 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 6570 | LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6571 | if (TLI) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 6572 | bool Modified = optimizeLoadExt(LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6573 | unsigned AS = LI->getPointerAddressSpace(); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 6574 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 6575 | return Modified; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6576 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 6577 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6578 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6579 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6580 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6581 | if (TLI && splitMergedValStore(*SI, *DL, *TLI)) |
| 6582 | return true; |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 6583 | SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6584 | if (TLI) { |
| 6585 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6586 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6587 | SI->getOperand(0)->getType(), AS); |
| 6588 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6589 | return false; |
| 6590 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6591 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 6592 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { |
| 6593 | unsigned AS = RMW->getPointerAddressSpace(); |
| 6594 | return optimizeMemoryInst(I, RMW->getPointerOperand(), |
| 6595 | RMW->getType(), AS); |
| 6596 | } |
| 6597 | |
| 6598 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { |
| 6599 | unsigned AS = CmpX->getPointerAddressSpace(); |
| 6600 | return optimizeMemoryInst(I, CmpX->getPointerOperand(), |
| 6601 | CmpX->getCompareOperand()->getType(), AS); |
| 6602 | } |
| 6603 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6604 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 6605 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 6606 | if (BinOp && (BinOp->getOpcode() == Instruction::And) && |
| 6607 | EnableAndCmpSinking && TLI) |
| 6608 | return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts); |
| 6609 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6610 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 6611 | BinOp->getOpcode() == Instruction::LShr)) { |
| 6612 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 6613 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6614 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6615 | |
| 6616 | return false; |
| 6617 | } |
| 6618 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6619 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6620 | if (GEPI->hasAllZeroIndices()) { |
| 6621 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 6622 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 6623 | GEPI->getName(), GEPI); |
Vedant Kumar | 40399a2 | 2018-05-24 23:00:21 +0000 | [diff] [blame] | 6624 | NC->setDebugLoc(GEPI->getDebugLoc()); |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6625 | GEPI->replaceAllUsesWith(NC); |
| 6626 | GEPI->eraseFromParent(); |
| 6627 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6628 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6629 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6630 | } |
Hiroshi Yamauchi | 9364432 | 2017-09-11 17:52:08 +0000 | [diff] [blame] | 6631 | if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) { |
| 6632 | return true; |
| 6633 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6634 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6635 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6636 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6637 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6638 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6639 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 6640 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6641 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 6642 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 6643 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6644 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 6645 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 6646 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 6647 | return optimizeSwitchInst(Switch); |
| 6648 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6649 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6650 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6651 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6652 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6653 | } |
| 6654 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6655 | /// Given an OR instruction, check to see if this is a bitreverse |
| 6656 | /// idiom. If so, insert the new intrinsic and return true. |
| 6657 | static bool makeBitReverse(Instruction &I, const DataLayout &DL, |
| 6658 | const TargetLowering &TLI) { |
| 6659 | if (!I.getType()->isIntegerTy() || |
| 6660 | !TLI.isOperationLegalOrCustom(ISD::BITREVERSE, |
| 6661 | TLI.getValueType(DL, I.getType(), true))) |
| 6662 | return false; |
| 6663 | |
| 6664 | SmallVector<Instruction*, 4> Insts; |
Chad Rosier | a00df49 | 2016-05-25 16:22:14 +0000 | [diff] [blame] | 6665 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6666 | return false; |
| 6667 | Instruction *LastInst = Insts.back(); |
| 6668 | I.replaceAllUsesWith(LastInst); |
| 6669 | RecursivelyDeleteTriviallyDeadInstructions(&I); |
| 6670 | return true; |
| 6671 | } |
| 6672 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 6673 | // In this pass we look for GEP and cast instructions that are used |
| 6674 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 6675 | // selection. |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 6676 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 6677 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 6678 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 6679 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 6680 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 6681 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 6682 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 6683 | if (ModifiedDT) |
| 6684 | return true; |
| 6685 | } |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 6686 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6687 | bool MadeBitReverse = true; |
| 6688 | while (TLI && MadeBitReverse) { |
| 6689 | MadeBitReverse = false; |
| 6690 | for (auto &I : reverse(BB)) { |
| 6691 | if (makeBitReverse(I, *DL, *TLI)) { |
| 6692 | MadeBitReverse = MadeChange = true; |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 6693 | ModifiedDT = true; |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6694 | break; |
| 6695 | } |
| 6696 | } |
| 6697 | } |
James Molloy | 3ef84c4 | 2016-01-15 10:36:01 +0000 | [diff] [blame] | 6698 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Junmo Park | 7d6c5f1 | 2016-01-28 09:42:39 +0000 | [diff] [blame] | 6699 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 6700 | return MadeChange; |
| 6701 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6702 | |
| 6703 | // 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] | 6704 | // 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] | 6705 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6706 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6707 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 6708 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 6709 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 6710 | 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] | 6711 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6712 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 6713 | // Leave dbg.values that refer to an alloca alone. These |
Craig Topper | 87e715f | 2017-11-07 20:56:17 +0000 | [diff] [blame] | 6714 | // intrinsics describe the address of a variable (= the alloca) |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 6715 | // being taken. They should not be moved next to the alloca |
| 6716 | // (and to the beginning of the scope), but rather stay close to |
| 6717 | // where said address is used. |
| 6718 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6719 | PrevNonDbgInst = Insn; |
| 6720 | continue; |
| 6721 | } |
| 6722 | |
| 6723 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 6724 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
Reid Kleckner | 8de1fe2 | 2015-12-08 23:00:03 +0000 | [diff] [blame] | 6725 | // If VI is a phi in a block with an EHPad terminator, we can't insert |
| 6726 | // after it. |
| 6727 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) |
| 6728 | continue; |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6729 | LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n" |
| 6730 | << *DVI << ' ' << *VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6731 | DVI->removeFromParent(); |
Reid Kleckner | e18f92b | 2015-12-08 22:33:23 +0000 | [diff] [blame] | 6732 | if (isa<PHINode>(VI)) |
| 6733 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
| 6734 | else |
| 6735 | DVI->insertAfter(VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6736 | MadeChange = true; |
| 6737 | ++NumDbgValueMoved; |
| 6738 | } |
| 6739 | } |
| 6740 | } |
| 6741 | return MadeChange; |
| 6742 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 6743 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6744 | /// Scale down both weights to fit into uint32_t. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6745 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 6746 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 6747 | uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1; |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6748 | NewTrue = NewTrue / Scale; |
| 6749 | NewFalse = NewFalse / Scale; |
| 6750 | } |
| 6751 | |
Adrian Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 6752 | /// Some targets prefer to split a conditional branch like: |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6753 | /// \code |
| 6754 | /// %0 = icmp ne i32 %a, 0 |
| 6755 | /// %1 = icmp ne i32 %b, 0 |
| 6756 | /// %or.cond = or i1 %0, %1 |
| 6757 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 6758 | /// \endcode |
| 6759 | /// into multiple branch instructions like: |
| 6760 | /// \code |
| 6761 | /// bb1: |
| 6762 | /// %0 = icmp ne i32 %a, 0 |
| 6763 | /// br i1 %0, label %TrueBB, label %bb2 |
| 6764 | /// bb2: |
| 6765 | /// %1 = icmp ne i32 %b, 0 |
| 6766 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 6767 | /// \endcode |
| 6768 | /// This usually allows instruction selection to do even further optimizations |
| 6769 | /// and combine the compare with the branch instruction. Currently this is |
| 6770 | /// applied for targets which have "cheap" jump instructions. |
| 6771 | /// |
| 6772 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 6773 | /// |
| 6774 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 6775 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6776 | return false; |
| 6777 | |
| 6778 | bool MadeChange = false; |
| 6779 | for (auto &BB : F) { |
| 6780 | // Does this BB end with the following? |
| 6781 | // %cond1 = icmp|fcmp|binary instruction ... |
| 6782 | // %cond2 = icmp|fcmp|binary instruction ... |
| 6783 | // %cond.or = or|and i1 %cond1, cond2 |
| 6784 | // br i1 %cond.or label %dest1, label %dest2" |
| 6785 | BinaryOperator *LogicOp; |
| 6786 | BasicBlock *TBB, *FBB; |
| 6787 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 6788 | continue; |
| 6789 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 6790 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 6791 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 6792 | continue; |
| 6793 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6794 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6795 | Value *Cond1, *Cond2; |
| 6796 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 6797 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6798 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6799 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 6800 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6801 | Opc = Instruction::Or; |
| 6802 | else |
| 6803 | continue; |
| 6804 | |
| 6805 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 6806 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 6807 | continue; |
| 6808 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6809 | LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6810 | |
| 6811 | // Create a new BB. |
Duncan P. N. Exon Smith | a848c47 | 2016-02-21 19:52:15 +0000 | [diff] [blame] | 6812 | auto TmpBB = |
| 6813 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", |
| 6814 | BB.getParent(), BB.getNextNode()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6815 | |
| 6816 | // Update original basic block by using the first condition directly by the |
| 6817 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6818 | Br1->setCondition(Cond1); |
| 6819 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6820 | |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 6821 | // Depending on the condition we have to either replace the true or the |
| 6822 | // false successor of the original branch instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6823 | if (Opc == Instruction::And) |
| 6824 | Br1->setSuccessor(0, TmpBB); |
| 6825 | else |
| 6826 | Br1->setSuccessor(1, TmpBB); |
| 6827 | |
| 6828 | // Fill in the new basic block. |
| 6829 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6830 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 6831 | I->removeFromParent(); |
| 6832 | I->insertBefore(Br2); |
| 6833 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6834 | |
| 6835 | // Update PHI nodes in both successors. The original BB needs to be |
Hiroshi Inoue | 6a391bb | 2017-06-27 10:35:37 +0000 | [diff] [blame] | 6836 | // replaced in one successor's PHI nodes, because the branch comes now from |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6837 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 6838 | // incoming edge to the PHI nodes, because both branch instructions target |
| 6839 | // now the same successor. Depending on the original branch condition |
| 6840 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 6841 | // we perform the correct update for the PHI nodes. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6842 | // This doesn't change the successor order of the just created branch |
| 6843 | // instruction (or any other instruction). |
| 6844 | if (Opc == Instruction::Or) |
| 6845 | std::swap(TBB, FBB); |
| 6846 | |
| 6847 | // Replace the old BB with the new BB. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 6848 | for (PHINode &PN : TBB->phis()) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6849 | int i; |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 6850 | while ((i = PN.getBasicBlockIndex(&BB)) >= 0) |
| 6851 | PN.setIncomingBlock(i, TmpBB); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6852 | } |
| 6853 | |
| 6854 | // Add another incoming edge form the new BB. |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 6855 | for (PHINode &PN : FBB->phis()) { |
| 6856 | auto *Val = PN.getIncomingValueForBlock(&BB); |
| 6857 | PN.addIncoming(Val, TmpBB); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6858 | } |
| 6859 | |
| 6860 | // Update the branch weights (from SelectionDAGBuilder:: |
| 6861 | // FindMergedConditions). |
| 6862 | if (Opc == Instruction::Or) { |
| 6863 | // Codegen X | Y as: |
| 6864 | // BB1: |
| 6865 | // jmp_if_X TBB |
| 6866 | // jmp TmpBB |
| 6867 | // TmpBB: |
| 6868 | // jmp_if_Y TBB |
| 6869 | // jmp FBB |
| 6870 | // |
| 6871 | |
| 6872 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 6873 | // The requirement is that |
| 6874 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 6875 | // = TrueProb for original BB. |
| 6876 | // Assuming the original weights are A and B, one choice is to set BB1's |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6877 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 6878 | // assumes that |
| 6879 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 6880 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 6881 | // TmpBB, but the math is more complicated. |
| 6882 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6883 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6884 | uint64_t NewTrueWeight = TrueWeight; |
| 6885 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 6886 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6887 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6888 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6889 | |
| 6890 | NewTrueWeight = TrueWeight; |
| 6891 | NewFalseWeight = 2 * FalseWeight; |
| 6892 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6893 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6894 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6895 | } |
| 6896 | } else { |
| 6897 | // Codegen X & Y as: |
| 6898 | // BB1: |
| 6899 | // jmp_if_X TmpBB |
| 6900 | // jmp FBB |
| 6901 | // TmpBB: |
| 6902 | // jmp_if_Y TBB |
| 6903 | // jmp FBB |
| 6904 | // |
| 6905 | // This requires creation of TmpBB after CurBB. |
| 6906 | |
| 6907 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 6908 | // The requirement is that |
| 6909 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
Hiroshi Inoue | c73b6d6 | 2018-06-20 05:29:26 +0000 | [diff] [blame] | 6910 | // = FalseProb for original BB. |
| 6911 | // Assuming the original weights are A and B, one choice is to set BB1's |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6912 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 6913 | // assumes that |
| 6914 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 6915 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6916 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6917 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 6918 | uint64_t NewFalseWeight = FalseWeight; |
| 6919 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6920 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6921 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6922 | |
| 6923 | NewTrueWeight = 2 * TrueWeight; |
| 6924 | NewFalseWeight = FalseWeight; |
| 6925 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6926 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6927 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6928 | } |
| 6929 | } |
| 6930 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6931 | // 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] | 6932 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6933 | ModifiedDT = true; |
| 6934 | |
| 6935 | MadeChange = true; |
| 6936 | |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 6937 | LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 6938 | TmpBB->dump()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6939 | } |
| 6940 | return MadeChange; |
| 6941 | } |