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" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 21 | #include "llvm/ADT/SetVector.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 22 | #include "llvm/ADT/SmallPtrSet.h" |
| 23 | #include "llvm/ADT/SmallVector.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 24 | #include "llvm/ADT/Statistic.h" |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/BlockFrequencyInfo.h" |
| 26 | #include "llvm/Analysis/BranchProbabilityInfo.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/ConstantFolding.h" |
Chandler Carruth | ed0881b | 2012-12-03 16:50:05 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/InstructionSimplify.h" |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/LoopInfo.h" |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 30 | #include "llvm/Analysis/MemoryBuiltins.h" |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 31 | #include "llvm/Analysis/ProfileSummaryInfo.h" |
Chandler Carruth | 62d4215 | 2015-01-15 02:16:27 +0000 | [diff] [blame] | 32 | #include "llvm/Analysis/TargetLibraryInfo.h" |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 33 | #include "llvm/Analysis/TargetTransformInfo.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" |
| 37 | #include "llvm/CodeGen/MachineValueType.h" |
| 38 | #include "llvm/CodeGen/SelectionDAGNodes.h" |
David Blaikie | b3bde2e | 2017-11-17 01:07:10 +0000 | [diff] [blame] | 39 | #include "llvm/CodeGen/TargetLowering.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 40 | #include "llvm/CodeGen/TargetPassConfig.h" |
David Blaikie | b3bde2e | 2017-11-17 01:07:10 +0000 | [diff] [blame] | 41 | #include "llvm/CodeGen/TargetSubtargetInfo.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 42 | #include "llvm/CodeGen/ValueTypes.h" |
| 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" |
| 83 | #include "llvm/Support/MathExtras.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 84 | #include "llvm/Support/raw_ostream.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 85 | #include "llvm/Target/TargetMachine.h" |
| 86 | #include "llvm/Target/TargetOptions.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 87 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 88 | #include "llvm/Transforms/Utils/BypassSlowDivision.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 89 | #include "llvm/Transforms/Utils/Cloning.h" |
Chandler Carruth | aafe091 | 2012-06-29 12:38:19 +0000 | [diff] [blame] | 90 | #include "llvm/Transforms/Utils/Local.h" |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 91 | #include "llvm/Transforms/Utils/SimplifyLibCalls.h" |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 92 | #include "llvm/Transforms/Utils/ValueMapper.h" |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 93 | #include <algorithm> |
| 94 | #include <cassert> |
| 95 | #include <cstdint> |
| 96 | #include <iterator> |
| 97 | #include <limits> |
| 98 | #include <memory> |
| 99 | #include <utility> |
| 100 | #include <vector> |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 101 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 102 | using namespace llvm; |
Chris Lattner | d616ef5 | 2008-11-25 04:42:10 +0000 | [diff] [blame] | 103 | using namespace llvm::PatternMatch; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 104 | |
Chandler Carruth | 1b9dde0 | 2014-04-22 02:02:50 +0000 | [diff] [blame] | 105 | #define DEBUG_TYPE "codegenprepare" |
| 106 | |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 107 | STATISTIC(NumBlocksElim, "Number of blocks eliminated"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 108 | STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated"); |
| 109 | STATISTIC(NumGEPsElim, "Number of GEPs converted to casts"); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 110 | STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of " |
| 111 | "sunken Cmps"); |
| 112 | STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses " |
| 113 | "of sunken Casts"); |
| 114 | STATISTIC(NumMemoryInsts, "Number of memory instructions whose address " |
| 115 | "computations were sunk"); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 116 | STATISTIC(NumMemoryInstsPhiCreated, |
| 117 | "Number of phis created when address " |
| 118 | "computations were sunk to memory instructions"); |
| 119 | STATISTIC(NumMemoryInstsSelectCreated, |
| 120 | "Number of select created when address " |
| 121 | "computations were sunk to memory instructions"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 122 | STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads"); |
| 123 | STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized"); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 124 | STATISTIC(NumAndsAdded, |
| 125 | "Number of and mask instructions added to form ext loads"); |
| 126 | STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized"); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 127 | STATISTIC(NumRetsDup, "Number of return instructions duplicated"); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 128 | STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 129 | STATISTIC(NumSelectsExpanded, "Number of selects turned into branches"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 130 | STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed"); |
Jakob Stoklund Olesen | eb12f49 | 2010-09-30 20:51:52 +0000 | [diff] [blame] | 131 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 132 | static cl::opt<bool> DisableBranchOpts( |
| 133 | "disable-cgp-branch-opts", cl::Hidden, cl::init(false), |
| 134 | cl::desc("Disable branch optimizations in CodeGenPrepare")); |
| 135 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 136 | static cl::opt<bool> |
| 137 | DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false), |
| 138 | cl::desc("Disable GC optimizations in CodeGenPrepare")); |
| 139 | |
Benjamin Kramer | 3d38c17 | 2012-05-06 14:25:16 +0000 | [diff] [blame] | 140 | static cl::opt<bool> DisableSelectToBranch( |
| 141 | "disable-cgp-select2branch", cl::Hidden, cl::init(false), |
| 142 | cl::desc("Disable select to branch conversion.")); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 143 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 144 | static cl::opt<bool> AddrSinkUsingGEPs( |
Eli Friedman | 5fba1e5 | 2017-04-06 22:42:18 +0000 | [diff] [blame] | 145 | "addr-sink-using-gep", cl::Hidden, cl::init(true), |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 146 | cl::desc("Address sinking in CGP using GEPs.")); |
| 147 | |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 148 | static cl::opt<bool> EnableAndCmpSinking( |
| 149 | "enable-andcmp-sinking", cl::Hidden, cl::init(true), |
| 150 | cl::desc("Enable sinkinig and/cmp into branches.")); |
| 151 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 152 | static cl::opt<bool> DisableStoreExtract( |
| 153 | "disable-cgp-store-extract", cl::Hidden, cl::init(false), |
| 154 | cl::desc("Disable store(extract) optimizations in CodeGenPrepare")); |
| 155 | |
| 156 | static cl::opt<bool> StressStoreExtract( |
| 157 | "stress-cgp-store-extract", cl::Hidden, cl::init(false), |
| 158 | cl::desc("Stress test store(extract) optimizations in CodeGenPrepare")); |
| 159 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 160 | static cl::opt<bool> DisableExtLdPromotion( |
| 161 | "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 162 | cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in " |
| 163 | "CodeGenPrepare")); |
| 164 | |
| 165 | static cl::opt<bool> StressExtLdPromotion( |
| 166 | "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false), |
| 167 | cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) " |
| 168 | "optimization in CodeGenPrepare")); |
| 169 | |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 170 | static cl::opt<bool> DisablePreheaderProtect( |
| 171 | "disable-preheader-prot", cl::Hidden, cl::init(false), |
| 172 | cl::desc("Disable protection against removing loop preheaders")); |
| 173 | |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 174 | static cl::opt<bool> ProfileGuidedSectionPrefix( |
David Callahan | 5960d9b1 | 2017-06-14 20:35:33 +0000 | [diff] [blame] | 175 | "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore, |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 176 | cl::desc("Use profile info to add section prefix for hot/cold functions")); |
| 177 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 178 | static cl::opt<unsigned> FreqRatioToSkipMerge( |
| 179 | "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2), |
| 180 | cl::desc("Skip merging empty blocks if (frequency of empty block) / " |
| 181 | "(frequency of destination block) is greater than this ratio")); |
| 182 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 183 | static cl::opt<bool> ForceSplitStore( |
| 184 | "force-split-store", cl::Hidden, cl::init(false), |
| 185 | cl::desc("Force store splitting no matter what the target query says.")); |
| 186 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 187 | static cl::opt<bool> |
| 188 | EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden, |
| 189 | cl::desc("Enable merging of redundant sexts when one is dominating" |
| 190 | " the other."), cl::init(true)); |
| 191 | |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 192 | static cl::opt<bool> DisableComplexAddrModes( |
Serguei Katkov | d4df744 | 2017-11-29 09:48:50 +0000 | [diff] [blame^] | 193 | "disable-complex-addr-modes", cl::Hidden, cl::init(false), |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 194 | cl::desc("Disables combining addressing modes with different parts " |
| 195 | "in optimizeMemoryInst.")); |
| 196 | |
| 197 | static cl::opt<bool> |
| 198 | AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false), |
| 199 | cl::desc("Allow creation of Phis in Address sinking.")); |
| 200 | |
| 201 | static cl::opt<bool> |
Serguei Katkov | 3652002 | 2017-11-07 09:43:08 +0000 | [diff] [blame] | 202 | AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(false), |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 203 | cl::desc("Allow creation of selects in Address sinking.")); |
| 204 | |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 205 | static cl::opt<bool> AddrSinkCombineBaseReg( |
| 206 | "addr-sink-combine-base-reg", cl::Hidden, cl::init(true), |
| 207 | cl::desc("Allow combining of BaseReg field in Address sinking.")); |
| 208 | |
| 209 | static cl::opt<bool> AddrSinkCombineBaseGV( |
| 210 | "addr-sink-combine-base-gv", cl::Hidden, cl::init(true), |
| 211 | cl::desc("Allow combining of BaseGV field in Address sinking.")); |
| 212 | |
| 213 | static cl::opt<bool> AddrSinkCombineBaseOffs( |
| 214 | "addr-sink-combine-base-offs", cl::Hidden, cl::init(true), |
| 215 | cl::desc("Allow combining of BaseOffs field in Address sinking.")); |
| 216 | |
| 217 | static cl::opt<bool> AddrSinkCombineScaledReg( |
| 218 | "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true), |
| 219 | cl::desc("Allow combining of ScaledReg field in Address sinking.")); |
| 220 | |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 221 | namespace { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 222 | |
| 223 | using SetOfInstrs = SmallPtrSet<Instruction *, 16>; |
| 224 | using TypeIsSExt = PointerIntPair<Type *, 1, bool>; |
| 225 | using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>; |
| 226 | using SExts = SmallVector<Instruction *, 16>; |
| 227 | using ValueToSExts = DenseMap<Value *, SExts>; |
| 228 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 229 | class TypePromotionTransaction; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 230 | |
Chris Lattner | 2dd09db | 2009-09-02 06:11:42 +0000 | [diff] [blame] | 231 | class CodeGenPrepare : public FunctionPass { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 232 | const TargetMachine *TM = nullptr; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 233 | const TargetSubtargetInfo *SubtargetInfo; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 234 | const TargetLowering *TLI = nullptr; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 235 | const TargetRegisterInfo *TRI; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 236 | const TargetTransformInfo *TTI = nullptr; |
Chad Rosier | c24b86f | 2011-12-01 03:08:23 +0000 | [diff] [blame] | 237 | const TargetLibraryInfo *TLInfo; |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 238 | const LoopInfo *LI; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 239 | std::unique_ptr<BlockFrequencyInfo> BFI; |
| 240 | std::unique_ptr<BranchProbabilityInfo> BPI; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 241 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 242 | /// As we scan instructions optimizing them, this is the next instruction |
| 243 | /// to optimize. Transforms that can invalidate this should update it. |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 244 | BasicBlock::iterator CurInstIterator; |
Evan Cheng | 3b3de7c | 2008-12-19 18:03:11 +0000 | [diff] [blame] | 245 | |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 246 | /// Keeps track of non-local addresses that have been sunk into a block. |
| 247 | /// This allows us to avoid inserting duplicate code for blocks with |
Simon Dardis | 230f453 | 2017-11-24 16:45:28 +0000 | [diff] [blame] | 248 | /// multiple load/stores of the same address. The usage of WeakTrackingVH |
| 249 | /// enables SunkAddrs to be treated as a cache whose entries can be |
| 250 | /// invalidated if a sunken address computation has been erased. |
| 251 | ValueMap<Value*, WeakTrackingVH> SunkAddrs; |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 252 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 253 | /// Keeps track of all instructions inserted for the current function. |
| 254 | SetOfInstrs InsertedInsts; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 255 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 256 | /// Keeps track of the type of the related instruction before their |
| 257 | /// promotion for the current function. |
| 258 | InstrToOrigTy PromotedInsts; |
| 259 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 260 | /// Keep track of instructions removed during promotion. |
| 261 | SetOfInstrs RemovedInsts; |
| 262 | |
| 263 | /// Keep track of sext chains based on their initial value. |
| 264 | DenseMap<Value *, Instruction *> SeenChainsForSExt; |
| 265 | |
| 266 | /// Keep track of SExt promoted. |
| 267 | ValueToSExts ValToSExtendedUses; |
| 268 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 269 | /// True if CFG is modified in any way. |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 270 | bool ModifiedDT; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 271 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 272 | /// True if optimizing for size. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 273 | bool OptSize; |
| 274 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 275 | /// DataLayout for the Function being processed. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 276 | const DataLayout *DL = nullptr; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 277 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 278 | public: |
Nick Lewycky | e7da2d6 | 2007-05-06 13:37:16 +0000 | [diff] [blame] | 279 | static char ID; // Pass identification, replacement for typeid |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 280 | |
| 281 | CodeGenPrepare() : FunctionPass(ID) { |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 282 | initializeCodeGenPreparePass(*PassRegistry::getPassRegistry()); |
| 283 | } |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 284 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 285 | bool runOnFunction(Function &F) override; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 286 | |
Mehdi Amini | 117296c | 2016-10-01 02:56:57 +0000 | [diff] [blame] | 287 | StringRef getPassName() const override { return "CodeGen Prepare"; } |
Evan Cheng | 99cafb1 | 2012-12-21 01:48:14 +0000 | [diff] [blame] | 288 | |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 289 | void getAnalysisUsage(AnalysisUsage &AU) const override { |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 290 | // FIXME: When we can selectively preserve passes, preserve the domtree. |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 291 | AU.addRequired<ProfileSummaryInfoWrapperPass>(); |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 292 | AU.addRequired<TargetLibraryInfoWrapperPass>(); |
Chandler Carruth | 705b185 | 2015-01-31 03:43:40 +0000 | [diff] [blame] | 293 | AU.addRequired<TargetTransformInfoWrapperPass>(); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 294 | AU.addRequired<LoopInfoWrapperPass>(); |
Andreas Neustifter | f8cb758 | 2009-09-16 09:26:52 +0000 | [diff] [blame] | 295 | } |
| 296 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 297 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 298 | bool eliminateFallThrough(Function &F); |
| 299 | bool eliminateMostlyEmptyBlocks(Function &F); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 300 | BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 301 | bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const; |
| 302 | void eliminateMostlyEmptyBlock(BasicBlock *BB); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 303 | bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB, |
| 304 | bool isPreheader); |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 305 | bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT); |
| 306 | bool optimizeInst(Instruction *I, bool &ModifiedDT); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 307 | bool optimizeMemoryInst(Instruction *I, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 308 | Type *AccessTy, unsigned AS); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 309 | bool optimizeInlineAsmInst(CallInst *CS); |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 310 | bool optimizeCallInst(CallInst *CI, bool &ModifiedDT); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 311 | bool optimizeExt(Instruction *&I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 312 | bool optimizeExtUses(Instruction *I); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 313 | bool optimizeLoadExt(LoadInst *I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 314 | bool optimizeSelectInst(SelectInst *SI); |
| 315 | bool optimizeShuffleVectorInst(ShuffleVectorInst *SI); |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 316 | bool optimizeSwitchInst(SwitchInst *CI); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 317 | bool optimizeExtractElementInst(Instruction *Inst); |
| 318 | bool dupRetToEnableTailCallOpts(BasicBlock *BB); |
| 319 | bool placeDbgValues(Function &F); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 320 | bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts, |
| 321 | LoadInst *&LI, Instruction *&Inst, bool HasPromoted); |
| 322 | bool tryToPromoteExts(TypePromotionTransaction &TPT, |
| 323 | const SmallVectorImpl<Instruction *> &Exts, |
| 324 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 325 | unsigned CreatedInstsCost = 0); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 326 | bool mergeSExts(Function &F); |
| 327 | bool performAddressTypePromotion( |
| 328 | Instruction *&Inst, |
| 329 | bool AllowPromotionWithoutCommonHeader, |
| 330 | bool HasPromoted, TypePromotionTransaction &TPT, |
| 331 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 332 | bool splitBranchCondition(Function &F); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 333 | bool simplifyOffsetableRelocate(Instruction &I); |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 334 | bool splitIndirectCriticalEdges(Function &F); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 335 | }; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 336 | |
| 337 | } // end anonymous namespace |
Devang Patel | 09f162c | 2007-05-01 21:15:47 +0000 | [diff] [blame] | 338 | |
Devang Patel | 8c78a0b | 2007-05-03 01:11:54 +0000 | [diff] [blame] | 339 | char CodeGenPrepare::ID = 0; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 340 | |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 341 | INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE, |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 342 | "Optimize for code generation", false, false) |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 343 | INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) |
Matthias Braun | 1527baa | 2017-05-25 21:26:32 +0000 | [diff] [blame] | 344 | INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 345 | "Optimize for code generation", false, false) |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 346 | |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 347 | FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); } |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 348 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 349 | bool CodeGenPrepare::runOnFunction(Function &F) { |
Andrew Kaylor | aa641a5 | 2016-04-22 22:06:11 +0000 | [diff] [blame] | 350 | if (skipFunction(F)) |
Paul Robinson | 7c99ec5 | 2014-03-31 17:43:35 +0000 | [diff] [blame] | 351 | return false; |
| 352 | |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 353 | DL = &F.getParent()->getDataLayout(); |
| 354 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 355 | bool EverMadeChange = false; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 356 | // Clear per function information. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 357 | InsertedInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 358 | PromotedInsts.clear(); |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 359 | BFI.reset(); |
| 360 | BPI.reset(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 361 | |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 362 | ModifiedDT = false; |
Francis Visoiu Mistrih | 8b61764 | 2017-05-18 17:21:13 +0000 | [diff] [blame] | 363 | if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) { |
| 364 | TM = &TPC->getTM<TargetMachine>(); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 365 | SubtargetInfo = TM->getSubtargetImpl(F); |
| 366 | TLI = SubtargetInfo->getTargetLowering(); |
| 367 | TRI = SubtargetInfo->getRegisterInfo(); |
| 368 | } |
Chandler Carruth | b98f63d | 2015-01-15 10:41:28 +0000 | [diff] [blame] | 369 | TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); |
Chandler Carruth | fdb9c57 | 2015-02-01 12:01:35 +0000 | [diff] [blame] | 370 | TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 371 | LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); |
Sanjay Patel | 82d91dd | 2015-08-11 19:39:36 +0000 | [diff] [blame] | 372 | OptSize = F.optForSize(); |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 373 | |
Easwaran Raman | 0d55b55 | 2017-11-14 19:31:51 +0000 | [diff] [blame] | 374 | ProfileSummaryInfo *PSI = |
| 375 | getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 376 | if (ProfileGuidedSectionPrefix) { |
Dehao Chen | 775341a | 2017-03-23 23:14:11 +0000 | [diff] [blame] | 377 | if (PSI->isFunctionHotInCallGraph(&F)) |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 378 | F.setSectionPrefix(".hot"); |
Dehao Chen | 775341a | 2017-03-23 23:14:11 +0000 | [diff] [blame] | 379 | else if (PSI->isFunctionColdInCallGraph(&F)) |
Teresa Johnson | 720d9b4 | 2017-05-09 01:43:24 +0000 | [diff] [blame] | 380 | F.setSectionPrefix(".unlikely"); |
Dehao Chen | 302b69c | 2016-10-18 20:42:47 +0000 | [diff] [blame] | 381 | } |
| 382 | |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 383 | /// This optimization identifies DIV instructions that can be |
| 384 | /// profitably bypassed and carried out with a shorter, faster divide. |
Easwaran Raman | 0d55b55 | 2017-11-14 19:31:51 +0000 | [diff] [blame] | 385 | if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI && |
| 386 | TLI->isSlowDivBypassed()) { |
Preston Gurd | 0d67f51 | 2012-10-04 21:33:40 +0000 | [diff] [blame] | 387 | const DenseMap<unsigned int, unsigned int> &BypassWidths = |
| 388 | TLI->getBypassSlowDivWidths(); |
Eric Christopher | 49a7d6c | 2016-01-04 23:18:58 +0000 | [diff] [blame] | 389 | BasicBlock* BB = &*F.begin(); |
| 390 | while (BB != nullptr) { |
| 391 | // bypassSlowDivision may create new BBs, but we don't want to reapply the |
| 392 | // optimization to those blocks. |
| 393 | BasicBlock* Next = BB->getNextNode(); |
| 394 | EverMadeChange |= bypassSlowDivision(BB, BypassWidths); |
| 395 | BB = Next; |
| 396 | } |
Preston Gurd | cdf540d | 2012-09-04 18:22:17 +0000 | [diff] [blame] | 397 | } |
| 398 | |
| 399 | // Eliminate blocks that contain only PHI nodes and an |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 400 | // unconditional branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 401 | EverMadeChange |= eliminateMostlyEmptyBlocks(F); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 402 | |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 403 | // 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] | 404 | // 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] | 405 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 406 | EverMadeChange |= placeDbgValues(F); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 407 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 408 | if (!DisableBranchOpts) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 409 | EverMadeChange |= splitBranchCondition(F); |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 410 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 411 | // Split some critical edges where one of the sources is an indirect branch, |
| 412 | // to help generate sane code for PHIs involving such edges. |
| 413 | EverMadeChange |= splitIndirectCriticalEdges(F); |
| 414 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 415 | bool MadeChange = true; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 416 | while (MadeChange) { |
| 417 | MadeChange = false; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 418 | SeenChainsForSExt.clear(); |
| 419 | ValToSExtendedUses.clear(); |
| 420 | RemovedInsts.clear(); |
Hans Wennborg | 02fbc71 | 2012-09-19 07:48:16 +0000 | [diff] [blame] | 421 | for (Function::iterator I = F.begin(); I != F.end(); ) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 422 | BasicBlock *BB = &*I++; |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 423 | bool ModifiedDTOnIteration = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 424 | MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 425 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 426 | // Restart BB iteration if the dominator tree of the Function was changed |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 427 | if (ModifiedDTOnIteration) |
| 428 | break; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 429 | } |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 430 | if (EnableTypePromotionMerge && !ValToSExtendedUses.empty()) |
| 431 | MadeChange |= mergeSExts(F); |
| 432 | |
| 433 | // Really free removed instructions during promotion. |
| 434 | for (Instruction *I : RemovedInsts) |
Reid Kleckner | 96ab872 | 2017-05-18 17:24:10 +0000 | [diff] [blame] | 435 | I->deleteValue(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 436 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 437 | EverMadeChange |= MadeChange; |
| 438 | } |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 439 | |
| 440 | SunkAddrs.clear(); |
| 441 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 442 | if (!DisableBranchOpts) { |
| 443 | MadeChange = false; |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 444 | SmallPtrSet<BasicBlock*, 8> WorkList; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 445 | for (BasicBlock &BB : F) { |
| 446 | SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB)); |
| 447 | MadeChange |= ConstantFoldTerminator(&BB, true); |
Bill Wendling | 97b9359 | 2012-03-04 10:46:01 +0000 | [diff] [blame] | 448 | if (!MadeChange) continue; |
| 449 | |
| 450 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 451 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 452 | if (pred_begin(*II) == pred_end(*II)) |
| 453 | WorkList.insert(*II); |
| 454 | } |
| 455 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 456 | // Delete the dead blocks and any of their dead successors. |
Bill Wendling | ab417b6 | 2012-12-06 00:30:20 +0000 | [diff] [blame] | 457 | MadeChange |= !WorkList.empty(); |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 458 | while (!WorkList.empty()) { |
| 459 | BasicBlock *BB = *WorkList.begin(); |
| 460 | WorkList.erase(BB); |
| 461 | SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB)); |
| 462 | |
| 463 | DeleteDeadBlock(BB); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 464 | |
Bill Wendling | f3614fd | 2012-11-28 23:23:48 +0000 | [diff] [blame] | 465 | for (SmallVectorImpl<BasicBlock*>::iterator |
| 466 | II = Successors.begin(), IE = Successors.end(); II != IE; ++II) |
| 467 | if (pred_begin(*II) == pred_end(*II)) |
| 468 | WorkList.insert(*II); |
| 469 | } |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 470 | |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 471 | // Merge pairs of basic blocks with unconditional branches, connected by |
| 472 | // a single edge. |
| 473 | if (EverMadeChange || MadeChange) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 474 | MadeChange |= eliminateFallThrough(F); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 475 | |
Cameron Zwarich | 338d362 | 2011-03-11 21:52:04 +0000 | [diff] [blame] | 476 | EverMadeChange |= MadeChange; |
| 477 | } |
| 478 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 479 | if (!DisableGCOpts) { |
| 480 | SmallVector<Instruction *, 2> Statepoints; |
| 481 | for (BasicBlock &BB : F) |
| 482 | for (Instruction &I : BB) |
| 483 | if (isStatepoint(I)) |
| 484 | Statepoints.push_back(&I); |
| 485 | for (auto &I : Statepoints) |
| 486 | EverMadeChange |= simplifyOffsetableRelocate(*I); |
| 487 | } |
| 488 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 489 | return EverMadeChange; |
| 490 | } |
| 491 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 492 | /// Merge basic blocks which are connected by a single edge, where one of the |
| 493 | /// basic blocks has a single successor pointing to the other basic block, |
| 494 | /// which has a single predecessor. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 495 | bool CodeGenPrepare::eliminateFallThrough(Function &F) { |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 496 | bool Changed = false; |
| 497 | // Scan all of the blocks in the function, except for the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 498 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 499 | BasicBlock *BB = &*I++; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 500 | // If the destination block has a single pred, then this is a trivial |
| 501 | // edge, just collapse it. |
| 502 | BasicBlock *SinglePred = BB->getSinglePredecessor(); |
| 503 | |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 504 | // Don't merge if BB's address is taken. |
| 505 | if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue; |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 506 | |
| 507 | BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); |
| 508 | if (Term && !Term->isConditional()) { |
| 509 | Changed = true; |
Michael Liao | 6e12d12 | 2012-08-21 05:55:22 +0000 | [diff] [blame] | 510 | DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n"); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 511 | // Remember if SinglePred was the entry block of the function. |
| 512 | // If so, we will need to move BB back to the entry position. |
| 513 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Quentin Colombet | 7bdd50d | 2015-03-18 23:17:28 +0000 | [diff] [blame] | 514 | MergeBasicBlockIntoOnlyPred(BB, nullptr); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 515 | |
| 516 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 517 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
| 518 | |
| 519 | // We have erased a block. Update the iterator. |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 520 | I = BB->getIterator(); |
Nadav Rotem | 7040999 | 2012-08-14 05:19:07 +0000 | [diff] [blame] | 521 | } |
| 522 | } |
| 523 | return Changed; |
| 524 | } |
| 525 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 526 | /// Find a destination block from BB if BB is mergeable empty block. |
| 527 | BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) { |
| 528 | // If this block doesn't end with an uncond branch, ignore it. |
| 529 | BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()); |
| 530 | if (!BI || !BI->isUnconditional()) |
| 531 | return nullptr; |
| 532 | |
| 533 | // If the instruction before the branch (skipping debug info) isn't a phi |
| 534 | // node, then other stuff is happening here. |
| 535 | BasicBlock::iterator BBI = BI->getIterator(); |
| 536 | if (BBI != BB->begin()) { |
| 537 | --BBI; |
| 538 | while (isa<DbgInfoIntrinsic>(BBI)) { |
| 539 | if (BBI == BB->begin()) |
| 540 | break; |
| 541 | --BBI; |
| 542 | } |
| 543 | if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI)) |
| 544 | return nullptr; |
| 545 | } |
| 546 | |
| 547 | // Do not break infinite loops. |
| 548 | BasicBlock *DestBB = BI->getSuccessor(0); |
| 549 | if (DestBB == BB) |
| 550 | return nullptr; |
| 551 | |
| 552 | if (!canMergeBlocks(BB, DestBB)) |
| 553 | DestBB = nullptr; |
| 554 | |
| 555 | return DestBB; |
| 556 | } |
| 557 | |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 558 | // Return the unique indirectbr predecessor of a block. This may return null |
| 559 | // even if such a predecessor exists, if it's not useful for splitting. |
| 560 | // If a predecessor is found, OtherPreds will contain all other (non-indirectbr) |
| 561 | // predecessors of BB. |
| 562 | static BasicBlock * |
| 563 | findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) { |
| 564 | // If the block doesn't have any PHIs, we don't care about it, since there's |
| 565 | // no point in splitting it. |
| 566 | PHINode *PN = dyn_cast<PHINode>(BB->begin()); |
| 567 | if (!PN) |
| 568 | return nullptr; |
| 569 | |
| 570 | // Verify we have exactly one IBR predecessor. |
| 571 | // Conservatively bail out if one of the other predecessors is not a "regular" |
| 572 | // terminator (that is, not a switch or a br). |
| 573 | BasicBlock *IBB = nullptr; |
| 574 | for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) { |
| 575 | BasicBlock *PredBB = PN->getIncomingBlock(Pred); |
| 576 | TerminatorInst *PredTerm = PredBB->getTerminator(); |
| 577 | switch (PredTerm->getOpcode()) { |
| 578 | case Instruction::IndirectBr: |
| 579 | if (IBB) |
| 580 | return nullptr; |
| 581 | IBB = PredBB; |
| 582 | break; |
| 583 | case Instruction::Br: |
| 584 | case Instruction::Switch: |
| 585 | OtherPreds.push_back(PredBB); |
| 586 | continue; |
| 587 | default: |
| 588 | return nullptr; |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | return IBB; |
| 593 | } |
| 594 | |
| 595 | // Split critical edges where the source of the edge is an indirectbr |
| 596 | // instruction. This isn't always possible, but we can handle some easy cases. |
| 597 | // This is useful because MI is unable to split such critical edges, |
| 598 | // which means it will not be able to sink instructions along those edges. |
| 599 | // This is especially painful for indirect branches with many successors, where |
| 600 | // we end up having to prepare all outgoing values in the origin block. |
| 601 | // |
| 602 | // Our normal algorithm for splitting critical edges requires us to update |
| 603 | // the outgoing edges of the edge origin block, but for an indirectbr this |
| 604 | // is hard, since it would require finding and updating the block addresses |
| 605 | // the indirect branch uses. But if a block only has a single indirectbr |
| 606 | // predecessor, with the others being regular branches, we can do it in a |
| 607 | // different way. |
| 608 | // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr. |
| 609 | // We can split D into D0 and D1, where D0 contains only the PHIs from D, |
| 610 | // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and |
| 611 | // create the following structure: |
| 612 | // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1 |
| 613 | bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) { |
| 614 | // Check whether the function has any indirectbrs, and collect which blocks |
| 615 | // they may jump to. Since most functions don't have indirect branches, |
| 616 | // this lowers the common case's overhead to O(Blocks) instead of O(Edges). |
| 617 | SmallSetVector<BasicBlock *, 16> Targets; |
| 618 | for (auto &BB : F) { |
| 619 | auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator()); |
| 620 | if (!IBI) |
| 621 | continue; |
| 622 | |
| 623 | for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ) |
| 624 | Targets.insert(IBI->getSuccessor(Succ)); |
| 625 | } |
| 626 | |
| 627 | if (Targets.empty()) |
| 628 | return false; |
| 629 | |
| 630 | bool Changed = false; |
| 631 | for (BasicBlock *Target : Targets) { |
| 632 | SmallVector<BasicBlock *, 16> OtherPreds; |
| 633 | BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds); |
| 634 | // If we did not found an indirectbr, or the indirectbr is the only |
| 635 | // incoming edge, this isn't the kind of edge we're looking for. |
| 636 | if (!IBRPred || OtherPreds.empty()) |
| 637 | continue; |
| 638 | |
| 639 | // Don't even think about ehpads/landingpads. |
| 640 | Instruction *FirstNonPHI = Target->getFirstNonPHI(); |
| 641 | if (FirstNonPHI->isEHPad() || Target->isLandingPad()) |
| 642 | continue; |
| 643 | |
| 644 | BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split"); |
| 645 | // It's possible Target was its own successor through an indirectbr. |
| 646 | // In this case, the indirectbr now comes from BodyBlock. |
| 647 | if (IBRPred == Target) |
| 648 | IBRPred = BodyBlock; |
| 649 | |
| 650 | // At this point Target only has PHIs, and BodyBlock has the rest of the |
| 651 | // block's body. Create a copy of Target that will be used by the "direct" |
| 652 | // preds. |
| 653 | ValueToValueMapTy VMap; |
| 654 | BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F); |
| 655 | |
Brendon Cahoon | 7769a08 | 2017-04-17 19:11:04 +0000 | [diff] [blame] | 656 | for (BasicBlock *Pred : OtherPreds) { |
| 657 | // If the target is a loop to itself, then the terminator of the split |
| 658 | // block needs to be updated. |
| 659 | if (Pred == Target) |
| 660 | BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc); |
| 661 | else |
| 662 | Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc); |
| 663 | } |
Michael Kuperstein | 13bf8a2 | 2017-02-28 00:11:34 +0000 | [diff] [blame] | 664 | |
| 665 | // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that |
| 666 | // they are clones, so the number of PHIs are the same. |
| 667 | // (a) Remove the edge coming from IBRPred from the "Direct" PHI |
| 668 | // (b) Leave that as the only edge in the "Indirect" PHI. |
| 669 | // (c) Merge the two in the body block. |
| 670 | BasicBlock::iterator Indirect = Target->begin(), |
| 671 | End = Target->getFirstNonPHI()->getIterator(); |
| 672 | BasicBlock::iterator Direct = DirectSucc->begin(); |
| 673 | BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt(); |
| 674 | |
| 675 | assert(&*End == Target->getTerminator() && |
| 676 | "Block was expected to only contain PHIs"); |
| 677 | |
| 678 | while (Indirect != End) { |
| 679 | PHINode *DirPHI = cast<PHINode>(Direct); |
| 680 | PHINode *IndPHI = cast<PHINode>(Indirect); |
| 681 | |
| 682 | // Now, clean up - the direct block shouldn't get the indirect value, |
| 683 | // and vice versa. |
| 684 | DirPHI->removeIncomingValue(IBRPred); |
| 685 | Direct++; |
| 686 | |
| 687 | // Advance the pointer here, to avoid invalidation issues when the old |
| 688 | // PHI is erased. |
| 689 | Indirect++; |
| 690 | |
| 691 | PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI); |
| 692 | NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred), |
| 693 | IBRPred); |
| 694 | |
| 695 | // Create a PHI in the body block, to merge the direct and indirect |
| 696 | // predecessors. |
| 697 | PHINode *MergePHI = |
| 698 | PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert); |
| 699 | MergePHI->addIncoming(NewIndPHI, Target); |
| 700 | MergePHI->addIncoming(DirPHI, DirectSucc); |
| 701 | |
| 702 | IndPHI->replaceAllUsesWith(MergePHI); |
| 703 | IndPHI->eraseFromParent(); |
| 704 | } |
| 705 | |
| 706 | Changed = true; |
| 707 | } |
| 708 | |
| 709 | return Changed; |
| 710 | } |
| 711 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 712 | /// Eliminate blocks that contain only PHI nodes, debug info directives, and an |
| 713 | /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split |
| 714 | /// edges in ways that are non-optimal for isel. Start by eliminating these |
| 715 | /// blocks so we can split them the way we want them. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 716 | bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) { |
Chuang-Yu Cheng | d3fb38c | 2016-04-05 14:06:20 +0000 | [diff] [blame] | 717 | SmallPtrSet<BasicBlock *, 16> Preheaders; |
| 718 | SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end()); |
| 719 | while (!LoopList.empty()) { |
| 720 | Loop *L = LoopList.pop_back_val(); |
| 721 | LoopList.insert(LoopList.end(), L->begin(), L->end()); |
| 722 | if (BasicBlock *Preheader = L->getLoopPreheader()) |
| 723 | Preheaders.insert(Preheader); |
| 724 | } |
| 725 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 726 | bool MadeChange = false; |
| 727 | // Note that this intentionally skips the entry block. |
Benjamin Kramer | b6d0bd4 | 2014-03-02 12:27:27 +0000 | [diff] [blame] | 728 | for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 729 | BasicBlock *BB = &*I++; |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 730 | BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB); |
| 731 | if (!DestBB || |
| 732 | !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB))) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 733 | continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 734 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 735 | eliminateMostlyEmptyBlock(BB); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 736 | MadeChange = true; |
| 737 | } |
| 738 | return MadeChange; |
| 739 | } |
| 740 | |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 741 | bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB, |
| 742 | BasicBlock *DestBB, |
| 743 | bool isPreheader) { |
| 744 | // Do not delete loop preheaders if doing so would create a critical edge. |
| 745 | // Loop preheaders can be good locations to spill registers. If the |
| 746 | // preheader is deleted and we create a critical edge, registers may be |
| 747 | // spilled in the loop body instead. |
| 748 | if (!DisablePreheaderProtect && isPreheader && |
| 749 | !(BB->getSinglePredecessor() && |
| 750 | BB->getSinglePredecessor()->getSingleSuccessor())) |
| 751 | return false; |
| 752 | |
| 753 | // Try to skip merging if the unique predecessor of BB is terminated by a |
| 754 | // switch or indirect branch instruction, and BB is used as an incoming block |
| 755 | // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to |
| 756 | // add COPY instructions in the predecessor of BB instead of BB (if it is not |
| 757 | // merged). Note that the critical edge created by merging such blocks wont be |
| 758 | // split in MachineSink because the jump table is not analyzable. By keeping |
| 759 | // such empty block (BB), ISel will place COPY instructions in BB, not in the |
| 760 | // predecessor of BB. |
| 761 | BasicBlock *Pred = BB->getUniquePredecessor(); |
| 762 | if (!Pred || |
| 763 | !(isa<SwitchInst>(Pred->getTerminator()) || |
| 764 | isa<IndirectBrInst>(Pred->getTerminator()))) |
| 765 | return true; |
| 766 | |
| 767 | if (BB->getTerminator() != BB->getFirstNonPHI()) |
| 768 | return true; |
| 769 | |
| 770 | // We use a simple cost heuristic which determine skipping merging is |
| 771 | // profitable if the cost of skipping merging is less than the cost of |
| 772 | // merging : Cost(skipping merging) < Cost(merging BB), where the |
| 773 | // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and |
| 774 | // the Cost(merging BB) is Freq(Pred) * Cost(Copy). |
| 775 | // Assuming Cost(Copy) == Cost(Branch), we could simplify it to : |
| 776 | // Freq(Pred) / Freq(BB) > 2. |
| 777 | // Note that if there are multiple empty blocks sharing the same incoming |
| 778 | // value for the PHIs in the DestBB, we consider them together. In such |
| 779 | // case, Cost(merging BB) will be the sum of their frequencies. |
| 780 | |
| 781 | if (!isa<PHINode>(DestBB->begin())) |
| 782 | return true; |
| 783 | |
| 784 | SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs; |
| 785 | |
| 786 | // Find all other incoming blocks from which incoming values of all PHIs in |
| 787 | // DestBB are the same as the ones from BB. |
| 788 | for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E; |
| 789 | ++PI) { |
| 790 | BasicBlock *DestBBPred = *PI; |
| 791 | if (DestBBPred == BB) |
| 792 | continue; |
| 793 | |
Balaram Makam | 32bcb5d | 2017-10-27 00:35:18 +0000 | [diff] [blame] | 794 | bool HasAllSameValue = true; |
| 795 | BasicBlock::const_iterator DestBBI = DestBB->begin(); |
| 796 | while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) { |
| 797 | if (DestPN->getIncomingValueForBlock(BB) != |
| 798 | DestPN->getIncomingValueForBlock(DestBBPred)) { |
| 799 | HasAllSameValue = false; |
| 800 | break; |
| 801 | } |
| 802 | } |
| 803 | if (HasAllSameValue) |
Jun Bum Lim | 90b6b50 | 2016-12-16 20:38:39 +0000 | [diff] [blame] | 804 | SameIncomingValueBBs.insert(DestBBPred); |
| 805 | } |
| 806 | |
| 807 | // See if all BB's incoming values are same as the value from Pred. In this |
| 808 | // case, no reason to skip merging because COPYs are expected to be place in |
| 809 | // Pred already. |
| 810 | if (SameIncomingValueBBs.count(Pred)) |
| 811 | return true; |
| 812 | |
| 813 | if (!BFI) { |
| 814 | Function &F = *BB->getParent(); |
| 815 | LoopInfo LI{DominatorTree(F)}; |
| 816 | BPI.reset(new BranchProbabilityInfo(F, LI)); |
| 817 | BFI.reset(new BlockFrequencyInfo(F, *BPI, LI)); |
| 818 | } |
| 819 | |
| 820 | BlockFrequency PredFreq = BFI->getBlockFreq(Pred); |
| 821 | BlockFrequency BBFreq = BFI->getBlockFreq(BB); |
| 822 | |
| 823 | for (auto SameValueBB : SameIncomingValueBBs) |
| 824 | if (SameValueBB->getUniquePredecessor() == Pred && |
| 825 | DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB)) |
| 826 | BBFreq += BFI->getBlockFreq(SameValueBB); |
| 827 | |
| 828 | return PredFreq.getFrequency() <= |
| 829 | BBFreq.getFrequency() * FreqRatioToSkipMerge; |
| 830 | } |
| 831 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 832 | /// Return true if we can merge BB into DestBB if there is a single |
| 833 | /// unconditional branch between them, and BB contains no other non-phi |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 834 | /// instructions. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 835 | bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB, |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 836 | const BasicBlock *DestBB) const { |
| 837 | // We only want to eliminate blocks whose phi nodes are used by phi nodes in |
| 838 | // the successor. If there are more complex condition (e.g. preheaders), |
| 839 | // don't mess around with them. |
| 840 | BasicBlock::const_iterator BBI = BB->begin(); |
| 841 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 842 | for (const User *U : PN->users()) { |
| 843 | const Instruction *UI = cast<Instruction>(U); |
| 844 | if (UI->getParent() != DestBB || !isa<PHINode>(UI)) |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 845 | return false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 846 | // If User is inside DestBB block and it is a PHINode then check |
| 847 | // incoming value. If incoming value is not from BB then this is |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 848 | // a complex condition (e.g. preheaders) we want to avoid here. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 849 | if (UI->getParent() == DestBB) { |
| 850 | if (const PHINode *UPN = dyn_cast<PHINode>(UI)) |
Devang Patel | d320852 | 2007-04-25 00:37:04 +0000 | [diff] [blame] | 851 | for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) { |
| 852 | Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I)); |
| 853 | if (Insn && Insn->getParent() == BB && |
| 854 | Insn->getParent() != UPN->getIncomingBlock(I)) |
| 855 | return false; |
| 856 | } |
| 857 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 858 | } |
| 859 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 860 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 861 | // If BB and DestBB contain any common predecessors, then the phi nodes in BB |
| 862 | // and DestBB may have conflicting incoming values for the block. If so, we |
| 863 | // can't merge the block. |
| 864 | const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin()); |
| 865 | if (!DestBBPN) return true; // no conflict. |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 866 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 867 | // Collect the preds of BB. |
Chris Lattner | 8201a9b | 2007-11-06 22:07:40 +0000 | [diff] [blame] | 868 | SmallPtrSet<const BasicBlock*, 16> BBPreds; |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 869 | if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 870 | // It is faster to get preds from a PHI than with pred_iterator. |
| 871 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 872 | BBPreds.insert(BBPN->getIncomingBlock(i)); |
| 873 | } else { |
| 874 | BBPreds.insert(pred_begin(BB), pred_end(BB)); |
| 875 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 876 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 877 | // Walk the preds of DestBB. |
| 878 | for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) { |
| 879 | BasicBlock *Pred = DestBBPN->getIncomingBlock(i); |
| 880 | if (BBPreds.count(Pred)) { // Common predecessor? |
| 881 | BBI = DestBB->begin(); |
| 882 | while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) { |
| 883 | const Value *V1 = PN->getIncomingValueForBlock(Pred); |
| 884 | const Value *V2 = PN->getIncomingValueForBlock(BB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 885 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 886 | // If V2 is a phi node in BB, look up what the mapped value will be. |
| 887 | if (const PHINode *V2PN = dyn_cast<PHINode>(V2)) |
| 888 | if (V2PN->getParent() == BB) |
| 889 | V2 = V2PN->getIncomingValueForBlock(Pred); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 890 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 891 | // If there is a conflict, bail out. |
| 892 | if (V1 != V2) return false; |
| 893 | } |
| 894 | } |
| 895 | } |
| 896 | |
| 897 | return true; |
| 898 | } |
| 899 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 900 | /// Eliminate a basic block that has only phi's and an unconditional branch in |
| 901 | /// it. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 902 | void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) { |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 903 | BranchInst *BI = cast<BranchInst>(BB->getTerminator()); |
| 904 | BasicBlock *DestBB = BI->getSuccessor(0); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 905 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 906 | DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 907 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 908 | // If the destination block has a single pred, then this is a trivial edge, |
| 909 | // just collapse it. |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 910 | if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) { |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 911 | if (SinglePred != DestBB) { |
| 912 | // Remember if SinglePred was the entry block of the function. If so, we |
| 913 | // will need to move BB back to the entry position. |
| 914 | bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock(); |
Balaram Makam | 32bcb5d | 2017-10-27 00:35:18 +0000 | [diff] [blame] | 915 | MergeBasicBlockIntoOnlyPred(DestBB, nullptr); |
Chris Lattner | 4059f43 | 2008-11-27 19:29:14 +0000 | [diff] [blame] | 916 | |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 917 | if (isEntry && BB != &BB->getParent()->getEntryBlock()) |
| 918 | BB->moveBefore(&BB->getParent()->getEntryBlock()); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 919 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 920 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | 8a172da | 2008-11-28 19:54:49 +0000 | [diff] [blame] | 921 | return; |
| 922 | } |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 923 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 924 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 925 | // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB |
| 926 | // to handle the new incoming edges it is about to have. |
| 927 | PHINode *PN; |
| 928 | for (BasicBlock::iterator BBI = DestBB->begin(); |
| 929 | (PN = dyn_cast<PHINode>(BBI)); ++BBI) { |
| 930 | // Remove the incoming value for BB, and remember it. |
| 931 | Value *InVal = PN->removeIncomingValue(BB, false); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 932 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 933 | // Two options: either the InVal is a phi node defined in BB or it is some |
| 934 | // value that dominates BB. |
| 935 | PHINode *InValPhi = dyn_cast<PHINode>(InVal); |
| 936 | if (InValPhi && InValPhi->getParent() == BB) { |
| 937 | // Add all of the input values of the input PHI as inputs of this phi. |
| 938 | for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i) |
| 939 | PN->addIncoming(InValPhi->getIncomingValue(i), |
| 940 | InValPhi->getIncomingBlock(i)); |
| 941 | } else { |
| 942 | // Otherwise, add one instance of the dominating value for each edge that |
| 943 | // we will be adding. |
| 944 | if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) { |
| 945 | for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i) |
| 946 | PN->addIncoming(InVal, BBPN->getIncomingBlock(i)); |
| 947 | } else { |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 948 | for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) |
| 949 | PN->addIncoming(InVal, *PI); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 950 | } |
| 951 | } |
| 952 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 953 | |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 954 | // The PHIs are now updated, change everything that refers to BB to use |
| 955 | // DestBB and remove BB. |
| 956 | BB->replaceAllUsesWith(DestBB); |
| 957 | BB->eraseFromParent(); |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 958 | ++NumBlocksElim; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 959 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 960 | DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n"); |
Chris Lattner | c374856 | 2007-04-02 01:35:34 +0000 | [diff] [blame] | 961 | } |
| 962 | |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 963 | // Computes a map of base pointer relocation instructions to corresponding |
| 964 | // derived pointer relocation instructions given a vector of all relocate calls |
| 965 | static void computeBaseDerivedRelocateMap( |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 966 | const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls, |
| 967 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> |
| 968 | &RelocateInstMap) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 969 | // Collect information in two maps: one primarily for locating the base object |
| 970 | // while filling the second map; the second map is the final structure holding |
| 971 | // a mapping between Base and corresponding Derived relocate calls |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 972 | DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap; |
| 973 | for (auto *ThisRelocate : AllRelocateCalls) { |
| 974 | auto K = std::make_pair(ThisRelocate->getBasePtrIndex(), |
| 975 | ThisRelocate->getDerivedPtrIndex()); |
| 976 | RelocateIdxMap.insert(std::make_pair(K, ThisRelocate)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 977 | } |
| 978 | for (auto &Item : RelocateIdxMap) { |
| 979 | std::pair<unsigned, unsigned> Key = Item.first; |
| 980 | if (Key.first == Key.second) |
| 981 | // Base relocation: nothing to insert |
| 982 | continue; |
| 983 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 984 | GCRelocateInst *I = Item.second; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 985 | auto BaseKey = std::make_pair(Key.first, Key.first); |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 986 | |
| 987 | // We're iterating over RelocateIdxMap so we cannot modify it. |
| 988 | auto MaybeBase = RelocateIdxMap.find(BaseKey); |
| 989 | if (MaybeBase == RelocateIdxMap.end()) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 990 | // TODO: We might want to insert a new base object relocate and gep off |
| 991 | // that, if there are enough derived object relocates. |
| 992 | continue; |
Sanjoy Das | b818676 | 2015-02-27 02:24:16 +0000 | [diff] [blame] | 993 | |
| 994 | RelocateInstMap[MaybeBase->second].push_back(I); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 995 | } |
| 996 | } |
| 997 | |
| 998 | // Accepts a GEP and extracts the operands into a vector provided they're all |
| 999 | // small integer constants |
| 1000 | static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP, |
| 1001 | SmallVectorImpl<Value *> &OffsetV) { |
| 1002 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) { |
| 1003 | // Only accept small constant integer operands |
| 1004 | auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i)); |
| 1005 | if (!Op || Op->getZExtValue() > 20) |
| 1006 | return false; |
| 1007 | } |
| 1008 | |
| 1009 | for (unsigned i = 1; i < GEP->getNumOperands(); i++) |
| 1010 | OffsetV.push_back(GEP->getOperand(i)); |
| 1011 | return true; |
| 1012 | } |
| 1013 | |
| 1014 | // Takes a RelocatedBase (base pointer relocation instruction) and Targets to |
| 1015 | // replace, computes a replacement, and affects it. |
| 1016 | static bool |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1017 | simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase, |
| 1018 | const SmallVectorImpl<GCRelocateInst *> &Targets) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1019 | bool MadeChange = false; |
Serguei Katkov | 9e5604d | 2017-08-17 05:48:30 +0000 | [diff] [blame] | 1020 | // We must ensure the relocation of derived pointer is defined after |
| 1021 | // relocation of base pointer. If we find a relocation corresponding to base |
| 1022 | // defined earlier than relocation of base then we move relocation of base |
| 1023 | // right before found relocation. We consider only relocation in the same |
| 1024 | // basic block as relocation of base. Relocations from other basic block will |
| 1025 | // be skipped by optimization and we do not care about them. |
| 1026 | for (auto R = RelocatedBase->getParent()->getFirstInsertionPt(); |
| 1027 | &*R != RelocatedBase; ++R) |
| 1028 | if (auto RI = dyn_cast<GCRelocateInst>(R)) |
| 1029 | if (RI->getStatepoint() == RelocatedBase->getStatepoint()) |
| 1030 | if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) { |
| 1031 | RelocatedBase->moveBefore(RI); |
| 1032 | break; |
| 1033 | } |
| 1034 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1035 | for (GCRelocateInst *ToReplace : Targets) { |
| 1036 | assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() && |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1037 | "Not relocating a derived object of the original base object"); |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1038 | if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) { |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1039 | // A duplicate relocate call. TODO: coalesce duplicates. |
| 1040 | continue; |
| 1041 | } |
| 1042 | |
Igor Laevsky | f637b4a | 2015-11-03 18:37:40 +0000 | [diff] [blame] | 1043 | if (RelocatedBase->getParent() != ToReplace->getParent()) { |
| 1044 | // Base and derived relocates are in different basic blocks. |
| 1045 | // In this case transform is only valid when base dominates derived |
| 1046 | // relocate. However it would be too expensive to check dominance |
| 1047 | // for each such relocate, so we skip the whole transformation. |
| 1048 | continue; |
| 1049 | } |
| 1050 | |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1051 | Value *Base = ToReplace->getBasePtr(); |
| 1052 | auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1053 | if (!Derived || Derived->getPointerOperand() != Base) |
| 1054 | continue; |
| 1055 | |
| 1056 | SmallVector<Value *, 2> OffsetV; |
| 1057 | if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV)) |
| 1058 | continue; |
| 1059 | |
| 1060 | // Create a Builder and replace the target callsite with a gep |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 1061 | assert(RelocatedBase->getNextNode() && |
| 1062 | "Should always have one since it's not a terminator"); |
Sanjoy Das | 3d705e3 | 2015-05-11 23:47:30 +0000 | [diff] [blame] | 1063 | |
| 1064 | // Insert after RelocatedBase |
| 1065 | IRBuilder<> Builder(RelocatedBase->getNextNode()); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1066 | Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1067 | |
| 1068 | // If gc_relocate does not match the actual type, cast it to the right type. |
| 1069 | // In theory, there must be a bitcast after gc_relocate if the type does not |
| 1070 | // match, and we should reuse it to get the derived pointer. But it could be |
| 1071 | // cases like this: |
| 1072 | // bb1: |
| 1073 | // ... |
| 1074 | // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 1075 | // br label %merge |
| 1076 | // |
| 1077 | // bb2: |
| 1078 | // ... |
| 1079 | // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...) |
| 1080 | // br label %merge |
| 1081 | // |
| 1082 | // merge: |
| 1083 | // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ] |
| 1084 | // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)* |
| 1085 | // |
| 1086 | // In this case, we can not find the bitcast any more. So we insert a new bitcast |
| 1087 | // no matter there is already one or not. In this way, we can handle all cases, and |
| 1088 | // the extra bitcast should be optimized away in later passes. |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 1089 | Value *ActualRelocatedBase = RelocatedBase; |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1090 | if (RelocatedBase->getType() != Base->getType()) { |
| 1091 | ActualRelocatedBase = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 1092 | Builder.CreateBitCast(RelocatedBase, Base->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1093 | } |
David Blaikie | 68d535c | 2015-03-24 22:38:16 +0000 | [diff] [blame] | 1094 | Value *Replacement = Builder.CreateGEP( |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1095 | Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV)); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1096 | Replacement->takeName(ToReplace); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1097 | // If the newly generated derived pointer's type does not match the original derived |
| 1098 | // 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] | 1099 | Value *ActualReplacement = Replacement; |
| 1100 | if (Replacement->getType() != ToReplace->getType()) { |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1101 | ActualReplacement = |
Manuel Jacob | 5b90b14 | 2015-12-19 18:38:42 +0000 | [diff] [blame] | 1102 | Builder.CreateBitCast(Replacement, ToReplace->getType()); |
Sanjoy Das | 89c5491 | 2015-05-11 18:49:34 +0000 | [diff] [blame] | 1103 | } |
| 1104 | ToReplace->replaceAllUsesWith(ActualReplacement); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1105 | ToReplace->eraseFromParent(); |
| 1106 | |
| 1107 | MadeChange = true; |
| 1108 | } |
| 1109 | return MadeChange; |
| 1110 | } |
| 1111 | |
| 1112 | // Turns this: |
| 1113 | // |
| 1114 | // %base = ... |
| 1115 | // %ptr = gep %base + 15 |
| 1116 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 1117 | // %base' = relocate(%tok, i32 4, i32 4) |
| 1118 | // %ptr' = relocate(%tok, i32 4, i32 5) |
| 1119 | // %val = load %ptr' |
| 1120 | // |
| 1121 | // into this: |
| 1122 | // |
| 1123 | // %base = ... |
| 1124 | // %ptr = gep %base + 15 |
| 1125 | // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr) |
| 1126 | // %base' = gc.relocate(%tok, i32 4, i32 4) |
| 1127 | // %ptr' = gep %base' + 15 |
| 1128 | // %val = load %ptr' |
| 1129 | bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) { |
| 1130 | bool MadeChange = false; |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1131 | SmallVector<GCRelocateInst *, 2> AllRelocateCalls; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1132 | |
| 1133 | for (auto *U : I.users()) |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1134 | if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U)) |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1135 | // Collect all the relocate calls associated with a statepoint |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1136 | AllRelocateCalls.push_back(Relocate); |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1137 | |
| 1138 | // We need atleast one base pointer relocation + one derived pointer |
| 1139 | // relocation to mangle |
| 1140 | if (AllRelocateCalls.size() < 2) |
| 1141 | return false; |
| 1142 | |
| 1143 | // RelocateInstMap is a mapping from the base relocate instruction to the |
| 1144 | // corresponding derived relocate instructions |
Manuel Jacob | 83eefa6 | 2016-01-05 04:03:00 +0000 | [diff] [blame] | 1145 | DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap; |
Ramkumar Ramachandra | dba7329 | 2015-01-14 23:27:07 +0000 | [diff] [blame] | 1146 | computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap); |
| 1147 | if (RelocateInstMap.empty()) |
| 1148 | return false; |
| 1149 | |
| 1150 | for (auto &Item : RelocateInstMap) |
| 1151 | // Item.first is the RelocatedBase to offset against |
| 1152 | // Item.second is the vector of Targets to replace |
| 1153 | MadeChange = simplifyRelocatesOffABase(Item.first, Item.second); |
| 1154 | return MadeChange; |
| 1155 | } |
| 1156 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1157 | /// SinkCast - Sink the specified cast instruction into its user blocks |
| 1158 | static bool SinkCast(CastInst *CI) { |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1159 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1160 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1161 | /// InsertedCasts - Only insert a cast in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1162 | DenseMap<BasicBlock*, CastInst*> InsertedCasts; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1163 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1164 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1165 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1166 | UI != E; ) { |
| 1167 | Use &TheUse = UI.getUse(); |
| 1168 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1169 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1170 | // Figure out which BB this cast is used in. For PHI's this is the |
| 1171 | // appropriate predecessor block. |
| 1172 | BasicBlock *UserBB = User->getParent(); |
| 1173 | if (PHINode *PN = dyn_cast<PHINode>(User)) { |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1174 | UserBB = PN->getIncomingBlock(TheUse); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1175 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1176 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1177 | // Preincrement use iterator so we don't invalidate it. |
| 1178 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1179 | |
David Majnemer | 0c80e2e | 2016-04-27 19:36:38 +0000 | [diff] [blame] | 1180 | // The first insertion point of a block containing an EH pad is after the |
| 1181 | // pad. If the pad is the user, we cannot sink the cast past the pad. |
| 1182 | if (User->isEHPad()) |
| 1183 | continue; |
| 1184 | |
Andrew Kaylor | d0430e8 | 2015-11-23 19:16:15 +0000 | [diff] [blame] | 1185 | // If the block selected to receive the cast is an EH pad that does not |
| 1186 | // allow non-PHI instructions before the terminator, we can't sink the |
| 1187 | // cast. |
| 1188 | if (UserBB->getTerminator()->isEHPad()) |
| 1189 | continue; |
| 1190 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1191 | // If this user is in the same block as the cast, don't change the cast. |
| 1192 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1193 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1194 | // If we have already inserted a cast into this block, use it. |
| 1195 | CastInst *&InsertedCast = InsertedCasts[UserBB]; |
| 1196 | |
| 1197 | if (!InsertedCast) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1198 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1199 | assert(InsertPt != UserBB->end()); |
| 1200 | InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0), |
| 1201 | CI->getType(), "", &*InsertPt); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1202 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1203 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1204 | // 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] | 1205 | TheUse = InsertedCast; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1206 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1207 | ++NumCastUses; |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1208 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1209 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1210 | // If we removed all uses, nuke the cast. |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1211 | if (CI->use_empty()) { |
Adrian Prantl | 261ac8b | 2017-11-03 21:55:03 +0000 | [diff] [blame] | 1212 | salvageDebugInfo(*CI); |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1213 | CI->eraseFromParent(); |
Duncan Sands | afa84da4 | 2008-01-20 16:51:46 +0000 | [diff] [blame] | 1214 | MadeChange = true; |
| 1215 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1216 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 1217 | return MadeChange; |
| 1218 | } |
| 1219 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1220 | /// If the specified cast instruction is a noop copy (e.g. it's casting from |
| 1221 | /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to |
| 1222 | /// reduce the number of virtual registers that must be created and coalesced. |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1223 | /// |
| 1224 | /// Return true if any changes are made. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1225 | static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI, |
| 1226 | const DataLayout &DL) { |
Justin Lebar | 3e50a5b | 2016-11-21 22:49:15 +0000 | [diff] [blame] | 1227 | // Sink only "cheap" (or nop) address-space casts. This is a weaker condition |
| 1228 | // than sinking only nop casts, but is helpful on some platforms. |
| 1229 | if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) { |
| 1230 | if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(), |
| 1231 | ASC->getDestAddressSpace())) |
| 1232 | return false; |
| 1233 | } |
| 1234 | |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1235 | // If this is a noop copy, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1236 | EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType()); |
| 1237 | EVT DstVT = TLI.getValueType(DL, CI->getType()); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 1238 | |
| 1239 | // This is an fp<->int conversion? |
| 1240 | if (SrcVT.isInteger() != DstVT.isInteger()) |
| 1241 | return false; |
| 1242 | |
| 1243 | // If this is an extension, it will be a zero or sign extension, which |
| 1244 | // isn't a noop. |
| 1245 | if (SrcVT.bitsLT(DstVT)) return false; |
| 1246 | |
| 1247 | // If these values will be promoted, find out what they will be promoted |
| 1248 | // to. This helps us consider truncates on PPC as noop copies when they |
| 1249 | // are. |
| 1250 | if (TLI.getTypeAction(CI->getContext(), SrcVT) == |
| 1251 | TargetLowering::TypePromoteInteger) |
| 1252 | SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT); |
| 1253 | if (TLI.getTypeAction(CI->getContext(), DstVT) == |
| 1254 | TargetLowering::TypePromoteInteger) |
| 1255 | DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT); |
| 1256 | |
| 1257 | // If, after promotion, these are the same types, this is a noop copy. |
| 1258 | if (SrcVT != DstVT) |
| 1259 | return false; |
| 1260 | |
| 1261 | return SinkCast(CI); |
| 1262 | } |
| 1263 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1264 | /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if |
| 1265 | /// possible. |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1266 | /// |
| 1267 | /// Return true if any changes were made. |
| 1268 | static bool CombineUAddWithOverflow(CmpInst *CI) { |
| 1269 | Value *A, *B; |
| 1270 | Instruction *AddI; |
| 1271 | if (!match(CI, |
| 1272 | m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI)))) |
| 1273 | return false; |
| 1274 | |
| 1275 | Type *Ty = AddI->getType(); |
| 1276 | if (!isa<IntegerType>(Ty)) |
| 1277 | return false; |
| 1278 | |
| 1279 | // We don't want to move around uses of condition values this late, so we we |
| 1280 | // check if it is legal to create the call to the intrinsic in the basic |
| 1281 | // block containing the icmp: |
| 1282 | |
| 1283 | if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse()) |
| 1284 | return false; |
| 1285 | |
| 1286 | #ifndef NDEBUG |
| 1287 | // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption |
| 1288 | // for now: |
| 1289 | if (AddI->hasOneUse()) |
| 1290 | assert(*AddI->user_begin() == CI && "expected!"); |
| 1291 | #endif |
| 1292 | |
Sanjay Patel | af674fb | 2015-12-14 17:24:23 +0000 | [diff] [blame] | 1293 | Module *M = CI->getModule(); |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1294 | Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty); |
| 1295 | |
| 1296 | auto *InsertPt = AddI->hasOneUse() ? CI : AddI; |
| 1297 | |
| 1298 | auto *UAddWithOverflow = |
| 1299 | CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt); |
| 1300 | auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt); |
| 1301 | auto *Overflow = |
| 1302 | ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt); |
| 1303 | |
| 1304 | CI->replaceAllUsesWith(Overflow); |
| 1305 | AddI->replaceAllUsesWith(UAdd); |
| 1306 | CI->eraseFromParent(); |
| 1307 | AddI->eraseFromParent(); |
| 1308 | return true; |
| 1309 | } |
| 1310 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1311 | /// Sink the given CmpInst into user blocks to reduce the number of virtual |
| 1312 | /// registers that must be created and coalesced. This is a clear win except on |
| 1313 | /// targets with multiple condition code registers (PowerPC), where it might |
| 1314 | /// lose; some adjustment may be wanted there. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1315 | /// |
| 1316 | /// Return true if any changes are made. |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1317 | static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1318 | BasicBlock *DefBB = CI->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1319 | |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1320 | // 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] | 1321 | if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI)) |
Peter Zotov | 0b6d7bc | 2016-04-03 16:36:17 +0000 | [diff] [blame] | 1322 | return false; |
| 1323 | |
| 1324 | // Only insert a cmp in each block once. |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1325 | DenseMap<BasicBlock*, CmpInst*> InsertedCmps; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1326 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1327 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 1328 | for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end(); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1329 | UI != E; ) { |
| 1330 | Use &TheUse = UI.getUse(); |
| 1331 | Instruction *User = cast<Instruction>(*UI); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1332 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1333 | // Preincrement use iterator so we don't invalidate it. |
| 1334 | ++UI; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1335 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1336 | // Don't bother for PHI nodes. |
| 1337 | if (isa<PHINode>(User)) |
| 1338 | continue; |
| 1339 | |
| 1340 | // Figure out which BB this cmp is used in. |
| 1341 | BasicBlock *UserBB = User->getParent(); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1342 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1343 | // If this user is in the same block as the cmp, don't change the cmp. |
| 1344 | if (UserBB == DefBB) continue; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1345 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1346 | // If we have already inserted a cmp into this block, use it. |
| 1347 | CmpInst *&InsertedCmp = InsertedCmps[UserBB]; |
| 1348 | |
| 1349 | if (!InsertedCmp) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 1350 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1351 | assert(InsertPt != UserBB->end()); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1352 | InsertedCmp = |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1353 | CmpInst::Create(CI->getOpcode(), CI->getPredicate(), |
| 1354 | CI->getOperand(0), CI->getOperand(1), "", &*InsertPt); |
Wolfgang Pieb | e51bede | 2016-10-06 21:43:45 +0000 | [diff] [blame] | 1355 | // Propagate the debug info. |
| 1356 | InsertedCmp->setDebugLoc(CI->getDebugLoc()); |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1357 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1358 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1359 | // Replace a use of the cmp with a use of the new cmp. |
| 1360 | TheUse = InsertedCmp; |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1361 | MadeChange = true; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 1362 | ++NumCmpUses; |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1363 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1364 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1365 | // If we removed all uses, nuke the cmp. |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1366 | if (CI->use_empty()) { |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1367 | CI->eraseFromParent(); |
Benjamin Kramer | b4bf14c | 2015-04-10 22:25:36 +0000 | [diff] [blame] | 1368 | MadeChange = true; |
| 1369 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 1370 | |
Dale Johannesen | edfec0b | 2007-06-12 16:50:17 +0000 | [diff] [blame] | 1371 | return MadeChange; |
| 1372 | } |
| 1373 | |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 1374 | static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) { |
Peter Zotov | 8efe38a | 2016-04-03 19:32:13 +0000 | [diff] [blame] | 1375 | if (SinkCmpExpression(CI, TLI)) |
Sanjoy Das | b6c5914 | 2015-04-10 21:07:09 +0000 | [diff] [blame] | 1376 | return true; |
| 1377 | |
| 1378 | if (CombineUAddWithOverflow(CI)) |
| 1379 | return true; |
| 1380 | |
| 1381 | return false; |
| 1382 | } |
| 1383 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 1384 | /// Duplicate and sink the given 'and' instruction into user blocks where it is |
| 1385 | /// used in a compare to allow isel to generate better code for targets where |
| 1386 | /// this operation can be combined. |
| 1387 | /// |
| 1388 | /// Return true if any changes are made. |
| 1389 | static bool sinkAndCmp0Expression(Instruction *AndI, |
| 1390 | const TargetLowering &TLI, |
| 1391 | SetOfInstrs &InsertedInsts) { |
| 1392 | // Double-check that we're not trying to optimize an instruction that was |
| 1393 | // already optimized by some other part of this pass. |
| 1394 | assert(!InsertedInsts.count(AndI) && |
| 1395 | "Attempting to optimize already optimized and instruction"); |
| 1396 | (void) InsertedInsts; |
| 1397 | |
| 1398 | // Nothing to do for single use in same basic block. |
| 1399 | if (AndI->hasOneUse() && |
| 1400 | AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent()) |
| 1401 | return false; |
| 1402 | |
| 1403 | // Try to avoid cases where sinking/duplicating is likely to increase register |
| 1404 | // pressure. |
| 1405 | if (!isa<ConstantInt>(AndI->getOperand(0)) && |
| 1406 | !isa<ConstantInt>(AndI->getOperand(1)) && |
| 1407 | AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse()) |
| 1408 | return false; |
| 1409 | |
| 1410 | for (auto *U : AndI->users()) { |
| 1411 | Instruction *User = cast<Instruction>(U); |
| 1412 | |
| 1413 | // Only sink for and mask feeding icmp with 0. |
| 1414 | if (!isa<ICmpInst>(User)) |
| 1415 | return false; |
| 1416 | |
| 1417 | auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1)); |
| 1418 | if (!CmpC || !CmpC->isZero()) |
| 1419 | return false; |
| 1420 | } |
| 1421 | |
| 1422 | if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI)) |
| 1423 | return false; |
| 1424 | |
| 1425 | DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n"); |
| 1426 | DEBUG(AndI->getParent()->dump()); |
| 1427 | |
| 1428 | // Push the 'and' into the same block as the icmp 0. There should only be |
| 1429 | // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any |
| 1430 | // others, so we don't need to keep track of which BBs we insert into. |
| 1431 | for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end(); |
| 1432 | UI != E; ) { |
| 1433 | Use &TheUse = UI.getUse(); |
| 1434 | Instruction *User = cast<Instruction>(*UI); |
| 1435 | |
| 1436 | // Preincrement use iterator so we don't invalidate it. |
| 1437 | ++UI; |
| 1438 | |
| 1439 | DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n"); |
| 1440 | |
| 1441 | // Keep the 'and' in the same place if the use is already in the same block. |
| 1442 | Instruction *InsertPt = |
| 1443 | User->getParent() == AndI->getParent() ? AndI : User; |
| 1444 | Instruction *InsertedAnd = |
| 1445 | BinaryOperator::Create(Instruction::And, AndI->getOperand(0), |
| 1446 | AndI->getOperand(1), "", InsertPt); |
| 1447 | // Propagate the debug info. |
| 1448 | InsertedAnd->setDebugLoc(AndI->getDebugLoc()); |
| 1449 | |
| 1450 | // Replace a use of the 'and' with a use of the new 'and'. |
| 1451 | TheUse = InsertedAnd; |
| 1452 | ++NumAndUses; |
| 1453 | DEBUG(User->getParent()->dump()); |
| 1454 | } |
| 1455 | |
| 1456 | // We removed all uses, nuke the and. |
| 1457 | AndI->eraseFromParent(); |
| 1458 | return true; |
| 1459 | } |
| 1460 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1461 | /// Check if the candidates could be combined with a shift instruction, which |
| 1462 | /// includes: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1463 | /// 1. Truncate instruction |
| 1464 | /// 2. And instruction and the imm is a mask of the low bits: |
| 1465 | /// imm & (imm+1) == 0 |
Benjamin Kramer | 322053c | 2014-04-27 14:54:59 +0000 | [diff] [blame] | 1466 | static bool isExtractBitsCandidateUse(Instruction *User) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1467 | if (!isa<TruncInst>(User)) { |
| 1468 | if (User->getOpcode() != Instruction::And || |
| 1469 | !isa<ConstantInt>(User->getOperand(1))) |
| 1470 | return false; |
| 1471 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1472 | const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue(); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1473 | |
Quentin Colombet | d4f4469 | 2014-04-22 01:20:34 +0000 | [diff] [blame] | 1474 | if ((Cimm & (Cimm + 1)).getBoolValue()) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1475 | return false; |
| 1476 | } |
| 1477 | return true; |
| 1478 | } |
| 1479 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1480 | /// 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] | 1481 | static bool |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1482 | SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI, |
| 1483 | DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1484 | const TargetLowering &TLI, const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1485 | BasicBlock *UserBB = User->getParent(); |
| 1486 | DenseMap<BasicBlock *, CastInst *> InsertedTruncs; |
| 1487 | TruncInst *TruncI = dyn_cast<TruncInst>(User); |
| 1488 | bool MadeChange = false; |
| 1489 | |
| 1490 | for (Value::user_iterator TruncUI = TruncI->user_begin(), |
| 1491 | TruncE = TruncI->user_end(); |
| 1492 | TruncUI != TruncE;) { |
| 1493 | |
| 1494 | Use &TruncTheUse = TruncUI.getUse(); |
| 1495 | Instruction *TruncUser = cast<Instruction>(*TruncUI); |
| 1496 | // Preincrement use iterator so we don't invalidate it. |
| 1497 | |
| 1498 | ++TruncUI; |
| 1499 | |
| 1500 | int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode()); |
| 1501 | if (!ISDOpcode) |
| 1502 | continue; |
| 1503 | |
Tim Northover | e2239ff | 2014-07-29 10:20:22 +0000 | [diff] [blame] | 1504 | // If the use is actually a legal node, there will not be an |
| 1505 | // implicit truncate. |
| 1506 | // FIXME: always querying the result type is just an |
| 1507 | // approximation; some nodes' legality is determined by the |
| 1508 | // 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] | 1509 | if (TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1510 | ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1511 | continue; |
| 1512 | |
| 1513 | // Don't bother for PHI nodes. |
| 1514 | if (isa<PHINode>(TruncUser)) |
| 1515 | continue; |
| 1516 | |
| 1517 | BasicBlock *TruncUserBB = TruncUser->getParent(); |
| 1518 | |
| 1519 | if (UserBB == TruncUserBB) |
| 1520 | continue; |
| 1521 | |
| 1522 | BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB]; |
| 1523 | CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB]; |
| 1524 | |
| 1525 | if (!InsertedShift && !InsertedTrunc) { |
| 1526 | BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1527 | assert(InsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1528 | // Sink the shift |
| 1529 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1530 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1531 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1532 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1533 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1534 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1535 | |
| 1536 | // Sink the trunc |
| 1537 | BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt(); |
| 1538 | TruncInsertPt++; |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1539 | assert(TruncInsertPt != TruncUserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1540 | |
| 1541 | InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift, |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1542 | TruncI->getType(), "", &*TruncInsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1543 | |
| 1544 | MadeChange = true; |
| 1545 | |
| 1546 | TruncTheUse = InsertedTrunc; |
| 1547 | } |
| 1548 | } |
| 1549 | return MadeChange; |
| 1550 | } |
| 1551 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1552 | /// Sink the shift *right* instruction into user blocks if the uses could |
| 1553 | /// potentially be combined with this shift instruction and generate BitExtract |
| 1554 | /// instruction. It will only be applied if the architecture supports BitExtract |
| 1555 | /// instruction. Here is an example: |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1556 | /// BB1: |
| 1557 | /// %x.extract.shift = lshr i64 %arg1, 32 |
| 1558 | /// BB2: |
| 1559 | /// %x.extract.trunc = trunc i64 %x.extract.shift to i16 |
| 1560 | /// ==> |
| 1561 | /// |
| 1562 | /// BB2: |
| 1563 | /// %x.extract.shift.1 = lshr i64 %arg1, 32 |
| 1564 | /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16 |
| 1565 | /// |
| 1566 | /// CodeGen will recoginze the pattern in BB2 and generate BitExtract |
| 1567 | /// instruction. |
| 1568 | /// Return true if any changes are made. |
| 1569 | static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI, |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1570 | const TargetLowering &TLI, |
| 1571 | const DataLayout &DL) { |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1572 | BasicBlock *DefBB = ShiftI->getParent(); |
| 1573 | |
| 1574 | /// Only insert instructions in each block once. |
| 1575 | DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts; |
| 1576 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1577 | bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType())); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1578 | |
| 1579 | bool MadeChange = false; |
| 1580 | for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end(); |
| 1581 | UI != E;) { |
| 1582 | Use &TheUse = UI.getUse(); |
| 1583 | Instruction *User = cast<Instruction>(*UI); |
| 1584 | // Preincrement use iterator so we don't invalidate it. |
| 1585 | ++UI; |
| 1586 | |
| 1587 | // Don't bother for PHI nodes. |
| 1588 | if (isa<PHINode>(User)) |
| 1589 | continue; |
| 1590 | |
| 1591 | if (!isExtractBitsCandidateUse(User)) |
| 1592 | continue; |
| 1593 | |
| 1594 | BasicBlock *UserBB = User->getParent(); |
| 1595 | |
| 1596 | if (UserBB == DefBB) { |
| 1597 | // If the shift and truncate instruction are in the same BB. The use of |
| 1598 | // the truncate(TruncUse) may still introduce another truncate if not |
| 1599 | // legal. In this case, we would like to sink both shift and truncate |
| 1600 | // instruction to the BB of TruncUse. |
| 1601 | // for example: |
| 1602 | // BB1: |
| 1603 | // i64 shift.result = lshr i64 opnd, imm |
| 1604 | // trunc.result = trunc shift.result to i16 |
| 1605 | // |
| 1606 | // BB2: |
| 1607 | // ----> We will have an implicit truncate here if the architecture does |
| 1608 | // not have i16 compare. |
| 1609 | // cmp i16 trunc.result, opnd2 |
| 1610 | // |
| 1611 | if (isa<TruncInst>(User) && shiftIsLegal |
| 1612 | // If the type of the truncate is legal, no trucate will be |
| 1613 | // introduced in other basic blocks. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1614 | && |
| 1615 | (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType())))) |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1616 | MadeChange = |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 1617 | SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1618 | |
| 1619 | continue; |
| 1620 | } |
| 1621 | // If we have already inserted a shift into this block, use it. |
| 1622 | BinaryOperator *&InsertedShift = InsertedShifts[UserBB]; |
| 1623 | |
| 1624 | if (!InsertedShift) { |
| 1625 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1626 | assert(InsertPt != UserBB->end()); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1627 | |
| 1628 | if (ShiftI->getOpcode() == Instruction::AShr) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1629 | InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, |
| 1630 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1631 | else |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 1632 | InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, |
| 1633 | "", &*InsertPt); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 1634 | |
| 1635 | MadeChange = true; |
| 1636 | } |
| 1637 | |
| 1638 | // Replace a use of the shift with a use of the new shift. |
| 1639 | TheUse = InsertedShift; |
| 1640 | } |
| 1641 | |
| 1642 | // If we removed all uses, nuke the shift. |
| 1643 | if (ShiftI->use_empty()) |
| 1644 | ShiftI->eraseFromParent(); |
| 1645 | |
| 1646 | return MadeChange; |
| 1647 | } |
| 1648 | |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1649 | /// If counting leading or trailing zeros is an expensive operation and a zero |
| 1650 | /// input is defined, add a check for zero to avoid calling the intrinsic. |
| 1651 | /// |
| 1652 | /// We want to transform: |
| 1653 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false) |
| 1654 | /// |
| 1655 | /// into: |
| 1656 | /// entry: |
| 1657 | /// %cmpz = icmp eq i64 %A, 0 |
| 1658 | /// br i1 %cmpz, label %cond.end, label %cond.false |
| 1659 | /// cond.false: |
| 1660 | /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true) |
| 1661 | /// br label %cond.end |
| 1662 | /// cond.end: |
| 1663 | /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ] |
| 1664 | /// |
| 1665 | /// If the transform is performed, return true and set ModifiedDT to true. |
| 1666 | static bool despeculateCountZeros(IntrinsicInst *CountZeros, |
| 1667 | const TargetLowering *TLI, |
| 1668 | const DataLayout *DL, |
| 1669 | bool &ModifiedDT) { |
| 1670 | if (!TLI || !DL) |
| 1671 | return false; |
| 1672 | |
| 1673 | // If a zero input is undefined, it doesn't make sense to despeculate that. |
| 1674 | if (match(CountZeros->getOperand(1), m_One())) |
| 1675 | return false; |
| 1676 | |
| 1677 | // If it's cheap to speculate, there's nothing to do. |
| 1678 | auto IntrinsicID = CountZeros->getIntrinsicID(); |
| 1679 | if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) || |
| 1680 | (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz())) |
| 1681 | return false; |
| 1682 | |
| 1683 | // Only handle legal scalar cases. Anything else requires too much work. |
| 1684 | Type *Ty = CountZeros->getType(); |
| 1685 | unsigned SizeInBits = Ty->getPrimitiveSizeInBits(); |
Jun Bum Lim | be11bdc | 2016-05-13 18:38:35 +0000 | [diff] [blame] | 1686 | if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits()) |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1687 | return false; |
| 1688 | |
| 1689 | // The intrinsic will be sunk behind a compare against zero and branch. |
| 1690 | BasicBlock *StartBlock = CountZeros->getParent(); |
| 1691 | BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false"); |
| 1692 | |
| 1693 | // Create another block after the count zero intrinsic. A PHI will be added |
| 1694 | // in this block to select the result of the intrinsic or the bit-width |
| 1695 | // constant if the input to the intrinsic is zero. |
| 1696 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros)); |
| 1697 | BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end"); |
| 1698 | |
| 1699 | // Set up a builder to create a compare, conditional branch, and PHI. |
| 1700 | IRBuilder<> Builder(CountZeros->getContext()); |
| 1701 | Builder.SetInsertPoint(StartBlock->getTerminator()); |
| 1702 | Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc()); |
| 1703 | |
| 1704 | // Replace the unconditional branch that was created by the first split with |
| 1705 | // a compare against zero and a conditional branch. |
| 1706 | Value *Zero = Constant::getNullValue(Ty); |
| 1707 | Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz"); |
| 1708 | Builder.CreateCondBr(Cmp, EndBlock, CallBlock); |
| 1709 | StartBlock->getTerminator()->eraseFromParent(); |
| 1710 | |
| 1711 | // Create a PHI in the end block to select either the output of the intrinsic |
| 1712 | // or the bit width of the operand. |
| 1713 | Builder.SetInsertPoint(&EndBlock->front()); |
| 1714 | PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz"); |
| 1715 | CountZeros->replaceAllUsesWith(PN); |
| 1716 | Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits)); |
| 1717 | PN->addIncoming(BitWidth, StartBlock); |
| 1718 | PN->addIncoming(CountZeros, CallBlock); |
| 1719 | |
| 1720 | // We are explicitly handling the zero case, so we can set the intrinsic's |
| 1721 | // undefined zero argument to 'true'. This will also prevent reprocessing the |
| 1722 | // intrinsic; we only despeculate when a zero input is defined. |
| 1723 | CountZeros->setArgOperand(1, Builder.getTrue()); |
| 1724 | ModifiedDT = true; |
| 1725 | return true; |
| 1726 | } |
| 1727 | |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 1728 | bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1729 | BasicBlock *BB = CI->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1730 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1731 | // Lower inline assembly if we can. |
| 1732 | // If we found an inline asm expession, and if the target knows how to |
| 1733 | // lower it to normal LLVM code, do so now. |
| 1734 | if (TLI && isa<InlineAsm>(CI->getCalledValue())) { |
| 1735 | if (TLI->ExpandInlineAsm(CI)) { |
| 1736 | // Avoid invalidating the iterator. |
| 1737 | CurInstIterator = BB->begin(); |
| 1738 | // Avoid processing instructions out of order, which could cause |
| 1739 | // reuse before a value is defined. |
| 1740 | SunkAddrs.clear(); |
| 1741 | return true; |
| 1742 | } |
| 1743 | // Sink address computing for memory operands into the block. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1744 | if (optimizeInlineAsmInst(CI)) |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 1745 | return true; |
| 1746 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1747 | |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1748 | // Align the pointer arguments to this call if the target thinks it's a good |
| 1749 | // idea |
| 1750 | unsigned MinSize, PrefAlign; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1751 | if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) { |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1752 | for (auto &Arg : CI->arg_operands()) { |
| 1753 | // We want to align both objects whose address is used directly and |
| 1754 | // objects whose address is used in casts and GEPs, though it only makes |
| 1755 | // sense for GEPs if the offset is a multiple of the desired alignment and |
| 1756 | // if size - offset meets the size threshold. |
| 1757 | if (!Arg->getType()->isPointerTy()) |
| 1758 | continue; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1759 | APInt Offset(DL->getPointerSizeInBits( |
| 1760 | cast<PointerType>(Arg->getType())->getAddressSpace()), |
| 1761 | 0); |
| 1762 | Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1763 | uint64_t Offset2 = Offset.getLimitedValue(); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1764 | if ((Offset2 & (PrefAlign-1)) != 0) |
| 1765 | continue; |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1766 | AllocaInst *AI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1767 | if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign && |
| 1768 | DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2) |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1769 | AI->setAlignment(PrefAlign); |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1770 | // Global variables can only be aligned if they are defined in this |
| 1771 | // object (i.e. they are uniquely initialized in this object), and |
| 1772 | // over-aligning global variables that have an explicit section is |
| 1773 | // forbidden. |
| 1774 | GlobalVariable *GV; |
James Y Knight | ac03dca | 2016-01-15 16:33:06 +0000 | [diff] [blame] | 1775 | if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() && |
Tim Northover | 918f050 | 2016-07-18 18:28:52 +0000 | [diff] [blame] | 1776 | GV->getPointerAlignment(*DL) < PrefAlign && |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 1777 | DL->getTypeAllocSize(GV->getValueType()) >= |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1778 | MinSize + Offset2) |
John Brawn | e8fd6c8 | 2015-04-13 10:47:39 +0000 | [diff] [blame] | 1779 | GV->setAlignment(PrefAlign); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1780 | } |
| 1781 | // If this is a memcpy (or similar) then we may be able to improve the |
| 1782 | // alignment |
| 1783 | if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1784 | unsigned Align = getKnownAlignment(MI->getDest(), *DL); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1785 | if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 1786 | Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL)); |
Pete Cooper | 67cf9a7 | 2015-11-19 05:56:52 +0000 | [diff] [blame] | 1787 | if (Align > MI->getAlignment()) |
| 1788 | MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align)); |
John Brawn | 0dbcd65 | 2015-03-18 12:01:59 +0000 | [diff] [blame] | 1789 | } |
| 1790 | } |
| 1791 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 1792 | // If we have a cold call site, try to sink addressing computation into the |
| 1793 | // cold block. This interacts with our handling for loads and stores to |
| 1794 | // ensure that we can fold all uses of a potential addressing computation |
| 1795 | // into their uses. TODO: generalize this to work over profiling data |
| 1796 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 1797 | for (auto &Arg : CI->arg_operands()) { |
| 1798 | if (!Arg->getType()->isPointerTy()) |
| 1799 | continue; |
| 1800 | unsigned AS = Arg->getType()->getPointerAddressSpace(); |
| 1801 | return optimizeMemoryInst(CI, Arg, Arg->getType(), AS); |
| 1802 | } |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 1803 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1804 | IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1805 | if (II) { |
| 1806 | switch (II->getIntrinsicID()) { |
| 1807 | default: break; |
| 1808 | case Intrinsic::objectsize: { |
| 1809 | // Lower all uses of llvm.objectsize.* |
George Burgess IV | 3f08914 | 2016-12-20 23:46:36 +0000 | [diff] [blame] | 1810 | ConstantInt *RetVal = |
| 1811 | lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1812 | // Substituting this can cause recursive simplifications, which can |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 1813 | // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case |
| 1814 | // this |
Sanjoy Das | 2cbeb00 | 2017-04-26 16:37:05 +0000 | [diff] [blame] | 1815 | // happens. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 1816 | Value *CurValue = &*CurInstIterator; |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 1817 | WeakTrackingVH IterHandle(CurValue); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 1818 | |
Sanjay Patel | 545a456 | 2016-01-20 18:59:16 +0000 | [diff] [blame] | 1819 | replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr); |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1820 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1821 | // If the iterator instruction was recursively deleted, start over at the |
| 1822 | // start of the block. |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 1823 | if (IterHandle != CurValue) { |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1824 | CurInstIterator = BB->begin(); |
| 1825 | SunkAddrs.clear(); |
| 1826 | } |
| 1827 | return true; |
Chris Lattner | 86d56c6 | 2011-01-18 20:53:04 +0000 | [diff] [blame] | 1828 | } |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1829 | case Intrinsic::aarch64_stlxr: |
| 1830 | case Intrinsic::aarch64_stxr: { |
| 1831 | ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0)); |
| 1832 | if (!ExtVal || !ExtVal->hasOneUse() || |
| 1833 | ExtVal->getParent() == CI->getParent()) |
| 1834 | return false; |
| 1835 | // Sink a zext feeding stlxr/stxr before it, so it can be folded into it. |
| 1836 | ExtVal->moveBefore(CI); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 1837 | // Mark this instruction as "inserted by CGP", so that other |
| 1838 | // optimizations don't touch it. |
| 1839 | InsertedInsts.insert(ExtVal); |
Ahmed Bougacha | 236f904 | 2015-05-22 21:37:17 +0000 | [diff] [blame] | 1840 | return true; |
| 1841 | } |
Piotr Padlewski | 6c15ec4 | 2015-09-15 18:32:14 +0000 | [diff] [blame] | 1842 | case Intrinsic::invariant_group_barrier: |
| 1843 | II->replaceAllUsesWith(II->getArgOperand(0)); |
| 1844 | II->eraseFromParent(); |
| 1845 | return true; |
Sanjay Patel | 4699b8a | 2015-11-19 16:37:10 +0000 | [diff] [blame] | 1846 | |
| 1847 | case Intrinsic::cttz: |
| 1848 | case Intrinsic::ctlz: |
| 1849 | // If counting zeros is expensive, try to avoid it. |
| 1850 | return despeculateCountZeros(II, TLI, DL, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1851 | } |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1852 | |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1853 | if (TLI) { |
| 1854 | SmallVector<Value*, 2> PtrOps; |
| 1855 | Type *AccessTy; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 1856 | if (TLI->getAddrModeArguments(II, PtrOps, AccessTy)) |
| 1857 | while (!PtrOps.empty()) { |
| 1858 | Value *PtrVal = PtrOps.pop_back_val(); |
| 1859 | unsigned AS = PtrVal->getType()->getPointerAddressSpace(); |
| 1860 | if (optimizeMemoryInst(II, PtrVal, AccessTy, AS)) |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1861 | return true; |
Matt Arsenault | 1672b1b | 2017-02-08 07:09:03 +0000 | [diff] [blame] | 1862 | } |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 1863 | } |
Pete Cooper | 615fd89 | 2012-03-13 20:59:56 +0000 | [diff] [blame] | 1864 | } |
| 1865 | |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1866 | // From here on out we're working with named functions. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1867 | if (!CI->getCalledFunction()) return false; |
Devang Patel | 0da5250 | 2011-05-26 21:51:06 +0000 | [diff] [blame] | 1868 | |
Benjamin Kramer | 7b88a49 | 2010-03-12 09:27:41 +0000 | [diff] [blame] | 1869 | // Lower all default uses of _chk calls. This is very similar |
| 1870 | // to what InstCombineCalls does, but here we are only lowering calls |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1871 | // to fortified library functions (e.g. __memcpy_chk) that have the default |
| 1872 | // "don't know" as the objectsize. Anything else should be left alone. |
Mehdi Amini | a28d91d | 2015-03-10 02:37:25 +0000 | [diff] [blame] | 1873 | FortifiedLibCallSimplifier Simplifier(TLInfo, true); |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1874 | if (Value *V = Simplifier.optimizeCall(CI)) { |
| 1875 | CI->replaceAllUsesWith(V); |
| 1876 | CI->eraseFromParent(); |
| 1877 | return true; |
| 1878 | } |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 1879 | |
Ahmed Bougacha | e03bef7 | 2015-01-12 17:22:43 +0000 | [diff] [blame] | 1880 | return false; |
Eric Christopher | 4b7948e | 2010-03-11 02:41:03 +0000 | [diff] [blame] | 1881 | } |
Chris Lattner | 1b93be5 | 2011-01-15 07:25:29 +0000 | [diff] [blame] | 1882 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 1883 | /// Look for opportunities to duplicate return instructions to the predecessor |
| 1884 | /// 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] | 1885 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1886 | /// bb0: |
| 1887 | /// %tmp0 = tail call i32 @f0() |
| 1888 | /// br label %return |
| 1889 | /// bb1: |
| 1890 | /// %tmp1 = tail call i32 @f1() |
| 1891 | /// br label %return |
| 1892 | /// bb2: |
| 1893 | /// %tmp2 = tail call i32 @f2() |
| 1894 | /// br label %return |
| 1895 | /// return: |
| 1896 | /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ] |
| 1897 | /// ret i32 %retval |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1898 | /// @endcode |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1899 | /// |
| 1900 | /// => |
| 1901 | /// |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1902 | /// @code |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1903 | /// bb0: |
| 1904 | /// %tmp0 = tail call i32 @f0() |
| 1905 | /// ret i32 %tmp0 |
| 1906 | /// bb1: |
| 1907 | /// %tmp1 = tail call i32 @f1() |
| 1908 | /// ret i32 %tmp1 |
| 1909 | /// bb2: |
| 1910 | /// %tmp2 = tail call i32 @f2() |
| 1911 | /// ret i32 %tmp2 |
Dmitri Gribenko | 2bc1d48 | 2012-09-13 12:34:29 +0000 | [diff] [blame] | 1912 | /// @endcode |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 1913 | bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) { |
Cameron Zwarich | 47e7175 | 2011-03-24 04:51:51 +0000 | [diff] [blame] | 1914 | if (!TLI) |
| 1915 | return false; |
| 1916 | |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1917 | ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator()); |
| 1918 | if (!RetI) |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 1919 | return false; |
| 1920 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 1921 | PHINode *PN = nullptr; |
| 1922 | BitCastInst *BCI = nullptr; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1923 | Value *V = RetI->getReturnValue(); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1924 | if (V) { |
| 1925 | BCI = dyn_cast<BitCastInst>(V); |
| 1926 | if (BCI) |
| 1927 | V = BCI->getOperand(0); |
| 1928 | |
| 1929 | PN = dyn_cast<PHINode>(V); |
| 1930 | if (!PN) |
| 1931 | return false; |
| 1932 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1933 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1934 | if (PN && PN->getParent() != BB) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1935 | return false; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1936 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1937 | // Make sure there are no instructions between the PHI and return, or that the |
| 1938 | // return is the first instruction in the block. |
| 1939 | if (PN) { |
| 1940 | BasicBlock::iterator BI = BB->begin(); |
| 1941 | do { ++BI; } while (isa<DbgInfoIntrinsic>(BI)); |
Evan Cheng | 249716e | 2012-07-27 21:21:26 +0000 | [diff] [blame] | 1942 | if (&*BI == BCI) |
| 1943 | // Also skip over the bitcast. |
| 1944 | ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1945 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1946 | return false; |
| 1947 | } else { |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1948 | BasicBlock::iterator BI = BB->begin(); |
| 1949 | while (isa<DbgInfoIntrinsic>(BI)) ++BI; |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 1950 | if (&*BI != RetI) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1951 | return false; |
| 1952 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1953 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1954 | /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail |
| 1955 | /// call. |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 1956 | const Function *F = BB->getParent(); |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1957 | SmallVector<CallInst*, 4> TailCalls; |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1958 | if (PN) { |
| 1959 | for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) { |
| 1960 | CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I)); |
| 1961 | // Make sure the phi value is indeed produced by the tail call. |
| 1962 | if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) && |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 1963 | TLI->mayBeEmittedAsTailCall(CI) && |
| 1964 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1965 | TailCalls.push_back(CI); |
| 1966 | } |
| 1967 | } else { |
| 1968 | SmallPtrSet<BasicBlock*, 4> VisitedBBs; |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1969 | 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] | 1970 | if (!VisitedBBs.insert(*PI).second) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1971 | continue; |
| 1972 | |
Duncan P. N. Exon Smith | 6c99015 | 2014-07-21 17:06:51 +0000 | [diff] [blame] | 1973 | BasicBlock::InstListType &InstList = (*PI)->getInstList(); |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1974 | BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin(); |
| 1975 | BasicBlock::InstListType::reverse_iterator RE = InstList.rend(); |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1976 | do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI)); |
| 1977 | if (RI == RE) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1978 | continue; |
Cameron Zwarich | 74157ab | 2011-03-24 16:34:59 +0000 | [diff] [blame] | 1979 | |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1980 | CallInst *CI = dyn_cast<CallInst>(&*RI); |
Michael Kuperstein | f79af6f | 2016-09-08 00:48:37 +0000 | [diff] [blame] | 1981 | if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) && |
| 1982 | attributesPermitTailCall(F, CI, RetI, *TLI)) |
Cameron Zwarich | 4649f17 | 2011-03-24 04:52:10 +0000 | [diff] [blame] | 1983 | TailCalls.push_back(CI); |
| 1984 | } |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 1985 | } |
| 1986 | |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1987 | bool Changed = false; |
| 1988 | for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) { |
| 1989 | CallInst *CI = TailCalls[i]; |
| 1990 | CallSite CS(CI); |
| 1991 | |
| 1992 | // Conservatively require the attributes of the call to match those of the |
| 1993 | // return. Ignore noalias because it doesn't affect the call sequence. |
Reid Kleckner | b518054 | 2017-03-21 16:57:19 +0000 | [diff] [blame] | 1994 | AttributeList CalleeAttrs = CS.getAttributes(); |
| 1995 | if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 1996 | .removeAttribute(Attribute::NoAlias) != |
| 1997 | AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex) |
| 1998 | .removeAttribute(Attribute::NoAlias)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 1999 | continue; |
| 2000 | |
| 2001 | // Make sure the call instruction is followed by an unconditional branch to |
| 2002 | // the return block. |
| 2003 | BasicBlock *CallBB = CI->getParent(); |
| 2004 | BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator()); |
| 2005 | if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB) |
| 2006 | continue; |
| 2007 | |
| 2008 | // Duplicate the return into CallBB. |
Michael Kuperstein | 7132156 | 2016-09-07 20:29:49 +0000 | [diff] [blame] | 2009 | (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB); |
Devang Patel | 8f606d7 | 2011-03-24 15:35:25 +0000 | [diff] [blame] | 2010 | ModifiedDT = Changed = true; |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2011 | ++NumRetsDup; |
| 2012 | } |
| 2013 | |
| 2014 | // If we eliminated all predecessors of the block, delete the block now. |
Evan Cheng | 64a223a | 2012-09-28 23:58:57 +0000 | [diff] [blame] | 2015 | if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB)) |
Cameron Zwarich | 0e331c0 | 2011-03-24 04:52:07 +0000 | [diff] [blame] | 2016 | BB->eraseFromParent(); |
| 2017 | |
| 2018 | return Changed; |
Evan Cheng | 0663f23 | 2011-03-21 01:19:09 +0000 | [diff] [blame] | 2019 | } |
| 2020 | |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2021 | //===----------------------------------------------------------------------===// |
Chris Lattner | 728f902 | 2008-11-25 07:09:13 +0000 | [diff] [blame] | 2022 | // Memory Optimization |
| 2023 | //===----------------------------------------------------------------------===// |
| 2024 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2025 | namespace { |
| 2026 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2027 | /// This is an extended version of TargetLowering::AddrMode |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2028 | /// which holds actual Value*'s for register values. |
Chandler Carruth | 95f83e0 | 2013-01-07 15:14:13 +0000 | [diff] [blame] | 2029 | struct ExtAddrMode : public TargetLowering::AddrMode { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2030 | Value *BaseReg = nullptr; |
| 2031 | Value *ScaledReg = nullptr; |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2032 | Value *OriginalValue = nullptr; |
| 2033 | |
| 2034 | enum FieldName { |
| 2035 | NoField = 0x00, |
| 2036 | BaseRegField = 0x01, |
| 2037 | BaseGVField = 0x02, |
| 2038 | BaseOffsField = 0x04, |
| 2039 | ScaledRegField = 0x08, |
| 2040 | ScaleField = 0x10, |
| 2041 | MultipleFields = 0xff |
| 2042 | }; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2043 | |
| 2044 | ExtAddrMode() = default; |
| 2045 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2046 | void print(raw_ostream &OS) const; |
| 2047 | void dump() const; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2048 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2049 | FieldName compare(const ExtAddrMode &other) { |
| 2050 | // First check that the types are the same on each field, as differing types |
| 2051 | // is something we can't cope with later on. |
| 2052 | if (BaseReg && other.BaseReg && |
| 2053 | BaseReg->getType() != other.BaseReg->getType()) |
| 2054 | return MultipleFields; |
| 2055 | if (BaseGV && other.BaseGV && |
| 2056 | BaseGV->getType() != other.BaseGV->getType()) |
| 2057 | return MultipleFields; |
| 2058 | if (ScaledReg && other.ScaledReg && |
| 2059 | ScaledReg->getType() != other.ScaledReg->getType()) |
| 2060 | return MultipleFields; |
| 2061 | |
| 2062 | // Check each field to see if it differs. |
| 2063 | unsigned Result = NoField; |
| 2064 | if (BaseReg != other.BaseReg) |
| 2065 | Result |= BaseRegField; |
| 2066 | if (BaseGV != other.BaseGV) |
| 2067 | Result |= BaseGVField; |
| 2068 | if (BaseOffs != other.BaseOffs) |
| 2069 | Result |= BaseOffsField; |
| 2070 | if (ScaledReg != other.ScaledReg) |
| 2071 | Result |= ScaledRegField; |
| 2072 | // Don't count 0 as being a different scale, because that actually means |
| 2073 | // unscaled (which will already be counted by having no ScaledReg). |
| 2074 | if (Scale && other.Scale && Scale != other.Scale) |
| 2075 | Result |= ScaleField; |
| 2076 | |
| 2077 | if (countPopulation(Result) > 1) |
| 2078 | return MultipleFields; |
| 2079 | else |
| 2080 | return static_cast<FieldName>(Result); |
| 2081 | } |
| 2082 | |
John Brawn | 4b47648 | 2017-11-27 11:29:15 +0000 | [diff] [blame] | 2083 | // An AddrMode is trivial if it involves no calculation i.e. it is just a base |
| 2084 | // with no offset. |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2085 | bool isTrivial() { |
John Brawn | 4b47648 | 2017-11-27 11:29:15 +0000 | [diff] [blame] | 2086 | // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is |
| 2087 | // trivial if at most one of these terms is nonzero, except that BaseGV and |
| 2088 | // BaseReg both being zero actually means a null pointer value, which we |
| 2089 | // consider to be 'non-zero' here. |
| 2090 | return !BaseOffs && !Scale && !(BaseGV && BaseReg); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2091 | } |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2092 | |
| 2093 | Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) { |
| 2094 | switch (Field) { |
| 2095 | default: |
| 2096 | return nullptr; |
| 2097 | case BaseRegField: |
| 2098 | return BaseReg; |
| 2099 | case BaseGVField: |
| 2100 | return BaseGV; |
| 2101 | case ScaledRegField: |
| 2102 | return ScaledReg; |
| 2103 | case BaseOffsField: |
| 2104 | return ConstantInt::get(IntPtrTy, BaseOffs); |
| 2105 | } |
| 2106 | } |
| 2107 | |
| 2108 | void SetCombinedField(FieldName Field, Value *V, |
| 2109 | const SmallVectorImpl<ExtAddrMode> &AddrModes) { |
| 2110 | switch (Field) { |
| 2111 | default: |
| 2112 | llvm_unreachable("Unhandled fields are expected to be rejected earlier"); |
| 2113 | break; |
| 2114 | case ExtAddrMode::BaseRegField: |
| 2115 | BaseReg = V; |
| 2116 | break; |
| 2117 | case ExtAddrMode::BaseGVField: |
| 2118 | // A combined BaseGV is an Instruction, not a GlobalValue, so it goes |
| 2119 | // in the BaseReg field. |
| 2120 | assert(BaseReg == nullptr); |
| 2121 | BaseReg = V; |
| 2122 | BaseGV = nullptr; |
| 2123 | break; |
| 2124 | case ExtAddrMode::ScaledRegField: |
| 2125 | ScaledReg = V; |
| 2126 | // If we have a mix of scaled and unscaled addrmodes then we want scale |
| 2127 | // to be the scale and not zero. |
| 2128 | if (!Scale) |
| 2129 | for (const ExtAddrMode &AM : AddrModes) |
| 2130 | if (AM.Scale) { |
| 2131 | Scale = AM.Scale; |
| 2132 | break; |
| 2133 | } |
| 2134 | break; |
| 2135 | case ExtAddrMode::BaseOffsField: |
| 2136 | // The offset is no longer a constant, so it goes in ScaledReg with a |
| 2137 | // scale of 1. |
| 2138 | assert(ScaledReg == nullptr); |
| 2139 | ScaledReg = V; |
| 2140 | Scale = 1; |
| 2141 | BaseOffs = 0; |
| 2142 | break; |
| 2143 | } |
| 2144 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2145 | }; |
| 2146 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2147 | } // end anonymous namespace |
| 2148 | |
Eli Friedman | c1f1f85 | 2013-09-10 23:09:24 +0000 | [diff] [blame] | 2149 | #ifndef NDEBUG |
| 2150 | static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) { |
| 2151 | AM.print(OS); |
| 2152 | return OS; |
| 2153 | } |
| 2154 | #endif |
| 2155 | |
Aaron Ballman | 615eb47 | 2017-10-15 14:32:27 +0000 | [diff] [blame] | 2156 | #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2157 | void ExtAddrMode::print(raw_ostream &OS) const { |
| 2158 | bool NeedPlus = false; |
| 2159 | OS << "["; |
| 2160 | if (BaseGV) { |
| 2161 | OS << (NeedPlus ? " + " : "") |
| 2162 | << "GV:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2163 | BaseGV->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2164 | NeedPlus = true; |
| 2165 | } |
| 2166 | |
Richard Trieu | c0f9121 | 2014-05-30 03:15:17 +0000 | [diff] [blame] | 2167 | if (BaseOffs) { |
| 2168 | OS << (NeedPlus ? " + " : "") |
| 2169 | << BaseOffs; |
| 2170 | NeedPlus = true; |
| 2171 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2172 | |
| 2173 | if (BaseReg) { |
| 2174 | OS << (NeedPlus ? " + " : "") |
| 2175 | << "Base:"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2176 | BaseReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2177 | NeedPlus = true; |
| 2178 | } |
| 2179 | if (Scale) { |
| 2180 | OS << (NeedPlus ? " + " : "") |
| 2181 | << Scale << "*"; |
Chandler Carruth | d48cdbf | 2014-01-09 02:29:41 +0000 | [diff] [blame] | 2182 | ScaledReg->printAsOperand(OS, /*PrintType=*/false); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2183 | } |
| 2184 | |
| 2185 | OS << ']'; |
| 2186 | } |
| 2187 | |
Yaron Keren | eb2a254 | 2016-01-29 20:50:44 +0000 | [diff] [blame] | 2188 | LLVM_DUMP_METHOD void ExtAddrMode::dump() const { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2189 | print(dbgs()); |
| 2190 | dbgs() << '\n'; |
| 2191 | } |
| 2192 | #endif |
| 2193 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2194 | namespace { |
| 2195 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2196 | /// \brief This class provides transaction based operation on the IR. |
| 2197 | /// Every change made through this class is recorded in the internal state and |
| 2198 | /// can be undone (rollback) until commit is called. |
| 2199 | class TypePromotionTransaction { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2200 | /// \brief This represents the common interface of the individual transaction. |
| 2201 | /// Each class implements the logic for doing one specific modification on |
| 2202 | /// the IR via the TypePromotionTransaction. |
| 2203 | class TypePromotionAction { |
| 2204 | protected: |
| 2205 | /// The Instruction modified. |
| 2206 | Instruction *Inst; |
| 2207 | |
| 2208 | public: |
| 2209 | /// \brief Constructor of the action. |
| 2210 | /// The constructor performs the related action on the IR. |
| 2211 | TypePromotionAction(Instruction *Inst) : Inst(Inst) {} |
| 2212 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2213 | virtual ~TypePromotionAction() = default; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2214 | |
| 2215 | /// \brief Undo the modification done by this action. |
| 2216 | /// When this method is called, the IR must be in the same state as it was |
| 2217 | /// before this action was applied. |
| 2218 | /// \pre Undoing the action works if and only if the IR is in the exact same |
| 2219 | /// state as it was directly after this action was applied. |
| 2220 | virtual void undo() = 0; |
| 2221 | |
| 2222 | /// \brief Advocate every change made by this action. |
| 2223 | /// When the results on the IR of the action are to be kept, it is important |
| 2224 | /// to call this function, otherwise hidden information may be kept forever. |
| 2225 | virtual void commit() { |
| 2226 | // Nothing to be done, this action is not doing anything. |
| 2227 | } |
| 2228 | }; |
| 2229 | |
| 2230 | /// \brief Utility to remember the position of an instruction. |
| 2231 | class InsertionHandler { |
| 2232 | /// Position of an instruction. |
| 2233 | /// Either an instruction: |
| 2234 | /// - Is the first in a basic block: BB is used. |
| 2235 | /// - Has a previous instructon: PrevInst is used. |
| 2236 | union { |
| 2237 | Instruction *PrevInst; |
| 2238 | BasicBlock *BB; |
| 2239 | } Point; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2240 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2241 | /// Remember whether or not the instruction had a previous instruction. |
| 2242 | bool HasPrevInstruction; |
| 2243 | |
| 2244 | public: |
| 2245 | /// \brief Record the position of \p Inst. |
| 2246 | InsertionHandler(Instruction *Inst) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2247 | BasicBlock::iterator It = Inst->getIterator(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2248 | HasPrevInstruction = (It != (Inst->getParent()->begin())); |
| 2249 | if (HasPrevInstruction) |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2250 | Point.PrevInst = &*--It; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2251 | else |
| 2252 | Point.BB = Inst->getParent(); |
| 2253 | } |
| 2254 | |
| 2255 | /// \brief Insert \p Inst at the recorded position. |
| 2256 | void insert(Instruction *Inst) { |
| 2257 | if (HasPrevInstruction) { |
| 2258 | if (Inst->getParent()) |
| 2259 | Inst->removeFromParent(); |
| 2260 | Inst->insertAfter(Point.PrevInst); |
| 2261 | } else { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 2262 | Instruction *Position = &*Point.BB->getFirstInsertionPt(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2263 | if (Inst->getParent()) |
| 2264 | Inst->moveBefore(Position); |
| 2265 | else |
| 2266 | Inst->insertBefore(Position); |
| 2267 | } |
| 2268 | } |
| 2269 | }; |
| 2270 | |
| 2271 | /// \brief Move an instruction before another. |
| 2272 | class InstructionMoveBefore : public TypePromotionAction { |
| 2273 | /// Original position of the instruction. |
| 2274 | InsertionHandler Position; |
| 2275 | |
| 2276 | public: |
| 2277 | /// \brief Move \p Inst before \p Before. |
| 2278 | InstructionMoveBefore(Instruction *Inst, Instruction *Before) |
| 2279 | : TypePromotionAction(Inst), Position(Inst) { |
| 2280 | DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n"); |
| 2281 | Inst->moveBefore(Before); |
| 2282 | } |
| 2283 | |
| 2284 | /// \brief Move the instruction back to its original position. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2285 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2286 | DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n"); |
| 2287 | Position.insert(Inst); |
| 2288 | } |
| 2289 | }; |
| 2290 | |
| 2291 | /// \brief Set the operand of an instruction with a new value. |
| 2292 | class OperandSetter : public TypePromotionAction { |
| 2293 | /// Original operand of the instruction. |
| 2294 | Value *Origin; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2295 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2296 | /// Index of the modified instruction. |
| 2297 | unsigned Idx; |
| 2298 | |
| 2299 | public: |
| 2300 | /// \brief Set \p Idx operand of \p Inst with \p NewVal. |
| 2301 | OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal) |
| 2302 | : TypePromotionAction(Inst), Idx(Idx) { |
| 2303 | DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n" |
| 2304 | << "for:" << *Inst << "\n" |
| 2305 | << "with:" << *NewVal << "\n"); |
| 2306 | Origin = Inst->getOperand(Idx); |
| 2307 | Inst->setOperand(Idx, NewVal); |
| 2308 | } |
| 2309 | |
| 2310 | /// \brief Restore the original value of the instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2311 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2312 | DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n" |
| 2313 | << "for: " << *Inst << "\n" |
| 2314 | << "with: " << *Origin << "\n"); |
| 2315 | Inst->setOperand(Idx, Origin); |
| 2316 | } |
| 2317 | }; |
| 2318 | |
| 2319 | /// \brief Hide the operands of an instruction. |
| 2320 | /// Do as if this instruction was not using any of its operands. |
| 2321 | class OperandsHider : public TypePromotionAction { |
| 2322 | /// The list of original operands. |
| 2323 | SmallVector<Value *, 4> OriginalValues; |
| 2324 | |
| 2325 | public: |
| 2326 | /// \brief Remove \p Inst from the uses of the operands of \p Inst. |
| 2327 | OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) { |
| 2328 | DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n"); |
| 2329 | unsigned NumOpnds = Inst->getNumOperands(); |
| 2330 | OriginalValues.reserve(NumOpnds); |
| 2331 | for (unsigned It = 0; It < NumOpnds; ++It) { |
| 2332 | // Save the current operand. |
| 2333 | Value *Val = Inst->getOperand(It); |
| 2334 | OriginalValues.push_back(Val); |
| 2335 | // Set a dummy one. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 2336 | // We could use OperandSetter here, but that would imply an overhead |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2337 | // that we are not willing to pay. |
| 2338 | Inst->setOperand(It, UndefValue::get(Val->getType())); |
| 2339 | } |
| 2340 | } |
| 2341 | |
| 2342 | /// \brief Restore the original list of uses. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2343 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2344 | DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n"); |
| 2345 | for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It) |
| 2346 | Inst->setOperand(It, OriginalValues[It]); |
| 2347 | } |
| 2348 | }; |
| 2349 | |
| 2350 | /// \brief Build a truncate instruction. |
| 2351 | class TruncBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2352 | Value *Val; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2353 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2354 | public: |
| 2355 | /// \brief Build a truncate instruction of \p Opnd producing a \p Ty |
| 2356 | /// result. |
| 2357 | /// trunc Opnd to Ty. |
| 2358 | TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) { |
| 2359 | IRBuilder<> Builder(Opnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2360 | Val = Builder.CreateTrunc(Opnd, Ty, "promoted"); |
| 2361 | DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2362 | } |
| 2363 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2364 | /// \brief Get the built value. |
| 2365 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2366 | |
| 2367 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2368 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2369 | DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n"); |
| 2370 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2371 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2372 | } |
| 2373 | }; |
| 2374 | |
| 2375 | /// \brief Build a sign extension instruction. |
| 2376 | class SExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2377 | Value *Val; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2378 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2379 | public: |
| 2380 | /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty |
| 2381 | /// result. |
| 2382 | /// sext Opnd to Ty. |
| 2383 | SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2384 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2385 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2386 | Val = Builder.CreateSExt(Opnd, Ty, "promoted"); |
| 2387 | DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n"); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2388 | } |
| 2389 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2390 | /// \brief Get the built value. |
| 2391 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2392 | |
| 2393 | /// \brief Remove the built instruction. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2394 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2395 | DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n"); |
| 2396 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2397 | IVal->eraseFromParent(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2398 | } |
| 2399 | }; |
| 2400 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2401 | /// \brief Build a zero extension instruction. |
| 2402 | class ZExtBuilder : public TypePromotionAction { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2403 | Value *Val; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2404 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2405 | public: |
| 2406 | /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty |
| 2407 | /// result. |
| 2408 | /// zext Opnd to Ty. |
| 2409 | ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty) |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2410 | : TypePromotionAction(InsertPt) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2411 | IRBuilder<> Builder(InsertPt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2412 | Val = Builder.CreateZExt(Opnd, Ty, "promoted"); |
| 2413 | DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n"); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2414 | } |
| 2415 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2416 | /// \brief Get the built value. |
| 2417 | Value *getBuiltValue() { return Val; } |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2418 | |
| 2419 | /// \brief Remove the built instruction. |
| 2420 | void undo() override { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2421 | DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n"); |
| 2422 | if (Instruction *IVal = dyn_cast<Instruction>(Val)) |
| 2423 | IVal->eraseFromParent(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2424 | } |
| 2425 | }; |
| 2426 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2427 | /// \brief Mutate an instruction to another type. |
| 2428 | class TypeMutator : public TypePromotionAction { |
| 2429 | /// Record the original type. |
| 2430 | Type *OrigTy; |
| 2431 | |
| 2432 | public: |
| 2433 | /// \brief Mutate the type of \p Inst into \p NewTy. |
| 2434 | TypeMutator(Instruction *Inst, Type *NewTy) |
| 2435 | : TypePromotionAction(Inst), OrigTy(Inst->getType()) { |
| 2436 | DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy |
| 2437 | << "\n"); |
| 2438 | Inst->mutateType(NewTy); |
| 2439 | } |
| 2440 | |
| 2441 | /// \brief Mutate the instruction back to its original type. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2442 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2443 | DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy |
| 2444 | << "\n"); |
| 2445 | Inst->mutateType(OrigTy); |
| 2446 | } |
| 2447 | }; |
| 2448 | |
| 2449 | /// \brief Replace the uses of an instruction by another instruction. |
| 2450 | class UsesReplacer : public TypePromotionAction { |
| 2451 | /// Helper structure to keep track of the replaced uses. |
| 2452 | struct InstructionAndIdx { |
| 2453 | /// The instruction using the instruction. |
| 2454 | Instruction *Inst; |
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 | /// The index where this instruction is used for Inst. |
| 2457 | unsigned Idx; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2458 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2459 | InstructionAndIdx(Instruction *Inst, unsigned Idx) |
| 2460 | : Inst(Inst), Idx(Idx) {} |
| 2461 | }; |
| 2462 | |
| 2463 | /// Keep track of the original uses (pair Instruction, Index). |
| 2464 | SmallVector<InstructionAndIdx, 4> OriginalUses; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2465 | |
| 2466 | using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2467 | |
| 2468 | public: |
| 2469 | /// \brief Replace all the use of \p Inst by \p New. |
| 2470 | UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) { |
| 2471 | DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New |
| 2472 | << "\n"); |
| 2473 | // Record the original uses. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 2474 | for (Use &U : Inst->uses()) { |
| 2475 | Instruction *UserI = cast<Instruction>(U.getUser()); |
| 2476 | OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2477 | } |
| 2478 | // Now, we can replace the uses. |
| 2479 | Inst->replaceAllUsesWith(New); |
| 2480 | } |
| 2481 | |
| 2482 | /// \brief Reassign the original uses of Inst to Inst. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2483 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2484 | DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n"); |
| 2485 | for (use_iterator UseIt = OriginalUses.begin(), |
| 2486 | EndIt = OriginalUses.end(); |
| 2487 | UseIt != EndIt; ++UseIt) { |
| 2488 | UseIt->Inst->setOperand(UseIt->Idx, Inst); |
| 2489 | } |
| 2490 | } |
| 2491 | }; |
| 2492 | |
| 2493 | /// \brief Remove an instruction from the IR. |
| 2494 | class InstructionRemover : public TypePromotionAction { |
| 2495 | /// Original position of the instruction. |
| 2496 | InsertionHandler Inserter; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2497 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2498 | /// Helper structure to hide all the link to the instruction. In other |
| 2499 | /// words, this helps to do as if the instruction was removed. |
| 2500 | OperandsHider Hider; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2501 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2502 | /// Keep track of the uses replaced, if any. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2503 | UsesReplacer *Replacer = nullptr; |
| 2504 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2505 | /// Keep track of instructions removed. |
| 2506 | SetOfInstrs &RemovedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2507 | |
| 2508 | public: |
| 2509 | /// \brief Remove all reference of \p Inst and optinally replace all its |
| 2510 | /// uses with New. |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2511 | /// \p RemovedInsts Keep track of the instructions removed by this Action. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2512 | /// \pre If !Inst->use_empty(), then New != nullptr |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2513 | InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts, |
| 2514 | Value *New = nullptr) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2515 | : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst), |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2516 | RemovedInsts(RemovedInsts) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2517 | if (New) |
| 2518 | Replacer = new UsesReplacer(Inst, New); |
| 2519 | DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n"); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2520 | RemovedInsts.insert(Inst); |
| 2521 | /// The instructions removed here will be freed after completing |
| 2522 | /// optimizeBlock() for all blocks as we need to keep track of the |
| 2523 | /// removed instructions during promotion. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2524 | Inst->removeFromParent(); |
| 2525 | } |
| 2526 | |
Alexander Kornienko | f817c1c | 2015-04-11 02:11:45 +0000 | [diff] [blame] | 2527 | ~InstructionRemover() override { delete Replacer; } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2528 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2529 | /// \brief Resurrect the instruction and reassign it to the proper uses if |
| 2530 | /// new value was provided when build this action. |
Craig Topper | 4584cd5 | 2014-03-07 09:26:03 +0000 | [diff] [blame] | 2531 | void undo() override { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2532 | DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n"); |
| 2533 | Inserter.insert(Inst); |
| 2534 | if (Replacer) |
| 2535 | Replacer->undo(); |
| 2536 | Hider.undo(); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2537 | RemovedInsts.erase(Inst); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2538 | } |
| 2539 | }; |
| 2540 | |
| 2541 | public: |
| 2542 | /// Restoration point. |
| 2543 | /// The restoration point is a pointer to an action instead of an iterator |
| 2544 | /// because the iterator may be invalidated but not the pointer. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2545 | using ConstRestorationPt = const TypePromotionAction *; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2546 | |
| 2547 | TypePromotionTransaction(SetOfInstrs &RemovedInsts) |
| 2548 | : RemovedInsts(RemovedInsts) {} |
| 2549 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2550 | /// Advocate every changes made in that transaction. |
| 2551 | void commit(); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2552 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2553 | /// Undo all the changes made after the given point. |
| 2554 | void rollback(ConstRestorationPt Point); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2555 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2556 | /// Get the current restoration point. |
| 2557 | ConstRestorationPt getRestorationPoint() const; |
| 2558 | |
| 2559 | /// \name API for IR modification with state keeping to support rollback. |
| 2560 | /// @{ |
| 2561 | /// Same as Instruction::setOperand. |
| 2562 | void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2563 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2564 | /// Same as Instruction::eraseFromParent. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2565 | void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2566 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2567 | /// Same as Value::replaceAllUsesWith. |
| 2568 | void replaceAllUsesWith(Instruction *Inst, Value *New); |
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 | /// Same as Value::mutateType. |
| 2571 | void mutateType(Instruction *Inst, Type *NewTy); |
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 | /// Same as IRBuilder::createTrunc. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2574 | Value *createTrunc(Instruction *Opnd, Type *Ty); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2575 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2576 | /// Same as IRBuilder::createSExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2577 | Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2578 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2579 | /// Same as IRBuilder::createZExt. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2580 | Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty); |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2581 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2582 | /// Same as Instruction::moveBefore. |
| 2583 | void moveBefore(Instruction *Inst, Instruction *Before); |
| 2584 | /// @} |
| 2585 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2586 | private: |
| 2587 | /// The ordered list of actions made so far. |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2588 | SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2589 | |
| 2590 | using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator; |
| 2591 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 2592 | SetOfInstrs &RemovedInsts; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2593 | }; |
| 2594 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2595 | } // end anonymous namespace |
| 2596 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2597 | void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx, |
| 2598 | Value *NewVal) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2599 | Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>( |
| 2600 | Inst, Idx, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2601 | } |
| 2602 | |
| 2603 | void TypePromotionTransaction::eraseInstruction(Instruction *Inst, |
| 2604 | Value *NewVal) { |
| 2605 | Actions.push_back( |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2606 | llvm::make_unique<TypePromotionTransaction::InstructionRemover>( |
| 2607 | Inst, RemovedInsts, NewVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2608 | } |
| 2609 | |
| 2610 | void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst, |
| 2611 | Value *New) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2612 | Actions.push_back( |
| 2613 | llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2614 | } |
| 2615 | |
| 2616 | void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2617 | Actions.push_back( |
| 2618 | llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2619 | } |
| 2620 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2621 | Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, |
| 2622 | Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2623 | std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2624 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2625 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2626 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2627 | } |
| 2628 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2629 | Value *TypePromotionTransaction::createSExt(Instruction *Inst, |
| 2630 | Value *Opnd, Type *Ty) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2631 | std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2632 | Value *Val = Ptr->getBuiltValue(); |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2633 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2634 | return Val; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2635 | } |
| 2636 | |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2637 | Value *TypePromotionTransaction::createZExt(Instruction *Inst, |
| 2638 | Value *Opnd, Type *Ty) { |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2639 | std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2640 | Value *Val = Ptr->getBuiltValue(); |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2641 | Actions.push_back(std::move(Ptr)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 2642 | return Val; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 2643 | } |
| 2644 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2645 | void TypePromotionTransaction::moveBefore(Instruction *Inst, |
| 2646 | Instruction *Before) { |
| 2647 | Actions.push_back( |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2648 | llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>( |
| 2649 | Inst, Before)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2650 | } |
| 2651 | |
| 2652 | TypePromotionTransaction::ConstRestorationPt |
| 2653 | TypePromotionTransaction::getRestorationPoint() const { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2654 | return !Actions.empty() ? Actions.back().get() : nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2655 | } |
| 2656 | |
| 2657 | void TypePromotionTransaction::commit() { |
| 2658 | for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2659 | ++It) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2660 | (*It)->commit(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2661 | Actions.clear(); |
| 2662 | } |
| 2663 | |
| 2664 | void TypePromotionTransaction::rollback( |
| 2665 | TypePromotionTransaction::ConstRestorationPt Point) { |
David Blaikie | 7620b31 | 2014-04-15 06:17:44 +0000 | [diff] [blame] | 2666 | while (!Actions.empty() && Point != Actions.back().get()) { |
| 2667 | std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2668 | Curr->undo(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2669 | } |
| 2670 | } |
| 2671 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2672 | namespace { |
| 2673 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2674 | /// \brief A helper class for matching addressing modes. |
| 2675 | /// |
| 2676 | /// This encapsulates the logic for matching the target-legal addressing modes. |
| 2677 | class AddressingModeMatcher { |
| 2678 | SmallVectorImpl<Instruction*> &AddrModeInsts; |
| 2679 | const TargetLowering &TLI; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2680 | const TargetRegisterInfo &TRI; |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2681 | const DataLayout &DL; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2682 | |
| 2683 | /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and |
| 2684 | /// the memory instruction that we're computing this address for. |
| 2685 | Type *AccessTy; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2686 | unsigned AddrSpace; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2687 | Instruction *MemoryInst; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2688 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2689 | /// This is the addressing mode that we're building up. This is |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2690 | /// part of the return value of this addressing mode matching stuff. |
| 2691 | ExtAddrMode &AddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2692 | |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2693 | /// The instructions inserted by other CodeGenPrepare optimizations. |
| 2694 | const SetOfInstrs &InsertedInsts; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2695 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2696 | /// A map from the instructions to their type before promotion. |
| 2697 | InstrToOrigTy &PromotedInsts; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2698 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2699 | /// The ongoing transaction where every action should be registered. |
| 2700 | TypePromotionTransaction &TPT; |
| 2701 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2702 | /// This is set to true when we should not do profitability checks. |
| 2703 | /// When true, IsProfitableToFoldIntoAddressingMode always returns true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2704 | bool IgnoreProfitability; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2705 | |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 2706 | AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2707 | const TargetLowering &TLI, |
| 2708 | const TargetRegisterInfo &TRI, |
| 2709 | Type *AT, unsigned AS, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2710 | Instruction *MI, ExtAddrMode &AM, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2711 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2712 | InstrToOrigTy &PromotedInsts, |
| 2713 | TypePromotionTransaction &TPT) |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2714 | : AddrModeInsts(AMI), TLI(TLI), TRI(TRI), |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 2715 | DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS), |
| 2716 | MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts), |
| 2717 | PromotedInsts(PromotedInsts), TPT(TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2718 | IgnoreProfitability = false; |
| 2719 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 2720 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2721 | public: |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 2722 | /// 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] | 2723 | /// give an access type of AccessTy. This returns a list of involved |
| 2724 | /// instructions in AddrModeInsts. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2725 | /// \p InsertedInsts The instructions inserted by other CodeGenPrepare |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2726 | /// optimizations. |
| 2727 | /// \p PromotedInsts maps the instructions to their type before promotion. |
| 2728 | /// \p The ongoing transaction where every action should be registered. |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 2729 | static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2730 | Instruction *MemoryInst, |
| 2731 | SmallVectorImpl<Instruction*> &AddrModeInsts, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2732 | const TargetLowering &TLI, |
| 2733 | const TargetRegisterInfo &TRI, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2734 | const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 2735 | InstrToOrigTy &PromotedInsts, |
| 2736 | TypePromotionTransaction &TPT) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2737 | ExtAddrMode Result; |
| 2738 | |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 2739 | bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, |
| 2740 | AccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 2741 | MemoryInst, Result, InsertedInsts, |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2742 | PromotedInsts, TPT).matchAddr(V, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2743 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 2744 | return Result; |
| 2745 | } |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 2746 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2747 | private: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2748 | bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth); |
| 2749 | bool matchAddr(Value *V, unsigned Depth); |
| 2750 | bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth, |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 2751 | bool *MovedAway = nullptr); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2752 | bool isProfitableToFoldIntoAddressingMode(Instruction *I, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2753 | ExtAddrMode &AMBefore, |
| 2754 | ExtAddrMode &AMAfter); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 2755 | bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2); |
| 2756 | bool isPromotionProfitable(unsigned NewCost, unsigned OldCost, |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 2757 | Value *PromotedOperand) const; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 2758 | }; |
| 2759 | |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2760 | /// \brief Keep track of simplification of Phi nodes. |
| 2761 | /// Accept the set of all phi nodes and erase phi node from this set |
| 2762 | /// if it is simplified. |
| 2763 | class SimplificationTracker { |
| 2764 | DenseMap<Value *, Value *> Storage; |
| 2765 | const SimplifyQuery &SQ; |
| 2766 | SmallPtrSetImpl<PHINode *> &AllPhiNodes; |
| 2767 | SmallPtrSetImpl<SelectInst *> &AllSelectNodes; |
| 2768 | |
| 2769 | public: |
| 2770 | SimplificationTracker(const SimplifyQuery &sq, |
| 2771 | SmallPtrSetImpl<PHINode *> &APN, |
| 2772 | SmallPtrSetImpl<SelectInst *> &ASN) |
| 2773 | : SQ(sq), AllPhiNodes(APN), AllSelectNodes(ASN) {} |
| 2774 | |
| 2775 | Value *Get(Value *V) { |
| 2776 | do { |
| 2777 | auto SV = Storage.find(V); |
| 2778 | if (SV == Storage.end()) |
| 2779 | return V; |
| 2780 | V = SV->second; |
| 2781 | } while (true); |
| 2782 | } |
| 2783 | |
| 2784 | Value *Simplify(Value *Val) { |
| 2785 | SmallVector<Value *, 32> WorkList; |
| 2786 | SmallPtrSet<Value *, 32> Visited; |
| 2787 | WorkList.push_back(Val); |
| 2788 | while (!WorkList.empty()) { |
| 2789 | auto P = WorkList.pop_back_val(); |
| 2790 | if (!Visited.insert(P).second) |
| 2791 | continue; |
| 2792 | if (auto *PI = dyn_cast<Instruction>(P)) |
| 2793 | if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) { |
| 2794 | for (auto *U : PI->users()) |
| 2795 | WorkList.push_back(cast<Value>(U)); |
| 2796 | Put(PI, V); |
| 2797 | PI->replaceAllUsesWith(V); |
| 2798 | if (auto *PHI = dyn_cast<PHINode>(PI)) |
| 2799 | AllPhiNodes.erase(PHI); |
| 2800 | if (auto *Select = dyn_cast<SelectInst>(PI)) |
| 2801 | AllSelectNodes.erase(Select); |
| 2802 | PI->eraseFromParent(); |
| 2803 | } |
| 2804 | } |
| 2805 | return Get(Val); |
| 2806 | } |
| 2807 | |
| 2808 | void Put(Value *From, Value *To) { |
| 2809 | Storage.insert({ From, To }); |
| 2810 | } |
| 2811 | }; |
| 2812 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2813 | /// \brief A helper class for combining addressing modes. |
| 2814 | class AddressingModeCombiner { |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2815 | typedef std::pair<Value *, BasicBlock *> ValueInBB; |
| 2816 | typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping; |
| 2817 | typedef std::pair<PHINode *, PHINode *> PHIPair; |
| 2818 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2819 | private: |
| 2820 | /// The addressing modes we've collected. |
| 2821 | SmallVector<ExtAddrMode, 16> AddrModes; |
| 2822 | |
| 2823 | /// The field in which the AddrModes differ, when we have more than one. |
| 2824 | ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField; |
| 2825 | |
| 2826 | /// Are the AddrModes that we have all just equal to their original values? |
| 2827 | bool AllAddrModesTrivial = true; |
| 2828 | |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2829 | /// Common Type for all different fields in addressing modes. |
| 2830 | Type *CommonType; |
| 2831 | |
| 2832 | /// SimplifyQuery for simplifyInstruction utility. |
| 2833 | const SimplifyQuery &SQ; |
| 2834 | |
| 2835 | /// Original Address. |
| 2836 | ValueInBB Original; |
| 2837 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2838 | public: |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2839 | AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue) |
| 2840 | : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {} |
| 2841 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2842 | /// \brief Get the combined AddrMode |
| 2843 | const ExtAddrMode &getAddrMode() const { |
| 2844 | return AddrModes[0]; |
| 2845 | } |
| 2846 | |
| 2847 | /// \brief Add a new AddrMode if it's compatible with the AddrModes we already |
| 2848 | /// have. |
| 2849 | /// \return True iff we succeeded in doing so. |
| 2850 | bool addNewAddrMode(ExtAddrMode &NewAddrMode) { |
| 2851 | // Take note of if we have any non-trivial AddrModes, as we need to detect |
| 2852 | // when all AddrModes are trivial as then we would introduce a phi or select |
| 2853 | // which just duplicates what's already there. |
| 2854 | AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial(); |
| 2855 | |
| 2856 | // If this is the first addrmode then everything is fine. |
| 2857 | if (AddrModes.empty()) { |
| 2858 | AddrModes.emplace_back(NewAddrMode); |
| 2859 | return true; |
| 2860 | } |
| 2861 | |
| 2862 | // Figure out how different this is from the other address modes, which we |
| 2863 | // can do just by comparing against the first one given that we only care |
| 2864 | // about the cumulative difference. |
| 2865 | ExtAddrMode::FieldName ThisDifferentField = |
| 2866 | AddrModes[0].compare(NewAddrMode); |
| 2867 | if (DifferentField == ExtAddrMode::NoField) |
| 2868 | DifferentField = ThisDifferentField; |
| 2869 | else if (DifferentField != ThisDifferentField) |
| 2870 | DifferentField = ExtAddrMode::MultipleFields; |
| 2871 | |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2872 | // If NewAddrMode differs in only one dimension, and that dimension isn't |
| 2873 | // the amount that ScaledReg is scaled by, then we can handle it by |
Serguei Katkov | 505359f | 2017-11-20 05:42:36 +0000 | [diff] [blame] | 2874 | // inserting a phi/select later on. Even if NewAddMode is the same |
| 2875 | // we still need to collect it due to original value is different. |
| 2876 | // And later we will need all original values as anchors during |
| 2877 | // finding the common Phi node. |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2878 | if (DifferentField != ExtAddrMode::MultipleFields && |
| 2879 | DifferentField != ExtAddrMode::ScaleField) { |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2880 | AddrModes.emplace_back(NewAddrMode); |
| 2881 | return true; |
| 2882 | } |
| 2883 | |
| 2884 | // We couldn't combine NewAddrMode with the rest, so return failure. |
| 2885 | AddrModes.clear(); |
| 2886 | return false; |
| 2887 | } |
| 2888 | |
| 2889 | /// \brief Combine the addressing modes we've collected into a single |
| 2890 | /// addressing mode. |
| 2891 | /// \return True iff we successfully combined them or we only had one so |
| 2892 | /// didn't need to combine them anyway. |
| 2893 | bool combineAddrModes() { |
| 2894 | // If we have no AddrModes then they can't be combined. |
| 2895 | if (AddrModes.size() == 0) |
| 2896 | return false; |
| 2897 | |
| 2898 | // A single AddrMode can trivially be combined. |
Serguei Katkov | 505359f | 2017-11-20 05:42:36 +0000 | [diff] [blame] | 2899 | if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField) |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 2900 | return true; |
| 2901 | |
| 2902 | // If the AddrModes we collected are all just equal to the value they are |
| 2903 | // derived from then combining them wouldn't do anything useful. |
| 2904 | if (AllAddrModesTrivial) |
| 2905 | return false; |
| 2906 | |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2907 | if (!addrModeCombiningAllowed()) |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2908 | return false; |
| 2909 | |
| 2910 | // Build a map between <original value, basic block where we saw it> to |
| 2911 | // value of base register. |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2912 | // Bail out if there is no common type. |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2913 | FoldAddrToValueMapping Map; |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2914 | if (!initializeMap(Map)) |
| 2915 | return false; |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2916 | |
| 2917 | Value *CommonValue = findCommon(Map); |
| 2918 | if (CommonValue) |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2919 | AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2920 | return CommonValue != nullptr; |
| 2921 | } |
| 2922 | |
| 2923 | private: |
| 2924 | /// \brief Initialize Map with anchor values. For address seen in some BB |
| 2925 | /// we set the value of different field saw in this address. |
| 2926 | /// If address is not an instruction than basic block is set to null. |
| 2927 | /// At the same time we find a common type for different field we will |
| 2928 | /// use to create new Phi/Select nodes. Keep it in CommonType field. |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2929 | /// Return false if there is no common type found. |
| 2930 | bool initializeMap(FoldAddrToValueMapping &Map) { |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2931 | // Keep track of keys where the value is null. We will need to replace it |
| 2932 | // with constant null when we know the common type. |
| 2933 | SmallVector<ValueInBB, 2> NullValue; |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2934 | Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType()); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2935 | for (auto &AM : AddrModes) { |
| 2936 | BasicBlock *BB = nullptr; |
| 2937 | if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue)) |
| 2938 | BB = I->getParent(); |
| 2939 | |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 2940 | Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy); |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2941 | if (DV) { |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2942 | auto *Type = DV->getType(); |
| 2943 | if (CommonType && CommonType != Type) |
| 2944 | return false; |
| 2945 | CommonType = Type; |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2946 | Map[{ AM.OriginalValue, BB }] = DV; |
| 2947 | } else { |
| 2948 | NullValue.push_back({ AM.OriginalValue, BB }); |
| 2949 | } |
| 2950 | } |
| 2951 | assert(CommonType && "At least one non-null value must be!"); |
| 2952 | for (auto VIBB : NullValue) |
| 2953 | Map[VIBB] = Constant::getNullValue(CommonType); |
Serguei Katkov | 5036459 | 2017-11-29 05:51:26 +0000 | [diff] [blame] | 2954 | return true; |
Serguei Katkov | d5d8d54 | 2017-11-05 05:50:33 +0000 | [diff] [blame] | 2955 | } |
| 2956 | |
| 2957 | /// \brief We have mapping between value A and basic block where value A |
| 2958 | /// seen to other value B where B was a field in addressing mode represented |
| 2959 | /// by A. Also we have an original value C representin an address in some |
| 2960 | /// basic block. Traversing from C through phi and selects we ended up with |
| 2961 | /// A's in a map. This utility function tries to find a value V which is a |
| 2962 | /// field in addressing mode C and traversing through phi nodes and selects |
| 2963 | /// we will end up in corresponded values B in a map. |
| 2964 | /// The utility will create a new Phi/Selects if needed. |
| 2965 | // The simple example looks as follows: |
| 2966 | // BB1: |
| 2967 | // p1 = b1 + 40 |
| 2968 | // br cond BB2, BB3 |
| 2969 | // BB2: |
| 2970 | // p2 = b2 + 40 |
| 2971 | // br BB3 |
| 2972 | // BB3: |
| 2973 | // p = phi [p1, BB1], [p2, BB2] |
| 2974 | // v = load p |
| 2975 | // Map is |
| 2976 | // <p1, BB1> -> b1 |
| 2977 | // <p2, BB2> -> b2 |
| 2978 | // Request is |
| 2979 | // <p, BB3> -> ? |
| 2980 | // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3 |
| 2981 | Value *findCommon(FoldAddrToValueMapping &Map) { |
| 2982 | // Tracks of new created Phi nodes. |
| 2983 | SmallPtrSet<PHINode *, 32> NewPhiNodes; |
| 2984 | // Tracks of new created Select nodes. |
| 2985 | SmallPtrSet<SelectInst *, 32> NewSelectNodes; |
| 2986 | // Tracks the simplification of new created phi nodes. The reason we use |
| 2987 | // this mapping is because we will add new created Phi nodes in AddrToBase. |
| 2988 | // Simplification of Phi nodes is recursive, so some Phi node may |
| 2989 | // be simplified after we added it to AddrToBase. |
| 2990 | // Using this mapping we can find the current value in AddrToBase. |
| 2991 | SimplificationTracker ST(SQ, NewPhiNodes, NewSelectNodes); |
| 2992 | |
| 2993 | // First step, DFS to create PHI nodes for all intermediate blocks. |
| 2994 | // Also fill traverse order for the second step. |
| 2995 | SmallVector<ValueInBB, 32> TraverseOrder; |
| 2996 | InsertPlaceholders(Map, TraverseOrder, NewPhiNodes, NewSelectNodes); |
| 2997 | |
| 2998 | // Second Step, fill new nodes by merged values and simplify if possible. |
| 2999 | FillPlaceholders(Map, TraverseOrder, ST); |
| 3000 | |
| 3001 | if (!AddrSinkNewSelects && NewSelectNodes.size() > 0) { |
| 3002 | DestroyNodes(NewPhiNodes); |
| 3003 | DestroyNodes(NewSelectNodes); |
| 3004 | return nullptr; |
| 3005 | } |
| 3006 | |
| 3007 | // Now we'd like to match New Phi nodes to existed ones. |
| 3008 | unsigned PhiNotMatchedCount = 0; |
| 3009 | if (!MatchPhiSet(NewPhiNodes, ST, AddrSinkNewPhis, PhiNotMatchedCount)) { |
| 3010 | DestroyNodes(NewPhiNodes); |
| 3011 | DestroyNodes(NewSelectNodes); |
| 3012 | return nullptr; |
| 3013 | } |
| 3014 | |
| 3015 | auto *Result = ST.Get(Map.find(Original)->second); |
| 3016 | if (Result) { |
| 3017 | NumMemoryInstsPhiCreated += NewPhiNodes.size() + PhiNotMatchedCount; |
| 3018 | NumMemoryInstsSelectCreated += NewSelectNodes.size(); |
| 3019 | } |
| 3020 | return Result; |
| 3021 | } |
| 3022 | |
| 3023 | /// \brief Destroy nodes from a set. |
| 3024 | template <typename T> void DestroyNodes(SmallPtrSetImpl<T *> &Instructions) { |
| 3025 | // For safe erasing, replace the Phi with dummy value first. |
| 3026 | auto Dummy = UndefValue::get(CommonType); |
| 3027 | for (auto I : Instructions) { |
| 3028 | I->replaceAllUsesWith(Dummy); |
| 3029 | I->eraseFromParent(); |
| 3030 | } |
| 3031 | } |
| 3032 | |
| 3033 | /// \brief Try to match PHI node to Candidate. |
| 3034 | /// Matcher tracks the matched Phi nodes. |
| 3035 | bool MatchPhiNode(PHINode *PHI, PHINode *Candidate, |
| 3036 | DenseSet<PHIPair> &Matcher, |
| 3037 | SmallPtrSetImpl<PHINode *> &PhiNodesToMatch) { |
| 3038 | SmallVector<PHIPair, 8> WorkList; |
| 3039 | Matcher.insert({ PHI, Candidate }); |
| 3040 | WorkList.push_back({ PHI, Candidate }); |
| 3041 | SmallSet<PHIPair, 8> Visited; |
| 3042 | while (!WorkList.empty()) { |
| 3043 | auto Item = WorkList.pop_back_val(); |
| 3044 | if (!Visited.insert(Item).second) |
| 3045 | continue; |
| 3046 | // We iterate over all incoming values to Phi to compare them. |
| 3047 | // If values are different and both of them Phi and the first one is a |
| 3048 | // Phi we added (subject to match) and both of them is in the same basic |
| 3049 | // block then we can match our pair if values match. So we state that |
| 3050 | // these values match and add it to work list to verify that. |
| 3051 | for (auto B : Item.first->blocks()) { |
| 3052 | Value *FirstValue = Item.first->getIncomingValueForBlock(B); |
| 3053 | Value *SecondValue = Item.second->getIncomingValueForBlock(B); |
| 3054 | if (FirstValue == SecondValue) |
| 3055 | continue; |
| 3056 | |
| 3057 | PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue); |
| 3058 | PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue); |
| 3059 | |
| 3060 | // One of them is not Phi or |
| 3061 | // The first one is not Phi node from the set we'd like to match or |
| 3062 | // Phi nodes from different basic blocks then |
| 3063 | // we will not be able to match. |
| 3064 | if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) || |
| 3065 | FirstPhi->getParent() != SecondPhi->getParent()) |
| 3066 | return false; |
| 3067 | |
| 3068 | // If we already matched them then continue. |
| 3069 | if (Matcher.count({ FirstPhi, SecondPhi })) |
| 3070 | continue; |
| 3071 | // So the values are different and does not match. So we need them to |
| 3072 | // match. |
| 3073 | Matcher.insert({ FirstPhi, SecondPhi }); |
| 3074 | // But me must check it. |
| 3075 | WorkList.push_back({ FirstPhi, SecondPhi }); |
| 3076 | } |
| 3077 | } |
| 3078 | return true; |
| 3079 | } |
| 3080 | |
| 3081 | /// \brief For the given set of PHI nodes try to find their equivalents. |
| 3082 | /// Returns false if this matching fails and creation of new Phi is disabled. |
| 3083 | bool MatchPhiSet(SmallPtrSetImpl<PHINode *> &PhiNodesToMatch, |
| 3084 | SimplificationTracker &ST, bool AllowNewPhiNodes, |
| 3085 | unsigned &PhiNotMatchedCount) { |
| 3086 | DenseSet<PHIPair> Matched; |
| 3087 | SmallPtrSet<PHINode *, 8> WillNotMatch; |
| 3088 | while (PhiNodesToMatch.size()) { |
| 3089 | PHINode *PHI = *PhiNodesToMatch.begin(); |
| 3090 | |
| 3091 | // Add us, if no Phi nodes in the basic block we do not match. |
| 3092 | WillNotMatch.clear(); |
| 3093 | WillNotMatch.insert(PHI); |
| 3094 | |
| 3095 | // Traverse all Phis until we found equivalent or fail to do that. |
| 3096 | bool IsMatched = false; |
| 3097 | for (auto &P : PHI->getParent()->phis()) { |
| 3098 | if (&P == PHI) |
| 3099 | continue; |
| 3100 | if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch))) |
| 3101 | break; |
| 3102 | // If it does not match, collect all Phi nodes from matcher. |
| 3103 | // if we end up with no match, them all these Phi nodes will not match |
| 3104 | // later. |
| 3105 | for (auto M : Matched) |
| 3106 | WillNotMatch.insert(M.first); |
| 3107 | Matched.clear(); |
| 3108 | } |
| 3109 | if (IsMatched) { |
| 3110 | // Replace all matched values and erase them. |
| 3111 | for (auto MV : Matched) { |
| 3112 | MV.first->replaceAllUsesWith(MV.second); |
| 3113 | PhiNodesToMatch.erase(MV.first); |
| 3114 | ST.Put(MV.first, MV.second); |
| 3115 | MV.first->eraseFromParent(); |
| 3116 | } |
| 3117 | Matched.clear(); |
| 3118 | continue; |
| 3119 | } |
| 3120 | // If we are not allowed to create new nodes then bail out. |
| 3121 | if (!AllowNewPhiNodes) |
| 3122 | return false; |
| 3123 | // Just remove all seen values in matcher. They will not match anything. |
| 3124 | PhiNotMatchedCount += WillNotMatch.size(); |
| 3125 | for (auto *P : WillNotMatch) |
| 3126 | PhiNodesToMatch.erase(P); |
| 3127 | } |
| 3128 | return true; |
| 3129 | } |
| 3130 | /// \brief Fill the placeholder with values from predecessors and simplify it. |
| 3131 | void FillPlaceholders(FoldAddrToValueMapping &Map, |
| 3132 | SmallVectorImpl<ValueInBB> &TraverseOrder, |
| 3133 | SimplificationTracker &ST) { |
| 3134 | while (!TraverseOrder.empty()) { |
| 3135 | auto Current = TraverseOrder.pop_back_val(); |
| 3136 | assert(Map.find(Current) != Map.end() && "No node to fill!!!"); |
| 3137 | Value *CurrentValue = Current.first; |
| 3138 | BasicBlock *CurrentBlock = Current.second; |
| 3139 | Value *V = Map[Current]; |
| 3140 | |
| 3141 | if (SelectInst *Select = dyn_cast<SelectInst>(V)) { |
| 3142 | // CurrentValue also must be Select. |
| 3143 | auto *CurrentSelect = cast<SelectInst>(CurrentValue); |
| 3144 | auto *TrueValue = CurrentSelect->getTrueValue(); |
| 3145 | ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue) |
| 3146 | ? CurrentBlock |
| 3147 | : nullptr }; |
| 3148 | assert(Map.find(TrueItem) != Map.end() && "No True Value!"); |
| 3149 | Select->setTrueValue(Map[TrueItem]); |
| 3150 | auto *FalseValue = CurrentSelect->getFalseValue(); |
| 3151 | ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue) |
| 3152 | ? CurrentBlock |
| 3153 | : nullptr }; |
| 3154 | assert(Map.find(FalseItem) != Map.end() && "No False Value!"); |
| 3155 | Select->setFalseValue(Map[FalseItem]); |
| 3156 | } else { |
| 3157 | // Must be a Phi node then. |
| 3158 | PHINode *PHI = cast<PHINode>(V); |
| 3159 | // Fill the Phi node with values from predecessors. |
| 3160 | bool IsDefinedInThisBB = |
| 3161 | cast<Instruction>(CurrentValue)->getParent() == CurrentBlock; |
| 3162 | auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue); |
| 3163 | for (auto B : predecessors(CurrentBlock)) { |
| 3164 | Value *PV = IsDefinedInThisBB |
| 3165 | ? CurrentPhi->getIncomingValueForBlock(B) |
| 3166 | : CurrentValue; |
| 3167 | ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr }; |
| 3168 | assert(Map.find(item) != Map.end() && "No predecessor Value!"); |
| 3169 | PHI->addIncoming(ST.Get(Map[item]), B); |
| 3170 | } |
| 3171 | } |
| 3172 | // Simplify if possible. |
| 3173 | Map[Current] = ST.Simplify(V); |
| 3174 | } |
| 3175 | } |
| 3176 | |
| 3177 | /// Starting from value recursively iterates over predecessors up to known |
| 3178 | /// ending values represented in a map. For each traversed block inserts |
| 3179 | /// a placeholder Phi or Select. |
| 3180 | /// Reports all new created Phi/Select nodes by adding them to set. |
| 3181 | /// Also reports and order in what basic blocks have been traversed. |
| 3182 | void InsertPlaceholders(FoldAddrToValueMapping &Map, |
| 3183 | SmallVectorImpl<ValueInBB> &TraverseOrder, |
| 3184 | SmallPtrSetImpl<PHINode *> &NewPhiNodes, |
| 3185 | SmallPtrSetImpl<SelectInst *> &NewSelectNodes) { |
| 3186 | SmallVector<ValueInBB, 32> Worklist; |
| 3187 | assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) && |
| 3188 | "Address must be a Phi or Select node"); |
| 3189 | auto *Dummy = UndefValue::get(CommonType); |
| 3190 | Worklist.push_back(Original); |
| 3191 | while (!Worklist.empty()) { |
| 3192 | auto Current = Worklist.pop_back_val(); |
| 3193 | // If value is not an instruction it is something global, constant, |
| 3194 | // parameter and we can say that this value is observable in any block. |
| 3195 | // Set block to null to denote it. |
| 3196 | // Also please take into account that it is how we build anchors. |
| 3197 | if (!isa<Instruction>(Current.first)) |
| 3198 | Current.second = nullptr; |
| 3199 | // if it is already visited or it is an ending value then skip it. |
| 3200 | if (Map.find(Current) != Map.end()) |
| 3201 | continue; |
| 3202 | TraverseOrder.push_back(Current); |
| 3203 | |
| 3204 | Value *CurrentValue = Current.first; |
| 3205 | BasicBlock *CurrentBlock = Current.second; |
| 3206 | // CurrentValue must be a Phi node or select. All others must be covered |
| 3207 | // by anchors. |
| 3208 | Instruction *CurrentI = cast<Instruction>(CurrentValue); |
| 3209 | bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock; |
| 3210 | |
| 3211 | unsigned PredCount = |
| 3212 | std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock)); |
| 3213 | // if Current Value is not defined in this basic block we are interested |
| 3214 | // in values in predecessors. |
| 3215 | if (!IsDefinedInThisBB) { |
| 3216 | assert(PredCount && "Unreachable block?!"); |
| 3217 | PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi", |
| 3218 | &CurrentBlock->front()); |
| 3219 | Map[Current] = PHI; |
| 3220 | NewPhiNodes.insert(PHI); |
| 3221 | // Add all predecessors in work list. |
| 3222 | for (auto B : predecessors(CurrentBlock)) |
| 3223 | Worklist.push_back({ CurrentValue, B }); |
| 3224 | continue; |
| 3225 | } |
| 3226 | // Value is defined in this basic block. |
| 3227 | if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) { |
| 3228 | // Is it OK to get metadata from OrigSelect?! |
| 3229 | // Create a Select placeholder with dummy value. |
| 3230 | SelectInst *Select = |
| 3231 | SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy, |
| 3232 | OrigSelect->getName(), OrigSelect, OrigSelect); |
| 3233 | Map[Current] = Select; |
| 3234 | NewSelectNodes.insert(Select); |
| 3235 | // We are interested in True and False value in this basic block. |
| 3236 | Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock }); |
| 3237 | Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock }); |
| 3238 | } else { |
| 3239 | // It must be a Phi node then. |
| 3240 | auto *CurrentPhi = cast<PHINode>(CurrentI); |
| 3241 | // Create new Phi node for merge of bases. |
| 3242 | assert(PredCount && "Unreachable block?!"); |
| 3243 | PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi", |
| 3244 | &CurrentBlock->front()); |
| 3245 | Map[Current] = PHI; |
| 3246 | NewPhiNodes.insert(PHI); |
| 3247 | |
| 3248 | // Add all predecessors in work list. |
| 3249 | for (auto B : predecessors(CurrentBlock)) |
| 3250 | Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B }); |
| 3251 | } |
| 3252 | } |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 3253 | } |
John Brawn | 70cdb5b | 2017-11-24 14:10:45 +0000 | [diff] [blame] | 3254 | |
| 3255 | bool addrModeCombiningAllowed() { |
| 3256 | if (DisableComplexAddrModes) |
| 3257 | return false; |
| 3258 | switch (DifferentField) { |
| 3259 | default: |
| 3260 | return false; |
| 3261 | case ExtAddrMode::BaseRegField: |
| 3262 | return AddrSinkCombineBaseReg; |
| 3263 | case ExtAddrMode::BaseGVField: |
| 3264 | return AddrSinkCombineBaseGV; |
| 3265 | case ExtAddrMode::BaseOffsField: |
| 3266 | return AddrSinkCombineBaseOffs; |
| 3267 | case ExtAddrMode::ScaledRegField: |
| 3268 | return AddrSinkCombineScaledReg; |
| 3269 | } |
| 3270 | } |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 3271 | }; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3272 | } // end anonymous namespace |
| 3273 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3274 | /// Try adding ScaleReg*Scale to the current addressing mode. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3275 | /// Return true and update AddrMode if this addr mode is legal for the target, |
| 3276 | /// false if not. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3277 | bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3278 | unsigned Depth) { |
| 3279 | // If Scale is 1, then this is the same as adding ScaleReg to the addressing |
| 3280 | // mode. Just process that directly. |
| 3281 | if (Scale == 1) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3282 | return matchAddr(ScaleReg, Depth); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3283 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3284 | // If the scale is 0, it takes nothing to add this. |
| 3285 | if (Scale == 0) |
| 3286 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3287 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3288 | // If we already have a scale of this value, we can add to it, otherwise, we |
| 3289 | // need an available scale field. |
| 3290 | if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg) |
| 3291 | return false; |
| 3292 | |
| 3293 | ExtAddrMode TestAddrMode = AddrMode; |
| 3294 | |
| 3295 | // Add scale to turn X*4+X*3 -> X*7. This could also do things like |
| 3296 | // [A+B + A*7] -> [B+A*8]. |
| 3297 | TestAddrMode.Scale += Scale; |
| 3298 | TestAddrMode.ScaledReg = ScaleReg; |
| 3299 | |
| 3300 | // If the new address isn't legal, bail out. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3301 | if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3302 | return false; |
| 3303 | |
| 3304 | // It was legal, so commit it. |
| 3305 | AddrMode = TestAddrMode; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3306 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3307 | // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now |
| 3308 | // to see if ScaleReg is actually X+C. If so, we can turn this into adding |
| 3309 | // X*Scale + C*Scale to addr mode. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3310 | ConstantInt *CI = nullptr; Value *AddLHS = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3311 | if (isa<Instruction>(ScaleReg) && // not a constant expr. |
| 3312 | match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) { |
| 3313 | TestAddrMode.ScaledReg = AddLHS; |
| 3314 | TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3315 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3316 | // If this addressing mode is legal, commit it and remember that we folded |
| 3317 | // this instruction. |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3318 | if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3319 | AddrModeInsts.push_back(cast<Instruction>(ScaleReg)); |
| 3320 | AddrMode = TestAddrMode; |
| 3321 | return true; |
| 3322 | } |
| 3323 | } |
| 3324 | |
| 3325 | // Otherwise, not (x+c)*scale, just return what we have. |
| 3326 | return true; |
| 3327 | } |
| 3328 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3329 | /// This is a little filter, which returns true if an addressing computation |
| 3330 | /// involving I might be folded into a load/store accessing it. |
| 3331 | /// 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] | 3332 | /// the set of instructions that MatchOperationAddr can. |
| 3333 | static bool MightBeFoldableInst(Instruction *I) { |
| 3334 | switch (I->getOpcode()) { |
| 3335 | case Instruction::BitCast: |
Eli Bendersky | f13a056 | 2014-05-22 00:02:52 +0000 | [diff] [blame] | 3336 | case Instruction::AddrSpaceCast: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3337 | // Don't touch identity bitcasts. |
| 3338 | if (I->getType() == I->getOperand(0)->getType()) |
| 3339 | return false; |
| 3340 | return I->getType()->isPointerTy() || I->getType()->isIntegerTy(); |
| 3341 | case Instruction::PtrToInt: |
| 3342 | // PtrToInt is always a noop, as we know that the int type is pointer sized. |
| 3343 | return true; |
| 3344 | case Instruction::IntToPtr: |
| 3345 | // We know the input is intptr_t, so this is foldable. |
| 3346 | return true; |
| 3347 | case Instruction::Add: |
| 3348 | return true; |
| 3349 | case Instruction::Mul: |
| 3350 | case Instruction::Shl: |
| 3351 | // Can only handle X*C and X << C. |
| 3352 | return isa<ConstantInt>(I->getOperand(1)); |
| 3353 | case Instruction::GetElementPtr: |
| 3354 | return true; |
| 3355 | default: |
| 3356 | return false; |
| 3357 | } |
| 3358 | } |
| 3359 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3360 | /// \brief Check whether or not \p Val is a legal instruction for \p TLI. |
| 3361 | /// \note \p Val is assumed to be the product of some type promotion. |
| 3362 | /// Therefore if \p Val has an undefined state in \p TLI, this is assumed |
| 3363 | /// 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] | 3364 | static bool isPromotedInstructionLegal(const TargetLowering &TLI, |
| 3365 | const DataLayout &DL, Value *Val) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3366 | Instruction *PromotedInst = dyn_cast<Instruction>(Val); |
| 3367 | if (!PromotedInst) |
| 3368 | return false; |
| 3369 | int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode()); |
| 3370 | // If the ISDOpcode is undefined, it was undefined before the promotion. |
| 3371 | if (!ISDOpcode) |
| 3372 | return true; |
| 3373 | // Otherwise, check if the promoted instruction is legal or not. |
| 3374 | return TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3375 | ISDOpcode, TLI.getValueType(DL, PromotedInst->getType())); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3376 | } |
| 3377 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3378 | namespace { |
| 3379 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3380 | /// \brief Hepler class to perform type promotion. |
| 3381 | class TypePromotionHelper { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3382 | /// \brief Utility function to check whether or not a sign or zero extension |
| 3383 | /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by |
| 3384 | /// either using the operands of \p Inst or promoting \p Inst. |
| 3385 | /// The type of the extension is defined by \p IsSExt. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3386 | /// In other words, check if: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3387 | /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3388 | /// #1 Promotion applies: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3389 | /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...). |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3390 | /// #2 Operand reuses: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3391 | /// ext opnd1 to ConsideredExtType. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3392 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3393 | static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType, |
| 3394 | const InstrToOrigTy &PromotedInsts, bool IsSExt); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3395 | |
| 3396 | /// \brief Utility function to determine if \p OpIdx should be promoted when |
| 3397 | /// promoting \p Inst. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3398 | static bool shouldExtOperand(const Instruction *Inst, int OpIdx) { |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3399 | return !(isa<SelectInst>(Inst) && OpIdx == 0); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3400 | } |
| 3401 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3402 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3403 | /// operand is a promotable trunc or sext or zext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3404 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3405 | /// \p CreatedInstsCost[out] contains the cost of all instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3406 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3407 | /// Newly added extensions are inserted in \p Exts. |
| 3408 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3409 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3410 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3411 | static Value *promoteOperandForTruncAndAnyExt( |
| 3412 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3413 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3414 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3415 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3416 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3417 | /// \brief Utility function to promote the operand of \p Ext when this |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3418 | /// operand is promotable and is not a supported trunc or sext. |
| 3419 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3420 | /// \p CreatedInstsCost[out] contains the cost of all the instructions |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3421 | /// created to promote the operand of Ext. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3422 | /// Newly added extensions are inserted in \p Exts. |
| 3423 | /// Newly added truncates are inserted in \p Truncs. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3424 | /// Should never be called directly. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3425 | /// \return The promoted value which is used instead of Ext. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3426 | static Value *promoteOperandForOther(Instruction *Ext, |
| 3427 | TypePromotionTransaction &TPT, |
| 3428 | InstrToOrigTy &PromotedInsts, |
| 3429 | unsigned &CreatedInstsCost, |
| 3430 | SmallVectorImpl<Instruction *> *Exts, |
| 3431 | SmallVectorImpl<Instruction *> *Truncs, |
| 3432 | const TargetLowering &TLI, bool IsSExt); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3433 | |
| 3434 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3435 | static Value *signExtendOperandForOther( |
| 3436 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3437 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3438 | SmallVectorImpl<Instruction *> *Exts, |
| 3439 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3440 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3441 | Exts, Truncs, TLI, true); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3442 | } |
| 3443 | |
| 3444 | /// \see promoteOperandForOther. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3445 | static Value *zeroExtendOperandForOther( |
| 3446 | Instruction *Ext, TypePromotionTransaction &TPT, |
| 3447 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
| 3448 | SmallVectorImpl<Instruction *> *Exts, |
| 3449 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
| 3450 | return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost, |
| 3451 | Exts, Truncs, TLI, false); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3452 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3453 | |
| 3454 | public: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3455 | /// Type for the utility function that promotes the operand of Ext. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3456 | using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT, |
| 3457 | InstrToOrigTy &PromotedInsts, |
| 3458 | unsigned &CreatedInstsCost, |
| 3459 | SmallVectorImpl<Instruction *> *Exts, |
| 3460 | SmallVectorImpl<Instruction *> *Truncs, |
| 3461 | const TargetLowering &TLI); |
| 3462 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3463 | /// \brief Given a sign/zero extend instruction \p Ext, return the approriate |
| 3464 | /// action to promote the operand of \p Ext instead of using Ext. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3465 | /// \return NULL if no promotable action is possible with the current |
| 3466 | /// sign extension. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3467 | /// \p InsertedInsts keeps track of all the instructions inserted by the |
| 3468 | /// other CodeGenPrepare optimizations. This information is important |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3469 | /// because we do not want to promote these instructions as CodeGenPrepare |
| 3470 | /// will reinsert them later. Thus creating an infinite loop: create/remove. |
| 3471 | /// \p PromotedInsts maps the instructions to their type before promotion. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3472 | static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3473 | const TargetLowering &TLI, |
| 3474 | const InstrToOrigTy &PromotedInsts); |
| 3475 | }; |
| 3476 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3477 | } // end anonymous namespace |
| 3478 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3479 | bool TypePromotionHelper::canGetThrough(const Instruction *Inst, |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3480 | Type *ConsideredExtType, |
| 3481 | const InstrToOrigTy &PromotedInsts, |
| 3482 | bool IsSExt) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3483 | // The promotion helper does not know how to deal with vector types yet. |
| 3484 | // To be able to fix that, we would need to fix the places where we |
| 3485 | // statically extend, e.g., constants and such. |
| 3486 | if (Inst->getType()->isVectorTy()) |
| 3487 | return false; |
| 3488 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3489 | // We can always get through zext. |
| 3490 | if (isa<ZExtInst>(Inst)) |
| 3491 | return true; |
| 3492 | |
| 3493 | // sext(sext) is ok too. |
| 3494 | if (IsSExt && isa<SExtInst>(Inst)) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3495 | return true; |
| 3496 | |
| 3497 | // We can get through binary operator, if it is legal. In other words, the |
| 3498 | // binary operator must have a nuw or nsw flag. |
| 3499 | const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst); |
| 3500 | if (BinOp && isa<OverflowingBinaryOperator>(BinOp) && |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3501 | ((!IsSExt && BinOp->hasNoUnsignedWrap()) || |
| 3502 | (IsSExt && BinOp->hasNoSignedWrap()))) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3503 | return true; |
| 3504 | |
| 3505 | // Check if we can do the following simplification. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3506 | // ext(trunc(opnd)) --> ext(opnd) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3507 | if (!isa<TruncInst>(Inst)) |
| 3508 | return false; |
| 3509 | |
| 3510 | Value *OpndVal = Inst->getOperand(0); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3511 | // Check if we can use this operand in the extension. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3512 | // 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] | 3513 | if (!OpndVal->getType()->isIntegerTy() || |
| 3514 | OpndVal->getType()->getIntegerBitWidth() > |
| 3515 | ConsideredExtType->getIntegerBitWidth()) |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3516 | return false; |
| 3517 | |
| 3518 | // If the operand of the truncate is not an instruction, we will not have |
| 3519 | // any information on the dropped bits. |
| 3520 | // (Actually we could for constant but it is not worth the extra logic). |
| 3521 | Instruction *Opnd = dyn_cast<Instruction>(OpndVal); |
| 3522 | if (!Opnd) |
| 3523 | return false; |
| 3524 | |
| 3525 | // Check if the source of the type is narrow enough. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3526 | // I.e., check that trunc just drops extended bits of the same kind of |
| 3527 | // the extension. |
| 3528 | // #1 get the type of the operand and check the kind of the extended bits. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3529 | const Type *OpndType; |
| 3530 | InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd); |
Benjamin Kramer | 4cd5faa | 2015-07-31 17:00:39 +0000 | [diff] [blame] | 3531 | if (It != PromotedInsts.end() && It->second.getInt() == IsSExt) |
| 3532 | OpndType = It->second.getPointer(); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3533 | else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd))) |
| 3534 | OpndType = Opnd->getOperand(0)->getType(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3535 | else |
| 3536 | return false; |
| 3537 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3538 | // #2 check that the truncate just drops extended bits. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 3539 | return Inst->getType()->getIntegerBitWidth() >= |
| 3540 | OpndType->getIntegerBitWidth(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3541 | } |
| 3542 | |
| 3543 | TypePromotionHelper::Action TypePromotionHelper::getAction( |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3544 | Instruction *Ext, const SetOfInstrs &InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3545 | const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3546 | assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && |
| 3547 | "Unexpected instruction type"); |
| 3548 | Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0)); |
| 3549 | Type *ExtTy = Ext->getType(); |
| 3550 | bool IsSExt = isa<SExtInst>(Ext); |
| 3551 | // If the operand of the extension is not an instruction, we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3552 | // get through. |
| 3553 | // If it, check we can get through. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3554 | if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3555 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3556 | |
| 3557 | // Do not promote if the operand has been added by codegenprepare. |
| 3558 | // Otherwise, it means we are undoing an optimization that is likely to be |
| 3559 | // redone, thus causing potential infinite loop. |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3560 | if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3561 | return nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3562 | |
| 3563 | // SExt or Trunc instructions. |
| 3564 | // Return the related handler. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3565 | if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) || |
| 3566 | isa<ZExtInst>(ExtOpnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3567 | return promoteOperandForTruncAndAnyExt; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3568 | |
| 3569 | // Regular instruction. |
| 3570 | // Abort early if we will have to insert non-free instructions. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3571 | if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType())) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 3572 | return nullptr; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3573 | return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3574 | } |
| 3575 | |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3576 | Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt( |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 3577 | Instruction *SExt, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3578 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3579 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3580 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3581 | // By construction, the operand of SExt is an instruction. Otherwise we cannot |
| 3582 | // get through it and this method should not be called. |
| 3583 | Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0)); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3584 | Value *ExtVal = SExt; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3585 | bool HasMergedNonFreeExt = false; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3586 | if (isa<ZExtInst>(SExtOpnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3587 | // Replace s|zext(zext(opnd)) |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3588 | // => zext(opnd). |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3589 | HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3590 | Value *ZExt = |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3591 | TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType()); |
| 3592 | TPT.replaceAllUsesWith(SExt, ZExt); |
| 3593 | TPT.eraseInstruction(SExt); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3594 | ExtVal = ZExt; |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3595 | } else { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3596 | // Replace z|sext(trunc(opnd)) or sext(sext(opnd)) |
| 3597 | // => z|sext(opnd). |
Quentin Colombet | b2c5c6d | 2014-09-11 21:22:14 +0000 | [diff] [blame] | 3598 | TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0)); |
| 3599 | } |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3600 | CreatedInstsCost = 0; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3601 | |
| 3602 | // Remove dead code. |
| 3603 | if (SExtOpnd->use_empty()) |
| 3604 | TPT.eraseInstruction(SExtOpnd); |
| 3605 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3606 | // Check if the extension is still needed. |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3607 | Instruction *ExtInst = dyn_cast<Instruction>(ExtVal); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3608 | if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) { |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3609 | if (ExtInst) { |
| 3610 | if (Exts) |
| 3611 | Exts->push_back(ExtInst); |
| 3612 | CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt; |
| 3613 | } |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3614 | return ExtVal; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3615 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3616 | |
Quentin Colombet | 9dcb724 | 2014-09-15 18:26:58 +0000 | [diff] [blame] | 3617 | // At this point we have: ext ty opnd to ty. |
| 3618 | // Reassign the uses of ExtInst to the opnd and remove ExtInst. |
| 3619 | Value *NextVal = ExtInst->getOperand(0); |
| 3620 | TPT.eraseInstruction(ExtInst, NextVal); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3621 | return NextVal; |
| 3622 | } |
| 3623 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3624 | Value *TypePromotionHelper::promoteOperandForOther( |
| 3625 | Instruction *Ext, TypePromotionTransaction &TPT, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3626 | InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost, |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3627 | SmallVectorImpl<Instruction *> *Exts, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3628 | SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI, |
| 3629 | bool IsSExt) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3630 | // By construction, the operand of Ext is an instruction. Otherwise we cannot |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3631 | // get through it and this method should not be called. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3632 | Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0)); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3633 | CreatedInstsCost = 0; |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3634 | if (!ExtOpnd->hasOneUse()) { |
| 3635 | // ExtOpnd will be promoted. |
| 3636 | // 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] | 3637 | // promoted version. |
| 3638 | // Create the truncate now. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3639 | Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType()); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3640 | if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) { |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3641 | // Insert it just after the definition. |
Sanjay Patel | 674d2c2 | 2017-08-29 14:07:48 +0000 | [diff] [blame] | 3642 | ITrunc->moveAfter(ExtOpnd); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3643 | if (Truncs) |
| 3644 | Truncs->push_back(ITrunc); |
Quentin Colombet | ac55b15 | 2014-09-16 22:36:07 +0000 | [diff] [blame] | 3645 | } |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3646 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3647 | TPT.replaceAllUsesWith(ExtOpnd, Trunc); |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3648 | // 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] | 3649 | // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3650 | TPT.setOperand(Ext, 0, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3651 | } |
| 3652 | |
| 3653 | // Get through the Instruction: |
| 3654 | // 1. Update its type. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3655 | // 2. Replace the uses of Ext by Inst. |
| 3656 | // 3. Extend each operand that needs to be extended. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3657 | |
| 3658 | // Remember the original type of the instruction before promotion. |
| 3659 | // This is useful to know that the high bits are sign extended bits. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3660 | PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>( |
| 3661 | ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt))); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3662 | // Step #1. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3663 | TPT.mutateType(ExtOpnd, Ext->getType()); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3664 | // Step #2. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3665 | TPT.replaceAllUsesWith(Ext, ExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3666 | // Step #3. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3667 | Instruction *ExtForOpnd = Ext; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3668 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3669 | DEBUG(dbgs() << "Propagate Ext to operands\n"); |
| 3670 | for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3671 | ++OpIdx) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3672 | DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n'); |
| 3673 | if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() || |
| 3674 | !shouldExtOperand(ExtOpnd, OpIdx)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3675 | DEBUG(dbgs() << "No need to propagate\n"); |
| 3676 | continue; |
| 3677 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3678 | // Check if we can statically extend the operand. |
| 3679 | Value *Opnd = ExtOpnd->getOperand(OpIdx); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3680 | if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3681 | DEBUG(dbgs() << "Statically extend\n"); |
| 3682 | unsigned BitWidth = Ext->getType()->getIntegerBitWidth(); |
| 3683 | APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth) |
| 3684 | : Cst->getValue().zext(BitWidth); |
| 3685 | TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal)); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3686 | continue; |
| 3687 | } |
| 3688 | // UndefValue are typed, so we have to statically sign extend them. |
| 3689 | if (isa<UndefValue>(Opnd)) { |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3690 | DEBUG(dbgs() << "Statically extend\n"); |
| 3691 | TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType())); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3692 | continue; |
| 3693 | } |
| 3694 | |
| 3695 | // Otherwise we have to explicity sign extend the operand. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3696 | // Check if Ext was reused to extend an operand. |
| 3697 | if (!ExtForOpnd) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3698 | // If yes, create a new one. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3699 | DEBUG(dbgs() << "More operands to ext\n"); |
Quentin Colombet | 84f89cc | 2014-12-22 18:11:52 +0000 | [diff] [blame] | 3700 | Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType()) |
| 3701 | : TPT.createZExt(Ext, Opnd, Ext->getType()); |
| 3702 | if (!isa<Instruction>(ValForExtOpnd)) { |
| 3703 | TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd); |
| 3704 | continue; |
| 3705 | } |
| 3706 | ExtForOpnd = cast<Instruction>(ValForExtOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3707 | } |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3708 | if (Exts) |
| 3709 | Exts->push_back(ExtForOpnd); |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3710 | TPT.setOperand(ExtForOpnd, 0, Opnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3711 | |
| 3712 | // Move the sign extension before the insertion point. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3713 | TPT.moveBefore(ExtForOpnd, ExtOpnd); |
| 3714 | TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3715 | CreatedInstsCost += !TLI.isExtFree(ExtForOpnd); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3716 | // If more sext are required, new instructions will have to be created. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3717 | ExtForOpnd = nullptr; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3718 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3719 | if (ExtForOpnd == Ext) { |
| 3720 | DEBUG(dbgs() << "Extension is useless now\n"); |
| 3721 | TPT.eraseInstruction(Ext); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3722 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3723 | return ExtOpnd; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3724 | } |
| 3725 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3726 | /// 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] | 3727 | /// \p NewCost gives the cost of extension instructions created by the |
| 3728 | /// promotion. |
| 3729 | /// \p OldCost gives the cost of extension instructions before the promotion |
| 3730 | /// plus the number of instructions that have been |
| 3731 | /// matched in the addressing mode the promotion. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3732 | /// \p PromotedOperand is the value that has been promoted. |
| 3733 | /// \return True if the promotion is profitable, false otherwise. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3734 | bool AddressingModeMatcher::isPromotionProfitable( |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3735 | unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const { |
| 3736 | DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n'); |
| 3737 | // The cost of the new extensions is greater than the cost of the |
| 3738 | // old extension plus what we folded. |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3739 | // This is not profitable. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3740 | if (NewCost > OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3741 | return false; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3742 | if (NewCost < OldCost) |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3743 | return true; |
| 3744 | // The promotion is neutral but it may help folding the sign extension in |
| 3745 | // loads for instance. |
| 3746 | // Check that we did not create an illegal instruction. |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3747 | return isPromotedInstructionLegal(TLI, DL, PromotedOperand); |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3748 | } |
| 3749 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3750 | /// 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] | 3751 | /// into the addressing mode. If so, update the addressing mode and return |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3752 | /// true, otherwise return false without modifying AddrMode. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3753 | /// If \p MovedAway is not NULL, it contains the information of whether or |
| 3754 | /// not AddrInst has to be folded into the addressing mode on success. |
| 3755 | /// If \p MovedAway == true, \p AddrInst will not be part of the addressing |
| 3756 | /// because it has been moved away. |
| 3757 | /// Thus AddrInst must not be added in the matched instructions. |
| 3758 | /// This state can happen when AddrInst is a sext, since it may be moved away. |
| 3759 | /// Therefore, AddrInst may not be valid when MovedAway is true and it must |
| 3760 | /// not be referenced anymore. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3761 | bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3762 | unsigned Depth, |
| 3763 | bool *MovedAway) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3764 | // Avoid exponential behavior on extremely deep expression trees. |
| 3765 | if (Depth >= 5) return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3766 | |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3767 | // By default, all matched instructions stay in place. |
| 3768 | if (MovedAway) |
| 3769 | *MovedAway = false; |
| 3770 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3771 | switch (Opcode) { |
| 3772 | case Instruction::PtrToInt: |
| 3773 | // 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] | 3774 | return matchAddr(AddrInst->getOperand(0), Depth); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3775 | case Instruction::IntToPtr: { |
| 3776 | auto AS = AddrInst->getType()->getPointerAddressSpace(); |
| 3777 | auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS)); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3778 | // 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] | 3779 | if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3780 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3781 | return false; |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 3782 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3783 | case Instruction::BitCast: |
| 3784 | // BitCast is always a noop, and we can handle it as long as it is |
| 3785 | // int->int or pointer->pointer (we don't want int<->fp or something). |
| 3786 | if ((AddrInst->getOperand(0)->getType()->isPointerTy() || |
| 3787 | AddrInst->getOperand(0)->getType()->isIntegerTy()) && |
| 3788 | // Don't touch identity bitcasts. These were probably put here by LSR, |
| 3789 | // and we don't want to mess around with them. Assume it knows what it |
| 3790 | // is doing. |
| 3791 | AddrInst->getOperand(0)->getType() != AddrInst->getType()) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3792 | return matchAddr(AddrInst->getOperand(0), Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3793 | return false; |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3794 | case Instruction::AddrSpaceCast: { |
| 3795 | unsigned SrcAS |
| 3796 | = AddrInst->getOperand(0)->getType()->getPointerAddressSpace(); |
| 3797 | unsigned DestAS = AddrInst->getType()->getPointerAddressSpace(); |
| 3798 | if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3799 | return matchAddr(AddrInst->getOperand(0), Depth); |
Matt Arsenault | f05b023 | 2015-05-26 16:59:43 +0000 | [diff] [blame] | 3800 | return false; |
| 3801 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3802 | case Instruction::Add: { |
| 3803 | // Check to see if we can merge in the RHS then the LHS. If so, we win. |
| 3804 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3805 | unsigned OldSize = AddrModeInsts.size(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3806 | // Start a transaction at this point. |
| 3807 | // The LHS may match but not the RHS. |
| 3808 | // Therefore, we need a higher level restoration point to undo partially |
| 3809 | // matched operation. |
| 3810 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3811 | TPT.getRestorationPoint(); |
| 3812 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3813 | if (matchAddr(AddrInst->getOperand(1), Depth+1) && |
| 3814 | matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3815 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3816 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3817 | // Restore the old addr mode info. |
| 3818 | AddrMode = BackupAddrMode; |
| 3819 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3820 | TPT.rollback(LastKnownGood); |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3821 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3822 | // 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] | 3823 | if (matchAddr(AddrInst->getOperand(0), Depth+1) && |
| 3824 | matchAddr(AddrInst->getOperand(1), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3825 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3826 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3827 | // Otherwise we definitely can't merge the ADD in. |
| 3828 | AddrMode = BackupAddrMode; |
| 3829 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3830 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3831 | break; |
| 3832 | } |
| 3833 | //case Instruction::Or: |
| 3834 | // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD. |
| 3835 | //break; |
| 3836 | case Instruction::Mul: |
| 3837 | case Instruction::Shl: { |
| 3838 | // Can only handle X*C and X << C. |
| 3839 | ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1)); |
Philip Reames | 9c3cbee | 2017-10-30 23:59:51 +0000 | [diff] [blame] | 3840 | if (!RHS || RHS->getBitWidth() > 64) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3841 | return false; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3842 | int64_t Scale = RHS->getSExtValue(); |
| 3843 | if (Opcode == Instruction::Shl) |
| 3844 | Scale = 1LL << Scale; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3845 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3846 | return matchScaledValue(AddrInst->getOperand(0), Scale, Depth); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3847 | } |
| 3848 | case Instruction::GetElementPtr: { |
| 3849 | // Scan the GEP. We check it if it contains constant offsets and at most |
| 3850 | // one variable offset. |
| 3851 | int VariableOperand = -1; |
| 3852 | unsigned VariableScale = 0; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3853 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3854 | int64_t ConstantOffset = 0; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3855 | gep_type_iterator GTI = gep_type_begin(AddrInst); |
| 3856 | for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) { |
Peter Collingbourne | ab85225b | 2016-12-02 02:24:42 +0000 | [diff] [blame] | 3857 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3858 | const StructLayout *SL = DL.getStructLayout(STy); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3859 | unsigned Idx = |
| 3860 | cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue(); |
| 3861 | ConstantOffset += SL->getElementOffset(Idx); |
| 3862 | } else { |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 3863 | uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3864 | if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) { |
| 3865 | ConstantOffset += CI->getSExtValue()*TypeSize; |
| 3866 | } else if (TypeSize) { // Scales of zero don't do anything. |
| 3867 | // We only allow one variable index at the moment. |
| 3868 | if (VariableOperand != -1) |
| 3869 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3870 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3871 | // Remember the variable index. |
| 3872 | VariableOperand = i; |
| 3873 | VariableScale = TypeSize; |
| 3874 | } |
| 3875 | } |
| 3876 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 3877 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3878 | // A common case is for the GEP to only do a constant offset. In this case, |
| 3879 | // just add it to the disp field and check validity. |
| 3880 | if (VariableOperand == -1) { |
| 3881 | AddrMode.BaseOffs += ConstantOffset; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 3882 | if (ConstantOffset == 0 || |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 3883 | TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3884 | // Check to see if we can fold the base pointer in too. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3885 | if (matchAddr(AddrInst->getOperand(0), Depth+1)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3886 | return true; |
| 3887 | } |
| 3888 | AddrMode.BaseOffs -= ConstantOffset; |
| 3889 | return false; |
| 3890 | } |
| 3891 | |
| 3892 | // Save the valid addressing mode in case we can't match. |
| 3893 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3894 | unsigned OldSize = AddrModeInsts.size(); |
| 3895 | |
| 3896 | // See if the scale and offset amount is valid for this target. |
| 3897 | AddrMode.BaseOffs += ConstantOffset; |
| 3898 | |
| 3899 | // Match the base operand of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3900 | if (!matchAddr(AddrInst->getOperand(0), Depth+1)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3901 | // If it couldn't be matched, just stuff the value in a register. |
| 3902 | if (AddrMode.HasBaseReg) { |
| 3903 | AddrMode = BackupAddrMode; |
| 3904 | AddrModeInsts.resize(OldSize); |
| 3905 | return false; |
| 3906 | } |
| 3907 | AddrMode.HasBaseReg = true; |
| 3908 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3909 | } |
| 3910 | |
| 3911 | // Match the remaining variable portion of the GEP. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3912 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3913 | Depth)) { |
| 3914 | // If it couldn't be matched, try stuffing the base into a register |
| 3915 | // instead of matching it, and retrying the match of the scale. |
| 3916 | AddrMode = BackupAddrMode; |
| 3917 | AddrModeInsts.resize(OldSize); |
| 3918 | if (AddrMode.HasBaseReg) |
| 3919 | return false; |
| 3920 | AddrMode.HasBaseReg = true; |
| 3921 | AddrMode.BaseReg = AddrInst->getOperand(0); |
| 3922 | AddrMode.BaseOffs += ConstantOffset; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3923 | if (!matchScaledValue(AddrInst->getOperand(VariableOperand), |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3924 | VariableScale, Depth)) { |
| 3925 | // If even that didn't work, bail. |
| 3926 | AddrMode = BackupAddrMode; |
| 3927 | AddrModeInsts.resize(OldSize); |
| 3928 | return false; |
| 3929 | } |
| 3930 | } |
| 3931 | |
| 3932 | return true; |
| 3933 | } |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3934 | case Instruction::SExt: |
| 3935 | case Instruction::ZExt: { |
| 3936 | Instruction *Ext = dyn_cast<Instruction>(AddrInst); |
| 3937 | if (!Ext) |
Sanjay Patel | d3bbfa1 | 2014-07-16 22:40:28 +0000 | [diff] [blame] | 3938 | return false; |
Sanjay Patel | ab60d04 | 2014-07-16 21:08:10 +0000 | [diff] [blame] | 3939 | |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3940 | // 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] | 3941 | // Ask for a method for doing so. |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3942 | TypePromotionHelper::Action TPH = |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 3943 | TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3944 | if (!TPH) |
| 3945 | return false; |
| 3946 | |
| 3947 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 3948 | TPT.getRestorationPoint(); |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3949 | unsigned CreatedInstsCost = 0; |
| 3950 | unsigned ExtCost = !TLI.isExtFree(Ext); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 3951 | Value *PromotedOperand = |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3952 | TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3953 | // SExt has been moved away. |
| 3954 | // Thus either it will be rematched later in the recursive calls or it is |
| 3955 | // gone. Anyway, we must not fold it into the addressing mode at this point. |
| 3956 | // E.g., |
| 3957 | // op = add opnd, 1 |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3958 | // idx = ext op |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3959 | // addr = gep base, idx |
| 3960 | // is now: |
Quentin Colombet | f5485bb | 2014-11-13 01:44:51 +0000 | [diff] [blame] | 3961 | // promotedOpnd = ext opnd <- no match here |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3962 | // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls) |
| 3963 | // addr = gep base, op <- match |
| 3964 | if (MovedAway) |
| 3965 | *MovedAway = true; |
| 3966 | |
| 3967 | assert(PromotedOperand && |
| 3968 | "TypePromotionHelper should have filtered out those cases"); |
| 3969 | |
| 3970 | ExtAddrMode BackupAddrMode = AddrMode; |
| 3971 | unsigned OldSize = AddrModeInsts.size(); |
| 3972 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3973 | if (!matchAddr(PromotedOperand, Depth) || |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3974 | // 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] | 3975 | // instructions. |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 3976 | // 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] | 3977 | // what we have saved in the addressing mode. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3978 | !isPromotionProfitable(CreatedInstsCost, |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 3979 | ExtCost + (AddrModeInsts.size() - OldSize), |
Quentin Colombet | 867c550 | 2014-02-14 22:23:22 +0000 | [diff] [blame] | 3980 | PromotedOperand)) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3981 | AddrMode = BackupAddrMode; |
| 3982 | AddrModeInsts.resize(OldSize); |
| 3983 | DEBUG(dbgs() << "Sign extension does not pay off: rollback\n"); |
| 3984 | TPT.rollback(LastKnownGood); |
| 3985 | return false; |
| 3986 | } |
| 3987 | return true; |
| 3988 | } |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3989 | } |
| 3990 | return false; |
| 3991 | } |
| 3992 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 3993 | /// If we can, try to add the value of 'Addr' into the current addressing mode. |
| 3994 | /// If Addr can't be added to AddrMode this returns false and leaves AddrMode |
| 3995 | /// unmodified. This assumes that Addr is either a pointer type or intptr_t |
| 3996 | /// for the target. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 3997 | /// |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 3998 | bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 3999 | // Start a transaction at this point that we will rollback if the matching |
| 4000 | // fails. |
| 4001 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4002 | TPT.getRestorationPoint(); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4003 | if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) { |
| 4004 | // Fold in immediates if legal for the target. |
| 4005 | AddrMode.BaseOffs += CI->getSExtValue(); |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 4006 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4007 | return true; |
| 4008 | AddrMode.BaseOffs -= CI->getSExtValue(); |
| 4009 | } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) { |
| 4010 | // 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] | 4011 | if (!AddrMode.BaseGV) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4012 | AddrMode.BaseGV = GV; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 4013 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4014 | return true; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4015 | AddrMode.BaseGV = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4016 | } |
| 4017 | } else if (Instruction *I = dyn_cast<Instruction>(Addr)) { |
| 4018 | ExtAddrMode BackupAddrMode = AddrMode; |
| 4019 | unsigned OldSize = AddrModeInsts.size(); |
| 4020 | |
| 4021 | // Check to see if it is possible to fold this operation. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4022 | bool MovedAway = false; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4023 | if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) { |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 4024 | // This instruction may have been moved away. If so, there is nothing |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4025 | // to check here. |
| 4026 | if (MovedAway) |
| 4027 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4028 | // Okay, it's possible to fold this. Check to see if it is actually |
| 4029 | // *profitable* to do so. We use a simple cost model to avoid increasing |
| 4030 | // register pressure too much. |
| 4031 | if (I->hasOneUse() || |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4032 | isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4033 | AddrModeInsts.push_back(I); |
| 4034 | return true; |
| 4035 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4036 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4037 | // It isn't profitable to do this, roll back. |
| 4038 | //cerr << "NOT FOLDING: " << *I; |
| 4039 | AddrMode = BackupAddrMode; |
| 4040 | AddrModeInsts.resize(OldSize); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4041 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4042 | } |
| 4043 | } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) { |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4044 | if (matchOperationAddr(CE, CE->getOpcode(), Depth)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4045 | return true; |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4046 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4047 | } else if (isa<ConstantPointerNull>(Addr)) { |
| 4048 | // Null pointer gets folded without affecting the addressing mode. |
| 4049 | return true; |
| 4050 | } |
| 4051 | |
| 4052 | // Worse case, the target should support [reg] addressing modes. :) |
| 4053 | if (!AddrMode.HasBaseReg) { |
| 4054 | AddrMode.HasBaseReg = true; |
| 4055 | AddrMode.BaseReg = Addr; |
| 4056 | // 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] | 4057 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4058 | return true; |
| 4059 | AddrMode.HasBaseReg = false; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4060 | AddrMode.BaseReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4061 | } |
| 4062 | |
| 4063 | // If the base register is already taken, see if we can do [r+r]. |
| 4064 | if (AddrMode.Scale == 0) { |
| 4065 | AddrMode.Scale = 1; |
| 4066 | AddrMode.ScaledReg = Addr; |
Mehdi Amini | 0cdec1e | 2015-07-09 02:09:40 +0000 | [diff] [blame] | 4067 | if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4068 | return true; |
| 4069 | AddrMode.Scale = 0; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4070 | AddrMode.ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4071 | } |
| 4072 | // Couldn't match. |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4073 | TPT.rollback(LastKnownGood); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4074 | return false; |
| 4075 | } |
| 4076 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4077 | /// Check to see if all uses of OpVal by the specified inline asm call are due |
| 4078 | /// to memory operands. If so, return true, otherwise return false. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4079 | static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal, |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4080 | const TargetLowering &TLI, |
| 4081 | const TargetRegisterInfo &TRI) { |
Sanjay Patel | 4137d51 | 2017-06-07 14:29:52 +0000 | [diff] [blame] | 4082 | const Function *F = CI->getFunction(); |
Eric Christopher | d75c00c | 2015-02-26 22:38:34 +0000 | [diff] [blame] | 4083 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4084 | TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4085 | ImmutableCallSite(CI)); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4086 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4087 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4088 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4089 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4090 | // Compute the constraint code and ConstraintType to use. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4091 | TLI.ComputeConstraintToUse(OpInfo, SDValue()); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4092 | |
| 4093 | // If this asm operand is our Value*, and if it isn't an indirect memory |
| 4094 | // operand, we can't fold it! |
| 4095 | if (OpInfo.CallOperandVal == OpVal && |
| 4096 | (OpInfo.ConstraintType != TargetLowering::C_Memory || |
| 4097 | !OpInfo.isIndirect)) |
| 4098 | return false; |
| 4099 | } |
| 4100 | |
| 4101 | return true; |
| 4102 | } |
| 4103 | |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4104 | // Max number of memory uses to look at before aborting the search to conserve |
| 4105 | // compile time. |
| 4106 | static constexpr int MaxMemoryUsesToScan = 20; |
| 4107 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4108 | /// Recursively walk all the uses of I until we find a memory use. |
| 4109 | /// If we find an obviously non-foldable instruction, return true. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4110 | /// Add the ultimately found memory instructions to MemoryUses. |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4111 | static bool FindAllMemoryUses( |
| 4112 | Instruction *I, |
| 4113 | SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses, |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4114 | SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI, |
| 4115 | const TargetRegisterInfo &TRI, int SeenInsts = 0) { |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4116 | // If we already considered this instruction, we're done. |
David Blaikie | 70573dc | 2014-11-19 07:49:26 +0000 | [diff] [blame] | 4117 | if (!ConsideredInsts.insert(I).second) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4118 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4119 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4120 | // If this is an obviously unfoldable instruction, bail out. |
| 4121 | if (!MightBeFoldableInst(I)) |
| 4122 | return true; |
| 4123 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4124 | const bool OptSize = I->getFunction()->optForSize(); |
| 4125 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4126 | // Loop over all the uses, recursively processing them. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4127 | for (Use &U : I->uses()) { |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4128 | // Conservatively return true if we're seeing a large number or a deep chain |
| 4129 | // of users. This avoids excessive compilation times in pathological cases. |
| 4130 | if (SeenInsts++ >= MaxMemoryUsesToScan) |
| 4131 | return true; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4132 | |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4133 | Instruction *UserI = cast<Instruction>(U.getUser()); |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4134 | if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) { |
| 4135 | MemoryUses.push_back(std::make_pair(LI, U.getOperandNo())); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4136 | continue; |
| 4137 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4138 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4139 | if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) { |
| 4140 | unsigned opNo = U.getOperandNo(); |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 4141 | if (opNo != StoreInst::getPointerOperandIndex()) |
| 4142 | return true; // Storing addr, not into addr. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4143 | MemoryUses.push_back(std::make_pair(SI, opNo)); |
| 4144 | continue; |
| 4145 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4146 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 4147 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) { |
| 4148 | unsigned opNo = U.getOperandNo(); |
| 4149 | if (opNo != AtomicRMWInst::getPointerOperandIndex()) |
| 4150 | return true; // Storing addr, not into addr. |
| 4151 | MemoryUses.push_back(std::make_pair(RMW, opNo)); |
| 4152 | continue; |
| 4153 | } |
| 4154 | |
| 4155 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) { |
| 4156 | unsigned opNo = U.getOperandNo(); |
| 4157 | if (opNo != AtomicCmpXchgInst::getPointerOperandIndex()) |
| 4158 | return true; // Storing addr, not into addr. |
| 4159 | MemoryUses.push_back(std::make_pair(CmpX, opNo)); |
| 4160 | continue; |
| 4161 | } |
| 4162 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 4163 | if (CallInst *CI = dyn_cast<CallInst>(UserI)) { |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4164 | // If this is a cold call, we can sink the addressing calculation into |
| 4165 | // the cold path. See optimizeCallInst |
| 4166 | if (!OptSize && CI->hasFnAttr(Attribute::Cold)) |
| 4167 | continue; |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 4168 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4169 | InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue()); |
| 4170 | if (!IA) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4171 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4172 | // If this is a memory operand, we're cool, otherwise bail out. |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4173 | if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4174 | return true; |
| 4175 | continue; |
| 4176 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4177 | |
Benjamin Kramer | fc638c1 | 2017-07-24 16:18:09 +0000 | [diff] [blame] | 4178 | if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, |
| 4179 | SeenInsts)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4180 | return true; |
| 4181 | } |
| 4182 | |
| 4183 | return false; |
| 4184 | } |
| 4185 | |
Sanjay Patel | 9fbe22b | 2015-10-09 18:01:03 +0000 | [diff] [blame] | 4186 | /// Return true if Val is already known to be live at the use site that we're |
| 4187 | /// folding it into. If so, there is no cost to include it in the addressing |
| 4188 | /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the |
| 4189 | /// instruction already. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4190 | bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4191 | Value *KnownLive2) { |
| 4192 | // 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] | 4193 | if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4194 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4195 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4196 | // All values other than instructions and arguments (e.g. constants) are live. |
| 4197 | if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4198 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4199 | // If Val is a constant sized alloca in the entry block, it is live, this is |
| 4200 | // true because it is just a reference to the stack/frame pointer, which is |
| 4201 | // live for the whole function. |
| 4202 | if (AllocaInst *AI = dyn_cast<AllocaInst>(Val)) |
| 4203 | if (AI->isStaticAlloca()) |
| 4204 | return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4205 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4206 | // Check to see if this value is already used in the memory instruction's |
| 4207 | // block. If so, it's already live into the block at the very least, so we |
| 4208 | // can reasonably fold it. |
| 4209 | return Val->isUsedInBasicBlock(MemoryInst->getParent()); |
| 4210 | } |
| 4211 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4212 | /// It is possible for the addressing mode of the machine to fold the specified |
| 4213 | /// instruction into a load or store that ultimately uses it. |
| 4214 | /// However, the specified instruction has multiple uses. |
| 4215 | /// Given this, it may actually increase register pressure to fold it |
| 4216 | /// into the load. For example, consider this code: |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4217 | /// |
| 4218 | /// X = ... |
| 4219 | /// Y = X+1 |
| 4220 | /// use(Y) -> nonload/store |
| 4221 | /// Z = Y+1 |
| 4222 | /// load Z |
| 4223 | /// |
| 4224 | /// In this case, Y has multiple uses, and can be folded into the load of Z |
| 4225 | /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to |
| 4226 | /// be live at the use(Y) line. If we don't fold Y into load Z, we use one |
| 4227 | /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the |
| 4228 | /// number of computations either. |
| 4229 | /// |
| 4230 | /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If |
| 4231 | /// X was live across 'load Z' for other reasons, we actually *would* want to |
| 4232 | /// fold the addressing mode in the Z case. This would make Y die earlier. |
| 4233 | bool AddressingModeMatcher:: |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4234 | isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore, |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4235 | ExtAddrMode &AMAfter) { |
| 4236 | if (IgnoreProfitability) return true; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4237 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4238 | // AMBefore is the addressing mode before this instruction was folded into it, |
| 4239 | // and AMAfter is the addressing mode after the instruction was folded. Get |
| 4240 | // the set of registers referenced by AMAfter and subtract out those |
| 4241 | // referenced by AMBefore: this is the set of values which folding in this |
| 4242 | // address extends the lifetime of. |
| 4243 | // |
| 4244 | // Note that there are only two potential values being referenced here, |
| 4245 | // BaseReg and ScaleReg (global addresses are always available, as are any |
| 4246 | // folded immediates). |
| 4247 | Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4248 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4249 | // If the BaseReg or ScaledReg was referenced by the previous addrmode, their |
| 4250 | // lifetime wasn't extended by adding this instruction. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4251 | if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4252 | BaseReg = nullptr; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4253 | if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg)) |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4254 | ScaledReg = nullptr; |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4255 | |
| 4256 | // If folding this instruction (and it's subexprs) didn't extend any live |
| 4257 | // ranges, we're ok with it. |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4258 | if (!BaseReg && !ScaledReg) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4259 | return true; |
| 4260 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4261 | // If all uses of this instruction can have the address mode sunk into them, |
| 4262 | // we can remove the addressing mode and effectively trade one live register |
| 4263 | // for another (at worst.) In this context, folding an addressing mode into |
Junmo Park | 6098cbb | 2016-03-11 07:05:32 +0000 | [diff] [blame] | 4264 | // the use is just a particularly nice way of sinking it. |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4265 | SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses; |
| 4266 | SmallPtrSet<Instruction*, 16> ConsideredInsts; |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4267 | if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4268 | return false; // Has a non-memory, non-foldable use! |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4269 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4270 | // Now that we know that all uses of this instruction are part of a chain of |
| 4271 | // computation involving only operations that could theoretically be folded |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4272 | // into a memory use, loop over each of these memory operation uses and see |
| 4273 | // if they could *actually* fold the instruction. The assumption is that |
| 4274 | // addressing modes are cheap and that duplicating the computation involved |
| 4275 | // many times is worthwhile, even on a fastpath. For sinking candidates |
| 4276 | // (i.e. cold call sites), this serves as a way to prevent excessive code |
| 4277 | // growth since most architectures have some reasonable small and fast way to |
| 4278 | // compute an effective address. (i.e LEA on x86) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4279 | SmallVector<Instruction*, 32> MatchedAddrModeInsts; |
| 4280 | for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) { |
| 4281 | Instruction *User = MemoryUses[i].first; |
| 4282 | unsigned OpNo = MemoryUses[i].second; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4283 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4284 | // Get the access type of this use. If the use isn't a pointer, we don't |
| 4285 | // know what it accesses. |
| 4286 | Value *Address = User->getOperand(OpNo); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4287 | PointerType *AddrTy = dyn_cast<PointerType>(Address->getType()); |
| 4288 | if (!AddrTy) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4289 | return false; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4290 | Type *AddressAccessTy = AddrTy->getElementType(); |
| 4291 | unsigned AS = AddrTy->getAddressSpace(); |
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 | // Do a match against the root of this address, ignoring profitability. This |
| 4294 | // will tell us if the addressing mode for the memory operation will |
| 4295 | // *actually* cover the shared instruction. |
| 4296 | ExtAddrMode Result; |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4297 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4298 | TPT.getRestorationPoint(); |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4299 | AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, |
| 4300 | AddressAccessTy, AS, |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 4301 | MemoryInst, Result, InsertedInsts, |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4302 | PromotedInsts, TPT); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4303 | Matcher.IgnoreProfitability = true; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4304 | bool Success = Matcher.matchAddr(Address, 0); |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4305 | (void)Success; assert(Success && "Couldn't select *anything*?"); |
| 4306 | |
Quentin Colombet | 5a69dda | 2014-02-11 01:59:02 +0000 | [diff] [blame] | 4307 | // The match was to check the profitability, the changes made are not |
| 4308 | // part of the original matcher. Therefore, they should be dropped |
| 4309 | // otherwise the original matcher will not present the right state. |
| 4310 | TPT.rollback(LastKnownGood); |
| 4311 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4312 | // 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] | 4313 | if (!is_contained(MatchedAddrModeInsts, I)) |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4314 | return false; |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4315 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4316 | MatchedAddrModeInsts.clear(); |
| 4317 | } |
Stephen Lin | 837bba1 | 2013-07-15 17:55:02 +0000 | [diff] [blame] | 4318 | |
Chandler Carruth | c892591 | 2013-01-05 02:09:22 +0000 | [diff] [blame] | 4319 | return true; |
| 4320 | } |
| 4321 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4322 | /// Return true if the specified values are defined in a |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4323 | /// different basic block than BB. |
| 4324 | static bool IsNonLocalValue(Value *V, BasicBlock *BB) { |
| 4325 | if (Instruction *I = dyn_cast<Instruction>(V)) |
| 4326 | return I->getParent() != BB; |
| 4327 | return false; |
| 4328 | } |
| 4329 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4330 | /// Sink addressing mode computation immediate before MemoryInst if doing so |
| 4331 | /// can be done without increasing register pressure. The need for the |
| 4332 | /// register pressure constraint means this can end up being an all or nothing |
| 4333 | /// decision for all uses of the same addressing computation. |
| 4334 | /// |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4335 | /// Load and Store Instructions often have addressing modes that can do |
| 4336 | /// significant amounts of computation. As such, instruction selection will try |
| 4337 | /// to get the load or store to do as much computation as possible for the |
| 4338 | /// program. The problem is that isel can only see within a single block. As |
| 4339 | /// 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] | 4340 | /// |
| 4341 | /// 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] | 4342 | /// operands. It's also used to sink addressing computations feeding into cold |
| 4343 | /// call sites into their (cold) basic block. |
| 4344 | /// |
| 4345 | /// The motivation for handling sinking into cold blocks is that doing so can |
| 4346 | /// both enable other address mode sinking (by satisfying the register pressure |
| 4347 | /// constraint above), and reduce register pressure globally (by removing the |
| 4348 | /// addressing mode computation from the fast path entirely.). |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4349 | bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 4350 | Type *AccessTy, unsigned AddrSpace) { |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4351 | Value *Repl = Addr; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4352 | |
| 4353 | // Try to collapse single-value PHI nodes. This is necessary to undo |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4354 | // unprofitable PRE transformations. |
Cameron Zwarich | 43cecb1 | 2011-01-03 06:33:01 +0000 | [diff] [blame] | 4355 | SmallVector<Value*, 8> worklist; |
| 4356 | SmallPtrSet<Value*, 16> Visited; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4357 | worklist.push_back(Addr); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4358 | |
John Brawn | eb83c75 | 2017-10-03 13:04:15 +0000 | [diff] [blame] | 4359 | // Use a worklist to iteratively look through PHI and select nodes, and |
| 4360 | // 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] | 4361 | // the graph are compatible. |
John Brawn | eb83c75 | 2017-10-03 13:04:15 +0000 | [diff] [blame] | 4362 | bool PhiOrSelectSeen = false; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4363 | SmallVector<Instruction*, 16> AddrModeInsts; |
Serguei Katkov | aee6375 | 2017-11-05 07:59:02 +0000 | [diff] [blame] | 4364 | const SimplifyQuery SQ(*DL, TLInfo); |
| 4365 | AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() }); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4366 | TypePromotionTransaction TPT(RemovedInsts); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4367 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4368 | TPT.getRestorationPoint(); |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4369 | while (!worklist.empty()) { |
| 4370 | Value *V = worklist.back(); |
| 4371 | worklist.pop_back(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4372 | |
Serguei Katkov | 4ea855e | 2017-07-19 04:49:17 +0000 | [diff] [blame] | 4373 | // We allow traversing cyclic Phi nodes. |
| 4374 | // In case of success after this loop we ensure that traversing through |
| 4375 | // Phi nodes ends up with all cases to compute address of the form |
| 4376 | // BaseGV + Base + Scale * Index + Offset |
| 4377 | // where Scale and Offset are constans and BaseGV, Base and Index |
| 4378 | // are exactly the same Values in all cases. |
| 4379 | // It means that BaseGV, Scale and Offset dominate our memory instruction |
| 4380 | // and have the same value as they had in address computation represented |
| 4381 | // as Phi. So we can safely sink address computation to memory instruction. |
| 4382 | if (!Visited.insert(V).second) |
| 4383 | continue; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4384 | |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4385 | // For a PHI node, push all of its incoming values. |
| 4386 | if (PHINode *P = dyn_cast<PHINode>(V)) { |
Pete Cooper | 833f34d | 2015-05-12 20:05:31 +0000 | [diff] [blame] | 4387 | for (Value *IncValue : P->incoming_values()) |
| 4388 | worklist.push_back(IncValue); |
John Brawn | eb83c75 | 2017-10-03 13:04:15 +0000 | [diff] [blame] | 4389 | PhiOrSelectSeen = true; |
| 4390 | continue; |
| 4391 | } |
| 4392 | // Similar for select. |
| 4393 | if (SelectInst *SI = dyn_cast<SelectInst>(V)) { |
| 4394 | worklist.push_back(SI->getFalseValue()); |
| 4395 | worklist.push_back(SI->getTrueValue()); |
| 4396 | PhiOrSelectSeen = true; |
Owen Anderson | 8ba5f39 | 2010-11-27 08:15:55 +0000 | [diff] [blame] | 4397 | continue; |
| 4398 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4399 | |
Philip Reames | ac115ed | 2016-03-09 23:13:12 +0000 | [diff] [blame] | 4400 | // For non-PHIs, determine the addressing mode being computed. Note that |
| 4401 | // the result may differ depending on what other uses our candidate |
| 4402 | // addressing instructions might have. |
Serguei Katkov | a6fba3d | 2017-07-18 05:16:38 +0000 | [diff] [blame] | 4403 | AddrModeInsts.clear(); |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4404 | ExtAddrMode NewAddrMode = AddressingModeMatcher::Match( |
Serguei Katkov | a6fba3d | 2017-07-18 05:16:38 +0000 | [diff] [blame] | 4405 | V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI, |
| 4406 | InsertedInsts, PromotedInsts, TPT); |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 4407 | NewAddrMode.OriginalValue = V; |
Cameron Zwarich | 13c885d | 2011-03-05 08:12:26 +0000 | [diff] [blame] | 4408 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 4409 | if (!AddrModes.addNewAddrMode(NewAddrMode)) |
| 4410 | break; |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4411 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4412 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 4413 | // Try to combine the AddrModes we've collected. If we couldn't collect any, |
| 4414 | // or we have multiple but either couldn't combine them or combining them |
| 4415 | // wouldn't do anything useful, bail out now. |
| 4416 | if (!AddrModes.combineAddrModes()) { |
Quentin Colombet | 3a4bf04 | 2014-02-06 21:44:56 +0000 | [diff] [blame] | 4417 | TPT.rollback(LastKnownGood); |
| 4418 | return false; |
| 4419 | } |
| 4420 | TPT.commit(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4421 | |
John Brawn | 736bf00 | 2017-10-03 13:08:22 +0000 | [diff] [blame] | 4422 | // Get the combined AddrMode (or the only AddrMode, if we only had one). |
| 4423 | ExtAddrMode AddrMode = AddrModes.getAddrMode(); |
| 4424 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4425 | // 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] | 4426 | // If we saw a Phi node then it is not local definitely, and if we saw a select |
| 4427 | // then we want to push the address calculation past it even if it's already |
| 4428 | // in this BB. |
| 4429 | if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) { |
Justin Lebar | 838c7f5 | 2016-11-21 22:49:11 +0000 | [diff] [blame] | 4430 | return IsNonLocalValue(V, MemoryInst->getParent()); |
Serguei Katkov | 0b7b59a | 2017-07-11 06:24:44 +0000 | [diff] [blame] | 4431 | })) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4432 | DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4433 | return false; |
| 4434 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4435 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4436 | // Insert this computation right after this user. Since our caller is |
| 4437 | // scanning from the top of the BB to the bottom, reuse of the expr are |
| 4438 | // guaranteed to happen later. |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4439 | IRBuilder<> Builder(MemoryInst); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4440 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4441 | // Now that we determined the addressing expression we want to use and know |
| 4442 | // 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] | 4443 | // done this for some other load/store instr in this block. If so, reuse |
| 4444 | // the computation. Before attempting reuse, check if the address is valid |
| 4445 | // as it may have been erased. |
| 4446 | |
| 4447 | WeakTrackingVH SunkAddrVH = SunkAddrs[Addr]; |
| 4448 | |
| 4449 | Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4450 | if (SunkAddr) { |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4451 | DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4452 | << *MemoryInst << "\n"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4453 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4454 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Eric Christopher | fccff37 | 2015-01-27 01:01:38 +0000 | [diff] [blame] | 4455 | } else if (AddrSinkUsingGEPs || |
| 4456 | (!AddrSinkUsingGEPs.getNumOccurrences() && TM && |
Igor Laevsky | 3be81ba | 2017-02-07 13:27:20 +0000 | [diff] [blame] | 4457 | SubtargetInfo->useAA())) { |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4458 | // By default, we use the GEP-based method when AA is used later. This |
| 4459 | // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities. |
| 4460 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4461 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4462 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4463 | Value *ResultPtr = nullptr, *ResultIndex = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4464 | |
| 4465 | // First, find the pointer. |
| 4466 | if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) { |
| 4467 | ResultPtr = AddrMode.BaseReg; |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4468 | AddrMode.BaseReg = nullptr; |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4469 | } |
| 4470 | |
| 4471 | if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) { |
| 4472 | // We can't add more than one pointer together, nor can we scale a |
| 4473 | // pointer (both of which seem meaningless). |
| 4474 | if (ResultPtr || AddrMode.Scale != 1) |
| 4475 | return false; |
| 4476 | |
| 4477 | ResultPtr = AddrMode.ScaledReg; |
| 4478 | AddrMode.Scale = 0; |
| 4479 | } |
| 4480 | |
Eli Friedman | 6f7c9ad | 2017-07-12 23:30:02 +0000 | [diff] [blame] | 4481 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4482 | // required to create it did not overflow before we extend it. Since |
| 4483 | // the original IR value was tossed in favor of a constant back when |
| 4484 | // the AddrMode was created we need to bail out gracefully if widths |
| 4485 | // do not match instead of extending it. |
| 4486 | // |
| 4487 | // (See below for code to add the scale.) |
| 4488 | if (AddrMode.Scale) { |
| 4489 | Type *ScaledRegTy = AddrMode.ScaledReg->getType(); |
| 4490 | if (cast<IntegerType>(IntPtrTy)->getBitWidth() > |
| 4491 | cast<IntegerType>(ScaledRegTy)->getBitWidth()) |
| 4492 | return false; |
| 4493 | } |
| 4494 | |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4495 | if (AddrMode.BaseGV) { |
| 4496 | if (ResultPtr) |
| 4497 | return false; |
| 4498 | |
| 4499 | ResultPtr = AddrMode.BaseGV; |
| 4500 | } |
| 4501 | |
| 4502 | // If the real base value actually came from an inttoptr, then the matcher |
| 4503 | // will look through it and provide only the integer value. In that case, |
| 4504 | // use it here. |
Keno Fischer | 05e4ac2 | 2017-06-29 20:28:59 +0000 | [diff] [blame] | 4505 | if (!DL->isNonIntegralPointerType(Addr->getType())) { |
| 4506 | if (!ResultPtr && AddrMode.BaseReg) { |
| 4507 | ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), |
| 4508 | "sunkaddr"); |
| 4509 | AddrMode.BaseReg = nullptr; |
| 4510 | } else if (!ResultPtr && AddrMode.Scale == 1) { |
| 4511 | ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), |
| 4512 | "sunkaddr"); |
| 4513 | AddrMode.Scale = 0; |
| 4514 | } |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4515 | } |
| 4516 | |
| 4517 | if (!ResultPtr && |
| 4518 | !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) { |
| 4519 | SunkAddr = Constant::getNullValue(Addr->getType()); |
| 4520 | } else if (!ResultPtr) { |
| 4521 | return false; |
| 4522 | } else { |
| 4523 | Type *I8PtrTy = |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4524 | Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace()); |
| 4525 | Type *I8Ty = Builder.getInt8Ty(); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4526 | |
| 4527 | // Start with the base register. Do this first so that subsequent address |
| 4528 | // matching finds it last, which will prevent it from trying to match it |
| 4529 | // as the scaled value in case it happens to be a mul. That would be |
| 4530 | // problematic if we've sunk a different mul for the scale, because then |
| 4531 | // we'd end up sinking both muls. |
| 4532 | if (AddrMode.BaseReg) { |
| 4533 | Value *V = AddrMode.BaseReg; |
| 4534 | if (V->getType() != IntPtrTy) |
| 4535 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
| 4536 | |
| 4537 | ResultIndex = V; |
| 4538 | } |
| 4539 | |
| 4540 | // Add the scale value. |
| 4541 | if (AddrMode.Scale) { |
| 4542 | Value *V = AddrMode.ScaledReg; |
| 4543 | if (V->getType() == IntPtrTy) { |
| 4544 | // done. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4545 | } else { |
Eli Friedman | 6f7c9ad | 2017-07-12 23:30:02 +0000 | [diff] [blame] | 4546 | assert(cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4547 | cast<IntegerType>(V->getType())->getBitWidth() && |
| 4548 | "We can't transform if ScaledReg is too narrow"); |
| 4549 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4550 | } |
| 4551 | |
| 4552 | if (AddrMode.Scale != 1) |
| 4553 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4554 | "sunkaddr"); |
| 4555 | if (ResultIndex) |
| 4556 | ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr"); |
| 4557 | else |
| 4558 | ResultIndex = V; |
| 4559 | } |
| 4560 | |
| 4561 | // Add in the Base Offset if present. |
| 4562 | if (AddrMode.BaseOffs) { |
| 4563 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
| 4564 | if (ResultIndex) { |
NAKAMURA Takumi | f51a34e | 2014-10-29 15:23:11 +0000 | [diff] [blame] | 4565 | // We need to add this separately from the scale above to help with |
| 4566 | // SDAG consecutive load/store merging. |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4567 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4568 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4569 | ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4570 | } |
| 4571 | |
| 4572 | ResultIndex = V; |
| 4573 | } |
| 4574 | |
| 4575 | if (!ResultIndex) { |
| 4576 | SunkAddr = ResultPtr; |
| 4577 | } else { |
| 4578 | if (ResultPtr->getType() != I8PtrTy) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4579 | ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy); |
David Blaikie | 3909da7 | 2015-03-30 20:42:56 +0000 | [diff] [blame] | 4580 | SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr"); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4581 | } |
| 4582 | |
| 4583 | if (SunkAddr->getType() != Addr->getType()) |
Eli Friedman | c12a5a7 | 2017-02-24 20:51:36 +0000 | [diff] [blame] | 4584 | SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType()); |
Hal Finkel | c399830 | 2014-04-12 00:59:48 +0000 | [diff] [blame] | 4585 | } |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4586 | } else { |
Keno Fischer | 05e4ac2 | 2017-06-29 20:28:59 +0000 | [diff] [blame] | 4587 | // We'd require a ptrtoint/inttoptr down the line, which we can't do for |
| 4588 | // non-integral pointers, so in that case bail out now. |
| 4589 | Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr; |
| 4590 | Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr; |
| 4591 | PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy); |
| 4592 | PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy); |
| 4593 | if (DL->isNonIntegralPointerType(Addr->getType()) || |
| 4594 | (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) || |
| 4595 | (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) || |
| 4596 | (AddrMode.BaseGV && |
| 4597 | DL->isNonIntegralPointerType(AddrMode.BaseGV->getType()))) |
| 4598 | return false; |
| 4599 | |
David Greene | 74e2d49 | 2010-01-05 01:27:11 +0000 | [diff] [blame] | 4600 | DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for " |
Louis Gerbarg | 1b91aa2 | 2014-05-13 21:54:22 +0000 | [diff] [blame] | 4601 | << *MemoryInst << "\n"); |
Mehdi Amini | 4fe3798 | 2015-07-07 18:45:17 +0000 | [diff] [blame] | 4602 | Type *IntPtrTy = DL->getIntPtrType(Addr->getType()); |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4603 | Value *Result = nullptr; |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4604 | |
| 4605 | // Start with the base register. Do this first so that subsequent address |
| 4606 | // matching finds it last, which will prevent it from trying to match it |
| 4607 | // as the scaled value in case it happens to be a mul. That would be |
| 4608 | // problematic if we've sunk a different mul for the scale, because then |
| 4609 | // we'd end up sinking both muls. |
| 4610 | if (AddrMode.BaseReg) { |
| 4611 | Value *V = AddrMode.BaseReg; |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4612 | if (V->getType()->isPointerTy()) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4613 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4614 | if (V->getType() != IntPtrTy) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4615 | V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr"); |
Dan Gohman | ca19445 | 2010-01-19 22:45:06 +0000 | [diff] [blame] | 4616 | Result = V; |
| 4617 | } |
| 4618 | |
| 4619 | // Add the scale value. |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4620 | if (AddrMode.Scale) { |
| 4621 | Value *V = AddrMode.ScaledReg; |
| 4622 | if (V->getType() == IntPtrTy) { |
| 4623 | // done. |
Duncan Sands | 19d0b47 | 2010-02-16 11:11:14 +0000 | [diff] [blame] | 4624 | } else if (V->getType()->isPointerTy()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4625 | V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4626 | } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() < |
| 4627 | cast<IntegerType>(V->getType())->getBitWidth()) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4628 | V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4629 | } else { |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4630 | // It is only safe to sign extend the BaseReg if we know that the math |
| 4631 | // required to create it did not overflow before we extend it. Since |
| 4632 | // the original IR value was tossed in favor of a constant back when |
| 4633 | // the AddrMode was created we need to bail out gracefully if widths |
| 4634 | // do not match instead of extending it. |
Joey Gouly | 12a8bf0 | 2014-05-13 15:42:45 +0000 | [diff] [blame] | 4635 | Instruction *I = dyn_cast_or_null<Instruction>(Result); |
Jim Grosbach | 83b44e1 | 2014-04-10 00:27:45 +0000 | [diff] [blame] | 4636 | if (I && (Result != AddrMode.BaseReg)) |
| 4637 | I->eraseFromParent(); |
Jim Grosbach | ed2cd39 | 2014-03-26 17:27:01 +0000 | [diff] [blame] | 4638 | return false; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4639 | } |
| 4640 | if (AddrMode.Scale != 1) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4641 | V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale), |
| 4642 | "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4643 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4644 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4645 | else |
| 4646 | Result = V; |
| 4647 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4648 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4649 | // Add in the BaseGV if present. |
| 4650 | if (AddrMode.BaseGV) { |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4651 | Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4652 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4653 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4654 | else |
| 4655 | Result = V; |
| 4656 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4657 | |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4658 | // Add in the Base Offset if present. |
| 4659 | if (AddrMode.BaseOffs) { |
Owen Anderson | edb4a70 | 2009-07-24 23:12:02 +0000 | [diff] [blame] | 4660 | Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4661 | if (Result) |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4662 | Result = Builder.CreateAdd(Result, V, "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4663 | else |
| 4664 | Result = V; |
| 4665 | } |
| 4666 | |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 4667 | if (!Result) |
Owen Anderson | 5a1acd9 | 2009-07-31 20:28:14 +0000 | [diff] [blame] | 4668 | SunkAddr = Constant::getNullValue(Addr->getType()); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4669 | else |
Devang Patel | c10e52a | 2011-09-06 18:49:53 +0000 | [diff] [blame] | 4670 | SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr"); |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4671 | } |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4672 | |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4673 | MemoryInst->replaceUsesOfWith(Repl, SunkAddr); |
Simon Dardis | 230f453 | 2017-11-24 16:45:28 +0000 | [diff] [blame] | 4674 | // Store the newly computed address into the cache. In the case we reused a |
| 4675 | // value, this should be idempotent. |
| 4676 | SunkAddrs[Addr] = WeakTrackingVH(SunkAddr); |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 4677 | |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4678 | // If we have no uses, recursively delete the value and all dead instructions |
| 4679 | // using it. |
Owen Anderson | dfb8c3b | 2010-11-19 22:15:03 +0000 | [diff] [blame] | 4680 | if (Repl->use_empty()) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4681 | // This can cause recursive deletion, which can invalidate our iterator. |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 4682 | // 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] | 4683 | Value *CurValue = &*CurInstIterator; |
Sanjoy Das | e6bca0e | 2017-05-01 17:07:49 +0000 | [diff] [blame] | 4684 | WeakTrackingVH IterHandle(CurValue); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4685 | BasicBlock *BB = CurInstIterator->getParent(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4686 | |
Benjamin Kramer | 8bcc971 | 2012-08-29 15:32:21 +0000 | [diff] [blame] | 4687 | RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo); |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4688 | |
Duncan P. N. Exon Smith | 7b26964 | 2016-02-21 19:37:45 +0000 | [diff] [blame] | 4689 | if (IterHandle != CurValue) { |
Chris Lattner | af1bcce | 2011-04-09 07:05:44 +0000 | [diff] [blame] | 4690 | // If the iterator instruction was recursively deleted, start over at the |
| 4691 | // start of the block. |
| 4692 | CurInstIterator = BB->begin(); |
| 4693 | SunkAddrs.clear(); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4694 | } |
Dale Johannesen | b67a6e66 | 2010-03-31 20:37:15 +0000 | [diff] [blame] | 4695 | } |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 4696 | ++NumMemoryInsts; |
Chris Lattner | feee64e | 2007-04-13 20:30:56 +0000 | [diff] [blame] | 4697 | return true; |
| 4698 | } |
| 4699 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4700 | /// If there are any memory operands, use OptimizeMemoryInst to sink their |
| 4701 | /// address computing into the block when possible / profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4702 | bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) { |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4703 | bool MadeChange = false; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4704 | |
Eric Christopher | 11e4df7 | 2015-02-26 22:38:43 +0000 | [diff] [blame] | 4705 | const TargetRegisterInfo *TRI = |
Sanjay Patel | 4137d51 | 2017-06-07 14:29:52 +0000 | [diff] [blame] | 4706 | TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo(); |
Mehdi Amini | 8ac7a9d | 2015-07-07 19:07:19 +0000 | [diff] [blame] | 4707 | TargetLowering::AsmOperandInfoVector TargetConstraints = |
| 4708 | TLI->ParseConstraints(*DL, TRI, CS); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4709 | unsigned ArgNo = 0; |
John Thompson | 1094c80 | 2010-09-13 18:15:37 +0000 | [diff] [blame] | 4710 | for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) { |
| 4711 | TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i]; |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 4712 | |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4713 | // Compute the constraint code and ConstraintType to use. |
Dale Johannesen | ce97d55 | 2010-06-25 21:55:36 +0000 | [diff] [blame] | 4714 | TLI->ComputeConstraintToUse(OpInfo, SDValue()); |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4715 | |
Eli Friedman | 666bbe3 | 2008-02-26 18:37:49 +0000 | [diff] [blame] | 4716 | if (OpInfo.ConstraintType == TargetLowering::C_Memory && |
| 4717 | OpInfo.isIndirect) { |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 4718 | Value *OpVal = CS->getArgOperand(ArgNo++); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 4719 | MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u); |
Dale Johannesen | f95f59a | 2010-09-16 18:30:55 +0000 | [diff] [blame] | 4720 | } else if (OpInfo.Type == InlineAsm::isInput) |
| 4721 | ArgNo++; |
Evan Cheng | 1da2500 | 2008-02-26 02:42:37 +0000 | [diff] [blame] | 4722 | } |
| 4723 | |
| 4724 | return MadeChange; |
| 4725 | } |
| 4726 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4727 | /// \brief Check if all the uses of \p Val are equivalent (or free) zero or |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4728 | /// sign extensions. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4729 | static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) { |
| 4730 | assert(!Val->use_empty() && "Input must have at least one use"); |
| 4731 | const Instruction *FirstUser = cast<Instruction>(*Val->user_begin()); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4732 | bool IsSExt = isa<SExtInst>(FirstUser); |
| 4733 | Type *ExtTy = FirstUser->getType(); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4734 | for (const User *U : Val->users()) { |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4735 | const Instruction *UI = cast<Instruction>(U); |
| 4736 | if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI))) |
| 4737 | return false; |
| 4738 | Type *CurTy = UI->getType(); |
| 4739 | // Same input and output types: Same instruction after CSE. |
| 4740 | if (CurTy == ExtTy) |
| 4741 | continue; |
| 4742 | |
| 4743 | // If IsSExt is true, we are in this situation: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4744 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4745 | // b = sext ty1 a to ty2 |
| 4746 | // c = sext ty1 a to ty3 |
| 4747 | // Assuming ty2 is shorter than ty3, this could be turned into: |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4748 | // a = Val |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4749 | // b = sext ty1 a to ty2 |
| 4750 | // c = sext ty2 b to ty3 |
| 4751 | // However, the last sext is not free. |
| 4752 | if (IsSExt) |
| 4753 | return false; |
| 4754 | |
| 4755 | // This is a ZExt, maybe this is free to extend from one type to another. |
| 4756 | // In that case, we would not account for a different use. |
| 4757 | Type *NarrowTy; |
| 4758 | Type *LargeTy; |
| 4759 | if (ExtTy->getScalarType()->getIntegerBitWidth() > |
| 4760 | CurTy->getScalarType()->getIntegerBitWidth()) { |
| 4761 | NarrowTy = CurTy; |
| 4762 | LargeTy = ExtTy; |
| 4763 | } else { |
| 4764 | NarrowTy = ExtTy; |
| 4765 | LargeTy = CurTy; |
| 4766 | } |
| 4767 | |
| 4768 | if (!TLI.isZExtFree(NarrowTy, LargeTy)) |
| 4769 | return false; |
| 4770 | } |
| 4771 | // All uses are the same or can be derived from one another for free. |
| 4772 | return true; |
| 4773 | } |
| 4774 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4775 | /// \brief Try to speculatively promote extensions in \p Exts and continue |
| 4776 | /// promoting through newly promoted operands recursively as far as doing so is |
| 4777 | /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts. |
| 4778 | /// When some promotion happened, \p TPT contains the proper state to revert |
| 4779 | /// them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4780 | /// |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4781 | /// \return true if some promotion happened, false otherwise. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4782 | bool CodeGenPrepare::tryToPromoteExts( |
| 4783 | TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts, |
| 4784 | SmallVectorImpl<Instruction *> &ProfitablyMovedExts, |
| 4785 | unsigned CreatedInstsCost) { |
| 4786 | bool Promoted = false; |
| 4787 | |
| 4788 | // Iterate over all the extensions to try to promote them. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4789 | for (auto I : Exts) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4790 | // Early check if we directly have ext(load). |
| 4791 | if (isa<LoadInst>(I->getOperand(0))) { |
| 4792 | ProfitablyMovedExts.push_back(I); |
| 4793 | continue; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4794 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4795 | |
| 4796 | // Check whether or not we want to do any promotion. The reason we have |
| 4797 | // this check inside the for loop is to catch the case where an extension |
| 4798 | // is directly fed by a load because in such case the extension can be moved |
| 4799 | // up without any promotion on its operands. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4800 | if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion) |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4801 | return false; |
| 4802 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4803 | // Get the action to perform the promotion. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4804 | TypePromotionHelper::Action TPH = |
| 4805 | TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4806 | // Check if we can promote. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4807 | if (!TPH) { |
| 4808 | // Save the current extension as we cannot move up through its operand. |
| 4809 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4810 | continue; |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4811 | } |
| 4812 | |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4813 | // Save the current state. |
| 4814 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
| 4815 | TPT.getRestorationPoint(); |
| 4816 | SmallVector<Instruction *, 4> NewExts; |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4817 | unsigned NewCreatedInstsCost = 0; |
| 4818 | unsigned ExtCost = !TLI->isExtFree(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4819 | // Promote. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4820 | Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost, |
| 4821 | &NewExts, nullptr, *TLI); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4822 | assert(PromotedVal && |
| 4823 | "TypePromotionHelper should have filtered out those cases"); |
| 4824 | |
| 4825 | // We would be able to merge only one extension in a load. |
| 4826 | // Therefore, if we have more than 1 new extension we heuristically |
| 4827 | // cut this search path, because it means we degrade the code quality. |
| 4828 | // With exactly 2, the transformation is neutral, because we will merge |
| 4829 | // one extension but leave one. However, we optimistically keep going, |
| 4830 | // because the new extension may be removed too. |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4831 | long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost; |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4832 | // 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] | 4833 | // conservatively ceiling it to 0. |
Jun Bum Lim | b99a06b | 2017-01-27 17:16:37 +0000 | [diff] [blame] | 4834 | TotalCreatedInstsCost = |
| 4835 | std::max((long long)0, (TotalCreatedInstsCost - ExtCost)); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4836 | if (!StressExtLdPromotion && |
Quentin Colombet | 1b274f9 | 2015-03-10 21:48:15 +0000 | [diff] [blame] | 4837 | (TotalCreatedInstsCost > 1 || |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 4838 | !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) { |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4839 | // This promotion is not profitable, rollback to the previous state, and |
| 4840 | // save the current extension in ProfitablyMovedExts as the latest |
| 4841 | // speculative promotion turned out to be unprofitable. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4842 | TPT.rollback(LastKnownGood); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4843 | ProfitablyMovedExts.push_back(I); |
| 4844 | continue; |
| 4845 | } |
| 4846 | // Continue promoting NewExts as far as doing so is profitable. |
| 4847 | SmallVector<Instruction *, 2> NewlyMovedExts; |
| 4848 | (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost); |
| 4849 | bool NewPromoted = false; |
| 4850 | for (auto ExtInst : NewlyMovedExts) { |
| 4851 | Instruction *MovedExt = cast<Instruction>(ExtInst); |
| 4852 | Value *ExtOperand = MovedExt->getOperand(0); |
| 4853 | // If we have reached to a load, we need this extra profitability check |
| 4854 | // as it could potentially be merged into an ext(load). |
| 4855 | if (isa<LoadInst>(ExtOperand) && |
| 4856 | !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost || |
| 4857 | (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI)))) |
| 4858 | continue; |
| 4859 | |
| 4860 | ProfitablyMovedExts.push_back(MovedExt); |
| 4861 | NewPromoted = true; |
| 4862 | } |
| 4863 | |
| 4864 | // If none of speculative promotions for NewExts is profitable, rollback |
| 4865 | // and save the current extension (I) as the last profitable extension. |
| 4866 | if (!NewPromoted) { |
| 4867 | TPT.rollback(LastKnownGood); |
| 4868 | ProfitablyMovedExts.push_back(I); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4869 | continue; |
| 4870 | } |
| 4871 | // The promotion is profitable. |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4872 | Promoted = true; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4873 | } |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4874 | return Promoted; |
| 4875 | } |
| 4876 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4877 | /// Merging redundant sexts when one is dominating the other. |
| 4878 | bool CodeGenPrepare::mergeSExts(Function &F) { |
| 4879 | DominatorTree DT(F); |
| 4880 | bool Changed = false; |
| 4881 | for (auto &Entry : ValToSExtendedUses) { |
| 4882 | SExts &Insts = Entry.second; |
| 4883 | SExts CurPts; |
| 4884 | for (Instruction *Inst : Insts) { |
| 4885 | if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) || |
| 4886 | Inst->getOperand(0) != Entry.first) |
| 4887 | continue; |
| 4888 | bool inserted = false; |
| 4889 | for (auto &Pt : CurPts) { |
| 4890 | if (DT.dominates(Inst, Pt)) { |
| 4891 | Pt->replaceAllUsesWith(Inst); |
| 4892 | RemovedInsts.insert(Pt); |
| 4893 | Pt->removeFromParent(); |
| 4894 | Pt = Inst; |
| 4895 | inserted = true; |
| 4896 | Changed = true; |
| 4897 | break; |
| 4898 | } |
| 4899 | if (!DT.dominates(Pt, Inst)) |
| 4900 | // Give up if we need to merge in a common dominator as the |
| 4901 | // expermients show it is not profitable. |
| 4902 | continue; |
| 4903 | Inst->replaceAllUsesWith(Pt); |
| 4904 | RemovedInsts.insert(Inst); |
| 4905 | Inst->removeFromParent(); |
| 4906 | inserted = true; |
| 4907 | Changed = true; |
| 4908 | break; |
| 4909 | } |
| 4910 | if (!inserted) |
| 4911 | CurPts.push_back(Inst); |
| 4912 | } |
| 4913 | } |
| 4914 | return Changed; |
| 4915 | } |
| 4916 | |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4917 | /// Return true, if an ext(load) can be formed from an extension in |
| 4918 | /// \p MovedExts. |
| 4919 | bool CodeGenPrepare::canFormExtLd( |
| 4920 | const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI, |
| 4921 | Instruction *&Inst, bool HasPromoted) { |
| 4922 | for (auto *MovedExtInst : MovedExts) { |
| 4923 | if (isa<LoadInst>(MovedExtInst->getOperand(0))) { |
| 4924 | LI = cast<LoadInst>(MovedExtInst->getOperand(0)); |
| 4925 | Inst = MovedExtInst; |
| 4926 | break; |
| 4927 | } |
| 4928 | } |
| 4929 | if (!LI) |
| 4930 | return false; |
| 4931 | |
| 4932 | // If they're already in the same block, there's nothing to do. |
| 4933 | // Make the cheap checks first if we did not promote. |
| 4934 | // If we promoted, we need to check if it is indeed profitable. |
| 4935 | if (!HasPromoted && LI->getParent() == Inst->getParent()) |
| 4936 | return false; |
| 4937 | |
Haicheng Wu | abdef9e | 2017-07-15 02:12:16 +0000 | [diff] [blame] | 4938 | return TLI->isExtLoad(LI, Inst, *DL); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4939 | } |
| 4940 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 4941 | /// Move a zext or sext fed by a load into the same basic block as the load, |
| 4942 | /// unless conditions are unfavorable. This allows SelectionDAG to fold the |
| 4943 | /// extend into the load. |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4944 | /// |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4945 | /// E.g., |
| 4946 | /// \code |
| 4947 | /// %ld = load i32* %addr |
| 4948 | /// %add = add nuw i32 %ld, 4 |
| 4949 | /// %zext = zext i32 %add to i64 |
| 4950 | // \endcode |
| 4951 | /// => |
| 4952 | /// \code |
| 4953 | /// %ld = load i32* %addr |
| 4954 | /// %zext = zext i32 %ld to i64 |
| 4955 | /// %add = add nuw i64 %zext, 4 |
| 4956 | /// \encode |
| 4957 | /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which |
| 4958 | /// allow us to match zext(load i32*) to i64. |
| 4959 | /// |
| 4960 | /// Also, try to promote the computations used to obtain a sign extended |
| 4961 | /// value used into memory accesses. |
| 4962 | /// E.g., |
| 4963 | /// \code |
| 4964 | /// a = add nsw i32 b, 3 |
| 4965 | /// d = sext i32 a to i64 |
| 4966 | /// e = getelementptr ..., i64 d |
| 4967 | /// \endcode |
| 4968 | /// => |
| 4969 | /// \code |
| 4970 | /// f = sext i32 b to i64 |
| 4971 | /// a = add nsw i64 f, 3 |
| 4972 | /// e = getelementptr ..., i64 a |
| 4973 | /// \endcode |
| 4974 | /// |
| 4975 | /// \p Inst[in/out] the extension may be modified during the process if some |
| 4976 | /// promotions apply. |
| 4977 | bool CodeGenPrepare::optimizeExt(Instruction *&Inst) { |
| 4978 | // ExtLoad formation and address type promotion infrastructure requires TLI to |
| 4979 | // be effective. |
Chandler Carruth | 0f139b4 | 2016-11-04 06:54:00 +0000 | [diff] [blame] | 4980 | if (!TLI) |
| 4981 | return false; |
| 4982 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4983 | bool AllowPromotionWithoutCommonHeader = false; |
| 4984 | /// See if it is an interesting sext operations for the address type |
| 4985 | /// promotion before trying to promote it, e.g., the ones with the right |
| 4986 | /// type and used in memory accesses. |
| 4987 | bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion( |
| 4988 | *Inst, AllowPromotionWithoutCommonHeader); |
| 4989 | TypePromotionTransaction TPT(RemovedInsts); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4990 | TypePromotionTransaction::ConstRestorationPt LastKnownGood = |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4991 | TPT.getRestorationPoint(); |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4992 | SmallVector<Instruction *, 1> Exts; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4993 | SmallVector<Instruction *, 2> SpeculativelyMovedExts; |
| 4994 | Exts.push_back(Inst); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4995 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 4996 | bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts); |
Jun Bum Lim | 4230101 | 2017-03-17 19:05:21 +0000 | [diff] [blame] | 4997 | |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 4998 | // Look for a load being extended. |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 4999 | LoadInst *LI = nullptr; |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5000 | Instruction *ExtFedByLoad; |
| 5001 | |
| 5002 | // Try to promote a chain of computation if it allows to form an extended |
| 5003 | // load. |
| 5004 | if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) { |
| 5005 | assert(LI && ExtFedByLoad && "Expect a valid load and extension"); |
| 5006 | TPT.commit(); |
| 5007 | // Move the extend into the same block as the load |
Sanjay Patel | 674d2c2 | 2017-08-29 14:07:48 +0000 | [diff] [blame] | 5008 | ExtFedByLoad->moveAfter(LI); |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5009 | // CGP does not check if the zext would be speculatively executed when moved |
| 5010 | // to the same basic block as the load. Preserving its original location |
| 5011 | // would pessimize the debugging experience, as well as negatively impact |
| 5012 | // the quality of sample pgo. We don't want to use "line 0" as that has a |
| 5013 | // size cost in the line-table section and logically the zext can be seen as |
| 5014 | // part of the load. Therefore we conservatively reuse the same debug |
| 5015 | // location for the load and the zext. |
| 5016 | ExtFedByLoad->setDebugLoc(LI->getDebugLoc()); |
| 5017 | ++NumExtsMoved; |
| 5018 | Inst = ExtFedByLoad; |
| 5019 | return true; |
| 5020 | } |
| 5021 | |
| 5022 | // Continue promoting SExts if known as considerable depending on targets. |
| 5023 | if (ATPConsiderable && |
| 5024 | performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader, |
| 5025 | HasPromoted, TPT, SpeculativelyMovedExts)) |
| 5026 | return true; |
| 5027 | |
| 5028 | TPT.rollback(LastKnownGood); |
| 5029 | return false; |
| 5030 | } |
| 5031 | |
| 5032 | // Perform address type promotion if doing so is profitable. |
| 5033 | // If AllowPromotionWithoutCommonHeader == false, we should find other sext |
| 5034 | // instructions that sign extended the same initial value. However, if |
| 5035 | // AllowPromotionWithoutCommonHeader == true, we expect promoting the |
| 5036 | // extension is just profitable. |
| 5037 | bool CodeGenPrepare::performAddressTypePromotion( |
| 5038 | Instruction *&Inst, bool AllowPromotionWithoutCommonHeader, |
| 5039 | bool HasPromoted, TypePromotionTransaction &TPT, |
| 5040 | SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) { |
| 5041 | bool Promoted = false; |
| 5042 | SmallPtrSet<Instruction *, 1> UnhandledExts; |
| 5043 | bool AllSeenFirst = true; |
| 5044 | for (auto I : SpeculativelyMovedExts) { |
| 5045 | Value *HeadOfChain = I->getOperand(0); |
| 5046 | DenseMap<Value *, Instruction *>::iterator AlreadySeen = |
| 5047 | SeenChainsForSExt.find(HeadOfChain); |
| 5048 | // If there is an unhandled SExt which has the same header, try to promote |
| 5049 | // it as well. |
| 5050 | if (AlreadySeen != SeenChainsForSExt.end()) { |
| 5051 | if (AlreadySeen->second != nullptr) |
| 5052 | UnhandledExts.insert(AlreadySeen->second); |
| 5053 | AllSeenFirst = false; |
| 5054 | } |
| 5055 | } |
| 5056 | |
| 5057 | if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader && |
| 5058 | SpeculativelyMovedExts.size() == 1)) { |
| 5059 | TPT.commit(); |
| 5060 | if (HasPromoted) |
| 5061 | Promoted = true; |
| 5062 | for (auto I : SpeculativelyMovedExts) { |
| 5063 | Value *HeadOfChain = I->getOperand(0); |
| 5064 | SeenChainsForSExt[HeadOfChain] = nullptr; |
| 5065 | ValToSExtendedUses[HeadOfChain].push_back(I); |
| 5066 | } |
| 5067 | // Update Inst as promotion happen. |
| 5068 | Inst = SpeculativelyMovedExts.pop_back_val(); |
| 5069 | } else { |
| 5070 | // This is the first chain visited from the header, keep the current chain |
| 5071 | // as unhandled. Defer to promote this until we encounter another SExt |
| 5072 | // chain derived from the same header. |
| 5073 | for (auto I : SpeculativelyMovedExts) { |
| 5074 | Value *HeadOfChain = I->getOperand(0); |
| 5075 | SeenChainsForSExt[HeadOfChain] = Inst; |
| 5076 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 5077 | return false; |
Quentin Colombet | fc2201e | 2014-12-17 01:36:17 +0000 | [diff] [blame] | 5078 | } |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 5079 | |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 5080 | if (!AllSeenFirst && !UnhandledExts.empty()) |
| 5081 | for (auto VisitedSExt : UnhandledExts) { |
| 5082 | if (RemovedInsts.count(VisitedSExt)) |
| 5083 | continue; |
| 5084 | TypePromotionTransaction TPT(RemovedInsts); |
| 5085 | SmallVector<Instruction *, 1> Exts; |
| 5086 | SmallVector<Instruction *, 2> Chains; |
| 5087 | Exts.push_back(VisitedSExt); |
| 5088 | bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains); |
| 5089 | TPT.commit(); |
| 5090 | if (HasPromoted) |
| 5091 | Promoted = true; |
| 5092 | for (auto I : Chains) { |
| 5093 | Value *HeadOfChain = I->getOperand(0); |
| 5094 | // Mark this as handled. |
| 5095 | SeenChainsForSExt[HeadOfChain] = nullptr; |
| 5096 | ValToSExtendedUses[HeadOfChain].push_back(I); |
| 5097 | } |
| 5098 | } |
| 5099 | return Promoted; |
Dan Gohman | 99429a0 | 2009-10-16 20:59:35 +0000 | [diff] [blame] | 5100 | } |
| 5101 | |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5102 | bool CodeGenPrepare::optimizeExtUses(Instruction *I) { |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5103 | BasicBlock *DefBB = I->getParent(); |
| 5104 | |
Bob Wilson | ff714f9 | 2010-09-21 21:44:14 +0000 | [diff] [blame] | 5105 | // 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] | 5106 | // other uses of the source with result of extension. |
| 5107 | Value *Src = I->getOperand(0); |
| 5108 | if (Src->hasOneUse()) |
| 5109 | return false; |
| 5110 | |
Evan Cheng | 2011df4 | 2007-12-13 07:50:36 +0000 | [diff] [blame] | 5111 | // Only do this xform if truncating is free. |
Gabor Greif | aa26172 | 2008-02-26 19:13:21 +0000 | [diff] [blame] | 5112 | if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType())) |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 5113 | return false; |
| 5114 | |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 5115 | // 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] | 5116 | // this block. |
| 5117 | if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent()) |
Evan Cheng | 7bc8942 | 2007-12-12 00:51:06 +0000 | [diff] [blame] | 5118 | return false; |
| 5119 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5120 | bool DefIsLiveOut = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5121 | for (User *U : I->users()) { |
| 5122 | Instruction *UI = cast<Instruction>(U); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5123 | |
| 5124 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5125 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5126 | if (UserBB == DefBB) continue; |
| 5127 | DefIsLiveOut = true; |
| 5128 | break; |
| 5129 | } |
| 5130 | if (!DefIsLiveOut) |
| 5131 | return false; |
| 5132 | |
Jim Grosbach | 0f38c1e | 2013-04-15 17:40:48 +0000 | [diff] [blame] | 5133 | // Make sure none of the uses are PHI nodes. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5134 | for (User *U : Src->users()) { |
| 5135 | Instruction *UI = cast<Instruction>(U); |
| 5136 | BasicBlock *UserBB = UI->getParent(); |
Evan Cheng | 37c36ed | 2007-12-13 03:32:53 +0000 | [diff] [blame] | 5137 | if (UserBB == DefBB) continue; |
| 5138 | // Be conservative. We don't want this xform to end up introducing |
| 5139 | // reloads just before load / store instructions. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5140 | if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI)) |
Evan Cheng | 63d33cf | 2007-12-12 02:53:41 +0000 | [diff] [blame] | 5141 | return false; |
| 5142 | } |
| 5143 | |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5144 | // InsertedTruncs - Only insert one trunc in each block once. |
| 5145 | DenseMap<BasicBlock*, Instruction*> InsertedTruncs; |
| 5146 | |
| 5147 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5148 | for (Use &U : Src->uses()) { |
| 5149 | Instruction *User = cast<Instruction>(U.getUser()); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5150 | |
| 5151 | // Figure out which BB this ext is used in. |
| 5152 | BasicBlock *UserBB = User->getParent(); |
| 5153 | if (UserBB == DefBB) continue; |
| 5154 | |
| 5155 | // Both src and def are live in this block. Rewrite the use. |
| 5156 | Instruction *&InsertedTrunc = InsertedTruncs[UserBB]; |
| 5157 | |
| 5158 | if (!InsertedTrunc) { |
Bill Wendling | 8ddfc09 | 2011-08-16 20:45:24 +0000 | [diff] [blame] | 5159 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5160 | assert(InsertPt != UserBB->end()); |
| 5161 | InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt); |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 5162 | InsertedInsts.insert(InsertedTrunc); |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5163 | } |
| 5164 | |
| 5165 | // 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] | 5166 | U = InsertedTrunc; |
Cameron Zwarich | ced753f | 2011-01-05 17:27:27 +0000 | [diff] [blame] | 5167 | ++NumExtUses; |
Evan Cheng | d3d8017 | 2007-12-05 23:58:20 +0000 | [diff] [blame] | 5168 | MadeChange = true; |
| 5169 | } |
| 5170 | |
| 5171 | return MadeChange; |
| 5172 | } |
| 5173 | |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5174 | // Find loads whose uses only use some of the loaded value's bits. Add an "and" |
| 5175 | // just after the load if the target can fold this into one extload instruction, |
| 5176 | // with the hope of eliminating some of the other later "and" instructions using |
| 5177 | // the loaded value. "and"s that are made trivially redundant by the insertion |
| 5178 | // of the new "and" are removed by this function, while others (e.g. those whose |
| 5179 | // path from the load goes through a phi) are left for isel to potentially |
| 5180 | // remove. |
| 5181 | // |
| 5182 | // For example: |
| 5183 | // |
| 5184 | // b0: |
| 5185 | // x = load i32 |
| 5186 | // ... |
| 5187 | // b1: |
| 5188 | // y = and x, 0xff |
| 5189 | // z = use y |
| 5190 | // |
| 5191 | // becomes: |
| 5192 | // |
| 5193 | // b0: |
| 5194 | // x = load i32 |
| 5195 | // x' = and x, 0xff |
| 5196 | // ... |
| 5197 | // b1: |
| 5198 | // z = use x' |
| 5199 | // |
| 5200 | // whereas: |
| 5201 | // |
| 5202 | // b0: |
| 5203 | // x1 = load i32 |
| 5204 | // ... |
| 5205 | // b1: |
| 5206 | // x2 = load i32 |
| 5207 | // ... |
| 5208 | // b2: |
| 5209 | // x = phi x1, x2 |
| 5210 | // y = and x, 0xff |
| 5211 | // |
| 5212 | // becomes (after a call to optimizeLoadExt for each load): |
| 5213 | // |
| 5214 | // b0: |
| 5215 | // x1 = load i32 |
| 5216 | // x1' = and x1, 0xff |
| 5217 | // ... |
| 5218 | // b1: |
| 5219 | // x2 = load i32 |
| 5220 | // x2' = and x2, 0xff |
| 5221 | // ... |
| 5222 | // b2: |
| 5223 | // x = phi x1', x2' |
| 5224 | // y = and x, 0xff |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5225 | bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5226 | if (!Load->isSimple() || |
| 5227 | !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy())) |
| 5228 | return false; |
| 5229 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5230 | // Skip loads we've already transformed. |
| 5231 | if (Load->hasOneUse() && |
| 5232 | InsertedInsts.count(cast<Instruction>(*Load->user_begin()))) |
| 5233 | return false; |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5234 | |
| 5235 | // Look at all uses of Load, looking through phis, to determine how many bits |
| 5236 | // of the loaded value are needed. |
| 5237 | SmallVector<Instruction *, 8> WorkList; |
| 5238 | SmallPtrSet<Instruction *, 16> Visited; |
| 5239 | SmallVector<Instruction *, 8> AndsToMaybeRemove; |
| 5240 | for (auto *U : Load->users()) |
| 5241 | WorkList.push_back(cast<Instruction>(U)); |
| 5242 | |
| 5243 | EVT LoadResultVT = TLI->getValueType(*DL, Load->getType()); |
| 5244 | unsigned BitWidth = LoadResultVT.getSizeInBits(); |
| 5245 | APInt DemandBits(BitWidth, 0); |
| 5246 | APInt WidestAndBits(BitWidth, 0); |
| 5247 | |
| 5248 | while (!WorkList.empty()) { |
| 5249 | Instruction *I = WorkList.back(); |
| 5250 | WorkList.pop_back(); |
| 5251 | |
| 5252 | // Break use-def graph loops. |
| 5253 | if (!Visited.insert(I).second) |
| 5254 | continue; |
| 5255 | |
| 5256 | // For a PHI node, push all of its users. |
| 5257 | if (auto *Phi = dyn_cast<PHINode>(I)) { |
| 5258 | for (auto *U : Phi->users()) |
| 5259 | WorkList.push_back(cast<Instruction>(U)); |
| 5260 | continue; |
| 5261 | } |
| 5262 | |
| 5263 | switch (I->getOpcode()) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5264 | case Instruction::And: { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5265 | auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 5266 | if (!AndC) |
| 5267 | return false; |
| 5268 | APInt AndBits = AndC->getValue(); |
| 5269 | DemandBits |= AndBits; |
| 5270 | // Keep track of the widest and mask we see. |
| 5271 | if (AndBits.ugt(WidestAndBits)) |
| 5272 | WidestAndBits = AndBits; |
| 5273 | if (AndBits == WidestAndBits && I->getOperand(0) == Load) |
| 5274 | AndsToMaybeRemove.push_back(I); |
| 5275 | break; |
| 5276 | } |
| 5277 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5278 | case Instruction::Shl: { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5279 | auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1)); |
| 5280 | if (!ShlC) |
| 5281 | return false; |
| 5282 | uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1); |
Craig Topper | fc947bc | 2017-04-18 17:14:21 +0000 | [diff] [blame] | 5283 | DemandBits.setLowBits(BitWidth - ShiftAmt); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5284 | break; |
| 5285 | } |
| 5286 | |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5287 | case Instruction::Trunc: { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5288 | EVT TruncVT = TLI->getValueType(*DL, I->getType()); |
| 5289 | unsigned TruncBitWidth = TruncVT.getSizeInBits(); |
Craig Topper | fc947bc | 2017-04-18 17:14:21 +0000 | [diff] [blame] | 5290 | DemandBits.setLowBits(TruncBitWidth); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5291 | break; |
| 5292 | } |
| 5293 | |
| 5294 | default: |
| 5295 | return false; |
| 5296 | } |
| 5297 | } |
| 5298 | |
| 5299 | uint32_t ActiveBits = DemandBits.getActiveBits(); |
| 5300 | // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the |
| 5301 | // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example, |
| 5302 | // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but |
| 5303 | // (and (load x) 1) is not matched as a single instruction, rather as a LDR |
| 5304 | // followed by an AND. |
| 5305 | // TODO: Look into removing this restriction by fixing backends to either |
| 5306 | // return false for isLoadExtLegal for i1 or have them select this pattern to |
| 5307 | // a single instruction. |
| 5308 | // |
| 5309 | // Also avoid hoisting if we didn't see any ands with the exact DemandBits |
| 5310 | // 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] | 5311 | if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) || |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5312 | WidestAndBits != DemandBits) |
| 5313 | return false; |
| 5314 | |
| 5315 | LLVMContext &Ctx = Load->getType()->getContext(); |
| 5316 | Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits); |
| 5317 | EVT TruncVT = TLI->getValueType(*DL, TruncTy); |
| 5318 | |
| 5319 | // Reject cases that won't be matched as extloads. |
| 5320 | if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() || |
| 5321 | !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT)) |
| 5322 | return false; |
| 5323 | |
| 5324 | IRBuilder<> Builder(Load->getNextNode()); |
| 5325 | auto *NewAnd = dyn_cast<Instruction>( |
| 5326 | Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits))); |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 5327 | // Mark this instruction as "inserted by CGP", so that other |
| 5328 | // optimizations don't touch it. |
| 5329 | InsertedInsts.insert(NewAnd); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 5330 | |
| 5331 | // Replace all uses of load with new and (except for the use of load in the |
| 5332 | // new and itself). |
| 5333 | Load->replaceAllUsesWith(NewAnd); |
| 5334 | NewAnd->setOperand(0, Load); |
| 5335 | |
| 5336 | // Remove any and instructions that are now redundant. |
| 5337 | for (auto *And : AndsToMaybeRemove) |
| 5338 | // Check that the and mask is the same as the one we decided to put on the |
| 5339 | // new and. |
| 5340 | if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) { |
| 5341 | And->replaceAllUsesWith(NewAnd); |
| 5342 | if (&*CurInstIterator == And) |
| 5343 | CurInstIterator = std::next(And->getIterator()); |
| 5344 | And->eraseFromParent(); |
| 5345 | ++NumAndUses; |
| 5346 | } |
| 5347 | |
| 5348 | ++NumAndsAdded; |
| 5349 | return true; |
| 5350 | } |
| 5351 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5352 | /// Check if V (an operand of a select instruction) is an expensive instruction |
| 5353 | /// that is only used once. |
| 5354 | static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) { |
| 5355 | auto *I = dyn_cast<Instruction>(V); |
| 5356 | // If it's safe to speculatively execute, then it should not have side |
| 5357 | // effects; therefore, it's safe to sink and possibly *not* execute. |
Rafael Espindola | 84921b9 | 2015-10-24 23:11:13 +0000 | [diff] [blame] | 5358 | return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) && |
| 5359 | TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5360 | } |
| 5361 | |
Sanjay Patel | 4ac6b11 | 2015-09-21 22:47:23 +0000 | [diff] [blame] | 5362 | /// Returns true if a SelectInst should be turned into an explicit branch. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5363 | static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI, |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5364 | const TargetLowering *TLI, |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5365 | SelectInst *SI) { |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5366 | // If even a predictable select is cheap, then a branch can't be cheaper. |
| 5367 | if (!TLI->isPredictableSelectExpensive()) |
| 5368 | return false; |
| 5369 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5370 | // FIXME: This should use the same heuristics as IfConversion to determine |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5371 | // whether a select is better represented as a branch. |
| 5372 | |
| 5373 | // If metadata tells us that the select condition is obviously predictable, |
| 5374 | // then we want to replace the select with a branch. |
| 5375 | uint64_t TrueWeight, FalseWeight; |
| 5376 | if (SI->extractProfMetadata(TrueWeight, FalseWeight)) { |
| 5377 | uint64_t Max = std::max(TrueWeight, FalseWeight); |
| 5378 | uint64_t Sum = TrueWeight + FalseWeight; |
Sanjay Patel | c7b91e6 | 2016-05-09 17:31:55 +0000 | [diff] [blame] | 5379 | if (Sum != 0) { |
| 5380 | auto Probability = BranchProbability::getBranchProbability(Max, Sum); |
| 5381 | if (Probability > TLI->getPredictableBranchThreshold()) |
| 5382 | return true; |
| 5383 | } |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5384 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5385 | |
| 5386 | CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); |
| 5387 | |
Sanjay Patel | 4e65276 | 2015-09-28 22:14:51 +0000 | [diff] [blame] | 5388 | // If a branch is predictable, an out-of-order CPU can avoid blocking on its |
| 5389 | // comparison condition. If the compare has more than one use, there's |
| 5390 | // 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] | 5391 | if (!Cmp || !Cmp->hasOneUse()) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5392 | return false; |
| 5393 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5394 | // If either operand of the select is expensive and only needed on one side |
| 5395 | // of the select, we should form a branch. |
| 5396 | if (sinkSelectOperand(TTI, SI->getTrueValue()) || |
| 5397 | sinkSelectOperand(TTI, SI->getFalseValue())) |
| 5398 | return true; |
| 5399 | |
| 5400 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5401 | } |
| 5402 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5403 | /// If \p isTrue is true, return the true value of \p SI, otherwise return |
| 5404 | /// false value of \p SI. If the true/false value of \p SI is defined by any |
| 5405 | /// select instructions in \p Selects, look through the defining select |
| 5406 | /// instruction until the true/false value is not defined in \p Selects. |
| 5407 | static Value *getTrueOrFalseValue( |
| 5408 | SelectInst *SI, bool isTrue, |
| 5409 | const SmallPtrSet<const Instruction *, 2> &Selects) { |
| 5410 | Value *V; |
| 5411 | |
| 5412 | for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI); |
| 5413 | DefSI = dyn_cast<SelectInst>(V)) { |
Dehao Chen | c32d712 | 2016-09-12 20:29:54 +0000 | [diff] [blame] | 5414 | assert(DefSI->getCondition() == SI->getCondition() && |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5415 | "The condition of DefSI does not match with SI"); |
| 5416 | V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue()); |
| 5417 | } |
| 5418 | return V; |
| 5419 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5420 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5421 | /// If we have a SelectInst that will likely profit from branch prediction, |
| 5422 | /// turn it into a branch. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5423 | bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) { |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5424 | // Find all consecutive select instructions that share the same condition. |
| 5425 | SmallVector<SelectInst *, 2> ASI; |
| 5426 | ASI.push_back(SI); |
| 5427 | for (BasicBlock::iterator It = ++BasicBlock::iterator(SI); |
| 5428 | It != SI->getParent()->end(); ++It) { |
| 5429 | SelectInst *I = dyn_cast<SelectInst>(&*It); |
| 5430 | if (I && SI->getCondition() == I->getCondition()) { |
| 5431 | ASI.push_back(I); |
| 5432 | } else { |
| 5433 | break; |
| 5434 | } |
| 5435 | } |
| 5436 | |
| 5437 | SelectInst *LastSI = ASI.back(); |
| 5438 | // Increment the current iterator to skip all the rest of select instructions |
| 5439 | // because they will be either "not lowered" or "all lowered" to branch. |
| 5440 | CurInstIterator = std::next(LastSI->getIterator()); |
| 5441 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5442 | bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1); |
| 5443 | |
| 5444 | // Can we convert the 'select' to CF ? |
Sanjay Patel | a31b0c0 | 2016-04-26 00:47:39 +0000 | [diff] [blame] | 5445 | if (DisableSelectToBranch || OptSize || !TLI || VectorCond || |
| 5446 | SI->getMetadata(LLVMContext::MD_unpredictable)) |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5447 | return false; |
| 5448 | |
Nadav Rotem | 9d83202 | 2012-09-02 12:10:19 +0000 | [diff] [blame] | 5449 | TargetLowering::SelectSupportKind SelectKind; |
| 5450 | if (VectorCond) |
| 5451 | SelectKind = TargetLowering::VectorMaskSelect; |
| 5452 | else if (SI->getType()->isVectorTy()) |
| 5453 | SelectKind = TargetLowering::ScalarCondVectorVal; |
| 5454 | else |
| 5455 | SelectKind = TargetLowering::ScalarValSelect; |
| 5456 | |
Sanjay Patel | d66607b | 2016-04-26 17:11:17 +0000 | [diff] [blame] | 5457 | if (TLI->isSelectSupported(SelectKind) && |
| 5458 | !isFormingBranchFromSelectProfitable(TTI, TLI, SI)) |
| 5459 | return false; |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5460 | |
| 5461 | ModifiedDT = true; |
| 5462 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5463 | // Transform a sequence like this: |
| 5464 | // start: |
| 5465 | // %cmp = cmp uge i32 %a, %b |
| 5466 | // %sel = select i1 %cmp, i32 %c, i32 %d |
| 5467 | // |
| 5468 | // Into: |
| 5469 | // start: |
| 5470 | // %cmp = cmp uge i32 %a, %b |
| 5471 | // br i1 %cmp, label %select.true, label %select.false |
| 5472 | // select.true: |
| 5473 | // br label %select.end |
| 5474 | // select.false: |
| 5475 | // br label %select.end |
| 5476 | // select.end: |
| 5477 | // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ] |
| 5478 | // |
| 5479 | // In addition, we may sink instructions that produce %c or %d from |
| 5480 | // the entry block into the destination(s) of the new branch. |
| 5481 | // If the true or false blocks do not contain a sunken instruction, that |
| 5482 | // block and its branch may be optimized away. In that case, one side of the |
| 5483 | // first branch will point directly to select.end, and the corresponding PHI |
| 5484 | // predecessor block will be the start block. |
| 5485 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5486 | // First, we split the block containing the select into 2 blocks. |
| 5487 | BasicBlock *StartBlock = SI->getParent(); |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5488 | BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI)); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5489 | BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end"); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5490 | |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5491 | // Delete the unconditional branch that was just created by the split. |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5492 | StartBlock->getTerminator()->eraseFromParent(); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5493 | |
| 5494 | // These are the new basic blocks for the conditional branch. |
| 5495 | // At least one will become an actual new basic block. |
| 5496 | BasicBlock *TrueBlock = nullptr; |
| 5497 | BasicBlock *FalseBlock = nullptr; |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5498 | BranchInst *TrueBranch = nullptr; |
| 5499 | BranchInst *FalseBranch = nullptr; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5500 | |
| 5501 | // Sink expensive instructions into the conditional blocks to avoid executing |
| 5502 | // them speculatively. |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5503 | for (SelectInst *SI : ASI) { |
| 5504 | if (sinkSelectOperand(TTI, SI->getTrueValue())) { |
| 5505 | if (TrueBlock == nullptr) { |
| 5506 | TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink", |
| 5507 | EndBlock->getParent(), EndBlock); |
| 5508 | TrueBranch = BranchInst::Create(EndBlock, TrueBlock); |
| 5509 | } |
| 5510 | auto *TrueInst = cast<Instruction>(SI->getTrueValue()); |
| 5511 | TrueInst->moveBefore(TrueBranch); |
| 5512 | } |
| 5513 | if (sinkSelectOperand(TTI, SI->getFalseValue())) { |
| 5514 | if (FalseBlock == nullptr) { |
| 5515 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink", |
| 5516 | EndBlock->getParent(), EndBlock); |
| 5517 | FalseBranch = BranchInst::Create(EndBlock, FalseBlock); |
| 5518 | } |
| 5519 | auto *FalseInst = cast<Instruction>(SI->getFalseValue()); |
| 5520 | FalseInst->moveBefore(FalseBranch); |
| 5521 | } |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5522 | } |
| 5523 | |
| 5524 | // If there was nothing to sink, then arbitrarily choose the 'false' side |
| 5525 | // for a new input value to the PHI. |
| 5526 | if (TrueBlock == FalseBlock) { |
| 5527 | assert(TrueBlock == nullptr && |
| 5528 | "Unexpected basic block transform while optimizing select"); |
| 5529 | |
| 5530 | FalseBlock = BasicBlock::Create(SI->getContext(), "select.false", |
| 5531 | EndBlock->getParent(), EndBlock); |
| 5532 | BranchInst::Create(EndBlock, FalseBlock); |
| 5533 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5534 | |
| 5535 | // Insert the real conditional branch based on the original condition. |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5536 | // If we did not create a new block for one of the 'true' or 'false' paths |
| 5537 | // of the condition, it means that side of the branch goes to the end block |
| 5538 | // directly and the path originates from the start block from the point of |
| 5539 | // view of the new PHI. |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5540 | BasicBlock *TT, *FT; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5541 | if (TrueBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5542 | TT = EndBlock; |
| 5543 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5544 | TrueBlock = StartBlock; |
| 5545 | } else if (FalseBlock == nullptr) { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5546 | TT = TrueBlock; |
| 5547 | FT = EndBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5548 | FalseBlock = StartBlock; |
| 5549 | } else { |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5550 | TT = TrueBlock; |
| 5551 | FT = FalseBlock; |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5552 | } |
Xinliang David Li | 241e6c7 | 2016-09-03 21:26:36 +0000 | [diff] [blame] | 5553 | IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5554 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5555 | SmallPtrSet<const Instruction *, 2> INS; |
| 5556 | INS.insert(ASI.begin(), ASI.end()); |
| 5557 | // Use reverse iterator because later select may use the value of the |
| 5558 | // earlier select, and we need to propagate value through earlier select |
| 5559 | // to get the PHI operand. |
| 5560 | for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) { |
| 5561 | SelectInst *SI = *It; |
| 5562 | // The select itself is replaced with a PHI Node. |
| 5563 | PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front()); |
| 5564 | PN->takeName(SI); |
| 5565 | PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock); |
| 5566 | PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock); |
Sanjay Patel | 69a50a1 | 2015-10-19 21:59:12 +0000 | [diff] [blame] | 5567 | |
Dehao Chen | 9bbb941 | 2016-09-12 20:23:28 +0000 | [diff] [blame] | 5568 | SI->replaceAllUsesWith(PN); |
| 5569 | SI->eraseFromParent(); |
| 5570 | INS.erase(SI); |
| 5571 | ++NumSelectsExpanded; |
| 5572 | } |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5573 | |
| 5574 | // Instruct OptimizeBlock to skip to the next block. |
| 5575 | CurInstIterator = StartBlock->end(); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 5576 | return true; |
| 5577 | } |
| 5578 | |
Benjamin Kramer | 573ff36 | 2014-03-01 17:24:40 +0000 | [diff] [blame] | 5579 | static bool isBroadcastShuffle(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5580 | SmallVector<int, 16> Mask(SVI->getShuffleMask()); |
| 5581 | int SplatElem = -1; |
| 5582 | for (unsigned i = 0; i < Mask.size(); ++i) { |
| 5583 | if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem) |
| 5584 | return false; |
| 5585 | SplatElem = Mask[i]; |
| 5586 | } |
| 5587 | |
| 5588 | return true; |
| 5589 | } |
| 5590 | |
| 5591 | /// Some targets have expensive vector shifts if the lanes aren't all the same |
| 5592 | /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases |
| 5593 | /// it's often worth sinking a shufflevector splat down to its use so that |
| 5594 | /// codegen can spot all lanes are identical. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 5595 | bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) { |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5596 | BasicBlock *DefBB = SVI->getParent(); |
| 5597 | |
| 5598 | // Only do this xform if variable vector shifts are particularly expensive. |
| 5599 | if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType())) |
| 5600 | return false; |
| 5601 | |
| 5602 | // We only expect better codegen by sinking a shuffle if we can recognise a |
| 5603 | // constant splat. |
| 5604 | if (!isBroadcastShuffle(SVI)) |
| 5605 | return false; |
| 5606 | |
| 5607 | // InsertedShuffles - Only insert a shuffle in each block once. |
| 5608 | DenseMap<BasicBlock*, Instruction*> InsertedShuffles; |
| 5609 | |
| 5610 | bool MadeChange = false; |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5611 | for (User *U : SVI->users()) { |
| 5612 | Instruction *UI = cast<Instruction>(U); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5613 | |
| 5614 | // Figure out which BB this ext is used in. |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5615 | BasicBlock *UserBB = UI->getParent(); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5616 | if (UserBB == DefBB) continue; |
| 5617 | |
| 5618 | // 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] | 5619 | if (!UI->isShift()) continue; |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5620 | |
| 5621 | // Everything checks out, sink the shuffle if the user's block doesn't |
| 5622 | // already have a copy. |
| 5623 | Instruction *&InsertedShuffle = InsertedShuffles[UserBB]; |
| 5624 | |
| 5625 | if (!InsertedShuffle) { |
| 5626 | BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt(); |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 5627 | assert(InsertPt != UserBB->end()); |
| 5628 | InsertedShuffle = |
| 5629 | new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1), |
| 5630 | SVI->getOperand(2), "", &*InsertPt); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5631 | } |
| 5632 | |
Chandler Carruth | cdf4788 | 2014-03-09 03:16:01 +0000 | [diff] [blame] | 5633 | UI->replaceUsesOfWith(SVI, InsertedShuffle); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 5634 | MadeChange = true; |
| 5635 | } |
| 5636 | |
| 5637 | // If we removed all uses, nuke the shuffle. |
| 5638 | if (SVI->use_empty()) { |
| 5639 | SVI->eraseFromParent(); |
| 5640 | MadeChange = true; |
| 5641 | } |
| 5642 | |
| 5643 | return MadeChange; |
| 5644 | } |
| 5645 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5646 | bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) { |
| 5647 | if (!TLI || !DL) |
| 5648 | return false; |
| 5649 | |
| 5650 | Value *Cond = SI->getCondition(); |
| 5651 | Type *OldType = Cond->getType(); |
| 5652 | LLVMContext &Context = Cond->getContext(); |
| 5653 | MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType)); |
| 5654 | unsigned RegWidth = RegType.getSizeInBits(); |
| 5655 | |
| 5656 | if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth()) |
| 5657 | return false; |
| 5658 | |
| 5659 | // If the register width is greater than the type width, expand the condition |
| 5660 | // of the switch instruction and each case constant to the width of the |
| 5661 | // register. By widening the type of the switch condition, subsequent |
| 5662 | // comparisons (for case comparisons) will not need to be extended to the |
| 5663 | // preferred register width, so we will potentially eliminate N-1 extends, |
| 5664 | // where N is the number of cases in the switch. |
| 5665 | auto *NewType = Type::getIntNTy(Context, RegWidth); |
| 5666 | |
| 5667 | // Zero-extend the switch condition and case constants unless the switch |
| 5668 | // condition is a function argument that is already being sign-extended. |
| 5669 | // In that case, we can avoid an unnecessary mask/extension by sign-extending |
| 5670 | // everything instead. |
| 5671 | Instruction::CastOps ExtType = Instruction::ZExt; |
| 5672 | if (auto *Arg = dyn_cast<Argument>(Cond)) |
| 5673 | if (Arg->hasSExtAttr()) |
| 5674 | ExtType = Instruction::SExt; |
| 5675 | |
| 5676 | auto *ExtInst = CastInst::Create(ExtType, Cond, NewType); |
| 5677 | ExtInst->insertBefore(SI); |
| 5678 | SI->setCondition(ExtInst); |
Chandler Carruth | 927d8e6 | 2017-04-12 07:27:28 +0000 | [diff] [blame] | 5679 | for (auto Case : SI->cases()) { |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 5680 | APInt NarrowConst = Case.getCaseValue()->getValue(); |
| 5681 | APInt WideConst = (ExtType == Instruction::ZExt) ? |
| 5682 | NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth); |
| 5683 | Case.setValue(ConstantInt::get(Context, WideConst)); |
| 5684 | } |
| 5685 | |
| 5686 | return true; |
| 5687 | } |
| 5688 | |
Zaara Syeda | 3a7578c | 2017-05-31 17:12:38 +0000 | [diff] [blame] | 5689 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5690 | namespace { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5691 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5692 | /// \brief Helper class to promote a scalar operation to a vector one. |
| 5693 | /// This class is used to move downward extractelement transition. |
| 5694 | /// E.g., |
| 5695 | /// a = vector_op <2 x i32> |
| 5696 | /// b = extractelement <2 x i32> a, i32 0 |
| 5697 | /// c = scalar_op b |
| 5698 | /// store c |
| 5699 | /// |
| 5700 | /// => |
| 5701 | /// a = vector_op <2 x i32> |
| 5702 | /// c = vector_op a (equivalent to scalar_op on the related lane) |
| 5703 | /// * d = extractelement <2 x i32> c, i32 0 |
| 5704 | /// * store d |
| 5705 | /// Assuming both extractelement and store can be combine, we get rid of the |
| 5706 | /// transition. |
| 5707 | class VectorPromoteHelper { |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5708 | /// DataLayout associated with the current module. |
| 5709 | const DataLayout &DL; |
| 5710 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5711 | /// Used to perform some checks on the legality of vector operations. |
| 5712 | const TargetLowering &TLI; |
| 5713 | |
| 5714 | /// Used to estimated the cost of the promoted chain. |
| 5715 | const TargetTransformInfo &TTI; |
| 5716 | |
| 5717 | /// The transition being moved downwards. |
| 5718 | Instruction *Transition; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5719 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5720 | /// The sequence of instructions to be promoted. |
| 5721 | SmallVector<Instruction *, 4> InstsToBePromoted; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5722 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5723 | /// Cost of combining a store and an extract. |
| 5724 | unsigned StoreExtractCombineCost; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5725 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5726 | /// Instruction that will be combined with the transition. |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5727 | Instruction *CombineInst = nullptr; |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5728 | |
| 5729 | /// \brief The instruction that represents the current end of the transition. |
| 5730 | /// Since we are faking the promotion until we reach the end of the chain |
| 5731 | /// of computation, we need a way to get the current end of the transition. |
| 5732 | Instruction *getEndOfTransition() const { |
| 5733 | if (InstsToBePromoted.empty()) |
| 5734 | return Transition; |
| 5735 | return InstsToBePromoted.back(); |
| 5736 | } |
| 5737 | |
| 5738 | /// \brief Return the index of the original value in the transition. |
| 5739 | /// E.g., for "extractelement <2 x i32> c, i32 1" the original value, |
| 5740 | /// c, is at index 0. |
| 5741 | unsigned getTransitionOriginalValueIdx() const { |
| 5742 | assert(isa<ExtractElementInst>(Transition) && |
| 5743 | "Other kind of transitions are not supported yet"); |
| 5744 | return 0; |
| 5745 | } |
| 5746 | |
| 5747 | /// \brief Return the index of the index in the transition. |
| 5748 | /// E.g., for "extractelement <2 x i32> c, i32 0" the index |
| 5749 | /// is at index 1. |
| 5750 | unsigned getTransitionIdx() const { |
| 5751 | assert(isa<ExtractElementInst>(Transition) && |
| 5752 | "Other kind of transitions are not supported yet"); |
| 5753 | return 1; |
| 5754 | } |
| 5755 | |
| 5756 | /// \brief Get the type of the transition. |
| 5757 | /// This is the type of the original value. |
| 5758 | /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the |
| 5759 | /// transition is <2 x i32>. |
| 5760 | Type *getTransitionType() const { |
| 5761 | return Transition->getOperand(getTransitionOriginalValueIdx())->getType(); |
| 5762 | } |
| 5763 | |
| 5764 | /// \brief Promote \p ToBePromoted by moving \p Def downward through. |
| 5765 | /// I.e., we have the following sequence: |
| 5766 | /// Def = Transition <ty1> a to <ty2> |
| 5767 | /// b = ToBePromoted <ty2> Def, ... |
| 5768 | /// => |
| 5769 | /// b = ToBePromoted <ty1> a, ... |
| 5770 | /// Def = Transition <ty1> ToBePromoted to <ty2> |
| 5771 | void promoteImpl(Instruction *ToBePromoted); |
| 5772 | |
| 5773 | /// \brief Check whether or not it is profitable to promote all the |
| 5774 | /// instructions enqueued to be promoted. |
| 5775 | bool isProfitableToPromote() { |
| 5776 | Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5777 | unsigned Index = isa<ConstantInt>(ValIdx) |
| 5778 | ? cast<ConstantInt>(ValIdx)->getZExtValue() |
| 5779 | : -1; |
| 5780 | Type *PromotedType = getTransitionType(); |
| 5781 | |
| 5782 | StoreInst *ST = cast<StoreInst>(CombineInst); |
| 5783 | unsigned AS = ST->getPointerAddressSpace(); |
| 5784 | unsigned Align = ST->getAlignment(); |
| 5785 | // Check if this store is supported. |
| 5786 | if (!TLI.allowsMisalignedMemoryAccesses( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5787 | TLI.getValueType(DL, ST->getValueOperand()->getType()), AS, |
| 5788 | Align)) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5789 | // If this is not supported, there is no way we can combine |
| 5790 | // the extract with the store. |
| 5791 | return false; |
| 5792 | } |
| 5793 | |
| 5794 | // The scalar chain of computation has to pay for the transition |
| 5795 | // scalar to vector. |
| 5796 | // The vector chain has to account for the combining cost. |
| 5797 | uint64_t ScalarCost = |
| 5798 | TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index); |
| 5799 | uint64_t VectorCost = StoreExtractCombineCost; |
| 5800 | for (const auto &Inst : InstsToBePromoted) { |
| 5801 | // Compute the cost. |
| 5802 | // By construction, all instructions being promoted are arithmetic ones. |
| 5803 | // Moreover, one argument is a constant that can be viewed as a splat |
| 5804 | // constant. |
| 5805 | Value *Arg0 = Inst->getOperand(0); |
| 5806 | bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) || |
| 5807 | isa<ConstantFP>(Arg0); |
| 5808 | TargetTransformInfo::OperandValueKind Arg0OVK = |
| 5809 | IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5810 | : TargetTransformInfo::OK_AnyValue; |
| 5811 | TargetTransformInfo::OperandValueKind Arg1OVK = |
| 5812 | !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue |
| 5813 | : TargetTransformInfo::OK_AnyValue; |
| 5814 | ScalarCost += TTI.getArithmeticInstrCost( |
| 5815 | Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK); |
| 5816 | VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType, |
| 5817 | Arg0OVK, Arg1OVK); |
| 5818 | } |
| 5819 | DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: " |
| 5820 | << ScalarCost << "\nVector: " << VectorCost << '\n'); |
| 5821 | return ScalarCost > VectorCost; |
| 5822 | } |
| 5823 | |
| 5824 | /// \brief Generate a constant vector with \p Val with the same |
| 5825 | /// number of elements as the transition. |
| 5826 | /// \p UseSplat defines whether or not \p Val should be replicated |
Benjamin Kramer | df005cb | 2015-08-08 18:27:36 +0000 | [diff] [blame] | 5827 | /// across the whole vector. |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5828 | /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>, |
| 5829 | /// otherwise we generate a vector with as many undef as possible: |
| 5830 | /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only |
| 5831 | /// used at the index of the extract. |
| 5832 | Value *getConstantVector(Constant *Val, bool UseSplat) const { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5833 | unsigned ExtractIdx = std::numeric_limits<unsigned>::max(); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5834 | if (!UseSplat) { |
| 5835 | // If we cannot determine where the constant must be, we have to |
| 5836 | // use a splat constant. |
| 5837 | Value *ValExtractIdx = Transition->getOperand(getTransitionIdx()); |
| 5838 | if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx)) |
| 5839 | ExtractIdx = CstVal->getSExtValue(); |
| 5840 | else |
| 5841 | UseSplat = true; |
| 5842 | } |
| 5843 | |
| 5844 | unsigned End = getTransitionType()->getVectorNumElements(); |
| 5845 | if (UseSplat) |
| 5846 | return ConstantVector::getSplat(End, Val); |
| 5847 | |
| 5848 | SmallVector<Constant *, 4> ConstVec; |
| 5849 | UndefValue *UndefVal = UndefValue::get(Val->getType()); |
| 5850 | for (unsigned Idx = 0; Idx != End; ++Idx) { |
| 5851 | if (Idx == ExtractIdx) |
| 5852 | ConstVec.push_back(Val); |
| 5853 | else |
| 5854 | ConstVec.push_back(UndefVal); |
| 5855 | } |
| 5856 | return ConstantVector::get(ConstVec); |
| 5857 | } |
| 5858 | |
| 5859 | /// \brief Check if promoting to a vector type an operand at \p OperandIdx |
| 5860 | /// in \p Use can trigger undefined behavior. |
| 5861 | static bool canCauseUndefinedBehavior(const Instruction *Use, |
| 5862 | unsigned OperandIdx) { |
| 5863 | // This is not safe to introduce undef when the operand is on |
| 5864 | // the right hand side of a division-like instruction. |
| 5865 | if (OperandIdx != 1) |
| 5866 | return false; |
| 5867 | switch (Use->getOpcode()) { |
| 5868 | default: |
| 5869 | return false; |
| 5870 | case Instruction::SDiv: |
| 5871 | case Instruction::UDiv: |
| 5872 | case Instruction::SRem: |
| 5873 | case Instruction::URem: |
| 5874 | return true; |
| 5875 | case Instruction::FDiv: |
| 5876 | case Instruction::FRem: |
| 5877 | return !Use->hasNoNaNs(); |
| 5878 | } |
| 5879 | llvm_unreachable(nullptr); |
| 5880 | } |
| 5881 | |
| 5882 | public: |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5883 | VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI, |
| 5884 | const TargetTransformInfo &TTI, Instruction *Transition, |
| 5885 | unsigned CombineCost) |
| 5886 | : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition), |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5887 | StoreExtractCombineCost(CombineCost) { |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5888 | assert(Transition && "Do not know how to promote null"); |
| 5889 | } |
| 5890 | |
| 5891 | /// \brief Check if we can promote \p ToBePromoted to \p Type. |
| 5892 | bool canPromote(const Instruction *ToBePromoted) const { |
| 5893 | // We could support CastInst too. |
| 5894 | return isa<BinaryOperator>(ToBePromoted); |
| 5895 | } |
| 5896 | |
| 5897 | /// \brief Check if it is profitable to promote \p ToBePromoted |
| 5898 | /// by moving downward the transition through. |
| 5899 | bool shouldPromote(const Instruction *ToBePromoted) const { |
| 5900 | // Promote only if all the operands can be statically expanded. |
| 5901 | // Indeed, we do not want to introduce any new kind of transitions. |
| 5902 | for (const Use &U : ToBePromoted->operands()) { |
| 5903 | const Value *Val = U.get(); |
| 5904 | if (Val == getEndOfTransition()) { |
| 5905 | // If the use is a division and the transition is on the rhs, |
| 5906 | // we cannot promote the operation, otherwise we may create a |
| 5907 | // division by zero. |
| 5908 | if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())) |
| 5909 | return false; |
| 5910 | continue; |
| 5911 | } |
| 5912 | if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) && |
| 5913 | !isa<ConstantFP>(Val)) |
| 5914 | return false; |
| 5915 | } |
| 5916 | // Check that the resulting operation is legal. |
| 5917 | int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode()); |
| 5918 | if (!ISDOpcode) |
| 5919 | return false; |
| 5920 | return StressStoreExtract || |
Ahmed Bougacha | 026600d | 2014-11-12 23:05:03 +0000 | [diff] [blame] | 5921 | TLI.isOperationLegalOrCustom( |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 5922 | ISDOpcode, TLI.getValueType(DL, getTransitionType(), true)); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5923 | } |
| 5924 | |
| 5925 | /// \brief Check whether or not \p Use can be combined |
| 5926 | /// with the transition. |
| 5927 | /// I.e., is it possible to do Use(Transition) => AnotherUse? |
| 5928 | bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); } |
| 5929 | |
| 5930 | /// \brief Record \p ToBePromoted as part of the chain to be promoted. |
| 5931 | void enqueueForPromotion(Instruction *ToBePromoted) { |
| 5932 | InstsToBePromoted.push_back(ToBePromoted); |
| 5933 | } |
| 5934 | |
| 5935 | /// \brief Set the instruction that will be combined with the transition. |
| 5936 | void recordCombineInstruction(Instruction *ToBeCombined) { |
| 5937 | assert(canCombine(ToBeCombined) && "Unsupported instruction to combine"); |
| 5938 | CombineInst = ToBeCombined; |
| 5939 | } |
| 5940 | |
| 5941 | /// \brief Promote all the instructions enqueued for promotion if it is |
| 5942 | /// is profitable. |
| 5943 | /// \return True if the promotion happened, false otherwise. |
| 5944 | bool promote() { |
| 5945 | // Check if there is something to promote. |
| 5946 | // Right now, if we do not have anything to combine with, |
| 5947 | // we assume the promotion is not profitable. |
| 5948 | if (InstsToBePromoted.empty() || !CombineInst) |
| 5949 | return false; |
| 5950 | |
| 5951 | // Check cost. |
| 5952 | if (!StressStoreExtract && !isProfitableToPromote()) |
| 5953 | return false; |
| 5954 | |
| 5955 | // Promote. |
| 5956 | for (auto &ToBePromoted : InstsToBePromoted) |
| 5957 | promoteImpl(ToBePromoted); |
| 5958 | InstsToBePromoted.clear(); |
| 5959 | return true; |
| 5960 | } |
| 5961 | }; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 5962 | |
| 5963 | } // end anonymous namespace |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 5964 | |
| 5965 | void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) { |
| 5966 | // At this point, we know that all the operands of ToBePromoted but Def |
| 5967 | // can be statically promoted. |
| 5968 | // For Def, we need to use its parameter in ToBePromoted: |
| 5969 | // b = ToBePromoted ty1 a |
| 5970 | // Def = Transition ty1 b to ty2 |
| 5971 | // Move the transition down. |
| 5972 | // 1. Replace all uses of the promoted operation by the transition. |
| 5973 | // = ... b => = ... Def. |
| 5974 | assert(ToBePromoted->getType() == Transition->getType() && |
| 5975 | "The type of the result of the transition does not match " |
| 5976 | "the final type"); |
| 5977 | ToBePromoted->replaceAllUsesWith(Transition); |
| 5978 | // 2. Update the type of the uses. |
| 5979 | // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def. |
| 5980 | Type *TransitionTy = getTransitionType(); |
| 5981 | ToBePromoted->mutateType(TransitionTy); |
| 5982 | // 3. Update all the operands of the promoted operation with promoted |
| 5983 | // operands. |
| 5984 | // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a. |
| 5985 | for (Use &U : ToBePromoted->operands()) { |
| 5986 | Value *Val = U.get(); |
| 5987 | Value *NewVal = nullptr; |
| 5988 | if (Val == Transition) |
| 5989 | NewVal = Transition->getOperand(getTransitionOriginalValueIdx()); |
| 5990 | else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) || |
| 5991 | isa<ConstantFP>(Val)) { |
| 5992 | // Use a splat constant if it is not safe to use undef. |
| 5993 | NewVal = getConstantVector( |
| 5994 | cast<Constant>(Val), |
| 5995 | isa<UndefValue>(Val) || |
| 5996 | canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo())); |
| 5997 | } else |
Craig Topper | d3c02f1 | 2015-01-05 10:15:49 +0000 | [diff] [blame] | 5998 | llvm_unreachable("Did you modified shouldPromote and forgot to update " |
| 5999 | "this?"); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6000 | ToBePromoted->setOperand(U.getOperandNo(), NewVal); |
| 6001 | } |
Sanjay Patel | 674d2c2 | 2017-08-29 14:07:48 +0000 | [diff] [blame] | 6002 | Transition->moveAfter(ToBePromoted); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6003 | Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted); |
| 6004 | } |
| 6005 | |
| 6006 | /// Some targets can do store(extractelement) with one instruction. |
| 6007 | /// Try to push the extractelement towards the stores when the target |
| 6008 | /// has this feature and this is profitable. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6009 | bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) { |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 6010 | unsigned CombineCost = std::numeric_limits<unsigned>::max(); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6011 | if (DisableStoreExtract || !TLI || |
| 6012 | (!StressStoreExtract && |
| 6013 | !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(), |
| 6014 | Inst->getOperand(1), CombineCost))) |
| 6015 | return false; |
| 6016 | |
| 6017 | // At this point we know that Inst is a vector to scalar transition. |
| 6018 | // Try to move it down the def-use chain, until: |
| 6019 | // - We can combine the transition with its single use |
| 6020 | // => we got rid of the transition. |
| 6021 | // - We escape the current basic block |
| 6022 | // => we would need to check that we are moving it at a cheaper place and |
| 6023 | // we do not do that for now. |
| 6024 | BasicBlock *Parent = Inst->getParent(); |
| 6025 | DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n'); |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6026 | VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6027 | // If the transition has more than one use, assume this is not going to be |
| 6028 | // beneficial. |
| 6029 | while (Inst->hasOneUse()) { |
| 6030 | Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin()); |
| 6031 | DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n'); |
| 6032 | |
| 6033 | if (ToBePromoted->getParent() != Parent) { |
| 6034 | DEBUG(dbgs() << "Instruction to promote is in a different block (" |
| 6035 | << ToBePromoted->getParent()->getName() |
| 6036 | << ") than the transition (" << Parent->getName() << ").\n"); |
| 6037 | return false; |
| 6038 | } |
| 6039 | |
| 6040 | if (VPH.canCombine(ToBePromoted)) { |
| 6041 | DEBUG(dbgs() << "Assume " << *Inst << '\n' |
| 6042 | << "will be combined with: " << *ToBePromoted << '\n'); |
| 6043 | VPH.recordCombineInstruction(ToBePromoted); |
| 6044 | bool Changed = VPH.promote(); |
| 6045 | NumStoreExtractExposed += Changed; |
| 6046 | return Changed; |
| 6047 | } |
| 6048 | |
| 6049 | DEBUG(dbgs() << "Try promoting.\n"); |
| 6050 | if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted)) |
| 6051 | return false; |
| 6052 | |
| 6053 | DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n"); |
| 6054 | |
| 6055 | VPH.enqueueForPromotion(ToBePromoted); |
| 6056 | Inst = ToBePromoted; |
| 6057 | } |
| 6058 | return false; |
| 6059 | } |
| 6060 | |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6061 | /// For the instruction sequence of store below, F and I values |
| 6062 | /// are bundled together as an i64 value before being stored into memory. |
| 6063 | /// Sometimes it is more efficent to generate separate stores for F and I, |
| 6064 | /// which can remove the bitwise instructions or sink them to colder places. |
| 6065 | /// |
| 6066 | /// (store (or (zext (bitcast F to i32) to i64), |
| 6067 | /// (shl (zext I to i64), 32)), addr) --> |
| 6068 | /// (store F, addr) and (store I, addr+4) |
| 6069 | /// |
| 6070 | /// Similarly, splitting for other merged store can also be beneficial, like: |
| 6071 | /// For pair of {i32, i32}, i64 store --> two i32 stores. |
| 6072 | /// For pair of {i32, i16}, i64 store --> two i32 stores. |
| 6073 | /// For pair of {i16, i16}, i32 store --> two i16 stores. |
| 6074 | /// For pair of {i16, i8}, i32 store --> two i16 stores. |
| 6075 | /// For pair of {i8, i8}, i16 store --> two i8 stores. |
| 6076 | /// |
| 6077 | /// We allow each target to determine specifically which kind of splitting is |
| 6078 | /// supported. |
| 6079 | /// |
| 6080 | /// The store patterns are commonly seen from the simple code snippet below |
| 6081 | /// if only std::make_pair(...) is sroa transformed before inlined into hoo. |
| 6082 | /// void goo(const std::pair<int, float> &); |
| 6083 | /// hoo() { |
| 6084 | /// ... |
| 6085 | /// goo(std::make_pair(tmp, ftmp)); |
| 6086 | /// ... |
| 6087 | /// } |
| 6088 | /// |
| 6089 | /// Although we already have similar splitting in DAG Combine, we duplicate |
| 6090 | /// it in CodeGenPrepare to catch the case in which pattern is across |
| 6091 | /// multiple BBs. The logic in DAG Combine is kept to catch case generated |
| 6092 | /// during code expansion. |
| 6093 | static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL, |
| 6094 | const TargetLowering &TLI) { |
| 6095 | // Handle simple but common cases only. |
| 6096 | Type *StoreType = SI.getValueOperand()->getType(); |
| 6097 | if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) || |
| 6098 | DL.getTypeSizeInBits(StoreType) == 0) |
| 6099 | return false; |
| 6100 | |
| 6101 | unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2; |
| 6102 | Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize); |
| 6103 | if (DL.getTypeStoreSizeInBits(SplitStoreType) != |
| 6104 | DL.getTypeSizeInBits(SplitStoreType)) |
| 6105 | return false; |
| 6106 | |
| 6107 | // Match the following patterns: |
| 6108 | // (store (or (zext LValue to i64), |
| 6109 | // (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 6110 | // or |
| 6111 | // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize) |
| 6112 | // (zext LValue to i64), |
| 6113 | // Expect both operands of OR and the first operand of SHL have only |
| 6114 | // one use. |
| 6115 | Value *LValue, *HValue; |
| 6116 | if (!match(SI.getValueOperand(), |
| 6117 | m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))), |
| 6118 | m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))), |
| 6119 | m_SpecificInt(HalfValBitSize)))))) |
| 6120 | return false; |
| 6121 | |
| 6122 | // Check LValue and HValue are int with size less or equal than 32. |
| 6123 | if (!LValue->getType()->isIntegerTy() || |
| 6124 | DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize || |
| 6125 | !HValue->getType()->isIntegerTy() || |
| 6126 | DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize) |
| 6127 | return false; |
| 6128 | |
| 6129 | // If LValue/HValue is a bitcast instruction, use the EVT before bitcast |
| 6130 | // as the input of target query. |
| 6131 | auto *LBC = dyn_cast<BitCastInst>(LValue); |
| 6132 | auto *HBC = dyn_cast<BitCastInst>(HValue); |
| 6133 | EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType()) |
| 6134 | : EVT::getEVT(LValue->getType()); |
| 6135 | EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType()) |
| 6136 | : EVT::getEVT(HValue->getType()); |
| 6137 | if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy)) |
| 6138 | return false; |
| 6139 | |
| 6140 | // Start to split store. |
| 6141 | IRBuilder<> Builder(SI.getContext()); |
| 6142 | Builder.SetInsertPoint(&SI); |
| 6143 | |
| 6144 | // If LValue/HValue is a bitcast in another BB, create a new one in current |
| 6145 | // BB so it may be merged with the splitted stores by dag combiner. |
| 6146 | if (LBC && LBC->getParent() != SI.getParent()) |
| 6147 | LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType()); |
| 6148 | if (HBC && HBC->getParent() != SI.getParent()) |
| 6149 | HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType()); |
| 6150 | |
| 6151 | auto CreateSplitStore = [&](Value *V, bool Upper) { |
| 6152 | V = Builder.CreateZExtOrBitCast(V, SplitStoreType); |
| 6153 | Value *Addr = Builder.CreateBitCast( |
| 6154 | SI.getOperand(1), |
| 6155 | SplitStoreType->getPointerTo(SI.getPointerAddressSpace())); |
| 6156 | if (Upper) |
| 6157 | Addr = Builder.CreateGEP( |
| 6158 | SplitStoreType, Addr, |
| 6159 | ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1)); |
| 6160 | Builder.CreateAlignedStore( |
| 6161 | V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment()); |
| 6162 | }; |
| 6163 | |
| 6164 | CreateSplitStore(LValue, false); |
| 6165 | CreateSplitStore(HValue, true); |
| 6166 | |
| 6167 | // Delete the old store. |
| 6168 | SI.eraseFromParent(); |
| 6169 | return true; |
| 6170 | } |
| 6171 | |
Hiroshi Yamauchi | 9364432 | 2017-09-11 17:52:08 +0000 | [diff] [blame] | 6172 | // Return true if the GEP has two operands, the first operand is of a sequential |
| 6173 | // type, and the second operand is a constant. |
| 6174 | static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) { |
| 6175 | gep_type_iterator I = gep_type_begin(*GEP); |
| 6176 | return GEP->getNumOperands() == 2 && |
| 6177 | I.isSequential() && |
| 6178 | isa<ConstantInt>(GEP->getOperand(1)); |
| 6179 | } |
| 6180 | |
| 6181 | // Try unmerging GEPs to reduce liveness interference (register pressure) across |
| 6182 | // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks, |
| 6183 | // reducing liveness interference across those edges benefits global register |
| 6184 | // allocation. Currently handles only certain cases. |
| 6185 | // |
| 6186 | // For example, unmerge %GEPI and %UGEPI as below. |
| 6187 | // |
| 6188 | // ---------- BEFORE ---------- |
| 6189 | // SrcBlock: |
| 6190 | // ... |
| 6191 | // %GEPIOp = ... |
| 6192 | // ... |
| 6193 | // %GEPI = gep %GEPIOp, Idx |
| 6194 | // ... |
| 6195 | // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ] |
| 6196 | // (* %GEPI is alive on the indirectbr edges due to other uses ahead) |
| 6197 | // (* %GEPIOp is alive on the indirectbr edges only because of it's used by |
| 6198 | // %UGEPI) |
| 6199 | // |
| 6200 | // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged) |
| 6201 | // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged) |
| 6202 | // ... |
| 6203 | // |
| 6204 | // DstBi: |
| 6205 | // ... |
| 6206 | // %UGEPI = gep %GEPIOp, UIdx |
| 6207 | // ... |
| 6208 | // --------------------------- |
| 6209 | // |
| 6210 | // ---------- AFTER ---------- |
| 6211 | // SrcBlock: |
| 6212 | // ... (same as above) |
| 6213 | // (* %GEPI is still alive on the indirectbr edges) |
| 6214 | // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the |
| 6215 | // unmerging) |
| 6216 | // ... |
| 6217 | // |
| 6218 | // DstBi: |
| 6219 | // ... |
| 6220 | // %UGEPI = gep %GEPI, (UIdx-Idx) |
| 6221 | // ... |
| 6222 | // --------------------------- |
| 6223 | // |
| 6224 | // The register pressure on the IndirectBr edges is reduced because %GEPIOp is |
| 6225 | // no longer alive on them. |
| 6226 | // |
| 6227 | // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging |
| 6228 | // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as |
| 6229 | // not to disable further simplications and optimizations as a result of GEP |
| 6230 | // merging. |
| 6231 | // |
| 6232 | // Note this unmerging may increase the length of the data flow critical path |
| 6233 | // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff |
| 6234 | // between the register pressure and the length of data-flow critical |
| 6235 | // path. Restricting this to the uncommon IndirectBr case would minimize the |
| 6236 | // impact of potentially longer critical path, if any, and the impact on compile |
| 6237 | // time. |
| 6238 | static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI, |
| 6239 | const TargetTransformInfo *TTI) { |
| 6240 | BasicBlock *SrcBlock = GEPI->getParent(); |
| 6241 | // Check that SrcBlock ends with an IndirectBr. If not, give up. The common |
| 6242 | // (non-IndirectBr) cases exit early here. |
| 6243 | if (!isa<IndirectBrInst>(SrcBlock->getTerminator())) |
| 6244 | return false; |
| 6245 | // Check that GEPI is a simple gep with a single constant index. |
| 6246 | if (!GEPSequentialConstIndexed(GEPI)) |
| 6247 | return false; |
| 6248 | ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1)); |
| 6249 | // Check that GEPI is a cheap one. |
| 6250 | if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType()) |
| 6251 | > TargetTransformInfo::TCC_Basic) |
| 6252 | return false; |
| 6253 | Value *GEPIOp = GEPI->getOperand(0); |
| 6254 | // Check that GEPIOp is an instruction that's also defined in SrcBlock. |
| 6255 | if (!isa<Instruction>(GEPIOp)) |
| 6256 | return false; |
| 6257 | auto *GEPIOpI = cast<Instruction>(GEPIOp); |
| 6258 | if (GEPIOpI->getParent() != SrcBlock) |
| 6259 | return false; |
| 6260 | // Check that GEP is used outside the block, meaning it's alive on the |
| 6261 | // IndirectBr edge(s). |
| 6262 | if (find_if(GEPI->users(), [&](User *Usr) { |
| 6263 | if (auto *I = dyn_cast<Instruction>(Usr)) { |
| 6264 | if (I->getParent() != SrcBlock) { |
| 6265 | return true; |
| 6266 | } |
| 6267 | } |
| 6268 | return false; |
| 6269 | }) == GEPI->users().end()) |
| 6270 | return false; |
| 6271 | // The second elements of the GEP chains to be unmerged. |
| 6272 | std::vector<GetElementPtrInst *> UGEPIs; |
| 6273 | // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive |
| 6274 | // on IndirectBr edges. |
| 6275 | for (User *Usr : GEPIOp->users()) { |
| 6276 | if (Usr == GEPI) continue; |
| 6277 | // Check if Usr is an Instruction. If not, give up. |
| 6278 | if (!isa<Instruction>(Usr)) |
| 6279 | return false; |
| 6280 | auto *UI = cast<Instruction>(Usr); |
| 6281 | // Check if Usr in the same block as GEPIOp, which is fine, skip. |
| 6282 | if (UI->getParent() == SrcBlock) |
| 6283 | continue; |
| 6284 | // Check if Usr is a GEP. If not, give up. |
| 6285 | if (!isa<GetElementPtrInst>(Usr)) |
| 6286 | return false; |
| 6287 | auto *UGEPI = cast<GetElementPtrInst>(Usr); |
| 6288 | // Check if UGEPI is a simple gep with a single constant index and GEPIOp is |
| 6289 | // the pointer operand to it. If so, record it in the vector. If not, give |
| 6290 | // up. |
| 6291 | if (!GEPSequentialConstIndexed(UGEPI)) |
| 6292 | return false; |
| 6293 | if (UGEPI->getOperand(0) != GEPIOp) |
| 6294 | return false; |
| 6295 | if (GEPIIdx->getType() != |
| 6296 | cast<ConstantInt>(UGEPI->getOperand(1))->getType()) |
| 6297 | return false; |
| 6298 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); |
| 6299 | if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType()) |
| 6300 | > TargetTransformInfo::TCC_Basic) |
| 6301 | return false; |
| 6302 | UGEPIs.push_back(UGEPI); |
| 6303 | } |
| 6304 | if (UGEPIs.size() == 0) |
| 6305 | return false; |
| 6306 | // Check the materializing cost of (Uidx-Idx). |
| 6307 | for (GetElementPtrInst *UGEPI : UGEPIs) { |
| 6308 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); |
| 6309 | APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue(); |
| 6310 | unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType()); |
| 6311 | if (ImmCost > TargetTransformInfo::TCC_Basic) |
| 6312 | return false; |
| 6313 | } |
| 6314 | // Now unmerge between GEPI and UGEPIs. |
| 6315 | for (GetElementPtrInst *UGEPI : UGEPIs) { |
| 6316 | UGEPI->setOperand(0, GEPI); |
| 6317 | ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1)); |
| 6318 | Constant *NewUGEPIIdx = |
| 6319 | ConstantInt::get(GEPIIdx->getType(), |
| 6320 | UGEPIIdx->getValue() - GEPIIdx->getValue()); |
| 6321 | UGEPI->setOperand(1, NewUGEPIIdx); |
| 6322 | // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not |
| 6323 | // inbounds to avoid UB. |
| 6324 | if (!GEPI->isInBounds()) { |
| 6325 | UGEPI->setIsInBounds(false); |
| 6326 | } |
| 6327 | } |
| 6328 | // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not |
| 6329 | // alive on IndirectBr edges). |
| 6330 | assert(find_if(GEPIOp->users(), [&](User *Usr) { |
| 6331 | return cast<Instruction>(Usr)->getParent() != SrcBlock; |
| 6332 | }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock"); |
| 6333 | return true; |
| 6334 | } |
| 6335 | |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 6336 | bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) { |
Ahmed Bougacha | f329914 | 2015-06-17 20:44:32 +0000 | [diff] [blame] | 6337 | // Bail out if we inserted the instruction to prevent optimizations from |
| 6338 | // stepping on each other's toes. |
| 6339 | if (InsertedInsts.count(I)) |
| 6340 | return false; |
| 6341 | |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6342 | if (PHINode *P = dyn_cast<PHINode>(I)) { |
| 6343 | // It is possible for very late stage optimizations (such as SimplifyCFG) |
| 6344 | // to introduce PHI nodes too late to be cleaned up. If we detect such a |
| 6345 | // trivial PHI, go ahead and zap it here. |
Daniel Berlin | 4d0fe64 | 2017-04-28 19:55:38 +0000 | [diff] [blame] | 6346 | if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6347 | P->replaceAllUsesWith(V); |
| 6348 | P->eraseFromParent(); |
| 6349 | ++NumPHIsElim; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6350 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6351 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6352 | return false; |
| 6353 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6354 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6355 | if (CastInst *CI = dyn_cast<CastInst>(I)) { |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6356 | // If the source of the cast is a constant, then this should have |
| 6357 | // already been constant folded. The only reason NOT to constant fold |
| 6358 | // it is if something (e.g. LSR) was careful to place the constant |
| 6359 | // evaluation in a block other than then one that uses it (e.g. to hoist |
| 6360 | // the address of globals out of a loop). If this is the case, we don't |
| 6361 | // want to forward-subst the cast. |
| 6362 | if (isa<Constant>(CI->getOperand(0))) |
| 6363 | return false; |
| 6364 | |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6365 | if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL)) |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6366 | return true; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6367 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6368 | if (isa<ZExtInst>(I) || isa<SExtInst>(I)) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6369 | /// Sink a zext or sext into its user blocks if the target type doesn't |
| 6370 | /// fit in one register |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6371 | if (TLI && |
| 6372 | TLI->getTypeAction(CI->getContext(), |
| 6373 | TLI->getValueType(*DL, CI->getType())) == |
| 6374 | TargetLowering::TypeExpandInteger) { |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6375 | return SinkCast(CI); |
| 6376 | } else { |
Jun Bum Lim | dee5565 | 2017-04-03 19:20:07 +0000 | [diff] [blame] | 6377 | bool MadeChange = optimizeExt(I); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6378 | return MadeChange | optimizeExtUses(I); |
Manuel Jacob | a7c48f9 | 2014-03-13 13:36:25 +0000 | [diff] [blame] | 6379 | } |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6380 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6381 | return false; |
| 6382 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6383 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6384 | if (CmpInst *CI = dyn_cast<CmpInst>(I)) |
Hal Finkel | decb024 | 2014-01-02 21:13:43 +0000 | [diff] [blame] | 6385 | if (!TLI || !TLI->hasMultipleConditionRegisters()) |
Peter Zotov | f87e550 | 2016-04-03 17:11:53 +0000 | [diff] [blame] | 6386 | return OptimizeCmpExpression(CI, TLI); |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6387 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6388 | if (LoadInst *LI = dyn_cast<LoadInst>(I)) { |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 6389 | LI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6390 | if (TLI) { |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 6391 | bool Modified = optimizeLoadExt(LI); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6392 | unsigned AS = LI->getPointerAddressSpace(); |
Geoff Berry | 5256fca | 2015-11-20 22:34:39 +0000 | [diff] [blame] | 6393 | Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS); |
| 6394 | return Modified; |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6395 | } |
Hans Wennborg | f325483 | 2012-10-30 11:23:25 +0000 | [diff] [blame] | 6396 | return false; |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6397 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6398 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6399 | if (StoreInst *SI = dyn_cast<StoreInst>(I)) { |
Wei Mi | a2f0b59 | 2016-12-22 19:44:45 +0000 | [diff] [blame] | 6400 | if (TLI && splitMergedValStore(*SI, *DL, *TLI)) |
| 6401 | return true; |
Sanjoy Das | 0075727 | 2016-12-16 20:29:39 +0000 | [diff] [blame] | 6402 | SI->setMetadata(LLVMContext::MD_invariant_group, nullptr); |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6403 | if (TLI) { |
| 6404 | unsigned AS = SI->getPointerAddressSpace(); |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6405 | return optimizeMemoryInst(I, SI->getOperand(1), |
Matt Arsenault | f72b49b | 2015-06-04 16:17:38 +0000 | [diff] [blame] | 6406 | SI->getOperand(0)->getType(), AS); |
| 6407 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6408 | return false; |
| 6409 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6410 | |
Matt Arsenault | 02d915b | 2017-03-15 22:35:20 +0000 | [diff] [blame] | 6411 | if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) { |
| 6412 | unsigned AS = RMW->getPointerAddressSpace(); |
| 6413 | return optimizeMemoryInst(I, RMW->getPointerOperand(), |
| 6414 | RMW->getType(), AS); |
| 6415 | } |
| 6416 | |
| 6417 | if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) { |
| 6418 | unsigned AS = CmpX->getPointerAddressSpace(); |
| 6419 | return optimizeMemoryInst(I, CmpX->getPointerOperand(), |
| 6420 | CmpX->getCompareOperand()->getType(), AS); |
| 6421 | } |
| 6422 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6423 | BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I); |
| 6424 | |
Geoff Berry | 5d534b6 | 2017-02-21 18:53:14 +0000 | [diff] [blame] | 6425 | if (BinOp && (BinOp->getOpcode() == Instruction::And) && |
| 6426 | EnableAndCmpSinking && TLI) |
| 6427 | return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts); |
| 6428 | |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6429 | if (BinOp && (BinOp->getOpcode() == Instruction::AShr || |
| 6430 | BinOp->getOpcode() == Instruction::LShr)) { |
| 6431 | ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1)); |
| 6432 | if (TLI && CI && TLI->hasExtractBitsInsn()) |
Mehdi Amini | 44ede33 | 2015-07-09 02:09:04 +0000 | [diff] [blame] | 6433 | return OptimizeExtractBits(BinOp, CI, *TLI, *DL); |
Yi Jiang | d069f63 | 2014-04-21 19:34:27 +0000 | [diff] [blame] | 6434 | |
| 6435 | return false; |
| 6436 | } |
| 6437 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6438 | if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6439 | if (GEPI->hasAllZeroIndices()) { |
| 6440 | /// The GEP operand must be a pointer, so must its result -> BitCast |
| 6441 | Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), |
| 6442 | GEPI->getName(), GEPI); |
| 6443 | GEPI->replaceAllUsesWith(NC); |
| 6444 | GEPI->eraseFromParent(); |
| 6445 | ++NumGEPsElim; |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6446 | optimizeInst(NC, ModifiedDT); |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6447 | return true; |
Cameron Zwarich | d28c78e | 2011-01-06 02:44:52 +0000 | [diff] [blame] | 6448 | } |
Hiroshi Yamauchi | 9364432 | 2017-09-11 17:52:08 +0000 | [diff] [blame] | 6449 | if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) { |
| 6450 | return true; |
| 6451 | } |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6452 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6453 | } |
Nadav Rotem | 465834c | 2012-07-24 10:51:42 +0000 | [diff] [blame] | 6454 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6455 | if (CallInst *CI = dyn_cast<CallInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6456 | return optimizeCallInst(CI, ModifiedDT); |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6457 | |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 6458 | if (SelectInst *SI = dyn_cast<SelectInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6459 | return optimizeSelectInst(SI); |
Benjamin Kramer | 047d7ca | 2012-05-05 12:49:22 +0000 | [diff] [blame] | 6460 | |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 6461 | if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6462 | return optimizeShuffleVectorInst(SVI); |
Tim Northover | aeb8e06 | 2014-02-19 10:02:43 +0000 | [diff] [blame] | 6463 | |
Sanjay Patel | 0ed9aea | 2015-11-02 23:22:49 +0000 | [diff] [blame] | 6464 | if (auto *Switch = dyn_cast<SwitchInst>(I)) |
| 6465 | return optimizeSwitchInst(Switch); |
| 6466 | |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6467 | if (isa<ExtractElementInst>(I)) |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6468 | return optimizeExtractElementInst(I); |
Quentin Colombet | c32615d | 2014-10-31 17:52:53 +0000 | [diff] [blame] | 6469 | |
Chris Lattner | ee588de | 2011-01-15 07:29:01 +0000 | [diff] [blame] | 6470 | return false; |
Cameron Zwarich | 14ac865 | 2011-01-06 02:37:26 +0000 | [diff] [blame] | 6471 | } |
| 6472 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6473 | /// Given an OR instruction, check to see if this is a bitreverse |
| 6474 | /// idiom. If so, insert the new intrinsic and return true. |
| 6475 | static bool makeBitReverse(Instruction &I, const DataLayout &DL, |
| 6476 | const TargetLowering &TLI) { |
| 6477 | if (!I.getType()->isIntegerTy() || |
| 6478 | !TLI.isOperationLegalOrCustom(ISD::BITREVERSE, |
| 6479 | TLI.getValueType(DL, I.getType(), true))) |
| 6480 | return false; |
| 6481 | |
| 6482 | SmallVector<Instruction*, 4> Insts; |
Chad Rosier | a00df49 | 2016-05-25 16:22:14 +0000 | [diff] [blame] | 6483 | if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts)) |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6484 | return false; |
| 6485 | Instruction *LastInst = Insts.back(); |
| 6486 | I.replaceAllUsesWith(LastInst); |
| 6487 | RecursivelyDeleteTriviallyDeadInstructions(&I); |
| 6488 | return true; |
| 6489 | } |
| 6490 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 6491 | // In this pass we look for GEP and cast instructions that are used |
| 6492 | // across basic blocks and rewrite them to improve basic-block-at-a-time |
| 6493 | // selection. |
Sanjay Patel | 3b8974b | 2017-06-08 20:00:09 +0000 | [diff] [blame] | 6494 | bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) { |
Cameron Zwarich | ce3b930 | 2011-01-06 00:42:50 +0000 | [diff] [blame] | 6495 | SunkAddrs.clear(); |
Cameron Zwarich | 5dd2aa2 | 2011-03-02 03:31:46 +0000 | [diff] [blame] | 6496 | bool MadeChange = false; |
Eric Christopher | c1ea149 | 2008-09-24 05:32:41 +0000 | [diff] [blame] | 6497 | |
Chris Lattner | 7a27714 | 2011-01-15 07:14:54 +0000 | [diff] [blame] | 6498 | CurInstIterator = BB.begin(); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 6499 | while (CurInstIterator != BB.end()) { |
Duncan P. N. Exon Smith | d83547a | 2015-10-09 18:44:40 +0000 | [diff] [blame] | 6500 | MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT); |
Elena Demikhovsky | 87700a7 | 2014-12-28 08:54:45 +0000 | [diff] [blame] | 6501 | if (ModifiedDT) |
| 6502 | return true; |
| 6503 | } |
Benjamin Kramer | 455fa35 | 2012-11-23 19:17:06 +0000 | [diff] [blame] | 6504 | |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6505 | bool MadeBitReverse = true; |
| 6506 | while (TLI && MadeBitReverse) { |
| 6507 | MadeBitReverse = false; |
| 6508 | for (auto &I : reverse(BB)) { |
| 6509 | if (makeBitReverse(I, *DL, *TLI)) { |
| 6510 | MadeBitReverse = MadeChange = true; |
George Burgess IV | d4febd1 | 2016-03-22 21:25:08 +0000 | [diff] [blame] | 6511 | ModifiedDT = true; |
James Molloy | f01488e | 2016-01-15 09:20:19 +0000 | [diff] [blame] | 6512 | break; |
| 6513 | } |
| 6514 | } |
| 6515 | } |
James Molloy | 3ef84c4 | 2016-01-15 10:36:01 +0000 | [diff] [blame] | 6516 | MadeChange |= dupRetToEnableTailCallOpts(&BB); |
Junmo Park | 7d6c5f1 | 2016-01-28 09:42:39 +0000 | [diff] [blame] | 6517 | |
Chris Lattner | f2836d1 | 2007-03-31 04:06:36 +0000 | [diff] [blame] | 6518 | return MadeChange; |
| 6519 | } |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6520 | |
| 6521 | // 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] | 6522 | // 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] | 6523 | // find a node corresponding to the value. |
Sanjay Patel | fc580a6 | 2015-09-21 23:03:16 +0000 | [diff] [blame] | 6524 | bool CodeGenPrepare::placeDbgValues(Function &F) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6525 | bool MadeChange = false; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 6526 | for (BasicBlock &BB : F) { |
Craig Topper | c0196b1 | 2014-04-14 00:51:57 +0000 | [diff] [blame] | 6527 | Instruction *PrevNonDbgInst = nullptr; |
Duncan P. N. Exon Smith | 5914a97 | 2015-01-08 20:44:33 +0000 | [diff] [blame] | 6528 | 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] | 6529 | Instruction *Insn = &*BI++; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6530 | DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn); |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 6531 | // Leave dbg.values that refer to an alloca alone. These |
Craig Topper | 87e715f | 2017-11-07 20:56:17 +0000 | [diff] [blame] | 6532 | // intrinsics describe the address of a variable (= the alloca) |
Adrian Prantl | 32da889 | 2014-04-25 20:49:25 +0000 | [diff] [blame] | 6533 | // being taken. They should not be moved next to the alloca |
| 6534 | // (and to the beginning of the scope), but rather stay close to |
| 6535 | // where said address is used. |
| 6536 | if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) { |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6537 | PrevNonDbgInst = Insn; |
| 6538 | continue; |
| 6539 | } |
| 6540 | |
| 6541 | Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue()); |
| 6542 | if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) { |
Reid Kleckner | 8de1fe2 | 2015-12-08 23:00:03 +0000 | [diff] [blame] | 6543 | // If VI is a phi in a block with an EHPad terminator, we can't insert |
| 6544 | // after it. |
| 6545 | if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad()) |
| 6546 | continue; |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6547 | DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI); |
| 6548 | DVI->removeFromParent(); |
Reid Kleckner | e18f92b | 2015-12-08 22:33:23 +0000 | [diff] [blame] | 6549 | if (isa<PHINode>(VI)) |
| 6550 | DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt()); |
| 6551 | else |
| 6552 | DVI->insertAfter(VI); |
Devang Patel | 53771ba | 2011-08-18 00:50:51 +0000 | [diff] [blame] | 6553 | MadeChange = true; |
| 6554 | ++NumDbgValueMoved; |
| 6555 | } |
| 6556 | } |
| 6557 | } |
| 6558 | return MadeChange; |
| 6559 | } |
Tim Northover | cea0abb | 2014-03-29 08:22:29 +0000 | [diff] [blame] | 6560 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6561 | /// \brief Scale down both weights to fit into uint32_t. |
| 6562 | static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) { |
| 6563 | uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse; |
Eugene Zelenko | 900b633 | 2017-08-29 22:32:07 +0000 | [diff] [blame] | 6564 | uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1; |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6565 | NewTrue = NewTrue / Scale; |
| 6566 | NewFalse = NewFalse / Scale; |
| 6567 | } |
| 6568 | |
| 6569 | /// \brief Some targets prefer to split a conditional branch like: |
| 6570 | /// \code |
| 6571 | /// %0 = icmp ne i32 %a, 0 |
| 6572 | /// %1 = icmp ne i32 %b, 0 |
| 6573 | /// %or.cond = or i1 %0, %1 |
| 6574 | /// br i1 %or.cond, label %TrueBB, label %FalseBB |
| 6575 | /// \endcode |
| 6576 | /// into multiple branch instructions like: |
| 6577 | /// \code |
| 6578 | /// bb1: |
| 6579 | /// %0 = icmp ne i32 %a, 0 |
| 6580 | /// br i1 %0, label %TrueBB, label %bb2 |
| 6581 | /// bb2: |
| 6582 | /// %1 = icmp ne i32 %b, 0 |
| 6583 | /// br i1 %1, label %TrueBB, label %FalseBB |
| 6584 | /// \endcode |
| 6585 | /// This usually allows instruction selection to do even further optimizations |
| 6586 | /// and combine the compare with the branch instruction. Currently this is |
| 6587 | /// applied for targets which have "cheap" jump instructions. |
| 6588 | /// |
| 6589 | /// FIXME: Remove the (equivalent?) implementation in SelectionDAG. |
| 6590 | /// |
| 6591 | bool CodeGenPrepare::splitBranchCondition(Function &F) { |
David Blaikie | dc3f01e | 2015-03-09 01:57:13 +0000 | [diff] [blame] | 6592 | if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive()) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6593 | return false; |
| 6594 | |
| 6595 | bool MadeChange = false; |
| 6596 | for (auto &BB : F) { |
| 6597 | // Does this BB end with the following? |
| 6598 | // %cond1 = icmp|fcmp|binary instruction ... |
| 6599 | // %cond2 = icmp|fcmp|binary instruction ... |
| 6600 | // %cond.or = or|and i1 %cond1, cond2 |
| 6601 | // br i1 %cond.or label %dest1, label %dest2" |
| 6602 | BinaryOperator *LogicOp; |
| 6603 | BasicBlock *TBB, *FBB; |
| 6604 | if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB))) |
| 6605 | continue; |
| 6606 | |
Sanjay Patel | 4257420 | 2015-09-02 19:23:23 +0000 | [diff] [blame] | 6607 | auto *Br1 = cast<BranchInst>(BB.getTerminator()); |
| 6608 | if (Br1->getMetadata(LLVMContext::MD_unpredictable)) |
| 6609 | continue; |
| 6610 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6611 | unsigned Opc; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6612 | Value *Cond1, *Cond2; |
| 6613 | if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)), |
| 6614 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6615 | Opc = Instruction::And; |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6616 | else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)), |
| 6617 | m_OneUse(m_Value(Cond2))))) |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6618 | Opc = Instruction::Or; |
| 6619 | else |
| 6620 | continue; |
| 6621 | |
| 6622 | if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) || |
| 6623 | !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) ) |
| 6624 | continue; |
| 6625 | |
| 6626 | DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump()); |
| 6627 | |
| 6628 | // Create a new BB. |
Duncan P. N. Exon Smith | a848c47 | 2016-02-21 19:52:15 +0000 | [diff] [blame] | 6629 | auto TmpBB = |
| 6630 | BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split", |
| 6631 | BB.getParent(), BB.getNextNode()); |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6632 | |
| 6633 | // Update original basic block by using the first condition directly by the |
| 6634 | // branch instruction and removing the no longer needed and/or instruction. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6635 | Br1->setCondition(Cond1); |
| 6636 | LogicOp->eraseFromParent(); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6637 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6638 | // Depending on the conditon we have to either replace the true or the false |
| 6639 | // successor of the original branch instruction. |
| 6640 | if (Opc == Instruction::And) |
| 6641 | Br1->setSuccessor(0, TmpBB); |
| 6642 | else |
| 6643 | Br1->setSuccessor(1, TmpBB); |
| 6644 | |
| 6645 | // Fill in the new basic block. |
| 6646 | auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB); |
Juergen Ributzka | 8bda738 | 2014-12-09 17:50:10 +0000 | [diff] [blame] | 6647 | if (auto *I = dyn_cast<Instruction>(Cond2)) { |
| 6648 | I->removeFromParent(); |
| 6649 | I->insertBefore(Br2); |
| 6650 | } |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6651 | |
| 6652 | // Update PHI nodes in both successors. The original BB needs to be |
Hiroshi Inoue | 6a391bb | 2017-06-27 10:35:37 +0000 | [diff] [blame] | 6653 | // 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] | 6654 | // the newly generated BB (NewBB). In the other successor we need to add one |
| 6655 | // incoming edge to the PHI nodes, because both branch instructions target |
| 6656 | // now the same successor. Depending on the original branch condition |
| 6657 | // (and/or) we have to swap the successors (TrueDest, FalseDest), so that |
Simon Pilgrim | f2fbf43 | 2016-11-20 13:47:59 +0000 | [diff] [blame] | 6658 | // we perform the correct update for the PHI nodes. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6659 | // This doesn't change the successor order of the just created branch |
| 6660 | // instruction (or any other instruction). |
| 6661 | if (Opc == Instruction::Or) |
| 6662 | std::swap(TBB, FBB); |
| 6663 | |
| 6664 | // Replace the old BB with the new BB. |
| 6665 | for (auto &I : *TBB) { |
| 6666 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 6667 | if (!PN) |
| 6668 | break; |
| 6669 | int i; |
| 6670 | while ((i = PN->getBasicBlockIndex(&BB)) >= 0) |
| 6671 | PN->setIncomingBlock(i, TmpBB); |
| 6672 | } |
| 6673 | |
| 6674 | // Add another incoming edge form the new BB. |
| 6675 | for (auto &I : *FBB) { |
| 6676 | PHINode *PN = dyn_cast<PHINode>(&I); |
| 6677 | if (!PN) |
| 6678 | break; |
| 6679 | auto *Val = PN->getIncomingValueForBlock(&BB); |
| 6680 | PN->addIncoming(Val, TmpBB); |
| 6681 | } |
| 6682 | |
| 6683 | // Update the branch weights (from SelectionDAGBuilder:: |
| 6684 | // FindMergedConditions). |
| 6685 | if (Opc == Instruction::Or) { |
| 6686 | // Codegen X | Y as: |
| 6687 | // BB1: |
| 6688 | // jmp_if_X TBB |
| 6689 | // jmp TmpBB |
| 6690 | // TmpBB: |
| 6691 | // jmp_if_Y TBB |
| 6692 | // jmp FBB |
| 6693 | // |
| 6694 | |
| 6695 | // We have flexibility in setting Prob for BB1 and Prob for NewBB. |
| 6696 | // The requirement is that |
| 6697 | // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) |
| 6698 | // = TrueProb for orignal BB. |
| 6699 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 6700 | // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice |
| 6701 | // assumes that |
| 6702 | // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. |
| 6703 | // Another choice is to assume TrueProb for BB1 equals to TrueProb for |
| 6704 | // TmpBB, but the math is more complicated. |
| 6705 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6706 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6707 | uint64_t NewTrueWeight = TrueWeight; |
| 6708 | uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight; |
| 6709 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6710 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6711 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6712 | |
| 6713 | NewTrueWeight = TrueWeight; |
| 6714 | NewFalseWeight = 2 * FalseWeight; |
| 6715 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6716 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6717 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6718 | } |
| 6719 | } else { |
| 6720 | // Codegen X & Y as: |
| 6721 | // BB1: |
| 6722 | // jmp_if_X TmpBB |
| 6723 | // jmp FBB |
| 6724 | // TmpBB: |
| 6725 | // jmp_if_Y TBB |
| 6726 | // jmp FBB |
| 6727 | // |
| 6728 | // This requires creation of TmpBB after CurBB. |
| 6729 | |
| 6730 | // We have flexibility in setting Prob for BB1 and Prob for TmpBB. |
| 6731 | // The requirement is that |
| 6732 | // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) |
| 6733 | // = FalseProb for orignal BB. |
| 6734 | // Assuming the orignal weights are A and B, one choice is to set BB1's |
| 6735 | // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice |
| 6736 | // assumes that |
| 6737 | // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB. |
| 6738 | uint64_t TrueWeight, FalseWeight; |
Sanjay Patel | dc88bd6 | 2016-04-23 20:01:22 +0000 | [diff] [blame] | 6739 | if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) { |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6740 | uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight; |
| 6741 | uint64_t NewFalseWeight = FalseWeight; |
| 6742 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6743 | Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext()) |
| 6744 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6745 | |
| 6746 | NewTrueWeight = 2 * TrueWeight; |
| 6747 | NewFalseWeight = FalseWeight; |
| 6748 | scaleWeights(NewTrueWeight, NewFalseWeight); |
| 6749 | Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext()) |
| 6750 | .createBranchWeights(TrueWeight, FalseWeight)); |
| 6751 | } |
| 6752 | } |
| 6753 | |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6754 | // 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] | 6755 | // available to CodeGenPrepare. |
Juergen Ributzka | c1bbcbb | 2014-12-09 16:36:13 +0000 | [diff] [blame] | 6756 | ModifiedDT = true; |
| 6757 | |
| 6758 | MadeChange = true; |
| 6759 | |
| 6760 | DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump(); |
| 6761 | TmpBB->dump()); |
| 6762 | } |
| 6763 | return MadeChange; |
| 6764 | } |