blob: 067f708e331cb016a700c8f6ae10420e3595da3c [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerf2836d12007-03-31 04:06:36 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000010// SelectionDAG-based code generation. This works around limitations in it's
11// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000012//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko900b6332017-08-29 22:32:07 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000018#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/ADT/STLExtras.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000020#include "llvm/ADT/SmallPtrSet.h"
21#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000023#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000025#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000027#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000029#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000030#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000031#include "llvm/Analysis/TargetTransformInfo.h"
David Blaikie31b98d22018-06-04 21:23:21 +000032#include "llvm/Transforms/Utils/Local.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000033#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000034#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000035#include "llvm/CodeGen/ISDOpcodes.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000037#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000038#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetSubtargetInfo.h"
Craig Topper2fa14362018-03-29 17:21:10 +000040#include "llvm/CodeGen/ValueTypes.h"
Nico Weber432a3882018-04-30 14:59:11 +000041#include "llvm/Config/llvm-config.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000042#include "llvm/IR/Argument.h"
43#include "llvm/IR/Attributes.h"
44#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000045#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000046#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000047#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000050#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000051#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000052#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000053#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000055#include "llvm/IR/IRBuilder.h"
56#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000057#include "llvm/IR/InstrTypes.h"
58#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000059#include "llvm/IR/Instructions.h"
60#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000061#include "llvm/IR/Intrinsics.h"
62#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000063#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000064#include "llvm/IR/Module.h"
65#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000066#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000067#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000068#include "llvm/IR/Type.h"
69#include "llvm/IR/Use.h"
70#include "llvm/IR/User.h"
71#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000072#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000073#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000074#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000075#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000076#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000077#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000078#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000079#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000080#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000081#include "llvm/Support/ErrorHandling.h"
David Blaikie13e77db2018-03-23 23:58:25 +000082#include "llvm/Support/MachineValueType.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000083#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000084#include "llvm/Support/raw_ostream.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000085#include "llvm/Target/TargetMachine.h"
86#include "llvm/Target/TargetOptions.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000087#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000088#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000089#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000090#include <algorithm>
91#include <cassert>
92#include <cstdint>
93#include <iterator>
94#include <limits>
95#include <memory>
96#include <utility>
97#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +000098
Chris Lattnerf2836d12007-03-31 04:06:36 +000099using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000100using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000101
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000102#define DEBUG_TYPE "codegenprepare"
103
Cameron Zwarichced753f2011-01-05 17:27:27 +0000104STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000105STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
106STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000107STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
108 "sunken Cmps");
109STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
110 "of sunken Casts");
111STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
112 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000113STATISTIC(NumMemoryInstsPhiCreated,
114 "Number of phis created when address "
115 "computations were sunk to memory instructions");
116STATISTIC(NumMemoryInstsSelectCreated,
117 "Number of select created when address "
118 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000119STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
120STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000121STATISTIC(NumAndsAdded,
122 "Number of and mask instructions added to form ext loads");
123STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000124STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000125STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000126STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000127STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000128
Cameron Zwarich338d3622011-03-11 21:52:04 +0000129static cl::opt<bool> DisableBranchOpts(
130 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
131 cl::desc("Disable branch optimizations in CodeGenPrepare"));
132
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000133static cl::opt<bool>
134 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
135 cl::desc("Disable GC optimizations in CodeGenPrepare"));
136
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000137static cl::opt<bool> DisableSelectToBranch(
138 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
139 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000140
Hal Finkelc3998302014-04-12 00:59:48 +0000141static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000142 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000143 cl::desc("Address sinking in CGP using GEPs."));
144
Tim Northovercea0abb2014-03-29 08:22:29 +0000145static cl::opt<bool> EnableAndCmpSinking(
146 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
147 cl::desc("Enable sinkinig and/cmp into branches."));
148
Quentin Colombetc32615d2014-10-31 17:52:53 +0000149static cl::opt<bool> DisableStoreExtract(
150 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
151 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
152
153static cl::opt<bool> StressStoreExtract(
154 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
155 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
156
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000157static cl::opt<bool> DisableExtLdPromotion(
158 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
159 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
160 "CodeGenPrepare"));
161
162static cl::opt<bool> StressExtLdPromotion(
163 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
164 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
165 "optimization in CodeGenPrepare"));
166
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000167static cl::opt<bool> DisablePreheaderProtect(
168 "disable-preheader-prot", cl::Hidden, cl::init(false),
169 cl::desc("Disable protection against removing loop preheaders"));
170
Dehao Chen302b69c2016-10-18 20:42:47 +0000171static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000172 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000173 cl::desc("Use profile info to add section prefix for hot/cold functions"));
174
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000175static cl::opt<unsigned> FreqRatioToSkipMerge(
176 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
177 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
178 "(frequency of destination block) is greater than this ratio"));
179
Wei Mia2f0b592016-12-22 19:44:45 +0000180static cl::opt<bool> ForceSplitStore(
181 "force-split-store", cl::Hidden, cl::init(false),
182 cl::desc("Force store splitting no matter what the target query says."));
183
Jun Bum Limdee55652017-04-03 19:20:07 +0000184static cl::opt<bool>
185EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
186 cl::desc("Enable merging of redundant sexts when one is dominating"
187 " the other."), cl::init(true));
188
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000189static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000190 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000191 cl::desc("Disables combining addressing modes with different parts "
192 "in optimizeMemoryInst."));
193
194static cl::opt<bool>
195AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
196 cl::desc("Allow creation of Phis in Address sinking."));
197
198static cl::opt<bool>
Serguei Katkov9fe05242018-01-26 06:26:56 +0000199AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000200 cl::desc("Allow creation of selects in Address sinking."));
201
John Brawn70cdb5b2017-11-24 14:10:45 +0000202static cl::opt<bool> AddrSinkCombineBaseReg(
203 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
204 cl::desc("Allow combining of BaseReg field in Address sinking."));
205
206static cl::opt<bool> AddrSinkCombineBaseGV(
207 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
208 cl::desc("Allow combining of BaseGV field in Address sinking."));
209
210static cl::opt<bool> AddrSinkCombineBaseOffs(
211 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
212 cl::desc("Allow combining of BaseOffs field in Address sinking."));
213
214static cl::opt<bool> AddrSinkCombineScaledReg(
215 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
216 cl::desc("Allow combining of ScaledReg field in Address sinking."));
217
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000218static cl::opt<bool>
219 EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
220 cl::init(true),
221 cl::desc("Enable splitting large offset of GEP."));
222
Eric Christopherc1ea1492008-09-24 05:32:41 +0000223namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000224
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000225enum ExtType {
226 ZeroExtension, // Zero extension has been seen.
227 SignExtension, // Sign extension has been seen.
228 BothExtension // This extension type is used if we saw sext after
229 // ZeroExtension had been set, or if we saw zext after
230 // SignExtension had been set. It makes the type
231 // information of a promoted instruction invalid.
232};
233
Eugene Zelenko900b6332017-08-29 22:32:07 +0000234using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
Guozhi Wei8c17f9a2018-08-15 22:08:26 +0000235using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000236using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
237using SExts = SmallVector<Instruction *, 16>;
238using ValueToSExts = DenseMap<Value *, SExts>;
239
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000240class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000241
Chris Lattner2dd09db2009-09-02 06:11:42 +0000242 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000243 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000244 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000245 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000246 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000247 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000248 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000249 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000250 std::unique_ptr<BlockFrequencyInfo> BFI;
251 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000252
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000253 /// As we scan instructions optimizing them, this is the next instruction
254 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000255 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000256
Evan Cheng0663f232011-03-21 01:19:09 +0000257 /// Keeps track of non-local addresses that have been sunk into a block.
258 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000259 /// multiple load/stores of the same address. The usage of WeakTrackingVH
260 /// enables SunkAddrs to be treated as a cache whose entries can be
261 /// invalidated if a sunken address computation has been erased.
262 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000263
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000264 /// Keeps track of all instructions inserted for the current function.
265 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000266
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000267 /// Keeps track of the type of the related instruction before their
268 /// promotion for the current function.
269 InstrToOrigTy PromotedInsts;
270
Jun Bum Limdee55652017-04-03 19:20:07 +0000271 /// Keep track of instructions removed during promotion.
272 SetOfInstrs RemovedInsts;
273
274 /// Keep track of sext chains based on their initial value.
275 DenseMap<Value *, Instruction *> SeenChainsForSExt;
276
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000277 /// Keep track of GEPs accessing the same data structures such as structs or
278 /// arrays that are candidates to be split later because of their large
279 /// size.
David Greene27e87c2018-09-12 10:19:10 +0000280 MapVector<
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000281 AssertingVH<Value>,
282 SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
283 LargeOffsetGEPMap;
284
285 /// Keep track of new GEP base after splitting the GEPs having large offset.
286 SmallSet<AssertingVH<Value>, 2> NewGEPBases;
287
288 /// Map serial numbers to Large offset GEPs.
289 DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
290
Jun Bum Limdee55652017-04-03 19:20:07 +0000291 /// Keep track of SExt promoted.
292 ValueToSExts ValToSExtendedUses;
293
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000294 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000295 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000296
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000297 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000298 bool OptSize;
299
Mehdi Amini4fe37982015-07-07 18:45:17 +0000300 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000301 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000302
Chris Lattnerf2836d12007-03-31 04:06:36 +0000303 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000304 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000305
306 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000307 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
308 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000309
Craig Topper4584cd52014-03-07 09:26:03 +0000310 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000311
Mehdi Amini117296c2016-10-01 02:56:57 +0000312 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000313
Craig Topper4584cd52014-03-07 09:26:03 +0000314 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000315 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000316 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000317 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000318 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000319 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000320 }
321
Chris Lattnerf2836d12007-03-31 04:06:36 +0000322 private:
James Y Knight72f76bf2018-11-07 15:24:12 +0000323 template <typename F>
324 void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
325 // Substituting can cause recursive simplifications, which can invalidate
326 // our iterator. Use a WeakTrackingVH to hold onto it in case this
327 // happens.
328 Value *CurValue = &*CurInstIterator;
329 WeakTrackingVH IterHandle(CurValue);
330
331 f();
332
333 // If the iterator instruction was recursively deleted, start over at the
334 // start of the block.
335 if (IterHandle != CurValue) {
336 CurInstIterator = BB->begin();
337 SunkAddrs.clear();
338 }
339 }
340
Sanjay Patelfc580a62015-09-21 23:03:16 +0000341 bool eliminateFallThrough(Function &F);
342 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000343 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000344 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
345 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000346 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
347 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000348 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
349 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000350 bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
351 Type *AccessTy, unsigned AddrSpace);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000352 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000353 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000354 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000355 bool optimizeExtUses(Instruction *I);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000356 bool optimizeLoadExt(LoadInst *Load);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000357 bool optimizeSelectInst(SelectInst *SI);
Fangrui Songcb0bab82018-07-16 18:51:40 +0000358 bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
359 bool optimizeSwitchInst(SwitchInst *SI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000360 bool optimizeExtractElementInst(Instruction *Inst);
361 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
362 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000363 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
364 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
365 bool tryToPromoteExts(TypePromotionTransaction &TPT,
366 const SmallVectorImpl<Instruction *> &Exts,
367 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
368 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000369 bool mergeSExts(Function &F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000370 bool splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000371 bool performAddressTypePromotion(
372 Instruction *&Inst,
373 bool AllowPromotionWithoutCommonHeader,
374 bool HasPromoted, TypePromotionTransaction &TPT,
375 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000376 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000377 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000378 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000379
380} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000381
Devang Patel8c78a0b2007-05-03 01:11:54 +0000382char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000383
Matthias Braun1527baa2017-05-25 21:26:32 +0000384INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000385 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000386INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000387INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000388 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000389
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000390FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000391
Chris Lattnerf2836d12007-03-31 04:06:36 +0000392bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000393 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000394 return false;
395
Mehdi Amini4fe37982015-07-07 18:45:17 +0000396 DL = &F.getParent()->getDataLayout();
397
Chris Lattnerf2836d12007-03-31 04:06:36 +0000398 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000399 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000400 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000401 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000402
Devang Patel8f606d72011-03-24 15:35:25 +0000403 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000404 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
405 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000406 SubtargetInfo = TM->getSubtargetImpl(F);
407 TLI = SubtargetInfo->getTargetLowering();
408 TRI = SubtargetInfo->getRegisterInfo();
409 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000410 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000411 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000412 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000413 BPI.reset(new BranchProbabilityInfo(F, *LI));
414 BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000415 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000416
Easwaran Raman0d55b552017-11-14 19:31:51 +0000417 ProfileSummaryInfo *PSI =
Vedant Kumare7b789b2018-11-19 05:23:16 +0000418 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000419 if (ProfileGuidedSectionPrefix) {
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000420 if (PSI->isFunctionHotInCallGraph(&F, *BFI))
Dehao Chen302b69c2016-10-18 20:42:47 +0000421 F.setSectionPrefix(".hot");
Teresa Johnsona4ce3bf2017-12-20 17:53:10 +0000422 else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000423 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000424 }
425
Preston Gurdcdf540d2012-09-04 18:22:17 +0000426 /// This optimization identifies DIV instructions that can be
427 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000428 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
429 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000430 const DenseMap<unsigned int, unsigned int> &BypassWidths =
431 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000432 BasicBlock* BB = &*F.begin();
433 while (BB != nullptr) {
434 // bypassSlowDivision may create new BBs, but we don't want to reapply the
435 // optimization to those blocks.
436 BasicBlock* Next = BB->getNextNode();
437 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
438 BB = Next;
439 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000440 }
441
442 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000443 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000444 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000445
Geoff Berry5d534b62017-02-21 18:53:14 +0000446 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000447 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000448
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000449 // Split some critical edges where one of the sources is an indirect branch,
450 // to help generate sane code for PHIs involving such edges.
Hiroshi Yamauchi9364fa32017-12-04 20:36:01 +0000451 EverMadeChange |= SplitIndirectBrCriticalEdges(F);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000452
Chris Lattnerc3748562007-04-02 01:35:34 +0000453 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000454 while (MadeChange) {
455 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000456 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000457 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000458 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000459 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000460
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000461 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000462 if (ModifiedDTOnIteration)
463 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000464 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000465 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
466 MadeChange |= mergeSExts(F);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +0000467 if (!LargeOffsetGEPMap.empty())
468 MadeChange |= splitLargeGEPOffsets();
Jun Bum Limdee55652017-04-03 19:20:07 +0000469
470 // Really free removed instructions during promotion.
471 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000472 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000473
Chris Lattnerf2836d12007-03-31 04:06:36 +0000474 EverMadeChange |= MadeChange;
Peter Collingbourneabd820a2018-10-23 21:23:18 +0000475 SeenChainsForSExt.clear();
476 ValToSExtendedUses.clear();
477 RemovedInsts.clear();
478 LargeOffsetGEPMap.clear();
479 LargeOffsetGEPID.clear();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000480 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000481
482 SunkAddrs.clear();
483
Cameron Zwarich338d3622011-03-11 21:52:04 +0000484 if (!DisableBranchOpts) {
485 MadeChange = false;
David Stenberg23bba562018-07-02 14:23:48 +0000486 // Use a set vector to get deterministic iteration order. The order the
487 // blocks are removed may affect whether or not PHI nodes in successors
488 // are removed.
489 SmallSetVector<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000490 for (BasicBlock &BB : F) {
491 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
492 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000493 if (!MadeChange) continue;
494
495 for (SmallVectorImpl<BasicBlock*>::iterator
496 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
497 if (pred_begin(*II) == pred_end(*II))
498 WorkList.insert(*II);
499 }
500
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000501 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000502 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000503 while (!WorkList.empty()) {
David Stenberg23bba562018-07-02 14:23:48 +0000504 BasicBlock *BB = WorkList.pop_back_val();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000505 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
506
507 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000508
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000509 for (SmallVectorImpl<BasicBlock*>::iterator
510 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
511 if (pred_begin(*II) == pred_end(*II))
512 WorkList.insert(*II);
513 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000514
Nadav Rotem70409992012-08-14 05:19:07 +0000515 // Merge pairs of basic blocks with unconditional branches, connected by
516 // a single edge.
517 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000518 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000519
Cameron Zwarich338d3622011-03-11 21:52:04 +0000520 EverMadeChange |= MadeChange;
521 }
522
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000523 if (!DisableGCOpts) {
524 SmallVector<Instruction *, 2> Statepoints;
525 for (BasicBlock &BB : F)
526 for (Instruction &I : BB)
527 if (isStatepoint(I))
528 Statepoints.push_back(&I);
529 for (auto &I : Statepoints)
530 EverMadeChange |= simplifyOffsetableRelocate(*I);
531 }
532
Vedant Kumar30406fd2018-08-21 23:43:08 +0000533 // Do this last to clean up use-before-def scenarios introduced by other
534 // preparatory transforms.
535 EverMadeChange |= placeDbgValues(F);
536
Chris Lattnerf2836d12007-03-31 04:06:36 +0000537 return EverMadeChange;
538}
539
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000540/// Merge basic blocks which are connected by a single edge, where one of the
541/// basic blocks has a single successor pointing to the other basic block,
542/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000543bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000544 bool Changed = false;
545 // Scan all of the blocks in the function, except for the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000546 // Use a temporary array to avoid iterator being invalidated when
547 // deleting blocks.
548 SmallVector<WeakTrackingVH, 16> Blocks;
549 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
550 Blocks.push_back(&Block);
551
552 for (auto &Block : Blocks) {
553 auto *BB = cast_or_null<BasicBlock>(Block);
554 if (!BB)
555 continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000556 // If the destination block has a single pred, then this is a trivial
557 // edge, just collapse it.
558 BasicBlock *SinglePred = BB->getSinglePredecessor();
559
Evan Cheng64a223a2012-09-28 23:58:57 +0000560 // Don't merge if BB's address is taken.
561 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000562
563 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
564 if (Term && !Term->isConditional()) {
565 Changed = true;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000566 LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000567
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000568 // Merge BB into SinglePred and delete it.
569 MergeBlockIntoPredecessor(BB);
Nadav Rotem70409992012-08-14 05:19:07 +0000570 }
571 }
572 return Changed;
573}
574
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000575/// Find a destination block from BB if BB is mergeable empty block.
576BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
577 // If this block doesn't end with an uncond branch, ignore it.
578 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
579 if (!BI || !BI->isUnconditional())
580 return nullptr;
581
582 // If the instruction before the branch (skipping debug info) isn't a phi
583 // node, then other stuff is happening here.
584 BasicBlock::iterator BBI = BI->getIterator();
585 if (BBI != BB->begin()) {
586 --BBI;
587 while (isa<DbgInfoIntrinsic>(BBI)) {
588 if (BBI == BB->begin())
589 break;
590 --BBI;
591 }
592 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
593 return nullptr;
594 }
595
596 // Do not break infinite loops.
597 BasicBlock *DestBB = BI->getSuccessor(0);
598 if (DestBB == BB)
599 return nullptr;
600
601 if (!canMergeBlocks(BB, DestBB))
602 DestBB = nullptr;
603
604 return DestBB;
605}
606
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000607/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
608/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
609/// edges in ways that are non-optimal for isel. Start by eliminating these
610/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000611bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000612 SmallPtrSet<BasicBlock *, 16> Preheaders;
613 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
614 while (!LoopList.empty()) {
615 Loop *L = LoopList.pop_back_val();
616 LoopList.insert(LoopList.end(), L->begin(), L->end());
617 if (BasicBlock *Preheader = L->getLoopPreheader())
618 Preheaders.insert(Preheader);
619 }
620
Chris Lattnerc3748562007-04-02 01:35:34 +0000621 bool MadeChange = false;
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000622 // Copy blocks into a temporary array to avoid iterator invalidation issues
623 // as we remove them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000624 // Note that this intentionally skips the entry block.
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000625 SmallVector<WeakTrackingVH, 16> Blocks;
626 for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
627 Blocks.push_back(&Block);
628
629 for (auto &Block : Blocks) {
630 BasicBlock *BB = cast_or_null<BasicBlock>(Block);
631 if (!BB)
632 continue;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000633 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
634 if (!DestBB ||
635 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000636 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000637
Sanjay Patelfc580a62015-09-21 23:03:16 +0000638 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000639 MadeChange = true;
640 }
641 return MadeChange;
642}
643
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000644bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
645 BasicBlock *DestBB,
646 bool isPreheader) {
647 // Do not delete loop preheaders if doing so would create a critical edge.
648 // Loop preheaders can be good locations to spill registers. If the
649 // preheader is deleted and we create a critical edge, registers may be
650 // spilled in the loop body instead.
651 if (!DisablePreheaderProtect && isPreheader &&
652 !(BB->getSinglePredecessor() &&
653 BB->getSinglePredecessor()->getSingleSuccessor()))
654 return false;
655
656 // Try to skip merging if the unique predecessor of BB is terminated by a
657 // switch or indirect branch instruction, and BB is used as an incoming block
658 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
659 // add COPY instructions in the predecessor of BB instead of BB (if it is not
660 // merged). Note that the critical edge created by merging such blocks wont be
661 // split in MachineSink because the jump table is not analyzable. By keeping
662 // such empty block (BB), ISel will place COPY instructions in BB, not in the
663 // predecessor of BB.
664 BasicBlock *Pred = BB->getUniquePredecessor();
665 if (!Pred ||
666 !(isa<SwitchInst>(Pred->getTerminator()) ||
667 isa<IndirectBrInst>(Pred->getTerminator())))
668 return true;
669
Jonas Devlieghere42243df2018-08-07 12:14:01 +0000670 if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000671 return true;
672
673 // We use a simple cost heuristic which determine skipping merging is
674 // profitable if the cost of skipping merging is less than the cost of
675 // merging : Cost(skipping merging) < Cost(merging BB), where the
676 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
677 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
678 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
679 // Freq(Pred) / Freq(BB) > 2.
680 // Note that if there are multiple empty blocks sharing the same incoming
681 // value for the PHIs in the DestBB, we consider them together. In such
682 // case, Cost(merging BB) will be the sum of their frequencies.
683
684 if (!isa<PHINode>(DestBB->begin()))
685 return true;
686
687 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
688
689 // Find all other incoming blocks from which incoming values of all PHIs in
690 // DestBB are the same as the ones from BB.
691 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
692 ++PI) {
693 BasicBlock *DestBBPred = *PI;
694 if (DestBBPred == BB)
695 continue;
696
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000697 if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
698 return DestPN.getIncomingValueForBlock(BB) ==
699 DestPN.getIncomingValueForBlock(DestBBPred);
700 }))
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000701 SameIncomingValueBBs.insert(DestBBPred);
702 }
703
704 // See if all BB's incoming values are same as the value from Pred. In this
705 // case, no reason to skip merging because COPYs are expected to be place in
706 // Pred already.
707 if (SameIncomingValueBBs.count(Pred))
708 return true;
709
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000710 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
711 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
712
713 for (auto SameValueBB : SameIncomingValueBBs)
714 if (SameValueBB->getUniquePredecessor() == Pred &&
715 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
716 BBFreq += BFI->getBlockFreq(SameValueBB);
717
718 return PredFreq.getFrequency() <=
719 BBFreq.getFrequency() * FreqRatioToSkipMerge;
720}
721
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000722/// Return true if we can merge BB into DestBB if there is a single
723/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000724/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000725bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000726 const BasicBlock *DestBB) const {
727 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
728 // the successor. If there are more complex condition (e.g. preheaders),
729 // don't mess around with them.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000730 for (const PHINode &PN : BB->phis()) {
731 for (const User *U : PN.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000732 const Instruction *UI = cast<Instruction>(U);
733 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000734 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000735 // If User is inside DestBB block and it is a PHINode then check
736 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000737 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000738 if (UI->getParent() == DestBB) {
739 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000740 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
741 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
742 if (Insn && Insn->getParent() == BB &&
743 Insn->getParent() != UPN->getIncomingBlock(I))
744 return false;
745 }
746 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000747 }
748 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000749
Chris Lattnerc3748562007-04-02 01:35:34 +0000750 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
751 // and DestBB may have conflicting incoming values for the block. If so, we
752 // can't merge the block.
753 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
754 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000755
Chris Lattnerc3748562007-04-02 01:35:34 +0000756 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000757 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000758 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
759 // It is faster to get preds from a PHI than with pred_iterator.
760 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
761 BBPreds.insert(BBPN->getIncomingBlock(i));
762 } else {
763 BBPreds.insert(pred_begin(BB), pred_end(BB));
764 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000765
Chris Lattnerc3748562007-04-02 01:35:34 +0000766 // Walk the preds of DestBB.
767 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
768 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
769 if (BBPreds.count(Pred)) { // Common predecessor?
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000770 for (const PHINode &PN : DestBB->phis()) {
771 const Value *V1 = PN.getIncomingValueForBlock(Pred);
772 const Value *V2 = PN.getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000773
Chris Lattnerc3748562007-04-02 01:35:34 +0000774 // If V2 is a phi node in BB, look up what the mapped value will be.
775 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
776 if (V2PN->getParent() == BB)
777 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000778
Chris Lattnerc3748562007-04-02 01:35:34 +0000779 // If there is a conflict, bail out.
780 if (V1 != V2) return false;
781 }
782 }
783 }
784
785 return true;
786}
787
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000788/// Eliminate a basic block that has only phi's and an unconditional branch in
789/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000790void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000791 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
792 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000793
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000794 LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
795 << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000796
Chris Lattnerc3748562007-04-02 01:35:34 +0000797 // If the destination block has a single pred, then this is a trivial edge,
798 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000799 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000800 if (SinglePred != DestBB) {
Alina Sbirleadfd14ad2018-06-20 22:01:04 +0000801 assert(SinglePred == BB &&
802 "Single predecessor not the same as predecessor");
803 // Merge DestBB into SinglePred/BB and delete it.
804 MergeBlockIntoPredecessor(DestBB);
805 // Note: BB(=SinglePred) will not be deleted on this path.
806 // DestBB(=its single successor) is the one that was deleted.
807 LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000808 return;
809 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000810 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000811
Chris Lattnerc3748562007-04-02 01:35:34 +0000812 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
813 // to handle the new incoming edges it is about to have.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000814 for (PHINode &PN : DestBB->phis()) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000815 // Remove the incoming value for BB, and remember it.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000816 Value *InVal = PN.removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000817
Chris Lattnerc3748562007-04-02 01:35:34 +0000818 // Two options: either the InVal is a phi node defined in BB or it is some
819 // value that dominates BB.
820 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
821 if (InValPhi && InValPhi->getParent() == BB) {
822 // Add all of the input values of the input PHI as inputs of this phi.
823 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000824 PN.addIncoming(InValPhi->getIncomingValue(i),
825 InValPhi->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000826 } else {
827 // Otherwise, add one instance of the dominating value for each edge that
828 // we will be adding.
829 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
830 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000831 PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
Chris Lattnerc3748562007-04-02 01:35:34 +0000832 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000833 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000834 PN.addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000835 }
836 }
837 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000838
Chris Lattnerc3748562007-04-02 01:35:34 +0000839 // The PHIs are now updated, change everything that refers to BB to use
840 // DestBB and remove BB.
841 BB->replaceAllUsesWith(DestBB);
842 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000843 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000844
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000845 LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000846}
847
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000848// Computes a map of base pointer relocation instructions to corresponding
849// derived pointer relocation instructions given a vector of all relocate calls
850static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000851 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
852 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
853 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000854 // Collect information in two maps: one primarily for locating the base object
855 // while filling the second map; the second map is the final structure holding
856 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000857 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
858 for (auto *ThisRelocate : AllRelocateCalls) {
859 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
860 ThisRelocate->getDerivedPtrIndex());
861 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000862 }
863 for (auto &Item : RelocateIdxMap) {
864 std::pair<unsigned, unsigned> Key = Item.first;
865 if (Key.first == Key.second)
866 // Base relocation: nothing to insert
867 continue;
868
Manuel Jacob83eefa62016-01-05 04:03:00 +0000869 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000870 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000871
872 // We're iterating over RelocateIdxMap so we cannot modify it.
873 auto MaybeBase = RelocateIdxMap.find(BaseKey);
874 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000875 // TODO: We might want to insert a new base object relocate and gep off
876 // that, if there are enough derived object relocates.
877 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000878
879 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000880 }
881}
882
883// Accepts a GEP and extracts the operands into a vector provided they're all
884// small integer constants
885static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
886 SmallVectorImpl<Value *> &OffsetV) {
887 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
888 // Only accept small constant integer operands
889 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
890 if (!Op || Op->getZExtValue() > 20)
891 return false;
892 }
893
894 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
895 OffsetV.push_back(GEP->getOperand(i));
896 return true;
897}
898
899// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
900// replace, computes a replacement, and affects it.
901static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000902simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
903 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000904 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +0000905 // We must ensure the relocation of derived pointer is defined after
906 // relocation of base pointer. If we find a relocation corresponding to base
907 // defined earlier than relocation of base then we move relocation of base
908 // right before found relocation. We consider only relocation in the same
909 // basic block as relocation of base. Relocations from other basic block will
910 // be skipped by optimization and we do not care about them.
911 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
912 &*R != RelocatedBase; ++R)
913 if (auto RI = dyn_cast<GCRelocateInst>(R))
914 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
915 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
916 RelocatedBase->moveBefore(RI);
917 break;
918 }
919
Manuel Jacob83eefa62016-01-05 04:03:00 +0000920 for (GCRelocateInst *ToReplace : Targets) {
921 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000922 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000923 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000924 // A duplicate relocate call. TODO: coalesce duplicates.
925 continue;
926 }
927
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000928 if (RelocatedBase->getParent() != ToReplace->getParent()) {
929 // Base and derived relocates are in different basic blocks.
930 // In this case transform is only valid when base dominates derived
931 // relocate. However it would be too expensive to check dominance
932 // for each such relocate, so we skip the whole transformation.
933 continue;
934 }
935
Manuel Jacob83eefa62016-01-05 04:03:00 +0000936 Value *Base = ToReplace->getBasePtr();
937 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000938 if (!Derived || Derived->getPointerOperand() != Base)
939 continue;
940
941 SmallVector<Value *, 2> OffsetV;
942 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
943 continue;
944
945 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000946 assert(RelocatedBase->getNextNode() &&
947 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000948
949 // Insert after RelocatedBase
950 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000951 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000952
953 // If gc_relocate does not match the actual type, cast it to the right type.
954 // In theory, there must be a bitcast after gc_relocate if the type does not
955 // match, and we should reuse it to get the derived pointer. But it could be
956 // cases like this:
957 // bb1:
958 // ...
959 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
960 // br label %merge
961 //
962 // bb2:
963 // ...
964 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
965 // br label %merge
966 //
967 // merge:
968 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
969 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
970 //
971 // In this case, we can not find the bitcast any more. So we insert a new bitcast
972 // no matter there is already one or not. In this way, we can handle all cases, and
973 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000974 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000975 if (RelocatedBase->getType() != Base->getType()) {
976 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000977 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000978 }
David Blaikie68d535c2015-03-24 22:38:16 +0000979 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000980 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000981 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000982 // If the newly generated derived pointer's type does not match the original derived
983 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000984 Value *ActualReplacement = Replacement;
985 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000986 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000987 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000988 }
989 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000990 ToReplace->eraseFromParent();
991
992 MadeChange = true;
993 }
994 return MadeChange;
995}
996
997// Turns this:
998//
999// %base = ...
1000// %ptr = gep %base + 15
1001// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1002// %base' = relocate(%tok, i32 4, i32 4)
1003// %ptr' = relocate(%tok, i32 4, i32 5)
1004// %val = load %ptr'
1005//
1006// into this:
1007//
1008// %base = ...
1009// %ptr = gep %base + 15
1010// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1011// %base' = gc.relocate(%tok, i32 4, i32 4)
1012// %ptr' = gep %base' + 15
1013// %val = load %ptr'
1014bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1015 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001016 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001017
1018 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001019 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001020 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001021 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001022
1023 // We need atleast one base pointer relocation + one derived pointer
1024 // relocation to mangle
1025 if (AllRelocateCalls.size() < 2)
1026 return false;
1027
1028 // RelocateInstMap is a mapping from the base relocate instruction to the
1029 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001030 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001031 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1032 if (RelocateInstMap.empty())
1033 return false;
1034
1035 for (auto &Item : RelocateInstMap)
1036 // Item.first is the RelocatedBase to offset against
1037 // Item.second is the vector of Targets to replace
1038 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1039 return MadeChange;
1040}
1041
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001042/// SinkCast - Sink the specified cast instruction into its user blocks
1043static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001044 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001045
Chris Lattnerf2836d12007-03-31 04:06:36 +00001046 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001047 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001048
Chris Lattnerf2836d12007-03-31 04:06:36 +00001049 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001050 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001051 UI != E; ) {
1052 Use &TheUse = UI.getUse();
1053 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001054
Chris Lattnerf2836d12007-03-31 04:06:36 +00001055 // Figure out which BB this cast is used in. For PHI's this is the
1056 // appropriate predecessor block.
1057 BasicBlock *UserBB = User->getParent();
1058 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001059 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001060 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001061
Chris Lattnerf2836d12007-03-31 04:06:36 +00001062 // Preincrement use iterator so we don't invalidate it.
1063 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001064
David Majnemer0c80e2e2016-04-27 19:36:38 +00001065 // The first insertion point of a block containing an EH pad is after the
1066 // pad. If the pad is the user, we cannot sink the cast past the pad.
1067 if (User->isEHPad())
1068 continue;
1069
Andrew Kaylord0430e82015-11-23 19:16:15 +00001070 // If the block selected to receive the cast is an EH pad that does not
1071 // allow non-PHI instructions before the terminator, we can't sink the
1072 // cast.
1073 if (UserBB->getTerminator()->isEHPad())
1074 continue;
1075
Chris Lattnerf2836d12007-03-31 04:06:36 +00001076 // If this user is in the same block as the cast, don't change the cast.
1077 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001078
Chris Lattnerf2836d12007-03-31 04:06:36 +00001079 // If we have already inserted a cast into this block, use it.
1080 CastInst *&InsertedCast = InsertedCasts[UserBB];
1081
1082 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001083 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001084 assert(InsertPt != UserBB->end());
1085 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1086 CI->getType(), "", &*InsertPt);
Vedant Kumar9374c042018-05-23 22:03:48 +00001087 InsertedCast->setDebugLoc(CI->getDebugLoc());
Chris Lattnerf2836d12007-03-31 04:06:36 +00001088 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001089
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001090 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001091 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001092 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001093 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001094 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001095
Chris Lattnerf2836d12007-03-31 04:06:36 +00001096 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001097 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001098 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001099 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001100 MadeChange = true;
1101 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001102
Chris Lattnerf2836d12007-03-31 04:06:36 +00001103 return MadeChange;
1104}
1105
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001106/// If the specified cast instruction is a noop copy (e.g. it's casting from
1107/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1108/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001109///
1110/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001111static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1112 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001113 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1114 // than sinking only nop casts, but is helpful on some platforms.
1115 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1116 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1117 ASC->getDestAddressSpace()))
1118 return false;
1119 }
1120
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001121 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001122 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1123 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001124
1125 // This is an fp<->int conversion?
1126 if (SrcVT.isInteger() != DstVT.isInteger())
1127 return false;
1128
1129 // If this is an extension, it will be a zero or sign extension, which
1130 // isn't a noop.
1131 if (SrcVT.bitsLT(DstVT)) return false;
1132
1133 // If these values will be promoted, find out what they will be promoted
1134 // to. This helps us consider truncates on PPC as noop copies when they
1135 // are.
1136 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1137 TargetLowering::TypePromoteInteger)
1138 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1139 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1140 TargetLowering::TypePromoteInteger)
1141 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1142
1143 // If, after promotion, these are the same types, this is a noop copy.
1144 if (SrcVT != DstVT)
1145 return false;
1146
1147 return SinkCast(CI);
1148}
1149
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001150/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1151/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001152///
1153/// Return true if any changes were made.
1154static bool CombineUAddWithOverflow(CmpInst *CI) {
1155 Value *A, *B;
1156 Instruction *AddI;
1157 if (!match(CI,
1158 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1159 return false;
1160
1161 Type *Ty = AddI->getType();
1162 if (!isa<IntegerType>(Ty))
1163 return false;
1164
1165 // We don't want to move around uses of condition values this late, so we we
1166 // check if it is legal to create the call to the intrinsic in the basic
1167 // block containing the icmp:
1168
1169 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1170 return false;
1171
1172#ifndef NDEBUG
1173 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1174 // for now:
1175 if (AddI->hasOneUse())
1176 assert(*AddI->user_begin() == CI && "expected!");
1177#endif
1178
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001179 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001180 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1181
1182 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1183
Vedant Kumara85ca3d2018-08-22 18:15:03 +00001184 DebugLoc Loc = CI->getDebugLoc();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001185 auto *UAddWithOverflow =
1186 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
Vedant Kumara85ca3d2018-08-22 18:15:03 +00001187 UAddWithOverflow->setDebugLoc(Loc);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001188 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
Vedant Kumara85ca3d2018-08-22 18:15:03 +00001189 UAdd->setDebugLoc(Loc);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001190 auto *Overflow =
1191 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
Vedant Kumara85ca3d2018-08-22 18:15:03 +00001192 Overflow->setDebugLoc(Loc);
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001193
1194 CI->replaceAllUsesWith(Overflow);
1195 AddI->replaceAllUsesWith(UAdd);
1196 CI->eraseFromParent();
1197 AddI->eraseFromParent();
1198 return true;
1199}
1200
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001201/// Sink the given CmpInst into user blocks to reduce the number of virtual
1202/// registers that must be created and coalesced. This is a clear win except on
1203/// targets with multiple condition code registers (PowerPC), where it might
1204/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001205///
1206/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001207static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001208 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001209
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001210 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001211 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001212 return false;
1213
1214 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001215 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001216
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001217 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001218 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001219 UI != E; ) {
1220 Use &TheUse = UI.getUse();
1221 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001222
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001223 // Preincrement use iterator so we don't invalidate it.
1224 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001225
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001226 // Don't bother for PHI nodes.
1227 if (isa<PHINode>(User))
1228 continue;
1229
1230 // Figure out which BB this cmp is used in.
1231 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001232
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001233 // If this user is in the same block as the cmp, don't change the cmp.
1234 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001235
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001236 // If we have already inserted a cmp into this block, use it.
1237 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1238
1239 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001240 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001241 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001242 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001243 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1244 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001245 // Propagate the debug info.
1246 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001247 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001248
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001249 // Replace a use of the cmp with a use of the new cmp.
1250 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001251 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001252 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001253 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001254
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001255 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001256 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001257 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001258 MadeChange = true;
1259 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001260
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001261 return MadeChange;
1262}
1263
Peter Zotovf87e5502016-04-03 17:11:53 +00001264static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001265 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001266 return true;
1267
1268 if (CombineUAddWithOverflow(CI))
1269 return true;
1270
1271 return false;
1272}
1273
Geoff Berry5d534b62017-02-21 18:53:14 +00001274/// Duplicate and sink the given 'and' instruction into user blocks where it is
1275/// used in a compare to allow isel to generate better code for targets where
1276/// this operation can be combined.
1277///
1278/// Return true if any changes are made.
1279static bool sinkAndCmp0Expression(Instruction *AndI,
1280 const TargetLowering &TLI,
1281 SetOfInstrs &InsertedInsts) {
1282 // Double-check that we're not trying to optimize an instruction that was
1283 // already optimized by some other part of this pass.
1284 assert(!InsertedInsts.count(AndI) &&
1285 "Attempting to optimize already optimized and instruction");
1286 (void) InsertedInsts;
1287
1288 // Nothing to do for single use in same basic block.
1289 if (AndI->hasOneUse() &&
1290 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1291 return false;
1292
1293 // Try to avoid cases where sinking/duplicating is likely to increase register
1294 // pressure.
1295 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1296 !isa<ConstantInt>(AndI->getOperand(1)) &&
1297 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1298 return false;
1299
1300 for (auto *U : AndI->users()) {
1301 Instruction *User = cast<Instruction>(U);
1302
1303 // Only sink for and mask feeding icmp with 0.
1304 if (!isa<ICmpInst>(User))
1305 return false;
1306
1307 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1308 if (!CmpC || !CmpC->isZero())
1309 return false;
1310 }
1311
1312 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1313 return false;
1314
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001315 LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1316 LLVM_DEBUG(AndI->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001317
1318 // Push the 'and' into the same block as the icmp 0. There should only be
1319 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1320 // others, so we don't need to keep track of which BBs we insert into.
1321 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1322 UI != E; ) {
1323 Use &TheUse = UI.getUse();
1324 Instruction *User = cast<Instruction>(*UI);
1325
1326 // Preincrement use iterator so we don't invalidate it.
1327 ++UI;
1328
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001329 LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
Geoff Berry5d534b62017-02-21 18:53:14 +00001330
1331 // Keep the 'and' in the same place if the use is already in the same block.
1332 Instruction *InsertPt =
1333 User->getParent() == AndI->getParent() ? AndI : User;
1334 Instruction *InsertedAnd =
1335 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1336 AndI->getOperand(1), "", InsertPt);
1337 // Propagate the debug info.
1338 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1339
1340 // Replace a use of the 'and' with a use of the new 'and'.
1341 TheUse = InsertedAnd;
1342 ++NumAndUses;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00001343 LLVM_DEBUG(User->getParent()->dump());
Geoff Berry5d534b62017-02-21 18:53:14 +00001344 }
1345
1346 // We removed all uses, nuke the and.
1347 AndI->eraseFromParent();
1348 return true;
1349}
1350
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001351/// Check if the candidates could be combined with a shift instruction, which
1352/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001353/// 1. Truncate instruction
1354/// 2. And instruction and the imm is a mask of the low bits:
1355/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001356static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001357 if (!isa<TruncInst>(User)) {
1358 if (User->getOpcode() != Instruction::And ||
1359 !isa<ConstantInt>(User->getOperand(1)))
1360 return false;
1361
Quentin Colombetd4f44692014-04-22 01:20:34 +00001362 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001363
Quentin Colombetd4f44692014-04-22 01:20:34 +00001364 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001365 return false;
1366 }
1367 return true;
1368}
1369
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001370/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001371static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001372SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1373 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001374 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001375 BasicBlock *UserBB = User->getParent();
1376 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1377 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1378 bool MadeChange = false;
1379
1380 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1381 TruncE = TruncI->user_end();
1382 TruncUI != TruncE;) {
1383
1384 Use &TruncTheUse = TruncUI.getUse();
1385 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1386 // Preincrement use iterator so we don't invalidate it.
1387
1388 ++TruncUI;
1389
1390 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1391 if (!ISDOpcode)
1392 continue;
1393
Tim Northovere2239ff2014-07-29 10:20:22 +00001394 // If the use is actually a legal node, there will not be an
1395 // implicit truncate.
1396 // FIXME: always querying the result type is just an
1397 // approximation; some nodes' legality is determined by the
1398 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001399 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001400 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001401 continue;
1402
1403 // Don't bother for PHI nodes.
1404 if (isa<PHINode>(TruncUser))
1405 continue;
1406
1407 BasicBlock *TruncUserBB = TruncUser->getParent();
1408
1409 if (UserBB == TruncUserBB)
1410 continue;
1411
1412 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1413 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1414
1415 if (!InsertedShift && !InsertedTrunc) {
1416 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001417 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001418 // Sink the shift
1419 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001420 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1421 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001422 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001423 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1424 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001425 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001426
1427 // Sink the trunc
1428 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1429 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001430 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001431
1432 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001433 TruncI->getType(), "", &*TruncInsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001434 InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001435
1436 MadeChange = true;
1437
1438 TruncTheUse = InsertedTrunc;
1439 }
1440 }
1441 return MadeChange;
1442}
1443
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001444/// Sink the shift *right* instruction into user blocks if the uses could
1445/// potentially be combined with this shift instruction and generate BitExtract
1446/// instruction. It will only be applied if the architecture supports BitExtract
1447/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001448/// BB1:
1449/// %x.extract.shift = lshr i64 %arg1, 32
1450/// BB2:
1451/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1452/// ==>
1453///
1454/// BB2:
1455/// %x.extract.shift.1 = lshr i64 %arg1, 32
1456/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1457///
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001458/// CodeGen will recognize the pattern in BB2 and generate BitExtract
Yi Jiangd069f632014-04-21 19:34:27 +00001459/// instruction.
1460/// Return true if any changes are made.
1461static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001462 const TargetLowering &TLI,
1463 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001464 BasicBlock *DefBB = ShiftI->getParent();
1465
1466 /// Only insert instructions in each block once.
1467 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1468
Mehdi Amini44ede332015-07-09 02:09:04 +00001469 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001470
1471 bool MadeChange = false;
1472 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1473 UI != E;) {
1474 Use &TheUse = UI.getUse();
1475 Instruction *User = cast<Instruction>(*UI);
1476 // Preincrement use iterator so we don't invalidate it.
1477 ++UI;
1478
1479 // Don't bother for PHI nodes.
1480 if (isa<PHINode>(User))
1481 continue;
1482
1483 if (!isExtractBitsCandidateUse(User))
1484 continue;
1485
1486 BasicBlock *UserBB = User->getParent();
1487
1488 if (UserBB == DefBB) {
1489 // If the shift and truncate instruction are in the same BB. The use of
1490 // the truncate(TruncUse) may still introduce another truncate if not
1491 // legal. In this case, we would like to sink both shift and truncate
1492 // instruction to the BB of TruncUse.
1493 // for example:
1494 // BB1:
1495 // i64 shift.result = lshr i64 opnd, imm
1496 // trunc.result = trunc shift.result to i16
1497 //
1498 // BB2:
1499 // ----> We will have an implicit truncate here if the architecture does
1500 // not have i16 compare.
1501 // cmp i16 trunc.result, opnd2
1502 //
1503 if (isa<TruncInst>(User) && shiftIsLegal
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00001504 // If the type of the truncate is legal, no truncate will be
Yi Jiangd069f632014-04-21 19:34:27 +00001505 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001506 &&
1507 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001508 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001509 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001510
1511 continue;
1512 }
1513 // If we have already inserted a shift into this block, use it.
1514 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1515
1516 if (!InsertedShift) {
1517 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001518 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001519
1520 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001521 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1522 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001523 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001524 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1525 "", &*InsertPt);
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001526 InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
Yi Jiangd069f632014-04-21 19:34:27 +00001527
1528 MadeChange = true;
1529 }
1530
1531 // Replace a use of the shift with a use of the new shift.
1532 TheUse = InsertedShift;
1533 }
1534
1535 // If we removed all uses, nuke the shift.
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001536 if (ShiftI->use_empty()) {
1537 salvageDebugInfo(*ShiftI);
Yi Jiangd069f632014-04-21 19:34:27 +00001538 ShiftI->eraseFromParent();
Vedant Kumar1b02dad2018-09-15 04:08:52 +00001539 }
Yi Jiangd069f632014-04-21 19:34:27 +00001540
1541 return MadeChange;
1542}
1543
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001544/// If counting leading or trailing zeros is an expensive operation and a zero
1545/// input is defined, add a check for zero to avoid calling the intrinsic.
1546///
1547/// We want to transform:
1548/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1549///
1550/// into:
1551/// entry:
1552/// %cmpz = icmp eq i64 %A, 0
1553/// br i1 %cmpz, label %cond.end, label %cond.false
1554/// cond.false:
1555/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1556/// br label %cond.end
1557/// cond.end:
1558/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1559///
1560/// If the transform is performed, return true and set ModifiedDT to true.
1561static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1562 const TargetLowering *TLI,
1563 const DataLayout *DL,
1564 bool &ModifiedDT) {
1565 if (!TLI || !DL)
1566 return false;
1567
1568 // If a zero input is undefined, it doesn't make sense to despeculate that.
1569 if (match(CountZeros->getOperand(1), m_One()))
1570 return false;
1571
1572 // If it's cheap to speculate, there's nothing to do.
1573 auto IntrinsicID = CountZeros->getIntrinsicID();
1574 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1575 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1576 return false;
1577
1578 // Only handle legal scalar cases. Anything else requires too much work.
1579 Type *Ty = CountZeros->getType();
1580 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001581 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001582 return false;
1583
1584 // The intrinsic will be sunk behind a compare against zero and branch.
1585 BasicBlock *StartBlock = CountZeros->getParent();
1586 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1587
1588 // Create another block after the count zero intrinsic. A PHI will be added
1589 // in this block to select the result of the intrinsic or the bit-width
1590 // constant if the input to the intrinsic is zero.
1591 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1592 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1593
1594 // Set up a builder to create a compare, conditional branch, and PHI.
1595 IRBuilder<> Builder(CountZeros->getContext());
1596 Builder.SetInsertPoint(StartBlock->getTerminator());
1597 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1598
1599 // Replace the unconditional branch that was created by the first split with
1600 // a compare against zero and a conditional branch.
1601 Value *Zero = Constant::getNullValue(Ty);
1602 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1603 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1604 StartBlock->getTerminator()->eraseFromParent();
1605
1606 // Create a PHI in the end block to select either the output of the intrinsic
1607 // or the bit width of the operand.
1608 Builder.SetInsertPoint(&EndBlock->front());
1609 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1610 CountZeros->replaceAllUsesWith(PN);
1611 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1612 PN->addIncoming(BitWidth, StartBlock);
1613 PN->addIncoming(CountZeros, CallBlock);
1614
1615 // We are explicitly handling the zero case, so we can set the intrinsic's
1616 // undefined zero argument to 'true'. This will also prevent reprocessing the
1617 // intrinsic; we only despeculate when a zero input is defined.
1618 CountZeros->setArgOperand(1, Builder.getTrue());
1619 ModifiedDT = true;
1620 return true;
1621}
1622
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001623bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001624 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001625
Chris Lattner7a277142011-01-15 07:14:54 +00001626 // Lower inline assembly if we can.
1627 // If we found an inline asm expession, and if the target knows how to
1628 // lower it to normal LLVM code, do so now.
1629 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1630 if (TLI->ExpandInlineAsm(CI)) {
1631 // Avoid invalidating the iterator.
1632 CurInstIterator = BB->begin();
1633 // Avoid processing instructions out of order, which could cause
1634 // reuse before a value is defined.
1635 SunkAddrs.clear();
1636 return true;
1637 }
1638 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001639 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001640 return true;
1641 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001642
John Brawn0dbcd652015-03-18 12:01:59 +00001643 // Align the pointer arguments to this call if the target thinks it's a good
1644 // idea
1645 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001646 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001647 for (auto &Arg : CI->arg_operands()) {
1648 // We want to align both objects whose address is used directly and
1649 // objects whose address is used in casts and GEPs, though it only makes
1650 // sense for GEPs if the offset is a multiple of the desired alignment and
1651 // if size - offset meets the size threshold.
1652 if (!Arg->getType()->isPointerTy())
1653 continue;
Elena Demikhovsky945b7e52018-02-14 06:58:08 +00001654 APInt Offset(DL->getIndexSizeInBits(
Mehdi Amini4fe37982015-07-07 18:45:17 +00001655 cast<PointerType>(Arg->getType())->getAddressSpace()),
1656 0);
1657 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001658 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001659 if ((Offset2 & (PrefAlign-1)) != 0)
1660 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001661 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001662 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1663 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001664 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001665 // Global variables can only be aligned if they are defined in this
1666 // object (i.e. they are uniquely initialized in this object), and
1667 // over-aligning global variables that have an explicit section is
1668 // forbidden.
1669 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001670 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001671 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001672 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001673 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001674 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001675 }
1676 // If this is a memcpy (or similar) then we may be able to improve the
1677 // alignment
1678 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Daniel Neilsonbe58a222018-01-31 17:24:53 +00001679 unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
1680 if (DestAlign > MI->getDestAlignment())
1681 MI->setDestAlignment(DestAlign);
1682 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1683 unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
1684 if (SrcAlign > MTI->getSourceAlignment())
1685 MTI->setSourceAlignment(SrcAlign);
1686 }
John Brawn0dbcd652015-03-18 12:01:59 +00001687 }
1688 }
1689
Philip Reamesac115ed2016-03-09 23:13:12 +00001690 // If we have a cold call site, try to sink addressing computation into the
1691 // cold block. This interacts with our handling for loads and stores to
1692 // ensure that we can fold all uses of a potential addressing computation
1693 // into their uses. TODO: generalize this to work over profiling data
1694 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1695 for (auto &Arg : CI->arg_operands()) {
1696 if (!Arg->getType()->isPointerTy())
1697 continue;
1698 unsigned AS = Arg->getType()->getPointerAddressSpace();
1699 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1700 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001701
Eric Christopher4b7948e2010-03-11 02:41:03 +00001702 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001703 if (II) {
1704 switch (II->getIntrinsicID()) {
1705 default: break;
1706 case Intrinsic::objectsize: {
1707 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001708 ConstantInt *RetVal =
1709 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Nadav Rotem465834c2012-07-24 10:51:42 +00001710
James Y Knight72f76bf2018-11-07 15:24:12 +00001711 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1712 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1713 });
1714 return true;
1715 }
1716 case Intrinsic::is_constant: {
1717 // If is_constant hasn't folded away yet, lower it to false now.
1718 Constant *RetVal = ConstantInt::get(II->getType(), 0);
1719 resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
1720 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
1721 });
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001722 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001723 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001724 case Intrinsic::aarch64_stlxr:
1725 case Intrinsic::aarch64_stxr: {
1726 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1727 if (!ExtVal || !ExtVal->hasOneUse() ||
1728 ExtVal->getParent() == CI->getParent())
1729 return false;
1730 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1731 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001732 // Mark this instruction as "inserted by CGP", so that other
1733 // optimizations don't touch it.
1734 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001735 return true;
1736 }
Piotr Padlewski5dde8092018-05-03 11:03:01 +00001737 case Intrinsic::launder_invariant_group:
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001738 case Intrinsic::strip_invariant_group: {
1739 Value *ArgVal = II->getArgOperand(0);
1740 auto it = LargeOffsetGEPMap.find(II);
1741 if (it != LargeOffsetGEPMap.end()) {
1742 // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
1743 // Make sure not to have to deal with iterator invalidation
1744 // after possibly adding ArgVal to LargeOffsetGEPMap.
1745 auto GEPs = std::move(it->second);
1746 LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
1747 LargeOffsetGEPMap.erase(II);
1748 }
1749
1750 II->replaceAllUsesWith(ArgVal);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001751 II->eraseFromParent();
1752 return true;
Krzysztof Pszeniczny2bfe7592018-10-19 19:02:16 +00001753 }
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001754 case Intrinsic::cttz:
1755 case Intrinsic::ctlz:
1756 // If counting zeros is expensive, try to avoid it.
1757 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001758 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001759
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001760 if (TLI) {
1761 SmallVector<Value*, 2> PtrOps;
1762 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001763 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1764 while (!PtrOps.empty()) {
1765 Value *PtrVal = PtrOps.pop_back_val();
1766 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1767 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001768 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001769 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001770 }
Pete Cooper615fd892012-03-13 20:59:56 +00001771 }
1772
Eric Christopher4b7948e2010-03-11 02:41:03 +00001773 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001774 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001775
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001776 // Lower all default uses of _chk calls. This is very similar
1777 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001778 // to fortified library functions (e.g. __memcpy_chk) that have the default
1779 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001780 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001781 if (Value *V = Simplifier.optimizeCall(CI)) {
1782 CI->replaceAllUsesWith(V);
1783 CI->eraseFromParent();
1784 return true;
1785 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001786
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001787 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001788}
Chris Lattner1b93be52011-01-15 07:25:29 +00001789
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001790/// Look for opportunities to duplicate return instructions to the predecessor
1791/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001792/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001793/// bb0:
1794/// %tmp0 = tail call i32 @f0()
1795/// br label %return
1796/// bb1:
1797/// %tmp1 = tail call i32 @f1()
1798/// br label %return
1799/// bb2:
1800/// %tmp2 = tail call i32 @f2()
1801/// br label %return
1802/// return:
1803/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1804/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001805/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001806///
1807/// =>
1808///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001809/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001810/// bb0:
1811/// %tmp0 = tail call i32 @f0()
1812/// ret i32 %tmp0
1813/// bb1:
1814/// %tmp1 = tail call i32 @f1()
1815/// ret i32 %tmp1
1816/// bb2:
1817/// %tmp2 = tail call i32 @f2()
1818/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001819/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001820bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001821 if (!TLI)
1822 return false;
1823
Michael Kuperstein71321562016-09-07 20:29:49 +00001824 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1825 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001826 return false;
1827
Craig Topperc0196b12014-04-14 00:51:57 +00001828 PHINode *PN = nullptr;
1829 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001830 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001831 if (V) {
1832 BCI = dyn_cast<BitCastInst>(V);
1833 if (BCI)
1834 V = BCI->getOperand(0);
1835
1836 PN = dyn_cast<PHINode>(V);
1837 if (!PN)
1838 return false;
1839 }
Evan Cheng0663f232011-03-21 01:19:09 +00001840
Cameron Zwarich4649f172011-03-24 04:52:10 +00001841 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001842 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001843
Cameron Zwarich4649f172011-03-24 04:52:10 +00001844 // Make sure there are no instructions between the PHI and return, or that the
1845 // return is the first instruction in the block.
1846 if (PN) {
1847 BasicBlock::iterator BI = BB->begin();
1848 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001849 if (&*BI == BCI)
1850 // Also skip over the bitcast.
1851 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001852 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001853 return false;
1854 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001855 BasicBlock::iterator BI = BB->begin();
1856 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001857 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001858 return false;
1859 }
Evan Cheng0663f232011-03-21 01:19:09 +00001860
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001861 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1862 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001863 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001864 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001865 if (PN) {
1866 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1867 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1868 // Make sure the phi value is indeed produced by the tail call.
1869 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001870 TLI->mayBeEmittedAsTailCall(CI) &&
1871 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001872 TailCalls.push_back(CI);
1873 }
1874 } else {
1875 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001876 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001877 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001878 continue;
1879
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001880 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001881 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1882 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001883 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1884 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001885 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001886
Cameron Zwarich4649f172011-03-24 04:52:10 +00001887 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001888 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1889 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001890 TailCalls.push_back(CI);
1891 }
Evan Cheng0663f232011-03-21 01:19:09 +00001892 }
1893
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001894 bool Changed = false;
1895 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1896 CallInst *CI = TailCalls[i];
1897 CallSite CS(CI);
1898
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001899 // Make sure the call instruction is followed by an unconditional branch to
1900 // the return block.
1901 BasicBlock *CallBB = CI->getParent();
1902 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1903 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1904 continue;
1905
1906 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001907 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001908 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001909 ++NumRetsDup;
1910 }
1911
1912 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001913 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001914 BB->eraseFromParent();
1915
1916 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001917}
1918
Chris Lattner728f9022008-11-25 07:09:13 +00001919//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001920// Memory Optimization
1921//===----------------------------------------------------------------------===//
1922
Chandler Carruthc8925912013-01-05 02:09:22 +00001923namespace {
1924
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001925/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001926/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001927struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00001928 Value *BaseReg = nullptr;
1929 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00001930 Value *OriginalValue = nullptr;
1931
1932 enum FieldName {
1933 NoField = 0x00,
1934 BaseRegField = 0x01,
1935 BaseGVField = 0x02,
1936 BaseOffsField = 0x04,
1937 ScaledRegField = 0x08,
1938 ScaleField = 0x10,
1939 MultipleFields = 0xff
1940 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00001941
1942 ExtAddrMode() = default;
1943
Chandler Carruthc8925912013-01-05 02:09:22 +00001944 void print(raw_ostream &OS) const;
1945 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001946
John Brawn736bf002017-10-03 13:08:22 +00001947 FieldName compare(const ExtAddrMode &other) {
1948 // First check that the types are the same on each field, as differing types
1949 // is something we can't cope with later on.
1950 if (BaseReg && other.BaseReg &&
1951 BaseReg->getType() != other.BaseReg->getType())
1952 return MultipleFields;
1953 if (BaseGV && other.BaseGV &&
1954 BaseGV->getType() != other.BaseGV->getType())
1955 return MultipleFields;
1956 if (ScaledReg && other.ScaledReg &&
1957 ScaledReg->getType() != other.ScaledReg->getType())
1958 return MultipleFields;
1959
1960 // Check each field to see if it differs.
1961 unsigned Result = NoField;
1962 if (BaseReg != other.BaseReg)
1963 Result |= BaseRegField;
1964 if (BaseGV != other.BaseGV)
1965 Result |= BaseGVField;
1966 if (BaseOffs != other.BaseOffs)
1967 Result |= BaseOffsField;
1968 if (ScaledReg != other.ScaledReg)
1969 Result |= ScaledRegField;
1970 // Don't count 0 as being a different scale, because that actually means
1971 // unscaled (which will already be counted by having no ScaledReg).
1972 if (Scale && other.Scale && Scale != other.Scale)
1973 Result |= ScaleField;
1974
1975 if (countPopulation(Result) > 1)
1976 return MultipleFields;
1977 else
1978 return static_cast<FieldName>(Result);
1979 }
1980
John Brawn4b476482017-11-27 11:29:15 +00001981 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
1982 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00001983 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00001984 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
1985 // trivial if at most one of these terms is nonzero, except that BaseGV and
1986 // BaseReg both being zero actually means a null pointer value, which we
1987 // consider to be 'non-zero' here.
1988 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00001989 }
John Brawn70cdb5b2017-11-24 14:10:45 +00001990
1991 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
1992 switch (Field) {
1993 default:
1994 return nullptr;
1995 case BaseRegField:
1996 return BaseReg;
1997 case BaseGVField:
1998 return BaseGV;
1999 case ScaledRegField:
2000 return ScaledReg;
2001 case BaseOffsField:
2002 return ConstantInt::get(IntPtrTy, BaseOffs);
2003 }
2004 }
2005
2006 void SetCombinedField(FieldName Field, Value *V,
2007 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2008 switch (Field) {
2009 default:
2010 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2011 break;
2012 case ExtAddrMode::BaseRegField:
2013 BaseReg = V;
2014 break;
2015 case ExtAddrMode::BaseGVField:
2016 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2017 // in the BaseReg field.
2018 assert(BaseReg == nullptr);
2019 BaseReg = V;
2020 BaseGV = nullptr;
2021 break;
2022 case ExtAddrMode::ScaledRegField:
2023 ScaledReg = V;
2024 // If we have a mix of scaled and unscaled addrmodes then we want scale
2025 // to be the scale and not zero.
2026 if (!Scale)
2027 for (const ExtAddrMode &AM : AddrModes)
2028 if (AM.Scale) {
2029 Scale = AM.Scale;
2030 break;
2031 }
2032 break;
2033 case ExtAddrMode::BaseOffsField:
2034 // The offset is no longer a constant, so it goes in ScaledReg with a
2035 // scale of 1.
2036 assert(ScaledReg == nullptr);
2037 ScaledReg = V;
2038 Scale = 1;
2039 BaseOffs = 0;
2040 break;
2041 }
2042 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002043};
2044
Eugene Zelenko900b6332017-08-29 22:32:07 +00002045} // end anonymous namespace
2046
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002047#ifndef NDEBUG
2048static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2049 AM.print(OS);
2050 return OS;
2051}
2052#endif
2053
Aaron Ballman615eb472017-10-15 14:32:27 +00002054#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002055void ExtAddrMode::print(raw_ostream &OS) const {
2056 bool NeedPlus = false;
2057 OS << "[";
2058 if (BaseGV) {
2059 OS << (NeedPlus ? " + " : "")
2060 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002061 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002062 NeedPlus = true;
2063 }
2064
Richard Trieuc0f91212014-05-30 03:15:17 +00002065 if (BaseOffs) {
2066 OS << (NeedPlus ? " + " : "")
2067 << BaseOffs;
2068 NeedPlus = true;
2069 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002070
2071 if (BaseReg) {
2072 OS << (NeedPlus ? " + " : "")
2073 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002074 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002075 NeedPlus = true;
2076 }
2077 if (Scale) {
2078 OS << (NeedPlus ? " + " : "")
2079 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002080 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002081 }
2082
2083 OS << ']';
2084}
2085
Yaron Kereneb2a2542016-01-29 20:50:44 +00002086LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002087 print(dbgs());
2088 dbgs() << '\n';
2089}
2090#endif
2091
Eugene Zelenko900b6332017-08-29 22:32:07 +00002092namespace {
2093
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002094/// This class provides transaction based operation on the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002095/// Every change made through this class is recorded in the internal state and
2096/// can be undone (rollback) until commit is called.
2097class TypePromotionTransaction {
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002098 /// This represents the common interface of the individual transaction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002099 /// Each class implements the logic for doing one specific modification on
2100 /// the IR via the TypePromotionTransaction.
2101 class TypePromotionAction {
2102 protected:
2103 /// The Instruction modified.
2104 Instruction *Inst;
2105
2106 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002107 /// Constructor of the action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002108 /// The constructor performs the related action on the IR.
2109 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2110
Eugene Zelenko900b6332017-08-29 22:32:07 +00002111 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002112
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002113 /// Undo the modification done by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002114 /// When this method is called, the IR must be in the same state as it was
2115 /// before this action was applied.
2116 /// \pre Undoing the action works if and only if the IR is in the exact same
2117 /// state as it was directly after this action was applied.
2118 virtual void undo() = 0;
2119
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002120 /// Advocate every change made by this action.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002121 /// When the results on the IR of the action are to be kept, it is important
2122 /// to call this function, otherwise hidden information may be kept forever.
2123 virtual void commit() {
2124 // Nothing to be done, this action is not doing anything.
2125 }
2126 };
2127
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002128 /// Utility to remember the position of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002129 class InsertionHandler {
2130 /// Position of an instruction.
2131 /// Either an instruction:
2132 /// - Is the first in a basic block: BB is used.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002133 /// - Has a previous instruction: PrevInst is used.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002134 union {
2135 Instruction *PrevInst;
2136 BasicBlock *BB;
2137 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002138
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002139 /// Remember whether or not the instruction had a previous instruction.
2140 bool HasPrevInstruction;
2141
2142 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002143 /// Record the position of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002144 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002145 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002146 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2147 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002148 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002149 else
2150 Point.BB = Inst->getParent();
2151 }
2152
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002153 /// Insert \p Inst at the recorded position.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002154 void insert(Instruction *Inst) {
2155 if (HasPrevInstruction) {
2156 if (Inst->getParent())
2157 Inst->removeFromParent();
2158 Inst->insertAfter(Point.PrevInst);
2159 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002160 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002161 if (Inst->getParent())
2162 Inst->moveBefore(Position);
2163 else
2164 Inst->insertBefore(Position);
2165 }
2166 }
2167 };
2168
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002169 /// Move an instruction before another.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002170 class InstructionMoveBefore : public TypePromotionAction {
2171 /// Original position of the instruction.
2172 InsertionHandler Position;
2173
2174 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002175 /// Move \p Inst before \p Before.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002176 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2177 : TypePromotionAction(Inst), Position(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002178 LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
2179 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002180 Inst->moveBefore(Before);
2181 }
2182
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002183 /// Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002184 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002185 LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002186 Position.insert(Inst);
2187 }
2188 };
2189
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002190 /// Set the operand of an instruction with a new value.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002191 class OperandSetter : public TypePromotionAction {
2192 /// Original operand of the instruction.
2193 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002194
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002195 /// Index of the modified instruction.
2196 unsigned Idx;
2197
2198 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002199 /// Set \p Idx operand of \p Inst with \p NewVal.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002200 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2201 : TypePromotionAction(Inst), Idx(Idx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002202 LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2203 << "for:" << *Inst << "\n"
2204 << "with:" << *NewVal << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002205 Origin = Inst->getOperand(Idx);
2206 Inst->setOperand(Idx, NewVal);
2207 }
2208
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002209 /// Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002210 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002211 LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2212 << "for: " << *Inst << "\n"
2213 << "with: " << *Origin << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002214 Inst->setOperand(Idx, Origin);
2215 }
2216 };
2217
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002218 /// Hide the operands of an instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002219 /// Do as if this instruction was not using any of its operands.
2220 class OperandsHider : public TypePromotionAction {
2221 /// The list of original operands.
2222 SmallVector<Value *, 4> OriginalValues;
2223
2224 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002225 /// Remove \p Inst from the uses of the operands of \p Inst.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002226 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002227 LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002228 unsigned NumOpnds = Inst->getNumOperands();
2229 OriginalValues.reserve(NumOpnds);
2230 for (unsigned It = 0; It < NumOpnds; ++It) {
2231 // Save the current operand.
2232 Value *Val = Inst->getOperand(It);
2233 OriginalValues.push_back(Val);
2234 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002235 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002236 // that we are not willing to pay.
2237 Inst->setOperand(It, UndefValue::get(Val->getType()));
2238 }
2239 }
2240
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002241 /// Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002242 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002243 LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002244 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2245 Inst->setOperand(It, OriginalValues[It]);
2246 }
2247 };
2248
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002249 /// Build a truncate instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002250 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002251 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002252
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002253 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002254 /// Build a truncate instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255 /// result.
2256 /// trunc Opnd to Ty.
2257 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2258 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002259 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002260 LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002261 }
2262
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002263 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002264 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002265
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002266 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002267 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002268 LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002269 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2270 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002271 }
2272 };
2273
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002274 /// Build a sign extension instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002275 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002276 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002277
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002278 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002279 /// Build a sign extension instruction of \p Opnd producing a \p Ty
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002280 /// result.
2281 /// sext Opnd to Ty.
2282 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002283 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002285 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002286 LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002287 }
2288
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002289 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002290 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002292 /// Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002293 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002294 LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002295 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2296 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002297 }
2298 };
2299
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002300 /// Build a zero extension instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002301 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002302 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002303
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002304 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002305 /// Build a zero extension instruction of \p Opnd producing a \p Ty
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002306 /// result.
2307 /// zext Opnd to Ty.
2308 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002309 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002310 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002311 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002312 LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002313 }
2314
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002315 /// Get the built value.
Quentin Colombetac55b152014-09-16 22:36:07 +00002316 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002317
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002318 /// Remove the built instruction.
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002319 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002320 LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
Quentin Colombetac55b152014-09-16 22:36:07 +00002321 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2322 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002323 }
2324 };
2325
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002326 /// Mutate an instruction to another type.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002327 class TypeMutator : public TypePromotionAction {
2328 /// Record the original type.
2329 Type *OrigTy;
2330
2331 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002332 /// Mutate the type of \p Inst into \p NewTy.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002333 TypeMutator(Instruction *Inst, Type *NewTy)
2334 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002335 LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2336 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002337 Inst->mutateType(NewTy);
2338 }
2339
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002340 /// Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002341 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002342 LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2343 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002344 Inst->mutateType(OrigTy);
2345 }
2346 };
2347
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002348 /// Replace the uses of an instruction by another instruction.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002349 class UsesReplacer : public TypePromotionAction {
2350 /// Helper structure to keep track of the replaced uses.
2351 struct InstructionAndIdx {
2352 /// The instruction using the instruction.
2353 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002354
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002355 /// The index where this instruction is used for Inst.
2356 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002357
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002358 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2359 : Inst(Inst), Idx(Idx) {}
2360 };
2361
2362 /// Keep track of the original uses (pair Instruction, Index).
2363 SmallVector<InstructionAndIdx, 4> OriginalUses;
Wolfgang Piebac874c42018-12-11 21:13:53 +00002364 /// Keep track of the debug users.
2365 SmallVector<DbgValueInst *, 1> DbgValues;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002366
2367 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002368
2369 public:
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002370 /// Replace all the use of \p Inst by \p New.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002371 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002372 LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2373 << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002374 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002375 for (Use &U : Inst->uses()) {
2376 Instruction *UserI = cast<Instruction>(U.getUser());
2377 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002378 }
Wolfgang Piebac874c42018-12-11 21:13:53 +00002379 // Record the debug uses separately. They are not in the instruction's
2380 // use list, but they are replaced by RAUW.
2381 findDbgValues(DbgValues, Inst);
2382
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002383 // Now, we can replace the uses.
2384 Inst->replaceAllUsesWith(New);
2385 }
2386
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002387 /// Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002388 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002389 LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002390 for (use_iterator UseIt = OriginalUses.begin(),
2391 EndIt = OriginalUses.end();
2392 UseIt != EndIt; ++UseIt) {
2393 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2394 }
Wolfgang Piebac874c42018-12-11 21:13:53 +00002395 // RAUW has replaced all original uses with references to the new value,
2396 // including the debug uses. Since we are undoing the replacements,
2397 // the original debug uses must also be reinstated to maintain the
2398 // correctness and utility of debug value instructions.
2399 for (auto *DVI: DbgValues) {
2400 LLVMContext &Ctx = Inst->getType()->getContext();
2401 auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst));
2402 DVI->setOperand(0, MV);
2403 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002404 }
2405 };
2406
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002407 /// Remove an instruction from the IR.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002408 class InstructionRemover : public TypePromotionAction {
2409 /// Original position of the instruction.
2410 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002411
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002412 /// Helper structure to hide all the link to the instruction. In other
2413 /// words, this helps to do as if the instruction was removed.
2414 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002415
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002416 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002417 UsesReplacer *Replacer = nullptr;
2418
Jun Bum Limdee55652017-04-03 19:20:07 +00002419 /// Keep track of instructions removed.
2420 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002421
2422 public:
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00002423 /// Remove all reference of \p Inst and optionally replace all its
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002424 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002425 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002426 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002427 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2428 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002429 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002430 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002431 if (New)
2432 Replacer = new UsesReplacer(Inst, New);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002433 LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002434 RemovedInsts.insert(Inst);
2435 /// The instructions removed here will be freed after completing
2436 /// optimizeBlock() for all blocks as we need to keep track of the
2437 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002438 Inst->removeFromParent();
2439 }
2440
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002441 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002442
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002443 /// Resurrect the instruction and reassign it to the proper uses if
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002444 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002445 void undo() override {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00002446 LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002447 Inserter.insert(Inst);
2448 if (Replacer)
2449 Replacer->undo();
2450 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002451 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002452 }
2453 };
2454
2455public:
2456 /// Restoration point.
2457 /// The restoration point is a pointer to an action instead of an iterator
2458 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002459 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002460
2461 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2462 : RemovedInsts(RemovedInsts) {}
2463
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464 /// Advocate every changes made in that transaction.
2465 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002466
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002467 /// Undo all the changes made after the given point.
2468 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002469
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002470 /// Get the current restoration point.
2471 ConstRestorationPt getRestorationPoint() const;
2472
2473 /// \name API for IR modification with state keeping to support rollback.
2474 /// @{
2475 /// Same as Instruction::setOperand.
2476 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002477
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002478 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002479 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002480
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002481 /// Same as Value::replaceAllUsesWith.
2482 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002483
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002484 /// Same as Value::mutateType.
2485 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002486
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002487 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002488 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002489
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002490 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002491 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002492
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002493 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002494 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002495
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002496 /// Same as Instruction::moveBefore.
2497 void moveBefore(Instruction *Inst, Instruction *Before);
2498 /// @}
2499
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002500private:
2501 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002502 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002503
2504 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2505
Jun Bum Limdee55652017-04-03 19:20:07 +00002506 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002507};
2508
Eugene Zelenko900b6332017-08-29 22:32:07 +00002509} // end anonymous namespace
2510
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2512 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002513 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2514 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002515}
2516
2517void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2518 Value *NewVal) {
2519 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002520 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2521 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002522}
2523
2524void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2525 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002526 Actions.push_back(
2527 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002528}
2529
2530void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002531 Actions.push_back(
2532 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002533}
2534
Quentin Colombetac55b152014-09-16 22:36:07 +00002535Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2536 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002537 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002538 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002539 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002540 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002541}
2542
Quentin Colombetac55b152014-09-16 22:36:07 +00002543Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2544 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002545 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002546 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002547 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002548 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002549}
2550
Quentin Colombetac55b152014-09-16 22:36:07 +00002551Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2552 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002553 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002554 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002555 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002556 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002557}
2558
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002559void TypePromotionTransaction::moveBefore(Instruction *Inst,
2560 Instruction *Before) {
2561 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002562 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2563 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002564}
2565
2566TypePromotionTransaction::ConstRestorationPt
2567TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002568 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002569}
2570
2571void TypePromotionTransaction::commit() {
2572 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002573 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002574 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002575 Actions.clear();
2576}
2577
2578void TypePromotionTransaction::rollback(
2579 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002580 while (!Actions.empty() && Point != Actions.back().get()) {
2581 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002583 }
2584}
2585
Eugene Zelenko900b6332017-08-29 22:32:07 +00002586namespace {
2587
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002588/// A helper class for matching addressing modes.
Chandler Carruthc8925912013-01-05 02:09:22 +00002589///
2590/// This encapsulates the logic for matching the target-legal addressing modes.
2591class AddressingModeMatcher {
2592 SmallVectorImpl<Instruction*> &AddrModeInsts;
2593 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002594 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002595 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002596
2597 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2598 /// the memory instruction that we're computing this address for.
2599 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002600 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002601 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002602
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002603 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002604 /// part of the return value of this addressing mode matching stuff.
2605 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002606
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002607 /// The instructions inserted by other CodeGenPrepare optimizations.
2608 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002609
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002610 /// A map from the instructions to their type before promotion.
2611 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002612
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002613 /// The ongoing transaction where every action should be registered.
2614 TypePromotionTransaction &TPT;
2615
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002616 // A GEP which has too large offset to be folded into the addressing mode.
2617 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
2618
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002619 /// This is set to true when we should not do profitability checks.
2620 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002621 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002622
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002623 AddressingModeMatcher(
2624 SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
2625 const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
2626 ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
2627 InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
2628 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002629 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002630 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2631 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002632 PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002633 IgnoreProfitability = false;
2634 }
Stephen Lin837bba12013-07-15 17:55:02 +00002635
Eugene Zelenko900b6332017-08-29 22:32:07 +00002636public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002637 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002638 /// give an access type of AccessTy. This returns a list of involved
2639 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002640 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002641 /// optimizations.
2642 /// \p PromotedInsts maps the instructions to their type before promotion.
2643 /// \p The ongoing transaction where every action should be registered.
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002644 static ExtAddrMode
2645 Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
2646 SmallVectorImpl<Instruction *> &AddrModeInsts,
2647 const TargetLowering &TLI, const TargetRegisterInfo &TRI,
2648 const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
2649 TypePromotionTransaction &TPT,
2650 std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002651 ExtAddrMode Result;
2652
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002653 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002654 MemoryInst, Result, InsertedInsts,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00002655 PromotedInsts, TPT, LargeOffsetGEP)
2656 .matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002657 (void)Success; assert(Success && "Couldn't select *anything*?");
2658 return Result;
2659 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002660
Chandler Carruthc8925912013-01-05 02:09:22 +00002661private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002662 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
Fangrui Songcb0bab82018-07-16 18:51:40 +00002663 bool matchAddr(Value *Addr, unsigned Depth);
2664 bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002665 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002666 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002667 ExtAddrMode &AMBefore,
2668 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002669 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2670 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002671 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002672};
2673
Ali Tamurd482b012018-11-12 21:43:43 +00002674class PhiNodeSet;
2675
2676/// An iterator for PhiNodeSet.
2677class PhiNodeSetIterator {
2678 PhiNodeSet * const Set;
2679 size_t CurrentIndex = 0;
2680
2681public:
2682 /// The constructor. Start should point to either a valid element, or be equal
2683 /// to the size of the underlying SmallVector of the PhiNodeSet.
2684 PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
2685 PHINode * operator*() const;
2686 PhiNodeSetIterator& operator++();
2687 bool operator==(const PhiNodeSetIterator &RHS) const;
2688 bool operator!=(const PhiNodeSetIterator &RHS) const;
2689};
2690
2691/// Keeps a set of PHINodes.
2692///
2693/// This is a minimal set implementation for a specific use case:
2694/// It is very fast when there are very few elements, but also provides good
2695/// performance when there are many. It is similar to SmallPtrSet, but also
2696/// provides iteration by insertion order, which is deterministic and stable
2697/// across runs. It is also similar to SmallSetVector, but provides removing
2698/// elements in O(1) time. This is achieved by not actually removing the element
2699/// from the underlying vector, so comes at the cost of using more memory, but
2700/// that is fine, since PhiNodeSets are used as short lived objects.
2701class PhiNodeSet {
2702 friend class PhiNodeSetIterator;
2703
2704 using MapType = SmallDenseMap<PHINode *, size_t, 32>;
2705 using iterator = PhiNodeSetIterator;
2706
2707 /// Keeps the elements in the order of their insertion in the underlying
2708 /// vector. To achieve constant time removal, it never deletes any element.
2709 SmallVector<PHINode *, 32> NodeList;
2710
2711 /// Keeps the elements in the underlying set implementation. This (and not the
2712 /// NodeList defined above) is the source of truth on whether an element
2713 /// is actually in the collection.
2714 MapType NodeMap;
2715
2716 /// Points to the first valid (not deleted) element when the set is not empty
2717 /// and the value is not zero. Equals to the size of the underlying vector
2718 /// when the set is empty. When the value is 0, as in the beginning, the
2719 /// first element may or may not be valid.
2720 size_t FirstValidElement = 0;
2721
2722public:
2723 /// Inserts a new element to the collection.
2724 /// \returns true if the element is actually added, i.e. was not in the
2725 /// collection before the operation.
2726 bool insert(PHINode *Ptr) {
2727 if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
2728 NodeList.push_back(Ptr);
2729 return true;
2730 }
2731 return false;
2732 }
2733
2734 /// Removes the element from the collection.
2735 /// \returns whether the element is actually removed, i.e. was in the
2736 /// collection before the operation.
2737 bool erase(PHINode *Ptr) {
2738 auto it = NodeMap.find(Ptr);
2739 if (it != NodeMap.end()) {
2740 NodeMap.erase(Ptr);
2741 SkipRemovedElements(FirstValidElement);
2742 return true;
2743 }
2744 return false;
2745 }
2746
2747 /// Removes all elements and clears the collection.
2748 void clear() {
2749 NodeMap.clear();
2750 NodeList.clear();
2751 FirstValidElement = 0;
2752 }
2753
2754 /// \returns an iterator that will iterate the elements in the order of
2755 /// insertion.
2756 iterator begin() {
2757 if (FirstValidElement == 0)
2758 SkipRemovedElements(FirstValidElement);
2759 return PhiNodeSetIterator(this, FirstValidElement);
2760 }
2761
2762 /// \returns an iterator that points to the end of the collection.
2763 iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
2764
2765 /// Returns the number of elements in the collection.
2766 size_t size() const {
2767 return NodeMap.size();
2768 }
2769
2770 /// \returns 1 if the given element is in the collection, and 0 if otherwise.
2771 size_t count(PHINode *Ptr) const {
2772 return NodeMap.count(Ptr);
2773 }
2774
2775private:
2776 /// Updates the CurrentIndex so that it will point to a valid element.
2777 ///
2778 /// If the element of NodeList at CurrentIndex is valid, it does not
2779 /// change it. If there are no more valid elements, it updates CurrentIndex
2780 /// to point to the end of the NodeList.
2781 void SkipRemovedElements(size_t &CurrentIndex) {
2782 while (CurrentIndex < NodeList.size()) {
2783 auto it = NodeMap.find(NodeList[CurrentIndex]);
2784 // If the element has been deleted and added again later, NodeMap will
2785 // point to a different index, so CurrentIndex will still be invalid.
2786 if (it != NodeMap.end() && it->second == CurrentIndex)
2787 break;
2788 ++CurrentIndex;
2789 }
2790 }
2791};
2792
2793PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
2794 : Set(Set), CurrentIndex(Start) {}
2795
2796PHINode * PhiNodeSetIterator::operator*() const {
2797 assert(CurrentIndex < Set->NodeList.size() &&
2798 "PhiNodeSet access out of range");
2799 return Set->NodeList[CurrentIndex];
2800}
2801
2802PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
2803 assert(CurrentIndex < Set->NodeList.size() &&
2804 "PhiNodeSet access out of range");
2805 ++CurrentIndex;
2806 Set->SkipRemovedElements(CurrentIndex);
2807 return *this;
2808}
2809
2810bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
2811 return CurrentIndex == RHS.CurrentIndex;
2812}
2813
2814bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
Serge Guelton12c7a962018-11-19 10:05:28 +00002815 return !((*this) == RHS);
Ali Tamurd482b012018-11-12 21:43:43 +00002816}
2817
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002818/// Keep track of simplification of Phi nodes.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002819/// Accept the set of all phi nodes and erase phi node from this set
2820/// if it is simplified.
2821class SimplificationTracker {
2822 DenseMap<Value *, Value *> Storage;
2823 const SimplifyQuery &SQ;
Ali Tamurd482b012018-11-12 21:43:43 +00002824 // Tracks newly created Phi nodes. The elements are iterated by insertion
2825 // order.
2826 PhiNodeSet AllPhiNodes;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002827 // Tracks newly created Select nodes.
2828 SmallPtrSet<SelectInst *, 32> AllSelectNodes;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002829
2830public:
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002831 SimplificationTracker(const SimplifyQuery &sq)
2832 : SQ(sq) {}
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002833
2834 Value *Get(Value *V) {
2835 do {
2836 auto SV = Storage.find(V);
2837 if (SV == Storage.end())
2838 return V;
2839 V = SV->second;
2840 } while (true);
2841 }
2842
2843 Value *Simplify(Value *Val) {
2844 SmallVector<Value *, 32> WorkList;
2845 SmallPtrSet<Value *, 32> Visited;
2846 WorkList.push_back(Val);
2847 while (!WorkList.empty()) {
2848 auto P = WorkList.pop_back_val();
2849 if (!Visited.insert(P).second)
2850 continue;
2851 if (auto *PI = dyn_cast<Instruction>(P))
2852 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2853 for (auto *U : PI->users())
2854 WorkList.push_back(cast<Value>(U));
2855 Put(PI, V);
2856 PI->replaceAllUsesWith(V);
2857 if (auto *PHI = dyn_cast<PHINode>(PI))
Ali Tamurd482b012018-11-12 21:43:43 +00002858 AllPhiNodes.erase(PHI);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002859 if (auto *Select = dyn_cast<SelectInst>(PI))
2860 AllSelectNodes.erase(Select);
2861 PI->eraseFromParent();
2862 }
2863 }
2864 return Get(Val);
2865 }
2866
2867 void Put(Value *From, Value *To) {
2868 Storage.insert({ From, To });
2869 }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002870
2871 void ReplacePhi(PHINode *From, PHINode *To) {
2872 Value* OldReplacement = Get(From);
2873 while (OldReplacement != From) {
2874 From = To;
2875 To = dyn_cast<PHINode>(OldReplacement);
2876 OldReplacement = Get(From);
2877 }
2878 assert(Get(To) == To && "Replacement PHI node is already replaced.");
2879 Put(From, To);
2880 From->replaceAllUsesWith(To);
Ali Tamurd482b012018-11-12 21:43:43 +00002881 AllPhiNodes.erase(From);
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002882 From->eraseFromParent();
2883 }
2884
Ali Tamurd482b012018-11-12 21:43:43 +00002885 PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00002886
2887 void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
2888
2889 void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
2890
2891 unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
2892
2893 unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
2894
2895 void destroyNewNodes(Type *CommonType) {
2896 // For safe erasing, replace the uses with dummy value first.
2897 auto Dummy = UndefValue::get(CommonType);
2898 for (auto I : AllPhiNodes) {
2899 I->replaceAllUsesWith(Dummy);
2900 I->eraseFromParent();
2901 }
2902 AllPhiNodes.clear();
2903 for (auto I : AllSelectNodes) {
2904 I->replaceAllUsesWith(Dummy);
2905 I->eraseFromParent();
2906 }
2907 AllSelectNodes.clear();
2908 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002909};
2910
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002911/// A helper class for combining addressing modes.
John Brawn736bf002017-10-03 13:08:22 +00002912class AddressingModeCombiner {
Serguei Katkov2673f172018-11-29 06:45:18 +00002913 typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002914 typedef std::pair<PHINode *, PHINode *> PHIPair;
2915
John Brawn736bf002017-10-03 13:08:22 +00002916private:
2917 /// The addressing modes we've collected.
2918 SmallVector<ExtAddrMode, 16> AddrModes;
2919
2920 /// The field in which the AddrModes differ, when we have more than one.
2921 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2922
2923 /// Are the AddrModes that we have all just equal to their original values?
2924 bool AllAddrModesTrivial = true;
2925
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002926 /// Common Type for all different fields in addressing modes.
2927 Type *CommonType;
2928
2929 /// SimplifyQuery for simplifyInstruction utility.
2930 const SimplifyQuery &SQ;
2931
2932 /// Original Address.
Serguei Katkov2673f172018-11-29 06:45:18 +00002933 Value *Original;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002934
John Brawn736bf002017-10-03 13:08:22 +00002935public:
Serguei Katkov2673f172018-11-29 06:45:18 +00002936 AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002937 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2938
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002939 /// Get the combined AddrMode
John Brawn736bf002017-10-03 13:08:22 +00002940 const ExtAddrMode &getAddrMode() const {
2941 return AddrModes[0];
2942 }
2943
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002944 /// Add a new AddrMode if it's compatible with the AddrModes we already
John Brawn736bf002017-10-03 13:08:22 +00002945 /// have.
2946 /// \return True iff we succeeded in doing so.
2947 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2948 // Take note of if we have any non-trivial AddrModes, as we need to detect
2949 // when all AddrModes are trivial as then we would introduce a phi or select
2950 // which just duplicates what's already there.
2951 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2952
2953 // If this is the first addrmode then everything is fine.
2954 if (AddrModes.empty()) {
2955 AddrModes.emplace_back(NewAddrMode);
2956 return true;
2957 }
2958
2959 // Figure out how different this is from the other address modes, which we
2960 // can do just by comparing against the first one given that we only care
2961 // about the cumulative difference.
2962 ExtAddrMode::FieldName ThisDifferentField =
2963 AddrModes[0].compare(NewAddrMode);
2964 if (DifferentField == ExtAddrMode::NoField)
2965 DifferentField = ThisDifferentField;
2966 else if (DifferentField != ThisDifferentField)
2967 DifferentField = ExtAddrMode::MultipleFields;
2968
Serguei Katkov17e57942018-01-23 12:07:49 +00002969 // If NewAddrMode differs in more than one dimension we cannot handle it.
2970 bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
2971
2972 // If Scale Field is different then we reject.
2973 CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
2974
Serguei Katkov4d1dd6b2018-01-09 04:37:06 +00002975 // We also must reject the case when base offset is different and
2976 // scale reg is not null, we cannot handle this case due to merge of
2977 // different offsets will be used as ScaleReg.
Serguei Katkov17e57942018-01-23 12:07:49 +00002978 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
2979 !NewAddrMode.ScaledReg);
John Brawn736bf002017-10-03 13:08:22 +00002980
Serguei Katkov17e57942018-01-23 12:07:49 +00002981 // We also must reject the case when GV is different and BaseReg installed
2982 // due to we want to use base reg as a merge of GV values.
2983 CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
2984 !NewAddrMode.HasBaseReg);
2985
2986 // Even if NewAddMode is the same we still need to collect it due to
2987 // original value is different. And later we will need all original values
2988 // as anchors during finding the common Phi node.
2989 if (CanHandle)
2990 AddrModes.emplace_back(NewAddrMode);
2991 else
2992 AddrModes.clear();
2993
2994 return CanHandle;
John Brawn736bf002017-10-03 13:08:22 +00002995 }
2996
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00002997 /// Combine the addressing modes we've collected into a single
John Brawn736bf002017-10-03 13:08:22 +00002998 /// addressing mode.
2999 /// \return True iff we successfully combined them or we only had one so
3000 /// didn't need to combine them anyway.
3001 bool combineAddrModes() {
3002 // If we have no AddrModes then they can't be combined.
3003 if (AddrModes.size() == 0)
3004 return false;
3005
3006 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00003007 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00003008 return true;
3009
3010 // If the AddrModes we collected are all just equal to the value they are
3011 // derived from then combining them wouldn't do anything useful.
3012 if (AllAddrModesTrivial)
3013 return false;
3014
John Brawn70cdb5b2017-11-24 14:10:45 +00003015 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003016 return false;
3017
3018 // Build a map between <original value, basic block where we saw it> to
3019 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00003020 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003021 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00003022 if (!initializeMap(Map))
3023 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003024
3025 Value *CommonValue = findCommon(Map);
3026 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00003027 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003028 return CommonValue != nullptr;
3029 }
3030
3031private:
Serguei Katkov2673f172018-11-29 06:45:18 +00003032 /// Initialize Map with anchor values. For address seen
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003033 /// we set the value of different field saw in this address.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003034 /// At the same time we find a common type for different field we will
3035 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00003036 /// Return false if there is no common type found.
3037 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003038 // Keep track of keys where the value is null. We will need to replace it
3039 // with constant null when we know the common type.
Serguei Katkov2673f172018-11-29 06:45:18 +00003040 SmallVector<Value *, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00003041 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003042 for (auto &AM : AddrModes) {
John Brawn70cdb5b2017-11-24 14:10:45 +00003043 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003044 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00003045 auto *Type = DV->getType();
3046 if (CommonType && CommonType != Type)
3047 return false;
3048 CommonType = Type;
Serguei Katkov2673f172018-11-29 06:45:18 +00003049 Map[AM.OriginalValue] = DV;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003050 } else {
Serguei Katkov2673f172018-11-29 06:45:18 +00003051 NullValue.push_back(AM.OriginalValue);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003052 }
3053 }
3054 assert(CommonType && "At least one non-null value must be!");
Serguei Katkov2673f172018-11-29 06:45:18 +00003055 for (auto *V : NullValue)
3056 Map[V] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00003057 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003058 }
3059
Serguei Katkov2673f172018-11-29 06:45:18 +00003060 /// We have mapping between value A and other value B where B was a field in
3061 /// addressing mode represented by A. Also we have an original value C
3062 /// representing an address we start with. Traversing from C through phi and
3063 /// selects we ended up with A's in a map. This utility function tries to find
3064 /// a value V which is a field in addressing mode C and traversing through phi
3065 /// nodes and selects we will end up in corresponded values B in a map.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003066 /// The utility will create a new Phi/Selects if needed.
3067 // The simple example looks as follows:
3068 // BB1:
3069 // p1 = b1 + 40
3070 // br cond BB2, BB3
3071 // BB2:
3072 // p2 = b2 + 40
3073 // br BB3
3074 // BB3:
3075 // p = phi [p1, BB1], [p2, BB2]
3076 // v = load p
3077 // Map is
Serguei Katkov2673f172018-11-29 06:45:18 +00003078 // p1 -> b1
3079 // p2 -> b2
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003080 // Request is
Serguei Katkov2673f172018-11-29 06:45:18 +00003081 // p -> ?
3082 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003083 Value *findCommon(FoldAddrToValueMapping &Map) {
Eric Christopherd72f78e2018-01-09 23:25:38 +00003084 // Tracks the simplification of newly created phi nodes. The reason we use
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003085 // this mapping is because we will add new created Phi nodes in AddrToBase.
3086 // Simplification of Phi nodes is recursive, so some Phi node may
Serguei Katkov2673f172018-11-29 06:45:18 +00003087 // be simplified after we added it to AddrToBase. In reality this
3088 // simplification is possible only if original phi/selects were not
3089 // simplified yet.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003090 // Using this mapping we can find the current value in AddrToBase.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003091 SimplificationTracker ST(SQ);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003092
3093 // First step, DFS to create PHI nodes for all intermediate blocks.
3094 // Also fill traverse order for the second step.
Serguei Katkov2673f172018-11-29 06:45:18 +00003095 SmallVector<Value *, 32> TraverseOrder;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003096 InsertPlaceholders(Map, TraverseOrder, ST);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003097
3098 // Second Step, fill new nodes by merged values and simplify if possible.
3099 FillPlaceholders(Map, TraverseOrder, ST);
3100
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003101 if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
3102 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003103 return nullptr;
3104 }
3105
3106 // Now we'd like to match New Phi nodes to existed ones.
3107 unsigned PhiNotMatchedCount = 0;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003108 if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3109 ST.destroyNewNodes(CommonType);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003110 return nullptr;
3111 }
3112
3113 auto *Result = ST.Get(Map.find(Original)->second);
3114 if (Result) {
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003115 NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
3116 NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003117 }
3118 return Result;
3119 }
3120
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003121 /// Try to match PHI node to Candidate.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003122 /// Matcher tracks the matched Phi nodes.
3123 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003124 SmallSetVector<PHIPair, 8> &Matcher,
Ali Tamurd482b012018-11-12 21:43:43 +00003125 PhiNodeSet &PhiNodesToMatch) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003126 SmallVector<PHIPair, 8> WorkList;
3127 Matcher.insert({ PHI, Candidate });
3128 WorkList.push_back({ PHI, Candidate });
3129 SmallSet<PHIPair, 8> Visited;
3130 while (!WorkList.empty()) {
3131 auto Item = WorkList.pop_back_val();
3132 if (!Visited.insert(Item).second)
3133 continue;
3134 // We iterate over all incoming values to Phi to compare them.
3135 // If values are different and both of them Phi and the first one is a
3136 // Phi we added (subject to match) and both of them is in the same basic
3137 // block then we can match our pair if values match. So we state that
3138 // these values match and add it to work list to verify that.
3139 for (auto B : Item.first->blocks()) {
3140 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3141 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3142 if (FirstValue == SecondValue)
3143 continue;
3144
3145 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3146 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3147
3148 // One of them is not Phi or
3149 // The first one is not Phi node from the set we'd like to match or
3150 // Phi nodes from different basic blocks then
3151 // we will not be able to match.
3152 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3153 FirstPhi->getParent() != SecondPhi->getParent())
3154 return false;
3155
3156 // If we already matched them then continue.
3157 if (Matcher.count({ FirstPhi, SecondPhi }))
3158 continue;
3159 // So the values are different and does not match. So we need them to
3160 // match.
3161 Matcher.insert({ FirstPhi, SecondPhi });
3162 // But me must check it.
3163 WorkList.push_back({ FirstPhi, SecondPhi });
3164 }
3165 }
3166 return true;
3167 }
3168
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003169 /// For the given set of PHI nodes (in the SimplificationTracker) try
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003170 /// to find their equivalents.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003171 /// Returns false if this matching fails and creation of new Phi is disabled.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003172 bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003173 unsigned &PhiNotMatchedCount) {
Ali Tamurd482b012018-11-12 21:43:43 +00003174 // Matched and PhiNodesToMatch iterate their elements in a deterministic
3175 // order, so the replacements (ReplacePhi) are also done in a deterministic
3176 // order.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003177 SmallSetVector<PHIPair, 8> Matched;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003178 SmallPtrSet<PHINode *, 8> WillNotMatch;
Ali Tamurd482b012018-11-12 21:43:43 +00003179 PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003180 while (PhiNodesToMatch.size()) {
3181 PHINode *PHI = *PhiNodesToMatch.begin();
3182
3183 // Add us, if no Phi nodes in the basic block we do not match.
3184 WillNotMatch.clear();
3185 WillNotMatch.insert(PHI);
3186
3187 // Traverse all Phis until we found equivalent or fail to do that.
3188 bool IsMatched = false;
3189 for (auto &P : PHI->getParent()->phis()) {
3190 if (&P == PHI)
3191 continue;
3192 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3193 break;
3194 // If it does not match, collect all Phi nodes from matcher.
3195 // if we end up with no match, them all these Phi nodes will not match
3196 // later.
3197 for (auto M : Matched)
3198 WillNotMatch.insert(M.first);
3199 Matched.clear();
3200 }
3201 if (IsMatched) {
Serguei Katkova20e05b2018-03-12 03:50:07 +00003202 // Replace all matched values and erase them.
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003203 for (auto MV : Matched)
3204 ST.ReplacePhi(MV.first, MV.second);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003205 Matched.clear();
3206 continue;
3207 }
3208 // If we are not allowed to create new nodes then bail out.
3209 if (!AllowNewPhiNodes)
3210 return false;
3211 // Just remove all seen values in matcher. They will not match anything.
3212 PhiNotMatchedCount += WillNotMatch.size();
3213 for (auto *P : WillNotMatch)
Ali Tamurd482b012018-11-12 21:43:43 +00003214 PhiNodesToMatch.erase(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003215 }
3216 return true;
3217 }
Serguei Katkov2673f172018-11-29 06:45:18 +00003218 /// Fill the placeholders with values from predecessors and simplify them.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003219 void FillPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003220 SmallVectorImpl<Value *> &TraverseOrder,
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003221 SimplificationTracker &ST) {
3222 while (!TraverseOrder.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003223 Value *Current = TraverseOrder.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003224 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003225 Value *V = Map[Current];
3226
3227 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3228 // CurrentValue also must be Select.
Serguei Katkov2673f172018-11-29 06:45:18 +00003229 auto *CurrentSelect = cast<SelectInst>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003230 auto *TrueValue = CurrentSelect->getTrueValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003231 assert(Map.find(TrueValue) != Map.end() && "No True Value!");
3232 Select->setTrueValue(ST.Get(Map[TrueValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003233 auto *FalseValue = CurrentSelect->getFalseValue();
Serguei Katkov2673f172018-11-29 06:45:18 +00003234 assert(Map.find(FalseValue) != Map.end() && "No False Value!");
3235 Select->setFalseValue(ST.Get(Map[FalseValue]));
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003236 } else {
3237 // Must be a Phi node then.
3238 PHINode *PHI = cast<PHINode>(V);
Serguei Katkov2673f172018-11-29 06:45:18 +00003239 auto *CurrentPhi = dyn_cast<PHINode>(Current);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003240 // Fill the Phi node with values from predecessors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003241 for (auto B : predecessors(PHI->getParent())) {
3242 Value *PV = CurrentPhi->getIncomingValueForBlock(B);
3243 assert(Map.find(PV) != Map.end() && "No predecessor Value!");
3244 PHI->addIncoming(ST.Get(Map[PV]), B);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003245 }
3246 }
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003247 Map[Current] = ST.Simplify(V);
3248 }
3249 }
3250
Serguei Katkov2673f172018-11-29 06:45:18 +00003251 /// Starting from original value recursively iterates over def-use chain up to
3252 /// known ending values represented in a map. For each traversed phi/select
3253 /// inserts a placeholder Phi or Select.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003254 /// Reports all new created Phi/Select nodes by adding them to set.
Serguei Katkov2673f172018-11-29 06:45:18 +00003255 /// Also reports and order in what values have been traversed.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003256 void InsertPlaceholders(FoldAddrToValueMapping &Map,
Serguei Katkov2673f172018-11-29 06:45:18 +00003257 SmallVectorImpl<Value *> &TraverseOrder,
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003258 SimplificationTracker &ST) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003259 SmallVector<Value *, 32> Worklist;
3260 assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003261 "Address must be a Phi or Select node");
3262 auto *Dummy = UndefValue::get(CommonType);
3263 Worklist.push_back(Original);
3264 while (!Worklist.empty()) {
Serguei Katkov2673f172018-11-29 06:45:18 +00003265 Value *Current = Worklist.pop_back_val();
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003266 // if it is already visited or it is an ending value then skip it.
3267 if (Map.find(Current) != Map.end())
3268 continue;
3269 TraverseOrder.push_back(Current);
3270
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003271 // CurrentValue must be a Phi node or select. All others must be covered
3272 // by anchors.
Serguei Katkov2673f172018-11-29 06:45:18 +00003273 if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003274 // Is it OK to get metadata from OrigSelect?!
3275 // Create a Select placeholder with dummy value.
Serguei Katkov2673f172018-11-29 06:45:18 +00003276 SelectInst *Select = SelectInst::Create(
3277 CurrentSelect->getCondition(), Dummy, Dummy,
3278 CurrentSelect->getName(), CurrentSelect, CurrentSelect);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003279 Map[Current] = Select;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003280 ST.insertNewSelect(Select);
Serguei Katkov2673f172018-11-29 06:45:18 +00003281 // We are interested in True and False values.
3282 Worklist.push_back(CurrentSelect->getTrueValue());
3283 Worklist.push_back(CurrentSelect->getFalseValue());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003284 } else {
3285 // It must be a Phi node then.
Serguei Katkov2673f172018-11-29 06:45:18 +00003286 PHINode *CurrentPhi = cast<PHINode>(Current);
3287 unsigned PredCount = CurrentPhi->getNumIncomingValues();
3288 PHINode *PHI =
3289 PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003290 Map[Current] = PHI;
Bjorn Petterssonbf3213e2018-03-20 09:06:37 +00003291 ST.insertNewPhi(PHI);
Serguei Katkov2673f172018-11-29 06:45:18 +00003292 for (Value *P : CurrentPhi->incoming_values())
3293 Worklist.push_back(P);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00003294 }
3295 }
John Brawn736bf002017-10-03 13:08:22 +00003296 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003297
3298 bool addrModeCombiningAllowed() {
3299 if (DisableComplexAddrModes)
3300 return false;
3301 switch (DifferentField) {
3302 default:
3303 return false;
3304 case ExtAddrMode::BaseRegField:
3305 return AddrSinkCombineBaseReg;
3306 case ExtAddrMode::BaseGVField:
3307 return AddrSinkCombineBaseGV;
3308 case ExtAddrMode::BaseOffsField:
3309 return AddrSinkCombineBaseOffs;
3310 case ExtAddrMode::ScaledRegField:
3311 return AddrSinkCombineScaledReg;
3312 }
3313 }
John Brawn736bf002017-10-03 13:08:22 +00003314};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003315} // end anonymous namespace
3316
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003317/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003318/// Return true and update AddrMode if this addr mode is legal for the target,
3319/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003320bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003321 unsigned Depth) {
3322 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3323 // mode. Just process that directly.
3324 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003325 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003326
Chandler Carruthc8925912013-01-05 02:09:22 +00003327 // If the scale is 0, it takes nothing to add this.
3328 if (Scale == 0)
3329 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003330
Chandler Carruthc8925912013-01-05 02:09:22 +00003331 // If we already have a scale of this value, we can add to it, otherwise, we
3332 // need an available scale field.
3333 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3334 return false;
3335
3336 ExtAddrMode TestAddrMode = AddrMode;
3337
3338 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3339 // [A+B + A*7] -> [B+A*8].
3340 TestAddrMode.Scale += Scale;
3341 TestAddrMode.ScaledReg = ScaleReg;
3342
3343 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003344 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003345 return false;
3346
3347 // It was legal, so commit it.
3348 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003349
Chandler Carruthc8925912013-01-05 02:09:22 +00003350 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3351 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3352 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003353 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003354 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3355 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3356 TestAddrMode.ScaledReg = AddLHS;
3357 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003358
Chandler Carruthc8925912013-01-05 02:09:22 +00003359 // If this addressing mode is legal, commit it and remember that we folded
3360 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003361 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003362 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3363 AddrMode = TestAddrMode;
3364 return true;
3365 }
3366 }
3367
3368 // Otherwise, not (x+c)*scale, just return what we have.
3369 return true;
3370}
3371
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003372/// This is a little filter, which returns true if an addressing computation
3373/// involving I might be folded into a load/store accessing it.
3374/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003375/// the set of instructions that MatchOperationAddr can.
3376static bool MightBeFoldableInst(Instruction *I) {
3377 switch (I->getOpcode()) {
3378 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003379 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003380 // Don't touch identity bitcasts.
3381 if (I->getType() == I->getOperand(0)->getType())
3382 return false;
Vedant Kumarb3091da2018-07-06 20:17:42 +00003383 return I->getType()->isIntOrPtrTy();
Chandler Carruthc8925912013-01-05 02:09:22 +00003384 case Instruction::PtrToInt:
3385 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3386 return true;
3387 case Instruction::IntToPtr:
3388 // We know the input is intptr_t, so this is foldable.
3389 return true;
3390 case Instruction::Add:
3391 return true;
3392 case Instruction::Mul:
3393 case Instruction::Shl:
3394 // Can only handle X*C and X << C.
3395 return isa<ConstantInt>(I->getOperand(1));
3396 case Instruction::GetElementPtr:
3397 return true;
3398 default:
3399 return false;
3400 }
3401}
3402
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003403/// Check whether or not \p Val is a legal instruction for \p TLI.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003404/// \note \p Val is assumed to be the product of some type promotion.
3405/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3406/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003407static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3408 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003409 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3410 if (!PromotedInst)
3411 return false;
3412 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3413 // If the ISDOpcode is undefined, it was undefined before the promotion.
3414 if (!ISDOpcode)
3415 return true;
3416 // Otherwise, check if the promoted instruction is legal or not.
3417 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003418 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003419}
3420
Eugene Zelenko900b6332017-08-29 22:32:07 +00003421namespace {
3422
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003423/// Hepler class to perform type promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003424class TypePromotionHelper {
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003425 /// Utility function to add a promoted instruction \p ExtOpnd to
3426 /// \p PromotedInsts and record the type of extension we have seen.
3427 static void addPromotedInst(InstrToOrigTy &PromotedInsts,
3428 Instruction *ExtOpnd,
3429 bool IsSExt) {
3430 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3431 InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
3432 if (It != PromotedInsts.end()) {
3433 // If the new extension is same as original, the information in
3434 // PromotedInsts[ExtOpnd] is still correct.
3435 if (It->second.getInt() == ExtTy)
3436 return;
3437
3438 // Now the new extension is different from old extension, we make
3439 // the type information invalid by setting extension type to
3440 // BothExtension.
3441 ExtTy = BothExtension;
3442 }
3443 PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
3444 }
3445
3446 /// Utility function to query the original type of instruction \p Opnd
3447 /// with a matched extension type. If the extension doesn't match, we
3448 /// cannot use the information we had on the original type.
3449 /// BothExtension doesn't match any extension type.
3450 static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
3451 Instruction *Opnd,
3452 bool IsSExt) {
3453 ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
3454 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
3455 if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
3456 return It->second.getPointer();
3457 return nullptr;
3458 }
3459
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003460 /// Utility function to check whether or not a sign or zero extension
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003461 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3462 /// either using the operands of \p Inst or promoting \p Inst.
3463 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003464 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003465 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003466 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003467 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003468 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003469 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003470 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003471 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3472 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003473
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003474 /// Utility function to determine if \p OpIdx should be promoted when
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003475 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003476 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003477 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003478 }
3479
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003480 /// Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003481 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003482 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003483 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003484 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003485 /// Newly added extensions are inserted in \p Exts.
3486 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003487 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003488 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003489 static Value *promoteOperandForTruncAndAnyExt(
3490 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003491 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003492 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003493 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003494
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00003495 /// Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003496 /// operand is promotable and is not a supported trunc or sext.
3497 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003498 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003499 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003500 /// Newly added extensions are inserted in \p Exts.
3501 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003502 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003503 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003504 static Value *promoteOperandForOther(Instruction *Ext,
3505 TypePromotionTransaction &TPT,
3506 InstrToOrigTy &PromotedInsts,
3507 unsigned &CreatedInstsCost,
3508 SmallVectorImpl<Instruction *> *Exts,
3509 SmallVectorImpl<Instruction *> *Truncs,
3510 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003511
3512 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003513 static Value *signExtendOperandForOther(
3514 Instruction *Ext, TypePromotionTransaction &TPT,
3515 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3516 SmallVectorImpl<Instruction *> *Exts,
3517 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3518 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3519 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003520 }
3521
3522 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003523 static Value *zeroExtendOperandForOther(
3524 Instruction *Ext, TypePromotionTransaction &TPT,
3525 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3526 SmallVectorImpl<Instruction *> *Exts,
3527 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3528 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3529 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003530 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003531
3532public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003533 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003534 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3535 InstrToOrigTy &PromotedInsts,
3536 unsigned &CreatedInstsCost,
3537 SmallVectorImpl<Instruction *> *Exts,
3538 SmallVectorImpl<Instruction *> *Truncs,
3539 const TargetLowering &TLI);
3540
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003541 /// Given a sign/zero extend instruction \p Ext, return the appropriate
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003542 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003543 /// \return NULL if no promotable action is possible with the current
3544 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003545 /// \p InsertedInsts keeps track of all the instructions inserted by the
3546 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003547 /// because we do not want to promote these instructions as CodeGenPrepare
3548 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3549 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003550 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003551 const TargetLowering &TLI,
3552 const InstrToOrigTy &PromotedInsts);
3553};
3554
Eugene Zelenko900b6332017-08-29 22:32:07 +00003555} // end anonymous namespace
3556
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003557bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003558 Type *ConsideredExtType,
3559 const InstrToOrigTy &PromotedInsts,
3560 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003561 // The promotion helper does not know how to deal with vector types yet.
3562 // To be able to fix that, we would need to fix the places where we
3563 // statically extend, e.g., constants and such.
3564 if (Inst->getType()->isVectorTy())
3565 return false;
3566
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003567 // We can always get through zext.
3568 if (isa<ZExtInst>(Inst))
3569 return true;
3570
3571 // sext(sext) is ok too.
3572 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003573 return true;
3574
3575 // We can get through binary operator, if it is legal. In other words, the
3576 // binary operator must have a nuw or nsw flag.
3577 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3578 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003579 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3580 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003581 return true;
3582
Guozhi Weic4c6b542018-06-05 21:03:52 +00003583 // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
3584 if ((Inst->getOpcode() == Instruction::And ||
3585 Inst->getOpcode() == Instruction::Or))
3586 return true;
3587
3588 // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
3589 if (Inst->getOpcode() == Instruction::Xor) {
3590 const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
3591 // Make sure it is not a NOT.
3592 if (Cst && !Cst->getValue().isAllOnesValue())
3593 return true;
3594 }
3595
3596 // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
3597 // It may change a poisoned value into a regular value, like
3598 // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
3599 // poisoned value regular value
3600 // It should be OK since undef covers valid value.
3601 if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
3602 return true;
3603
3604 // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
3605 // It may change a poisoned value into a regular value, like
3606 // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
3607 // poisoned value regular value
3608 // It should be OK since undef covers valid value.
3609 if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
3610 const Instruction *ExtInst =
3611 dyn_cast<const Instruction>(*Inst->user_begin());
3612 if (ExtInst->hasOneUse()) {
3613 const Instruction *AndInst =
3614 dyn_cast<const Instruction>(*ExtInst->user_begin());
3615 if (AndInst && AndInst->getOpcode() == Instruction::And) {
3616 const ConstantInt *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
3617 if (Cst &&
3618 Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
3619 return true;
3620 }
3621 }
3622 }
3623
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003624 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003625 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003626 if (!isa<TruncInst>(Inst))
3627 return false;
3628
3629 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003630 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003631 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003632 if (!OpndVal->getType()->isIntegerTy() ||
3633 OpndVal->getType()->getIntegerBitWidth() >
3634 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003635 return false;
3636
3637 // If the operand of the truncate is not an instruction, we will not have
3638 // any information on the dropped bits.
3639 // (Actually we could for constant but it is not worth the extra logic).
3640 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3641 if (!Opnd)
3642 return false;
3643
3644 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003645 // I.e., check that trunc just drops extended bits of the same kind of
3646 // the extension.
3647 // #1 get the type of the operand and check the kind of the extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003648 const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
3649 if (OpndType)
3650 ;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003651 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3652 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003653 else
3654 return false;
3655
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003656 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003657 return Inst->getType()->getIntegerBitWidth() >=
3658 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003659}
3660
3661TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003662 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003663 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003664 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3665 "Unexpected instruction type");
3666 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3667 Type *ExtTy = Ext->getType();
3668 bool IsSExt = isa<SExtInst>(Ext);
3669 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003670 // get through.
3671 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003672 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003673 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003674
3675 // Do not promote if the operand has been added by codegenprepare.
3676 // Otherwise, it means we are undoing an optimization that is likely to be
3677 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003678 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003679 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003680
3681 // SExt or Trunc instructions.
3682 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003683 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3684 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003685 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003686
3687 // Regular instruction.
3688 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003689 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003690 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003691 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003692}
3693
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003694Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003695 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003696 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003697 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003698 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003699 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3700 // get through it and this method should not be called.
3701 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003702 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003703 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003704 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003705 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003706 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003707 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003708 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003709 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3710 TPT.replaceAllUsesWith(SExt, ZExt);
3711 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003712 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003713 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003714 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3715 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003716 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3717 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003718 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003719
3720 // Remove dead code.
3721 if (SExtOpnd->use_empty())
3722 TPT.eraseInstruction(SExtOpnd);
3723
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003724 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003725 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003726 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003727 if (ExtInst) {
3728 if (Exts)
3729 Exts->push_back(ExtInst);
3730 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3731 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003732 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003733 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003734
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003735 // At this point we have: ext ty opnd to ty.
3736 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3737 Value *NextVal = ExtInst->getOperand(0);
3738 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003739 return NextVal;
3740}
3741
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003742Value *TypePromotionHelper::promoteOperandForOther(
3743 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003744 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003745 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003746 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3747 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003748 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003749 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003750 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003751 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003752 if (!ExtOpnd->hasOneUse()) {
3753 // ExtOpnd will be promoted.
3754 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003755 // promoted version.
3756 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003757 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003758 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003759 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003760 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003761 if (Truncs)
3762 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003763 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003764
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003765 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003766 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003767 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003768 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003769 }
3770
3771 // Get through the Instruction:
3772 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003773 // 2. Replace the uses of Ext by Inst.
3774 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003775
3776 // Remember the original type of the instruction before promotion.
3777 // This is useful to know that the high bits are sign extended bits.
Guozhi Wei8c17f9a2018-08-15 22:08:26 +00003778 addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003779 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003780 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003781 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003782 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003783 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003784 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003785
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003786 LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003787 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003788 ++OpIdx) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003789 LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003790 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3791 !shouldExtOperand(ExtOpnd, OpIdx)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003792 LLVM_DEBUG(dbgs() << "No need to propagate\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003793 continue;
3794 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003795 // Check if we can statically extend the operand.
3796 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003797 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003798 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003799 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3800 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3801 : Cst->getValue().zext(BitWidth);
3802 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003803 continue;
3804 }
3805 // UndefValue are typed, so we have to statically sign extend them.
3806 if (isa<UndefValue>(Opnd)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003807 LLVM_DEBUG(dbgs() << "Statically extend\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003808 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003809 continue;
3810 }
3811
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00003812 // Otherwise we have to explicitly sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003813 // Check if Ext was reused to extend an operand.
3814 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003815 // If yes, create a new one.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003816 LLVM_DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003817 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3818 : TPT.createZExt(Ext, Opnd, Ext->getType());
3819 if (!isa<Instruction>(ValForExtOpnd)) {
3820 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3821 continue;
3822 }
3823 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003824 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003825 if (Exts)
3826 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003827 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003828
3829 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003830 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3831 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003832 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003833 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003834 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003835 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003836 if (ExtForOpnd == Ext) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003837 LLVM_DEBUG(dbgs() << "Extension is useless now\n");
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003838 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003839 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003840 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003841}
3842
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003843/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003844/// \p NewCost gives the cost of extension instructions created by the
3845/// promotion.
3846/// \p OldCost gives the cost of extension instructions before the promotion
3847/// plus the number of instructions that have been
3848/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003849/// \p PromotedOperand is the value that has been promoted.
3850/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003851bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003852 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003853 LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
3854 << '\n');
Quentin Colombet1b274f92015-03-10 21:48:15 +00003855 // The cost of the new extensions is greater than the cost of the
3856 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003857 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003858 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003859 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003860 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003861 return true;
3862 // The promotion is neutral but it may help folding the sign extension in
3863 // loads for instance.
3864 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003865 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003866}
3867
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003868/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003869/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003870/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003871/// If \p MovedAway is not NULL, it contains the information of whether or
3872/// not AddrInst has to be folded into the addressing mode on success.
3873/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3874/// because it has been moved away.
3875/// Thus AddrInst must not be added in the matched instructions.
3876/// This state can happen when AddrInst is a sext, since it may be moved away.
3877/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3878/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003879bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003880 unsigned Depth,
3881 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003882 // Avoid exponential behavior on extremely deep expression trees.
3883 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003884
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003885 // By default, all matched instructions stay in place.
3886 if (MovedAway)
3887 *MovedAway = false;
3888
Chandler Carruthc8925912013-01-05 02:09:22 +00003889 switch (Opcode) {
3890 case Instruction::PtrToInt:
3891 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003892 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003893 case Instruction::IntToPtr: {
3894 auto AS = AddrInst->getType()->getPointerAddressSpace();
3895 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003896 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003897 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003898 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003899 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003900 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003901 case Instruction::BitCast:
3902 // BitCast is always a noop, and we can handle it as long as it is
3903 // int->int or pointer->pointer (we don't want int<->fp or something).
Vedant Kumarb3091da2018-07-06 20:17:42 +00003904 if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
Chandler Carruthc8925912013-01-05 02:09:22 +00003905 // Don't touch identity bitcasts. These were probably put here by LSR,
3906 // and we don't want to mess around with them. Assume it knows what it
3907 // is doing.
3908 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003909 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003910 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003911 case Instruction::AddrSpaceCast: {
3912 unsigned SrcAS
3913 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3914 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3915 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003916 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003917 return false;
3918 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003919 case Instruction::Add: {
3920 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3921 ExtAddrMode BackupAddrMode = AddrMode;
3922 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003923 // Start a transaction at this point.
3924 // The LHS may match but not the RHS.
3925 // Therefore, we need a higher level restoration point to undo partially
3926 // matched operation.
3927 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3928 TPT.getRestorationPoint();
3929
Sanjay Patelfc580a62015-09-21 23:03:16 +00003930 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3931 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003932 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003933
Chandler Carruthc8925912013-01-05 02:09:22 +00003934 // Restore the old addr mode info.
3935 AddrMode = BackupAddrMode;
3936 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003937 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003938
Chandler Carruthc8925912013-01-05 02:09:22 +00003939 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003940 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3941 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003942 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003943
Chandler Carruthc8925912013-01-05 02:09:22 +00003944 // Otherwise we definitely can't merge the ADD in.
3945 AddrMode = BackupAddrMode;
3946 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003947 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003948 break;
3949 }
3950 //case Instruction::Or:
3951 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3952 //break;
3953 case Instruction::Mul:
3954 case Instruction::Shl: {
3955 // Can only handle X*C and X << C.
3956 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003957 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003958 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003959 int64_t Scale = RHS->getSExtValue();
3960 if (Opcode == Instruction::Shl)
3961 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003962
Sanjay Patelfc580a62015-09-21 23:03:16 +00003963 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003964 }
3965 case Instruction::GetElementPtr: {
3966 // Scan the GEP. We check it if it contains constant offsets and at most
3967 // one variable offset.
3968 int VariableOperand = -1;
3969 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003970
Chandler Carruthc8925912013-01-05 02:09:22 +00003971 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003972 gep_type_iterator GTI = gep_type_begin(AddrInst);
3973 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003974 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003975 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003976 unsigned Idx =
3977 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3978 ConstantOffset += SL->getElementOffset(Idx);
3979 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003980 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003981 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
Simon Pilgrimee82a792018-08-13 12:10:09 +00003982 const APInt &CVal = CI->getValue();
3983 if (CVal.getMinSignedBits() <= 64) {
3984 ConstantOffset += CVal.getSExtValue() * TypeSize;
3985 continue;
3986 }
3987 }
3988 if (TypeSize) { // Scales of zero don't do anything.
Chandler Carruthc8925912013-01-05 02:09:22 +00003989 // We only allow one variable index at the moment.
3990 if (VariableOperand != -1)
3991 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003992
Chandler Carruthc8925912013-01-05 02:09:22 +00003993 // Remember the variable index.
3994 VariableOperand = i;
3995 VariableScale = TypeSize;
3996 }
3997 }
3998 }
Stephen Lin837bba12013-07-15 17:55:02 +00003999
Chandler Carruthc8925912013-01-05 02:09:22 +00004000 // A common case is for the GEP to only do a constant offset. In this case,
4001 // just add it to the disp field and check validity.
4002 if (VariableOperand == -1) {
4003 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004004 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004005 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004006 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004007 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00004008 return true;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004009 } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
4010 TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
4011 ConstantOffset > 0) {
4012 // Record GEPs with non-zero offsets as candidates for splitting in the
4013 // event that the offset cannot fit into the r+i addressing mode.
4014 // Simple and common case that only one GEP is used in calculating the
4015 // address for the memory access.
4016 Value *Base = AddrInst->getOperand(0);
4017 auto *BaseI = dyn_cast<Instruction>(Base);
4018 auto *GEP = cast<GetElementPtrInst>(AddrInst);
4019 if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
4020 (BaseI && !isa<CastInst>(BaseI) &&
4021 !isa<GetElementPtrInst>(BaseI))) {
4022 // If the base is an instruction, make sure the GEP is not in the same
4023 // basic block as the base. If the base is an argument or global
4024 // value, make sure the GEP is not in the entry block. Otherwise,
4025 // instruction selection can undo the split. Also make sure the
4026 // parent block allows inserting non-PHI instructions before the
4027 // terminator.
4028 BasicBlock *Parent =
4029 BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
4030 if (GEP->getParent() != Parent && !Parent->getTerminator()->isEHPad())
4031 LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
4032 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004033 }
4034 AddrMode.BaseOffs -= ConstantOffset;
4035 return false;
4036 }
4037
4038 // Save the valid addressing mode in case we can't match.
4039 ExtAddrMode BackupAddrMode = AddrMode;
4040 unsigned OldSize = AddrModeInsts.size();
4041
4042 // See if the scale and offset amount is valid for this target.
4043 AddrMode.BaseOffs += ConstantOffset;
4044
4045 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004046 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004047 // If it couldn't be matched, just stuff the value in a register.
4048 if (AddrMode.HasBaseReg) {
4049 AddrMode = BackupAddrMode;
4050 AddrModeInsts.resize(OldSize);
4051 return false;
4052 }
4053 AddrMode.HasBaseReg = true;
4054 AddrMode.BaseReg = AddrInst->getOperand(0);
4055 }
4056
4057 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004058 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00004059 Depth)) {
4060 // If it couldn't be matched, try stuffing the base into a register
4061 // instead of matching it, and retrying the match of the scale.
4062 AddrMode = BackupAddrMode;
4063 AddrModeInsts.resize(OldSize);
4064 if (AddrMode.HasBaseReg)
4065 return false;
4066 AddrMode.HasBaseReg = true;
4067 AddrMode.BaseReg = AddrInst->getOperand(0);
4068 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004069 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00004070 VariableScale, Depth)) {
4071 // If even that didn't work, bail.
4072 AddrMode = BackupAddrMode;
4073 AddrModeInsts.resize(OldSize);
4074 return false;
4075 }
4076 }
4077
4078 return true;
4079 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004080 case Instruction::SExt:
4081 case Instruction::ZExt: {
4082 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
4083 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00004084 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00004085
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004086 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004087 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004088 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004089 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004090 if (!TPH)
4091 return false;
4092
4093 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4094 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00004095 unsigned CreatedInstsCost = 0;
4096 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004097 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00004098 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004099 // SExt has been moved away.
4100 // Thus either it will be rematched later in the recursive calls or it is
4101 // gone. Anyway, we must not fold it into the addressing mode at this point.
4102 // E.g.,
4103 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004104 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004105 // addr = gep base, idx
4106 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00004107 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004108 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
4109 // addr = gep base, op <- match
4110 if (MovedAway)
4111 *MovedAway = true;
4112
4113 assert(PromotedOperand &&
4114 "TypePromotionHelper should have filtered out those cases");
4115
4116 ExtAddrMode BackupAddrMode = AddrMode;
4117 unsigned OldSize = AddrModeInsts.size();
4118
Sanjay Patelfc580a62015-09-21 23:03:16 +00004119 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004120 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00004121 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004122 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00004123 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004124 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004125 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00004126 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004127 AddrMode = BackupAddrMode;
4128 AddrModeInsts.resize(OldSize);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004129 LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004130 TPT.rollback(LastKnownGood);
4131 return false;
4132 }
4133 return true;
4134 }
Chandler Carruthc8925912013-01-05 02:09:22 +00004135 }
4136 return false;
4137}
4138
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004139/// If we can, try to add the value of 'Addr' into the current addressing mode.
4140/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
4141/// unmodified. This assumes that Addr is either a pointer type or intptr_t
4142/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00004143///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004144bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004145 // Start a transaction at this point that we will rollback if the matching
4146 // fails.
4147 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4148 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00004149 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4150 // Fold in immediates if legal for the target.
4151 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004152 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004153 return true;
4154 AddrMode.BaseOffs -= CI->getSExtValue();
4155 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4156 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004157 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004158 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004159 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004160 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004161 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004162 }
4163 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4164 ExtAddrMode BackupAddrMode = AddrMode;
4165 unsigned OldSize = AddrModeInsts.size();
4166
4167 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004168 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004169 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004170 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004171 // to check here.
4172 if (MovedAway)
4173 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004174 // Okay, it's possible to fold this. Check to see if it is actually
4175 // *profitable* to do so. We use a simple cost model to avoid increasing
4176 // register pressure too much.
4177 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004178 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004179 AddrModeInsts.push_back(I);
4180 return true;
4181 }
Stephen Lin837bba12013-07-15 17:55:02 +00004182
Chandler Carruthc8925912013-01-05 02:09:22 +00004183 // It isn't profitable to do this, roll back.
4184 //cerr << "NOT FOLDING: " << *I;
4185 AddrMode = BackupAddrMode;
4186 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004187 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004188 }
4189 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004190 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004191 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004192 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004193 } else if (isa<ConstantPointerNull>(Addr)) {
4194 // Null pointer gets folded without affecting the addressing mode.
4195 return true;
4196 }
4197
4198 // Worse case, the target should support [reg] addressing modes. :)
4199 if (!AddrMode.HasBaseReg) {
4200 AddrMode.HasBaseReg = true;
4201 AddrMode.BaseReg = Addr;
4202 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004203 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004204 return true;
4205 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004206 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004207 }
4208
4209 // If the base register is already taken, see if we can do [r+r].
4210 if (AddrMode.Scale == 0) {
4211 AddrMode.Scale = 1;
4212 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004213 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004214 return true;
4215 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004216 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004217 }
4218 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004219 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004220 return false;
4221}
4222
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004223/// Check to see if all uses of OpVal by the specified inline asm call are due
4224/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004225static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004226 const TargetLowering &TLI,
4227 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004228 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004229 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004230 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004231 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004232
Chandler Carruthc8925912013-01-05 02:09:22 +00004233 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4234 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004235
Chandler Carruthc8925912013-01-05 02:09:22 +00004236 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004237 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004238
4239 // If this asm operand is our Value*, and if it isn't an indirect memory
4240 // operand, we can't fold it!
4241 if (OpInfo.CallOperandVal == OpVal &&
4242 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4243 !OpInfo.isIndirect))
4244 return false;
4245 }
4246
4247 return true;
4248}
4249
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004250// Max number of memory uses to look at before aborting the search to conserve
4251// compile time.
4252static constexpr int MaxMemoryUsesToScan = 20;
4253
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004254/// Recursively walk all the uses of I until we find a memory use.
4255/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004256/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004257static bool FindAllMemoryUses(
4258 Instruction *I,
4259 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004260 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4261 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004262 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004263 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004264 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004265
Chandler Carruthc8925912013-01-05 02:09:22 +00004266 // If this is an obviously unfoldable instruction, bail out.
4267 if (!MightBeFoldableInst(I))
4268 return true;
4269
Philip Reamesac115ed2016-03-09 23:13:12 +00004270 const bool OptSize = I->getFunction()->optForSize();
4271
Chandler Carruthc8925912013-01-05 02:09:22 +00004272 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004273 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004274 // Conservatively return true if we're seeing a large number or a deep chain
4275 // of users. This avoids excessive compilation times in pathological cases.
4276 if (SeenInsts++ >= MaxMemoryUsesToScan)
4277 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004278
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004279 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004280 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4281 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004282 continue;
4283 }
Stephen Lin837bba12013-07-15 17:55:02 +00004284
Chandler Carruthcdf47882014-03-09 03:16:01 +00004285 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4286 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004287 if (opNo != StoreInst::getPointerOperandIndex())
4288 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004289 MemoryUses.push_back(std::make_pair(SI, opNo));
4290 continue;
4291 }
Stephen Lin837bba12013-07-15 17:55:02 +00004292
Matt Arsenault02d915b2017-03-15 22:35:20 +00004293 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4294 unsigned opNo = U.getOperandNo();
4295 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4296 return true; // Storing addr, not into addr.
4297 MemoryUses.push_back(std::make_pair(RMW, opNo));
4298 continue;
4299 }
4300
4301 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4302 unsigned opNo = U.getOperandNo();
4303 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4304 return true; // Storing addr, not into addr.
4305 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4306 continue;
4307 }
4308
Chandler Carruthcdf47882014-03-09 03:16:01 +00004309 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004310 // If this is a cold call, we can sink the addressing calculation into
4311 // the cold path. See optimizeCallInst
4312 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4313 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004314
Chandler Carruthc8925912013-01-05 02:09:22 +00004315 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4316 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004317
Chandler Carruthc8925912013-01-05 02:09:22 +00004318 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004319 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004320 return true;
4321 continue;
4322 }
Stephen Lin837bba12013-07-15 17:55:02 +00004323
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004324 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4325 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004326 return true;
4327 }
4328
4329 return false;
4330}
4331
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004332/// Return true if Val is already known to be live at the use site that we're
4333/// folding it into. If so, there is no cost to include it in the addressing
4334/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4335/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004336bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004337 Value *KnownLive2) {
4338 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004339 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004340 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004341
Chandler Carruthc8925912013-01-05 02:09:22 +00004342 // All values other than instructions and arguments (e.g. constants) are live.
4343 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004344
Chandler Carruthc8925912013-01-05 02:09:22 +00004345 // If Val is a constant sized alloca in the entry block, it is live, this is
4346 // true because it is just a reference to the stack/frame pointer, which is
4347 // live for the whole function.
4348 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4349 if (AI->isStaticAlloca())
4350 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004351
Chandler Carruthc8925912013-01-05 02:09:22 +00004352 // Check to see if this value is already used in the memory instruction's
4353 // block. If so, it's already live into the block at the very least, so we
4354 // can reasonably fold it.
4355 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4356}
4357
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004358/// It is possible for the addressing mode of the machine to fold the specified
4359/// instruction into a load or store that ultimately uses it.
4360/// However, the specified instruction has multiple uses.
4361/// Given this, it may actually increase register pressure to fold it
4362/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004363///
4364/// X = ...
4365/// Y = X+1
4366/// use(Y) -> nonload/store
4367/// Z = Y+1
4368/// load Z
4369///
4370/// In this case, Y has multiple uses, and can be folded into the load of Z
4371/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4372/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4373/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4374/// number of computations either.
4375///
4376/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4377/// X was live across 'load Z' for other reasons, we actually *would* want to
4378/// fold the addressing mode in the Z case. This would make Y die earlier.
4379bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004380isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004381 ExtAddrMode &AMAfter) {
4382 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004383
Chandler Carruthc8925912013-01-05 02:09:22 +00004384 // AMBefore is the addressing mode before this instruction was folded into it,
4385 // and AMAfter is the addressing mode after the instruction was folded. Get
4386 // the set of registers referenced by AMAfter and subtract out those
4387 // referenced by AMBefore: this is the set of values which folding in this
4388 // address extends the lifetime of.
4389 //
4390 // Note that there are only two potential values being referenced here,
4391 // BaseReg and ScaleReg (global addresses are always available, as are any
4392 // folded immediates).
4393 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004394
Chandler Carruthc8925912013-01-05 02:09:22 +00004395 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4396 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004397 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004398 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004399 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004400 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004401
4402 // If folding this instruction (and it's subexprs) didn't extend any live
4403 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004404 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004405 return true;
4406
Philip Reamesac115ed2016-03-09 23:13:12 +00004407 // If all uses of this instruction can have the address mode sunk into them,
4408 // we can remove the addressing mode and effectively trade one live register
4409 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004410 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004411 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4412 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004413 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004414 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004415
Chandler Carruthc8925912013-01-05 02:09:22 +00004416 // Now that we know that all uses of this instruction are part of a chain of
4417 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004418 // into a memory use, loop over each of these memory operation uses and see
4419 // if they could *actually* fold the instruction. The assumption is that
4420 // addressing modes are cheap and that duplicating the computation involved
4421 // many times is worthwhile, even on a fastpath. For sinking candidates
4422 // (i.e. cold call sites), this serves as a way to prevent excessive code
4423 // growth since most architectures have some reasonable small and fast way to
4424 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004425 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4426 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4427 Instruction *User = MemoryUses[i].first;
4428 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004429
Chandler Carruthc8925912013-01-05 02:09:22 +00004430 // Get the access type of this use. If the use isn't a pointer, we don't
4431 // know what it accesses.
4432 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004433 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4434 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004435 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004436 Type *AddressAccessTy = AddrTy->getElementType();
4437 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004438
Chandler Carruthc8925912013-01-05 02:09:22 +00004439 // Do a match against the root of this address, ignoring profitability. This
4440 // will tell us if the addressing mode for the memory operation will
4441 // *actually* cover the shared instruction.
4442 ExtAddrMode Result;
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004443 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4444 0);
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004445 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4446 TPT.getRestorationPoint();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004447 AddressingModeMatcher Matcher(
4448 MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
4449 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Chandler Carruthc8925912013-01-05 02:09:22 +00004450 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004451 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004452 (void)Success; assert(Success && "Couldn't select *anything*?");
4453
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004454 // The match was to check the profitability, the changes made are not
4455 // part of the original matcher. Therefore, they should be dropped
4456 // otherwise the original matcher will not present the right state.
4457 TPT.rollback(LastKnownGood);
4458
Chandler Carruthc8925912013-01-05 02:09:22 +00004459 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004460 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004461 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004462
Chandler Carruthc8925912013-01-05 02:09:22 +00004463 MatchedAddrModeInsts.clear();
4464 }
Stephen Lin837bba12013-07-15 17:55:02 +00004465
Chandler Carruthc8925912013-01-05 02:09:22 +00004466 return true;
4467}
4468
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004469/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004470/// different basic block than BB.
4471static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4472 if (Instruction *I = dyn_cast<Instruction>(V))
4473 return I->getParent() != BB;
4474 return false;
4475}
4476
Philip Reamesac115ed2016-03-09 23:13:12 +00004477/// Sink addressing mode computation immediate before MemoryInst if doing so
4478/// can be done without increasing register pressure. The need for the
4479/// register pressure constraint means this can end up being an all or nothing
4480/// decision for all uses of the same addressing computation.
4481///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004482/// Load and Store Instructions often have addressing modes that can do
4483/// significant amounts of computation. As such, instruction selection will try
4484/// to get the load or store to do as much computation as possible for the
4485/// program. The problem is that isel can only see within a single block. As
4486/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004487///
4488/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004489/// operands. It's also used to sink addressing computations feeding into cold
4490/// call sites into their (cold) basic block.
4491///
4492/// The motivation for handling sinking into cold blocks is that doing so can
4493/// both enable other address mode sinking (by satisfying the register pressure
4494/// constraint above), and reduce register pressure globally (by removing the
4495/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004496bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004497 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004498 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004499
4500 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004501 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004502 SmallVector<Value*, 8> worklist;
4503 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004504 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004505
John Brawneb83c752017-10-03 13:04:15 +00004506 // Use a worklist to iteratively look through PHI and select nodes, and
4507 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004508 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004509 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004510 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004511 const SimplifyQuery SQ(*DL, TLInfo);
Serguei Katkov2673f172018-11-29 06:45:18 +00004512 AddressingModeCombiner AddrModes(SQ, Addr);
Jun Bum Limdee55652017-04-03 19:20:07 +00004513 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004514 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4515 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004516 while (!worklist.empty()) {
4517 Value *V = worklist.back();
4518 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004519
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004520 // We allow traversing cyclic Phi nodes.
4521 // In case of success after this loop we ensure that traversing through
4522 // Phi nodes ends up with all cases to compute address of the form
4523 // BaseGV + Base + Scale * Index + Offset
4524 // where Scale and Offset are constans and BaseGV, Base and Index
4525 // are exactly the same Values in all cases.
4526 // It means that BaseGV, Scale and Offset dominate our memory instruction
4527 // and have the same value as they had in address computation represented
4528 // as Phi. So we can safely sink address computation to memory instruction.
4529 if (!Visited.insert(V).second)
4530 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004531
Owen Anderson8ba5f392010-11-27 08:15:55 +00004532 // For a PHI node, push all of its incoming values.
4533 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004534 for (Value *IncValue : P->incoming_values())
4535 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004536 PhiOrSelectSeen = true;
4537 continue;
4538 }
4539 // Similar for select.
4540 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4541 worklist.push_back(SI->getFalseValue());
4542 worklist.push_back(SI->getTrueValue());
4543 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004544 continue;
4545 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004546
Philip Reamesac115ed2016-03-09 23:13:12 +00004547 // For non-PHIs, determine the addressing mode being computed. Note that
4548 // the result may differ depending on what other uses our candidate
4549 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004550 AddrModeInsts.clear();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004551 std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
4552 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004553 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004554 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004555 InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004556
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00004557 GetElementPtrInst *GEP = LargeOffsetGEP.first;
4558 if (GEP && GEP->getParent() != MemoryInst->getParent() &&
4559 !NewGEPBases.count(GEP)) {
4560 // If splitting the underlying data structure can reduce the offset of a
4561 // GEP, collect the GEP. Skip the GEPs that are the new bases of
4562 // previously split data structures.
4563 LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
4564 if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
4565 LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
4566 }
4567
4568 NewAddrMode.OriginalValue = V;
John Brawn736bf002017-10-03 13:08:22 +00004569 if (!AddrModes.addNewAddrMode(NewAddrMode))
4570 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004571 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004572
John Brawn736bf002017-10-03 13:08:22 +00004573 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4574 // or we have multiple but either couldn't combine them or combining them
4575 // wouldn't do anything useful, bail out now.
4576 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004577 TPT.rollback(LastKnownGood);
4578 return false;
4579 }
4580 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004581
John Brawn736bf002017-10-03 13:08:22 +00004582 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4583 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4584
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004585 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004586 // If we saw a Phi node then it is not local definitely, and if we saw a select
4587 // then we want to push the address calculation past it even if it's already
4588 // in this BB.
4589 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004590 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004591 })) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004592 LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
4593 << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004594 return false;
4595 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004596
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004597 // Insert this computation right after this user. Since our caller is
4598 // scanning from the top of the BB to the bottom, reuse of the expr are
4599 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004600 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004601
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004602 // Now that we determined the addressing expression we want to use and know
4603 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004604 // done this for some other load/store instr in this block. If so, reuse
4605 // the computation. Before attempting reuse, check if the address is valid
4606 // as it may have been erased.
4607
4608 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4609
4610 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004611 if (SunkAddr) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004612 LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
4613 << " for " << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004614 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004615 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004616 } else if (AddrSinkUsingGEPs ||
David Blaikie8ad9a972018-03-28 22:28:50 +00004617 (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004618 // By default, we use the GEP-based method when AA is used later. This
4619 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004620 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4621 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004622 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004623 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004624
4625 // First, find the pointer.
4626 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4627 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004628 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004629 }
4630
4631 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4632 // We can't add more than one pointer together, nor can we scale a
4633 // pointer (both of which seem meaningless).
4634 if (ResultPtr || AddrMode.Scale != 1)
4635 return false;
4636
4637 ResultPtr = AddrMode.ScaledReg;
4638 AddrMode.Scale = 0;
4639 }
4640
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004641 // It is only safe to sign extend the BaseReg if we know that the math
4642 // required to create it did not overflow before we extend it. Since
4643 // the original IR value was tossed in favor of a constant back when
4644 // the AddrMode was created we need to bail out gracefully if widths
4645 // do not match instead of extending it.
4646 //
4647 // (See below for code to add the scale.)
4648 if (AddrMode.Scale) {
4649 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4650 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4651 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4652 return false;
4653 }
4654
Hal Finkelc3998302014-04-12 00:59:48 +00004655 if (AddrMode.BaseGV) {
4656 if (ResultPtr)
4657 return false;
4658
4659 ResultPtr = AddrMode.BaseGV;
4660 }
4661
4662 // If the real base value actually came from an inttoptr, then the matcher
4663 // will look through it and provide only the integer value. In that case,
4664 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004665 if (!DL->isNonIntegralPointerType(Addr->getType())) {
Roman Tereshina0383d62019-01-19 03:37:25 +00004666 const auto getResultPtr = [MemoryInst, Addr,
4667 &Builder](Value *Reg) -> Value * {
4668 BasicBlock *BB = MemoryInst->getParent();
4669 for (User *U : Reg->users())
4670 if (auto *I2P = dyn_cast<IntToPtrInst>(U))
4671 if (I2P->getType() == Addr->getType() && I2P->getParent() == BB) {
4672 auto *RegInst = dyn_cast<Instruction>(Reg);
4673 if (RegInst && RegInst->getParent() == BB &&
4674 !isa<PHINode>(RegInst) && !RegInst->isEHPad())
4675 I2P->moveAfter(RegInst);
4676 else
4677 I2P->moveBefore(*BB, BB->getFirstInsertionPt());
4678 return I2P;
4679 }
4680 return Builder.CreateIntToPtr(Reg, Addr->getType(), "sunkaddr");
4681 };
Keno Fischer05e4ac22017-06-29 20:28:59 +00004682 if (!ResultPtr && AddrMode.BaseReg) {
Roman Tereshina0383d62019-01-19 03:37:25 +00004683 ResultPtr = getResultPtr(AddrMode.BaseReg);
Keno Fischer05e4ac22017-06-29 20:28:59 +00004684 AddrMode.BaseReg = nullptr;
4685 } else if (!ResultPtr && AddrMode.Scale == 1) {
Roman Tereshina0383d62019-01-19 03:37:25 +00004686 ResultPtr = getResultPtr(AddrMode.ScaledReg);
Keno Fischer05e4ac22017-06-29 20:28:59 +00004687 AddrMode.Scale = 0;
4688 }
Hal Finkelc3998302014-04-12 00:59:48 +00004689 }
4690
4691 if (!ResultPtr &&
4692 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4693 SunkAddr = Constant::getNullValue(Addr->getType());
4694 } else if (!ResultPtr) {
4695 return false;
4696 } else {
4697 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004698 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4699 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004700
4701 // Start with the base register. Do this first so that subsequent address
4702 // matching finds it last, which will prevent it from trying to match it
4703 // as the scaled value in case it happens to be a mul. That would be
4704 // problematic if we've sunk a different mul for the scale, because then
4705 // we'd end up sinking both muls.
4706 if (AddrMode.BaseReg) {
4707 Value *V = AddrMode.BaseReg;
4708 if (V->getType() != IntPtrTy)
4709 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4710
4711 ResultIndex = V;
4712 }
4713
4714 // Add the scale value.
4715 if (AddrMode.Scale) {
4716 Value *V = AddrMode.ScaledReg;
4717 if (V->getType() == IntPtrTy) {
4718 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004719 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004720 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4721 cast<IntegerType>(V->getType())->getBitWidth() &&
4722 "We can't transform if ScaledReg is too narrow");
4723 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004724 }
4725
4726 if (AddrMode.Scale != 1)
4727 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4728 "sunkaddr");
4729 if (ResultIndex)
4730 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4731 else
4732 ResultIndex = V;
4733 }
4734
4735 // Add in the Base Offset if present.
4736 if (AddrMode.BaseOffs) {
4737 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4738 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004739 // We need to add this separately from the scale above to help with
4740 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004741 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004742 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004743 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004744 }
4745
4746 ResultIndex = V;
4747 }
4748
4749 if (!ResultIndex) {
4750 SunkAddr = ResultPtr;
4751 } else {
4752 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004753 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004754 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004755 }
4756
4757 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004758 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004759 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004760 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004761 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4762 // non-integral pointers, so in that case bail out now.
4763 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4764 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4765 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4766 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4767 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4768 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4769 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4770 (AddrMode.BaseGV &&
4771 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4772 return false;
4773
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004774 LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
4775 << " for " << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004776 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004777 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004778
4779 // Start with the base register. Do this first so that subsequent address
4780 // matching finds it last, which will prevent it from trying to match it
4781 // as the scaled value in case it happens to be a mul. That would be
4782 // problematic if we've sunk a different mul for the scale, because then
4783 // we'd end up sinking both muls.
4784 if (AddrMode.BaseReg) {
4785 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004786 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004787 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004788 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004789 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004790 Result = V;
4791 }
4792
4793 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004794 if (AddrMode.Scale) {
4795 Value *V = AddrMode.ScaledReg;
4796 if (V->getType() == IntPtrTy) {
4797 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004798 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004799 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004800 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4801 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004802 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004803 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004804 // It is only safe to sign extend the BaseReg if we know that the math
4805 // required to create it did not overflow before we extend it. Since
4806 // the original IR value was tossed in favor of a constant back when
4807 // the AddrMode was created we need to bail out gracefully if widths
4808 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004809 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004810 if (I && (Result != AddrMode.BaseReg))
4811 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004812 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004813 }
4814 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004815 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4816 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004817 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004818 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004819 else
4820 Result = V;
4821 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004822
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004823 // Add in the BaseGV if present.
4824 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004825 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004826 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004827 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004828 else
4829 Result = V;
4830 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004831
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004832 // Add in the Base Offset if present.
4833 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004834 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004835 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004836 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004837 else
4838 Result = V;
4839 }
4840
Craig Topperc0196b12014-04-14 00:51:57 +00004841 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004842 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004843 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004844 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004845 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004846
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004847 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004848 // Store the newly computed address into the cache. In the case we reused a
4849 // value, this should be idempotent.
4850 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004851
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004852 // If we have no uses, recursively delete the value and all dead instructions
4853 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004854 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004855 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004856 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004857 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004858 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004859 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004860
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004861 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004862
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004863 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004864 // If the iterator instruction was recursively deleted, start over at the
4865 // start of the block.
4866 CurInstIterator = BB->begin();
4867 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004868 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004869 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004870 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004871 return true;
4872}
4873
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004874/// If there are any memory operands, use OptimizeMemoryInst to sink their
4875/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004876bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004877 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004878
Eric Christopher11e4df72015-02-26 22:38:43 +00004879 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004880 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004881 TargetLowering::AsmOperandInfoVector TargetConstraints =
4882 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004883 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004884 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4885 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004886
Evan Cheng1da25002008-02-26 02:42:37 +00004887 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004888 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004889
Eli Friedman666bbe32008-02-26 18:37:49 +00004890 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4891 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004892 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004893 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004894 } else if (OpInfo.Type == InlineAsm::isInput)
4895 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004896 }
4897
4898 return MadeChange;
4899}
4900
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004901/// Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004902/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004903static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4904 assert(!Val->use_empty() && "Input must have at least one use");
4905 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004906 bool IsSExt = isa<SExtInst>(FirstUser);
4907 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004908 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004909 const Instruction *UI = cast<Instruction>(U);
4910 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4911 return false;
4912 Type *CurTy = UI->getType();
4913 // Same input and output types: Same instruction after CSE.
4914 if (CurTy == ExtTy)
4915 continue;
4916
4917 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004918 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004919 // b = sext ty1 a to ty2
4920 // c = sext ty1 a to ty3
4921 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004922 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004923 // b = sext ty1 a to ty2
4924 // c = sext ty2 b to ty3
4925 // However, the last sext is not free.
4926 if (IsSExt)
4927 return false;
4928
4929 // This is a ZExt, maybe this is free to extend from one type to another.
4930 // In that case, we would not account for a different use.
4931 Type *NarrowTy;
4932 Type *LargeTy;
4933 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4934 CurTy->getScalarType()->getIntegerBitWidth()) {
4935 NarrowTy = CurTy;
4936 LargeTy = ExtTy;
4937 } else {
4938 NarrowTy = ExtTy;
4939 LargeTy = CurTy;
4940 }
4941
4942 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4943 return false;
4944 }
4945 // All uses are the same or can be derived from one another for free.
4946 return true;
4947}
4948
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00004949/// Try to speculatively promote extensions in \p Exts and continue
Jun Bum Lim42301012017-03-17 19:05:21 +00004950/// promoting through newly promoted operands recursively as far as doing so is
4951/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4952/// When some promotion happened, \p TPT contains the proper state to revert
4953/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004954///
Jun Bum Lim42301012017-03-17 19:05:21 +00004955/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004956bool CodeGenPrepare::tryToPromoteExts(
4957 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4958 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4959 unsigned CreatedInstsCost) {
4960 bool Promoted = false;
4961
4962 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004963 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004964 // Early check if we directly have ext(load).
4965 if (isa<LoadInst>(I->getOperand(0))) {
4966 ProfitablyMovedExts.push_back(I);
4967 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004968 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004969
4970 // Check whether or not we want to do any promotion. The reason we have
4971 // this check inside the for loop is to catch the case where an extension
4972 // is directly fed by a load because in such case the extension can be moved
4973 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004974 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004975 return false;
4976
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004977 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004978 TypePromotionHelper::Action TPH =
4979 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004980 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004981 if (!TPH) {
4982 // Save the current extension as we cannot move up through its operand.
4983 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004984 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004985 }
4986
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004987 // Save the current state.
4988 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4989 TPT.getRestorationPoint();
4990 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004991 unsigned NewCreatedInstsCost = 0;
4992 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004993 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004994 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4995 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004996 assert(PromotedVal &&
4997 "TypePromotionHelper should have filtered out those cases");
4998
4999 // We would be able to merge only one extension in a load.
5000 // Therefore, if we have more than 1 new extension we heuristically
5001 // cut this search path, because it means we degrade the code quality.
5002 // With exactly 2, the transformation is neutral, because we will merge
5003 // one extension but leave one. However, we optimistically keep going,
5004 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00005005 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005006 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00005007 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00005008 TotalCreatedInstsCost =
5009 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005010 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00005011 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00005012 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00005013 // This promotion is not profitable, rollback to the previous state, and
5014 // save the current extension in ProfitablyMovedExts as the latest
5015 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005016 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00005017 ProfitablyMovedExts.push_back(I);
5018 continue;
5019 }
5020 // Continue promoting NewExts as far as doing so is profitable.
5021 SmallVector<Instruction *, 2> NewlyMovedExts;
5022 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
5023 bool NewPromoted = false;
5024 for (auto ExtInst : NewlyMovedExts) {
5025 Instruction *MovedExt = cast<Instruction>(ExtInst);
5026 Value *ExtOperand = MovedExt->getOperand(0);
5027 // If we have reached to a load, we need this extra profitability check
5028 // as it could potentially be merged into an ext(load).
5029 if (isa<LoadInst>(ExtOperand) &&
5030 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
5031 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
5032 continue;
5033
5034 ProfitablyMovedExts.push_back(MovedExt);
5035 NewPromoted = true;
5036 }
5037
5038 // If none of speculative promotions for NewExts is profitable, rollback
5039 // and save the current extension (I) as the last profitable extension.
5040 if (!NewPromoted) {
5041 TPT.rollback(LastKnownGood);
5042 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005043 continue;
5044 }
5045 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00005046 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005047 }
Jun Bum Lim42301012017-03-17 19:05:21 +00005048 return Promoted;
5049}
5050
Jun Bum Limdee55652017-04-03 19:20:07 +00005051/// Merging redundant sexts when one is dominating the other.
5052bool CodeGenPrepare::mergeSExts(Function &F) {
5053 DominatorTree DT(F);
5054 bool Changed = false;
5055 for (auto &Entry : ValToSExtendedUses) {
5056 SExts &Insts = Entry.second;
5057 SExts CurPts;
5058 for (Instruction *Inst : Insts) {
5059 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
5060 Inst->getOperand(0) != Entry.first)
5061 continue;
5062 bool inserted = false;
5063 for (auto &Pt : CurPts) {
5064 if (DT.dominates(Inst, Pt)) {
5065 Pt->replaceAllUsesWith(Inst);
5066 RemovedInsts.insert(Pt);
5067 Pt->removeFromParent();
5068 Pt = Inst;
5069 inserted = true;
5070 Changed = true;
5071 break;
5072 }
5073 if (!DT.dominates(Pt, Inst))
5074 // Give up if we need to merge in a common dominator as the
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00005075 // experiments show it is not profitable.
Jun Bum Limdee55652017-04-03 19:20:07 +00005076 continue;
5077 Inst->replaceAllUsesWith(Pt);
5078 RemovedInsts.insert(Inst);
5079 Inst->removeFromParent();
5080 inserted = true;
5081 Changed = true;
5082 break;
5083 }
5084 if (!inserted)
5085 CurPts.push_back(Inst);
5086 }
5087 }
5088 return Changed;
5089}
5090
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005091// Spliting large data structures so that the GEPs accessing them can have
5092// smaller offsets so that they can be sunk to the same blocks as their users.
5093// For example, a large struct starting from %base is splitted into two parts
5094// where the second part starts from %new_base.
5095//
5096// Before:
5097// BB0:
5098// %base =
5099//
5100// BB1:
5101// %gep0 = gep %base, off0
5102// %gep1 = gep %base, off1
5103// %gep2 = gep %base, off2
5104//
5105// BB2:
5106// %load1 = load %gep0
5107// %load2 = load %gep1
5108// %load3 = load %gep2
5109//
5110// After:
5111// BB0:
5112// %base =
5113// %new_base = gep %base, off0
5114//
5115// BB1:
5116// %new_gep0 = %new_base
5117// %new_gep1 = gep %new_base, off1 - off0
5118// %new_gep2 = gep %new_base, off2 - off0
5119//
5120// BB2:
5121// %load1 = load i32, i32* %new_gep0
5122// %load2 = load i32, i32* %new_gep1
5123// %load3 = load i32, i32* %new_gep2
5124//
5125// %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
5126// their offsets are smaller enough to fit into the addressing mode.
5127bool CodeGenPrepare::splitLargeGEPOffsets() {
5128 bool Changed = false;
5129 for (auto &Entry : LargeOffsetGEPMap) {
5130 Value *OldBase = Entry.first;
5131 SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
5132 &LargeOffsetGEPs = Entry.second;
5133 auto compareGEPOffset =
5134 [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
5135 const std::pair<GetElementPtrInst *, int64_t> &RHS) {
5136 if (LHS.first == RHS.first)
5137 return false;
5138 if (LHS.second != RHS.second)
5139 return LHS.second < RHS.second;
5140 return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
5141 };
5142 // Sorting all the GEPs of the same data structures based on the offsets.
Fangrui Song0cac7262018-09-27 02:13:45 +00005143 llvm::sort(LargeOffsetGEPs, compareGEPOffset);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005144 LargeOffsetGEPs.erase(
5145 std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
5146 LargeOffsetGEPs.end());
5147 // Skip if all the GEPs have the same offsets.
5148 if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
5149 continue;
5150 GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
5151 int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
5152 Value *NewBaseGEP = nullptr;
5153
5154 auto LargeOffsetGEP = LargeOffsetGEPs.begin();
5155 while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
5156 GetElementPtrInst *GEP = LargeOffsetGEP->first;
5157 int64_t Offset = LargeOffsetGEP->second;
5158 if (Offset != BaseOffset) {
5159 TargetLowering::AddrMode AddrMode;
5160 AddrMode.BaseOffs = Offset - BaseOffset;
5161 // The result type of the GEP might not be the type of the memory
5162 // access.
5163 if (!TLI->isLegalAddressingMode(*DL, AddrMode,
5164 GEP->getResultElementType(),
5165 GEP->getAddressSpace())) {
5166 // We need to create a new base if the offset to the current base is
5167 // too large to fit into the addressing mode. So, a very large struct
5168 // may be splitted into several parts.
5169 BaseGEP = GEP;
5170 BaseOffset = Offset;
5171 NewBaseGEP = nullptr;
5172 }
5173 }
5174
5175 // Generate a new GEP to replace the current one.
Eli Friedmana69084f2018-12-19 22:52:04 +00005176 LLVMContext &Ctx = GEP->getContext();
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005177 Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
5178 Type *I8PtrTy =
Eli Friedmana69084f2018-12-19 22:52:04 +00005179 Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
5180 Type *I8Ty = Type::getInt8Ty(Ctx);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005181
5182 if (!NewBaseGEP) {
5183 // Create a new base if we don't have one yet. Find the insertion
5184 // pointer for the new base first.
5185 BasicBlock::iterator NewBaseInsertPt;
5186 BasicBlock *NewBaseInsertBB;
5187 if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
5188 // If the base of the struct is an instruction, the new base will be
5189 // inserted close to it.
5190 NewBaseInsertBB = BaseI->getParent();
5191 if (isa<PHINode>(BaseI))
5192 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5193 else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
5194 NewBaseInsertBB =
5195 SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
5196 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5197 } else
5198 NewBaseInsertPt = std::next(BaseI->getIterator());
5199 } else {
5200 // If the current base is an argument or global value, the new base
5201 // will be inserted to the entry block.
5202 NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
5203 NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
5204 }
5205 IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
5206 // Create a new base.
5207 Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
5208 NewBaseGEP = OldBase;
5209 if (NewBaseGEP->getType() != I8PtrTy)
5210 NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
5211 NewBaseGEP =
5212 NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
5213 NewGEPBases.insert(NewBaseGEP);
5214 }
5215
Eli Friedmana69084f2018-12-19 22:52:04 +00005216 IRBuilder<> Builder(GEP);
Haicheng Wu0aae2bc2018-05-10 18:27:36 +00005217 Value *NewGEP = NewBaseGEP;
5218 if (Offset == BaseOffset) {
5219 if (GEP->getType() != I8PtrTy)
5220 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5221 } else {
5222 // Calculate the new offset for the new GEP.
5223 Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
5224 NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
5225
5226 if (GEP->getType() != I8PtrTy)
5227 NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
5228 }
5229 GEP->replaceAllUsesWith(NewGEP);
5230 LargeOffsetGEPID.erase(GEP);
5231 LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
5232 GEP->eraseFromParent();
5233 Changed = true;
5234 }
5235 }
5236 return Changed;
5237}
5238
Jun Bum Lim42301012017-03-17 19:05:21 +00005239/// Return true, if an ext(load) can be formed from an extension in
5240/// \p MovedExts.
5241bool CodeGenPrepare::canFormExtLd(
5242 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
5243 Instruction *&Inst, bool HasPromoted) {
5244 for (auto *MovedExtInst : MovedExts) {
5245 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
5246 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
5247 Inst = MovedExtInst;
5248 break;
5249 }
5250 }
5251 if (!LI)
5252 return false;
5253
5254 // If they're already in the same block, there's nothing to do.
5255 // Make the cheap checks first if we did not promote.
5256 // If we promoted, we need to check if it is indeed profitable.
5257 if (!HasPromoted && LI->getParent() == Inst->getParent())
5258 return false;
5259
Haicheng Wuabdef9e2017-07-15 02:12:16 +00005260 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005261}
5262
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005263/// Move a zext or sext fed by a load into the same basic block as the load,
5264/// unless conditions are unfavorable. This allows SelectionDAG to fold the
5265/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00005266///
Jun Bum Limdee55652017-04-03 19:20:07 +00005267/// E.g.,
5268/// \code
5269/// %ld = load i32* %addr
5270/// %add = add nuw i32 %ld, 4
5271/// %zext = zext i32 %add to i64
5272// \endcode
5273/// =>
5274/// \code
5275/// %ld = load i32* %addr
5276/// %zext = zext i32 %ld to i64
5277/// %add = add nuw i64 %zext, 4
5278/// \encode
5279/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
5280/// allow us to match zext(load i32*) to i64.
5281///
5282/// Also, try to promote the computations used to obtain a sign extended
5283/// value used into memory accesses.
5284/// E.g.,
5285/// \code
5286/// a = add nsw i32 b, 3
5287/// d = sext i32 a to i64
5288/// e = getelementptr ..., i64 d
5289/// \endcode
5290/// =>
5291/// \code
5292/// f = sext i32 b to i64
5293/// a = add nsw i64 f, 3
5294/// e = getelementptr ..., i64 a
5295/// \endcode
5296///
5297/// \p Inst[in/out] the extension may be modified during the process if some
5298/// promotions apply.
5299bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
5300 // ExtLoad formation and address type promotion infrastructure requires TLI to
5301 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00005302 if (!TLI)
5303 return false;
5304
Jun Bum Limdee55652017-04-03 19:20:07 +00005305 bool AllowPromotionWithoutCommonHeader = false;
5306 /// See if it is an interesting sext operations for the address type
5307 /// promotion before trying to promote it, e.g., the ones with the right
5308 /// type and used in memory accesses.
5309 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
5310 *Inst, AllowPromotionWithoutCommonHeader);
5311 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005312 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00005313 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005314 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00005315 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
5316 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00005317
Jun Bum Limdee55652017-04-03 19:20:07 +00005318 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00005319
Dan Gohman99429a02009-10-16 20:59:35 +00005320 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005321 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005322 Instruction *ExtFedByLoad;
5323
5324 // Try to promote a chain of computation if it allows to form an extended
5325 // load.
5326 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5327 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5328 TPT.commit();
5329 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005330 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005331 // CGP does not check if the zext would be speculatively executed when moved
5332 // to the same basic block as the load. Preserving its original location
5333 // would pessimize the debugging experience, as well as negatively impact
5334 // the quality of sample pgo. We don't want to use "line 0" as that has a
5335 // size cost in the line-table section and logically the zext can be seen as
5336 // part of the load. Therefore we conservatively reuse the same debug
5337 // location for the load and the zext.
5338 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5339 ++NumExtsMoved;
5340 Inst = ExtFedByLoad;
5341 return true;
5342 }
5343
5344 // Continue promoting SExts if known as considerable depending on targets.
5345 if (ATPConsiderable &&
5346 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5347 HasPromoted, TPT, SpeculativelyMovedExts))
5348 return true;
5349
5350 TPT.rollback(LastKnownGood);
5351 return false;
5352}
5353
5354// Perform address type promotion if doing so is profitable.
5355// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5356// instructions that sign extended the same initial value. However, if
5357// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5358// extension is just profitable.
5359bool CodeGenPrepare::performAddressTypePromotion(
5360 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5361 bool HasPromoted, TypePromotionTransaction &TPT,
5362 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5363 bool Promoted = false;
5364 SmallPtrSet<Instruction *, 1> UnhandledExts;
5365 bool AllSeenFirst = true;
5366 for (auto I : SpeculativelyMovedExts) {
5367 Value *HeadOfChain = I->getOperand(0);
5368 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5369 SeenChainsForSExt.find(HeadOfChain);
5370 // If there is an unhandled SExt which has the same header, try to promote
5371 // it as well.
5372 if (AlreadySeen != SeenChainsForSExt.end()) {
5373 if (AlreadySeen->second != nullptr)
5374 UnhandledExts.insert(AlreadySeen->second);
5375 AllSeenFirst = false;
5376 }
5377 }
5378
5379 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5380 SpeculativelyMovedExts.size() == 1)) {
5381 TPT.commit();
5382 if (HasPromoted)
5383 Promoted = true;
5384 for (auto I : SpeculativelyMovedExts) {
5385 Value *HeadOfChain = I->getOperand(0);
5386 SeenChainsForSExt[HeadOfChain] = nullptr;
5387 ValToSExtendedUses[HeadOfChain].push_back(I);
5388 }
5389 // Update Inst as promotion happen.
5390 Inst = SpeculativelyMovedExts.pop_back_val();
5391 } else {
5392 // This is the first chain visited from the header, keep the current chain
5393 // as unhandled. Defer to promote this until we encounter another SExt
5394 // chain derived from the same header.
5395 for (auto I : SpeculativelyMovedExts) {
5396 Value *HeadOfChain = I->getOperand(0);
5397 SeenChainsForSExt[HeadOfChain] = Inst;
5398 }
Dan Gohman99429a02009-10-16 20:59:35 +00005399 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005400 }
Dan Gohman99429a02009-10-16 20:59:35 +00005401
Jun Bum Limdee55652017-04-03 19:20:07 +00005402 if (!AllSeenFirst && !UnhandledExts.empty())
5403 for (auto VisitedSExt : UnhandledExts) {
5404 if (RemovedInsts.count(VisitedSExt))
5405 continue;
5406 TypePromotionTransaction TPT(RemovedInsts);
5407 SmallVector<Instruction *, 1> Exts;
5408 SmallVector<Instruction *, 2> Chains;
5409 Exts.push_back(VisitedSExt);
5410 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5411 TPT.commit();
5412 if (HasPromoted)
5413 Promoted = true;
5414 for (auto I : Chains) {
5415 Value *HeadOfChain = I->getOperand(0);
5416 // Mark this as handled.
5417 SeenChainsForSExt[HeadOfChain] = nullptr;
5418 ValToSExtendedUses[HeadOfChain].push_back(I);
5419 }
5420 }
5421 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005422}
5423
Sanjay Patelfc580a62015-09-21 23:03:16 +00005424bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005425 BasicBlock *DefBB = I->getParent();
5426
Bob Wilsonff714f92010-09-21 21:44:14 +00005427 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005428 // other uses of the source with result of extension.
5429 Value *Src = I->getOperand(0);
5430 if (Src->hasOneUse())
5431 return false;
5432
Evan Cheng2011df42007-12-13 07:50:36 +00005433 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005434 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005435 return false;
5436
Evan Cheng7bc89422007-12-12 00:51:06 +00005437 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005438 // this block.
5439 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005440 return false;
5441
Evan Chengd3d80172007-12-05 23:58:20 +00005442 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005443 for (User *U : I->users()) {
5444 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005445
5446 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005447 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005448 if (UserBB == DefBB) continue;
5449 DefIsLiveOut = true;
5450 break;
5451 }
5452 if (!DefIsLiveOut)
5453 return false;
5454
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005455 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005456 for (User *U : Src->users()) {
5457 Instruction *UI = cast<Instruction>(U);
5458 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005459 if (UserBB == DefBB) continue;
5460 // Be conservative. We don't want this xform to end up introducing
5461 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005462 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005463 return false;
5464 }
5465
Evan Chengd3d80172007-12-05 23:58:20 +00005466 // InsertedTruncs - Only insert one trunc in each block once.
5467 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5468
5469 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005470 for (Use &U : Src->uses()) {
5471 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005472
5473 // Figure out which BB this ext is used in.
5474 BasicBlock *UserBB = User->getParent();
5475 if (UserBB == DefBB) continue;
5476
5477 // Both src and def are live in this block. Rewrite the use.
5478 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5479
5480 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005481 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005482 assert(InsertPt != UserBB->end());
5483 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005484 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005485 }
5486
5487 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005488 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005489 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005490 MadeChange = true;
5491 }
5492
5493 return MadeChange;
5494}
5495
Geoff Berry5256fca2015-11-20 22:34:39 +00005496// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5497// just after the load if the target can fold this into one extload instruction,
5498// with the hope of eliminating some of the other later "and" instructions using
5499// the loaded value. "and"s that are made trivially redundant by the insertion
5500// of the new "and" are removed by this function, while others (e.g. those whose
5501// path from the load goes through a phi) are left for isel to potentially
5502// remove.
5503//
5504// For example:
5505//
5506// b0:
5507// x = load i32
5508// ...
5509// b1:
5510// y = and x, 0xff
5511// z = use y
5512//
5513// becomes:
5514//
5515// b0:
5516// x = load i32
5517// x' = and x, 0xff
5518// ...
5519// b1:
5520// z = use x'
5521//
5522// whereas:
5523//
5524// b0:
5525// x1 = load i32
5526// ...
5527// b1:
5528// x2 = load i32
5529// ...
5530// b2:
5531// x = phi x1, x2
5532// y = and x, 0xff
5533//
5534// becomes (after a call to optimizeLoadExt for each load):
5535//
5536// b0:
5537// x1 = load i32
5538// x1' = and x1, 0xff
5539// ...
5540// b1:
5541// x2 = load i32
5542// x2' = and x2, 0xff
5543// ...
5544// b2:
5545// x = phi x1', x2'
5546// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005547bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Vedant Kumarb3091da2018-07-06 20:17:42 +00005548 if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
Geoff Berry5256fca2015-11-20 22:34:39 +00005549 return false;
5550
Geoff Berry5d534b62017-02-21 18:53:14 +00005551 // Skip loads we've already transformed.
5552 if (Load->hasOneUse() &&
5553 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5554 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005555
5556 // Look at all uses of Load, looking through phis, to determine how many bits
5557 // of the loaded value are needed.
5558 SmallVector<Instruction *, 8> WorkList;
5559 SmallPtrSet<Instruction *, 16> Visited;
5560 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5561 for (auto *U : Load->users())
5562 WorkList.push_back(cast<Instruction>(U));
5563
5564 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5565 unsigned BitWidth = LoadResultVT.getSizeInBits();
5566 APInt DemandBits(BitWidth, 0);
5567 APInt WidestAndBits(BitWidth, 0);
5568
5569 while (!WorkList.empty()) {
5570 Instruction *I = WorkList.back();
5571 WorkList.pop_back();
5572
5573 // Break use-def graph loops.
5574 if (!Visited.insert(I).second)
5575 continue;
5576
5577 // For a PHI node, push all of its users.
5578 if (auto *Phi = dyn_cast<PHINode>(I)) {
5579 for (auto *U : Phi->users())
5580 WorkList.push_back(cast<Instruction>(U));
5581 continue;
5582 }
5583
5584 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005585 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005586 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5587 if (!AndC)
5588 return false;
5589 APInt AndBits = AndC->getValue();
5590 DemandBits |= AndBits;
5591 // Keep track of the widest and mask we see.
5592 if (AndBits.ugt(WidestAndBits))
5593 WidestAndBits = AndBits;
5594 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5595 AndsToMaybeRemove.push_back(I);
5596 break;
5597 }
5598
Eugene Zelenko900b6332017-08-29 22:32:07 +00005599 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005600 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5601 if (!ShlC)
5602 return false;
5603 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005604 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005605 break;
5606 }
5607
Eugene Zelenko900b6332017-08-29 22:32:07 +00005608 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005609 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5610 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005611 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005612 break;
5613 }
5614
5615 default:
5616 return false;
5617 }
5618 }
5619
5620 uint32_t ActiveBits = DemandBits.getActiveBits();
5621 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5622 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5623 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5624 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5625 // followed by an AND.
5626 // TODO: Look into removing this restriction by fixing backends to either
5627 // return false for isLoadExtLegal for i1 or have them select this pattern to
5628 // a single instruction.
5629 //
5630 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5631 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005632 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005633 WidestAndBits != DemandBits)
5634 return false;
5635
5636 LLVMContext &Ctx = Load->getType()->getContext();
5637 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5638 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5639
5640 // Reject cases that won't be matched as extloads.
5641 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5642 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5643 return false;
5644
5645 IRBuilder<> Builder(Load->getNextNode());
5646 auto *NewAnd = dyn_cast<Instruction>(
5647 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005648 // Mark this instruction as "inserted by CGP", so that other
5649 // optimizations don't touch it.
5650 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005651
5652 // Replace all uses of load with new and (except for the use of load in the
5653 // new and itself).
5654 Load->replaceAllUsesWith(NewAnd);
5655 NewAnd->setOperand(0, Load);
5656
5657 // Remove any and instructions that are now redundant.
5658 for (auto *And : AndsToMaybeRemove)
5659 // Check that the and mask is the same as the one we decided to put on the
5660 // new and.
5661 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5662 And->replaceAllUsesWith(NewAnd);
5663 if (&*CurInstIterator == And)
5664 CurInstIterator = std::next(And->getIterator());
5665 And->eraseFromParent();
5666 ++NumAndUses;
5667 }
5668
5669 ++NumAndsAdded;
5670 return true;
5671}
5672
Sanjay Patel69a50a12015-10-19 21:59:12 +00005673/// Check if V (an operand of a select instruction) is an expensive instruction
5674/// that is only used once.
5675static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5676 auto *I = dyn_cast<Instruction>(V);
5677 // If it's safe to speculatively execute, then it should not have side
5678 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005679 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5680 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005681}
5682
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005683/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005684static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005685 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005686 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005687 // If even a predictable select is cheap, then a branch can't be cheaper.
5688 if (!TLI->isPredictableSelectExpensive())
5689 return false;
5690
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005691 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005692 // whether a select is better represented as a branch.
5693
5694 // If metadata tells us that the select condition is obviously predictable,
5695 // then we want to replace the select with a branch.
5696 uint64_t TrueWeight, FalseWeight;
5697 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5698 uint64_t Max = std::max(TrueWeight, FalseWeight);
5699 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005700 if (Sum != 0) {
5701 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5702 if (Probability > TLI->getPredictableBranchThreshold())
5703 return true;
5704 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005705 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005706
5707 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5708
Sanjay Patel4e652762015-09-28 22:14:51 +00005709 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5710 // comparison condition. If the compare has more than one use, there's
5711 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005712 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005713 return false;
5714
Sanjay Patel69a50a12015-10-19 21:59:12 +00005715 // If either operand of the select is expensive and only needed on one side
5716 // of the select, we should form a branch.
5717 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5718 sinkSelectOperand(TTI, SI->getFalseValue()))
5719 return true;
5720
5721 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005722}
5723
Dehao Chen9bbb9412016-09-12 20:23:28 +00005724/// If \p isTrue is true, return the true value of \p SI, otherwise return
5725/// false value of \p SI. If the true/false value of \p SI is defined by any
5726/// select instructions in \p Selects, look through the defining select
5727/// instruction until the true/false value is not defined in \p Selects.
5728static Value *getTrueOrFalseValue(
5729 SelectInst *SI, bool isTrue,
5730 const SmallPtrSet<const Instruction *, 2> &Selects) {
5731 Value *V;
5732
5733 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5734 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005735 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005736 "The condition of DefSI does not match with SI");
5737 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5738 }
5739 return V;
5740}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005741
Nadav Rotem9d832022012-09-02 12:10:19 +00005742/// If we have a SelectInst that will likely profit from branch prediction,
5743/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005744bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Vedant Kumarfbc38732018-08-21 23:42:23 +00005745 // If branch conversion isn't desirable, exit early.
5746 if (DisableSelectToBranch || OptSize || !TLI)
5747 return false;
5748
Dehao Chen9bbb9412016-09-12 20:23:28 +00005749 // Find all consecutive select instructions that share the same condition.
5750 SmallVector<SelectInst *, 2> ASI;
5751 ASI.push_back(SI);
David Blaikie7d306532018-08-28 00:55:19 +00005752 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5753 It != SI->getParent()->end(); ++It) {
5754 SelectInst *I = dyn_cast<SelectInst>(&*It);
Dehao Chen9bbb9412016-09-12 20:23:28 +00005755 if (I && SI->getCondition() == I->getCondition()) {
5756 ASI.push_back(I);
5757 } else {
5758 break;
5759 }
5760 }
5761
5762 SelectInst *LastSI = ASI.back();
5763 // Increment the current iterator to skip all the rest of select instructions
5764 // because they will be either "not lowered" or "all lowered" to branch.
5765 CurInstIterator = std::next(LastSI->getIterator());
5766
Nadav Rotem9d832022012-09-02 12:10:19 +00005767 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5768
5769 // Can we convert the 'select' to CF ?
Vedant Kumarfbc38732018-08-21 23:42:23 +00005770 if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005771 return false;
5772
Nadav Rotem9d832022012-09-02 12:10:19 +00005773 TargetLowering::SelectSupportKind SelectKind;
5774 if (VectorCond)
5775 SelectKind = TargetLowering::VectorMaskSelect;
5776 else if (SI->getType()->isVectorTy())
5777 SelectKind = TargetLowering::ScalarCondVectorVal;
5778 else
5779 SelectKind = TargetLowering::ScalarValSelect;
5780
Sanjay Pateld66607b2016-04-26 17:11:17 +00005781 if (TLI->isSelectSupported(SelectKind) &&
5782 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5783 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005784
5785 ModifiedDT = true;
5786
Sanjay Patel69a50a12015-10-19 21:59:12 +00005787 // Transform a sequence like this:
5788 // start:
5789 // %cmp = cmp uge i32 %a, %b
5790 // %sel = select i1 %cmp, i32 %c, i32 %d
5791 //
5792 // Into:
5793 // start:
5794 // %cmp = cmp uge i32 %a, %b
5795 // br i1 %cmp, label %select.true, label %select.false
5796 // select.true:
5797 // br label %select.end
5798 // select.false:
5799 // br label %select.end
5800 // select.end:
5801 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5802 //
5803 // In addition, we may sink instructions that produce %c or %d from
5804 // the entry block into the destination(s) of the new branch.
5805 // If the true or false blocks do not contain a sunken instruction, that
5806 // block and its branch may be optimized away. In that case, one side of the
5807 // first branch will point directly to select.end, and the corresponding PHI
5808 // predecessor block will be the start block.
5809
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005810 // First, we split the block containing the select into 2 blocks.
5811 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005812 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005813 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005814
Sanjay Patel69a50a12015-10-19 21:59:12 +00005815 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005816 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005817
5818 // These are the new basic blocks for the conditional branch.
5819 // At least one will become an actual new basic block.
5820 BasicBlock *TrueBlock = nullptr;
5821 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005822 BranchInst *TrueBranch = nullptr;
5823 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005824
5825 // Sink expensive instructions into the conditional blocks to avoid executing
5826 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005827 for (SelectInst *SI : ASI) {
5828 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5829 if (TrueBlock == nullptr) {
5830 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5831 EndBlock->getParent(), EndBlock);
5832 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005833 TrueBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00005834 }
5835 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5836 TrueInst->moveBefore(TrueBranch);
5837 }
5838 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5839 if (FalseBlock == nullptr) {
5840 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5841 EndBlock->getParent(), EndBlock);
5842 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005843 FalseBranch->setDebugLoc(SI->getDebugLoc());
Dehao Chen9bbb9412016-09-12 20:23:28 +00005844 }
5845 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5846 FalseInst->moveBefore(FalseBranch);
5847 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005848 }
5849
5850 // If there was nothing to sink, then arbitrarily choose the 'false' side
5851 // for a new input value to the PHI.
5852 if (TrueBlock == FalseBlock) {
5853 assert(TrueBlock == nullptr &&
5854 "Unexpected basic block transform while optimizing select");
5855
5856 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5857 EndBlock->getParent(), EndBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005858 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5859 FalseBranch->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00005860 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005861
5862 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005863 // If we did not create a new block for one of the 'true' or 'false' paths
5864 // of the condition, it means that side of the branch goes to the end block
5865 // directly and the path originates from the start block from the point of
5866 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005867 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005868 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005869 TT = EndBlock;
5870 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005871 TrueBlock = StartBlock;
5872 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005873 TT = TrueBlock;
5874 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005875 FalseBlock = StartBlock;
5876 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005877 TT = TrueBlock;
5878 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005879 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005880 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005881
Dehao Chen9bbb9412016-09-12 20:23:28 +00005882 SmallPtrSet<const Instruction *, 2> INS;
5883 INS.insert(ASI.begin(), ASI.end());
5884 // Use reverse iterator because later select may use the value of the
5885 // earlier select, and we need to propagate value through earlier select
5886 // to get the PHI operand.
5887 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5888 SelectInst *SI = *It;
5889 // The select itself is replaced with a PHI Node.
5890 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5891 PN->takeName(SI);
5892 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5893 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Vedant Kumar1e8a2c92018-08-22 00:10:37 +00005894 PN->setDebugLoc(SI->getDebugLoc());
Sanjay Patel69a50a12015-10-19 21:59:12 +00005895
Dehao Chen9bbb9412016-09-12 20:23:28 +00005896 SI->replaceAllUsesWith(PN);
5897 SI->eraseFromParent();
5898 INS.erase(SI);
5899 ++NumSelectsExpanded;
5900 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005901
5902 // Instruct OptimizeBlock to skip to the next block.
5903 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005904 return true;
5905}
5906
Benjamin Kramer573ff362014-03-01 17:24:40 +00005907static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005908 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5909 int SplatElem = -1;
5910 for (unsigned i = 0; i < Mask.size(); ++i) {
5911 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5912 return false;
5913 SplatElem = Mask[i];
5914 }
5915
5916 return true;
5917}
5918
5919/// Some targets have expensive vector shifts if the lanes aren't all the same
5920/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5921/// it's often worth sinking a shufflevector splat down to its use so that
5922/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005923bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005924 BasicBlock *DefBB = SVI->getParent();
5925
5926 // Only do this xform if variable vector shifts are particularly expensive.
5927 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5928 return false;
5929
5930 // We only expect better codegen by sinking a shuffle if we can recognise a
5931 // constant splat.
5932 if (!isBroadcastShuffle(SVI))
5933 return false;
5934
5935 // InsertedShuffles - Only insert a shuffle in each block once.
5936 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5937
5938 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005939 for (User *U : SVI->users()) {
5940 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005941
5942 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005943 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005944 if (UserBB == DefBB) continue;
5945
5946 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005947 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005948
5949 // Everything checks out, sink the shuffle if the user's block doesn't
5950 // already have a copy.
5951 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5952
5953 if (!InsertedShuffle) {
5954 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005955 assert(InsertPt != UserBB->end());
5956 InsertedShuffle =
5957 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5958 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005959 }
5960
Chandler Carruthcdf47882014-03-09 03:16:01 +00005961 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005962 MadeChange = true;
5963 }
5964
5965 // If we removed all uses, nuke the shuffle.
5966 if (SVI->use_empty()) {
5967 SVI->eraseFromParent();
5968 MadeChange = true;
5969 }
5970
5971 return MadeChange;
5972}
5973
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005974bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5975 if (!TLI || !DL)
5976 return false;
5977
5978 Value *Cond = SI->getCondition();
5979 Type *OldType = Cond->getType();
5980 LLVMContext &Context = Cond->getContext();
5981 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5982 unsigned RegWidth = RegType.getSizeInBits();
5983
5984 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5985 return false;
5986
5987 // If the register width is greater than the type width, expand the condition
5988 // of the switch instruction and each case constant to the width of the
5989 // register. By widening the type of the switch condition, subsequent
5990 // comparisons (for case comparisons) will not need to be extended to the
5991 // preferred register width, so we will potentially eliminate N-1 extends,
5992 // where N is the number of cases in the switch.
5993 auto *NewType = Type::getIntNTy(Context, RegWidth);
5994
5995 // Zero-extend the switch condition and case constants unless the switch
5996 // condition is a function argument that is already being sign-extended.
5997 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5998 // everything instead.
5999 Instruction::CastOps ExtType = Instruction::ZExt;
6000 if (auto *Arg = dyn_cast<Argument>(Cond))
6001 if (Arg->hasSExtAttr())
6002 ExtType = Instruction::SExt;
6003
6004 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
6005 ExtInst->insertBefore(SI);
Vedant Kumar47606862018-08-22 01:23:31 +00006006 ExtInst->setDebugLoc(SI->getDebugLoc());
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006007 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00006008 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006009 APInt NarrowConst = Case.getCaseValue()->getValue();
6010 APInt WideConst = (ExtType == Instruction::ZExt) ?
6011 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
6012 Case.setValue(ConstantInt::get(Context, WideConst));
6013 }
6014
6015 return true;
6016}
6017
Zaara Syeda3a7578c2017-05-31 17:12:38 +00006018
Quentin Colombetc32615d2014-10-31 17:52:53 +00006019namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006020
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006021/// Helper class to promote a scalar operation to a vector one.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006022/// This class is used to move downward extractelement transition.
6023/// E.g.,
6024/// a = vector_op <2 x i32>
6025/// b = extractelement <2 x i32> a, i32 0
6026/// c = scalar_op b
6027/// store c
6028///
6029/// =>
6030/// a = vector_op <2 x i32>
6031/// c = vector_op a (equivalent to scalar_op on the related lane)
6032/// * d = extractelement <2 x i32> c, i32 0
6033/// * store d
6034/// Assuming both extractelement and store can be combine, we get rid of the
6035/// transition.
6036class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00006037 /// DataLayout associated with the current module.
6038 const DataLayout &DL;
6039
Quentin Colombetc32615d2014-10-31 17:52:53 +00006040 /// Used to perform some checks on the legality of vector operations.
6041 const TargetLowering &TLI;
6042
6043 /// Used to estimated the cost of the promoted chain.
6044 const TargetTransformInfo &TTI;
6045
6046 /// The transition being moved downwards.
6047 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006048
Quentin Colombetc32615d2014-10-31 17:52:53 +00006049 /// The sequence of instructions to be promoted.
6050 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006051
Quentin Colombetc32615d2014-10-31 17:52:53 +00006052 /// Cost of combining a store and an extract.
6053 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006054
Quentin Colombetc32615d2014-10-31 17:52:53 +00006055 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00006056 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00006057
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006058 /// The instruction that represents the current end of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006059 /// Since we are faking the promotion until we reach the end of the chain
6060 /// of computation, we need a way to get the current end of the transition.
6061 Instruction *getEndOfTransition() const {
6062 if (InstsToBePromoted.empty())
6063 return Transition;
6064 return InstsToBePromoted.back();
6065 }
6066
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006067 /// Return the index of the original value in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006068 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
6069 /// c, is at index 0.
6070 unsigned getTransitionOriginalValueIdx() const {
6071 assert(isa<ExtractElementInst>(Transition) &&
6072 "Other kind of transitions are not supported yet");
6073 return 0;
6074 }
6075
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006076 /// Return the index of the index in the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006077 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
6078 /// is at index 1.
6079 unsigned getTransitionIdx() const {
6080 assert(isa<ExtractElementInst>(Transition) &&
6081 "Other kind of transitions are not supported yet");
6082 return 1;
6083 }
6084
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006085 /// Get the type of the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006086 /// This is the type of the original value.
6087 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
6088 /// transition is <2 x i32>.
6089 Type *getTransitionType() const {
6090 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
6091 }
6092
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006093 /// Promote \p ToBePromoted by moving \p Def downward through.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006094 /// I.e., we have the following sequence:
6095 /// Def = Transition <ty1> a to <ty2>
6096 /// b = ToBePromoted <ty2> Def, ...
6097 /// =>
6098 /// b = ToBePromoted <ty1> a, ...
6099 /// Def = Transition <ty1> ToBePromoted to <ty2>
6100 void promoteImpl(Instruction *ToBePromoted);
6101
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006102 /// Check whether or not it is profitable to promote all the
Quentin Colombetc32615d2014-10-31 17:52:53 +00006103 /// instructions enqueued to be promoted.
6104 bool isProfitableToPromote() {
6105 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
6106 unsigned Index = isa<ConstantInt>(ValIdx)
6107 ? cast<ConstantInt>(ValIdx)->getZExtValue()
6108 : -1;
6109 Type *PromotedType = getTransitionType();
6110
6111 StoreInst *ST = cast<StoreInst>(CombineInst);
6112 unsigned AS = ST->getPointerAddressSpace();
6113 unsigned Align = ST->getAlignment();
6114 // Check if this store is supported.
6115 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00006116 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
6117 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006118 // If this is not supported, there is no way we can combine
6119 // the extract with the store.
6120 return false;
6121 }
6122
6123 // The scalar chain of computation has to pay for the transition
6124 // scalar to vector.
6125 // The vector chain has to account for the combining cost.
6126 uint64_t ScalarCost =
6127 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
6128 uint64_t VectorCost = StoreExtractCombineCost;
6129 for (const auto &Inst : InstsToBePromoted) {
6130 // Compute the cost.
6131 // By construction, all instructions being promoted are arithmetic ones.
6132 // Moreover, one argument is a constant that can be viewed as a splat
6133 // constant.
6134 Value *Arg0 = Inst->getOperand(0);
6135 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
6136 isa<ConstantFP>(Arg0);
6137 TargetTransformInfo::OperandValueKind Arg0OVK =
6138 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6139 : TargetTransformInfo::OK_AnyValue;
6140 TargetTransformInfo::OperandValueKind Arg1OVK =
6141 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
6142 : TargetTransformInfo::OK_AnyValue;
6143 ScalarCost += TTI.getArithmeticInstrCost(
6144 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
6145 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
6146 Arg0OVK, Arg1OVK);
6147 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006148 LLVM_DEBUG(
6149 dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
6150 << ScalarCost << "\nVector: " << VectorCost << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006151 return ScalarCost > VectorCost;
6152 }
6153
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006154 /// Generate a constant vector with \p Val with the same
Quentin Colombetc32615d2014-10-31 17:52:53 +00006155 /// number of elements as the transition.
6156 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00006157 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006158 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
6159 /// otherwise we generate a vector with as many undef as possible:
6160 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
6161 /// used at the index of the extract.
6162 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006163 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006164 if (!UseSplat) {
6165 // If we cannot determine where the constant must be, we have to
6166 // use a splat constant.
6167 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
6168 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
6169 ExtractIdx = CstVal->getSExtValue();
6170 else
6171 UseSplat = true;
6172 }
6173
6174 unsigned End = getTransitionType()->getVectorNumElements();
6175 if (UseSplat)
6176 return ConstantVector::getSplat(End, Val);
6177
6178 SmallVector<Constant *, 4> ConstVec;
6179 UndefValue *UndefVal = UndefValue::get(Val->getType());
6180 for (unsigned Idx = 0; Idx != End; ++Idx) {
6181 if (Idx == ExtractIdx)
6182 ConstVec.push_back(Val);
6183 else
6184 ConstVec.push_back(UndefVal);
6185 }
6186 return ConstantVector::get(ConstVec);
6187 }
6188
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006189 /// Check if promoting to a vector type an operand at \p OperandIdx
Quentin Colombetc32615d2014-10-31 17:52:53 +00006190 /// in \p Use can trigger undefined behavior.
6191 static bool canCauseUndefinedBehavior(const Instruction *Use,
6192 unsigned OperandIdx) {
6193 // This is not safe to introduce undef when the operand is on
6194 // the right hand side of a division-like instruction.
6195 if (OperandIdx != 1)
6196 return false;
6197 switch (Use->getOpcode()) {
6198 default:
6199 return false;
6200 case Instruction::SDiv:
6201 case Instruction::UDiv:
6202 case Instruction::SRem:
6203 case Instruction::URem:
6204 return true;
6205 case Instruction::FDiv:
6206 case Instruction::FRem:
6207 return !Use->hasNoNaNs();
6208 }
6209 llvm_unreachable(nullptr);
6210 }
6211
6212public:
Mehdi Amini44ede332015-07-09 02:09:04 +00006213 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
6214 const TargetTransformInfo &TTI, Instruction *Transition,
6215 unsigned CombineCost)
6216 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00006217 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00006218 assert(Transition && "Do not know how to promote null");
6219 }
6220
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006221 /// Check if we can promote \p ToBePromoted to \p Type.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006222 bool canPromote(const Instruction *ToBePromoted) const {
6223 // We could support CastInst too.
6224 return isa<BinaryOperator>(ToBePromoted);
6225 }
6226
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006227 /// Check if it is profitable to promote \p ToBePromoted
Quentin Colombetc32615d2014-10-31 17:52:53 +00006228 /// by moving downward the transition through.
6229 bool shouldPromote(const Instruction *ToBePromoted) const {
6230 // Promote only if all the operands can be statically expanded.
6231 // Indeed, we do not want to introduce any new kind of transitions.
6232 for (const Use &U : ToBePromoted->operands()) {
6233 const Value *Val = U.get();
6234 if (Val == getEndOfTransition()) {
6235 // If the use is a division and the transition is on the rhs,
6236 // we cannot promote the operation, otherwise we may create a
6237 // division by zero.
6238 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
6239 return false;
6240 continue;
6241 }
6242 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
6243 !isa<ConstantFP>(Val))
6244 return false;
6245 }
6246 // Check that the resulting operation is legal.
6247 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
6248 if (!ISDOpcode)
6249 return false;
6250 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00006251 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00006252 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00006253 }
6254
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006255 /// Check whether or not \p Use can be combined
Quentin Colombetc32615d2014-10-31 17:52:53 +00006256 /// with the transition.
6257 /// I.e., is it possible to do Use(Transition) => AnotherUse?
6258 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
6259
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006260 /// Record \p ToBePromoted as part of the chain to be promoted.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006261 void enqueueForPromotion(Instruction *ToBePromoted) {
6262 InstsToBePromoted.push_back(ToBePromoted);
6263 }
6264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006265 /// Set the instruction that will be combined with the transition.
Quentin Colombetc32615d2014-10-31 17:52:53 +00006266 void recordCombineInstruction(Instruction *ToBeCombined) {
6267 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
6268 CombineInst = ToBeCombined;
6269 }
6270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006271 /// Promote all the instructions enqueued for promotion if it is
Quentin Colombetc32615d2014-10-31 17:52:53 +00006272 /// is profitable.
6273 /// \return True if the promotion happened, false otherwise.
6274 bool promote() {
6275 // Check if there is something to promote.
6276 // Right now, if we do not have anything to combine with,
6277 // we assume the promotion is not profitable.
6278 if (InstsToBePromoted.empty() || !CombineInst)
6279 return false;
6280
6281 // Check cost.
6282 if (!StressStoreExtract && !isProfitableToPromote())
6283 return false;
6284
6285 // Promote.
6286 for (auto &ToBePromoted : InstsToBePromoted)
6287 promoteImpl(ToBePromoted);
6288 InstsToBePromoted.clear();
6289 return true;
6290 }
6291};
Eugene Zelenko900b6332017-08-29 22:32:07 +00006292
6293} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00006294
6295void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
6296 // At this point, we know that all the operands of ToBePromoted but Def
6297 // can be statically promoted.
6298 // For Def, we need to use its parameter in ToBePromoted:
6299 // b = ToBePromoted ty1 a
6300 // Def = Transition ty1 b to ty2
6301 // Move the transition down.
6302 // 1. Replace all uses of the promoted operation by the transition.
6303 // = ... b => = ... Def.
6304 assert(ToBePromoted->getType() == Transition->getType() &&
6305 "The type of the result of the transition does not match "
6306 "the final type");
6307 ToBePromoted->replaceAllUsesWith(Transition);
6308 // 2. Update the type of the uses.
6309 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
6310 Type *TransitionTy = getTransitionType();
6311 ToBePromoted->mutateType(TransitionTy);
6312 // 3. Update all the operands of the promoted operation with promoted
6313 // operands.
6314 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
6315 for (Use &U : ToBePromoted->operands()) {
6316 Value *Val = U.get();
6317 Value *NewVal = nullptr;
6318 if (Val == Transition)
6319 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
6320 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
6321 isa<ConstantFP>(Val)) {
6322 // Use a splat constant if it is not safe to use undef.
6323 NewVal = getConstantVector(
6324 cast<Constant>(Val),
6325 isa<UndefValue>(Val) ||
6326 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
6327 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00006328 llvm_unreachable("Did you modified shouldPromote and forgot to update "
6329 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006330 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6331 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006332 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006333 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6334}
6335
6336/// Some targets can do store(extractelement) with one instruction.
6337/// Try to push the extractelement towards the stores when the target
6338/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006339bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006340 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006341 if (DisableStoreExtract || !TLI ||
6342 (!StressStoreExtract &&
6343 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6344 Inst->getOperand(1), CombineCost)))
6345 return false;
6346
6347 // At this point we know that Inst is a vector to scalar transition.
6348 // Try to move it down the def-use chain, until:
6349 // - We can combine the transition with its single use
6350 // => we got rid of the transition.
6351 // - We escape the current basic block
6352 // => we would need to check that we are moving it at a cheaper place and
6353 // we do not do that for now.
6354 BasicBlock *Parent = Inst->getParent();
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006355 LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006356 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006357 // If the transition has more than one use, assume this is not going to be
6358 // beneficial.
6359 while (Inst->hasOneUse()) {
6360 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006361 LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006362
6363 if (ToBePromoted->getParent() != Parent) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006364 LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
6365 << ToBePromoted->getParent()->getName()
6366 << ") than the transition (" << Parent->getName()
6367 << ").\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006368 return false;
6369 }
6370
6371 if (VPH.canCombine(ToBePromoted)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006372 LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
6373 << "will be combined with: " << *ToBePromoted << '\n');
Quentin Colombetc32615d2014-10-31 17:52:53 +00006374 VPH.recordCombineInstruction(ToBePromoted);
6375 bool Changed = VPH.promote();
6376 NumStoreExtractExposed += Changed;
6377 return Changed;
6378 }
6379
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006380 LLVM_DEBUG(dbgs() << "Try promoting.\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006381 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6382 return false;
6383
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006384 LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006385
6386 VPH.enqueueForPromotion(ToBePromoted);
6387 Inst = ToBePromoted;
6388 }
6389 return false;
6390}
6391
Wei Mia2f0b592016-12-22 19:44:45 +00006392/// For the instruction sequence of store below, F and I values
6393/// are bundled together as an i64 value before being stored into memory.
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006394/// Sometimes it is more efficient to generate separate stores for F and I,
Wei Mia2f0b592016-12-22 19:44:45 +00006395/// which can remove the bitwise instructions or sink them to colder places.
6396///
6397/// (store (or (zext (bitcast F to i32) to i64),
6398/// (shl (zext I to i64), 32)), addr) -->
6399/// (store F, addr) and (store I, addr+4)
6400///
6401/// Similarly, splitting for other merged store can also be beneficial, like:
6402/// For pair of {i32, i32}, i64 store --> two i32 stores.
6403/// For pair of {i32, i16}, i64 store --> two i32 stores.
6404/// For pair of {i16, i16}, i32 store --> two i16 stores.
6405/// For pair of {i16, i8}, i32 store --> two i16 stores.
6406/// For pair of {i8, i8}, i16 store --> two i8 stores.
6407///
6408/// We allow each target to determine specifically which kind of splitting is
6409/// supported.
6410///
6411/// The store patterns are commonly seen from the simple code snippet below
6412/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6413/// void goo(const std::pair<int, float> &);
6414/// hoo() {
6415/// ...
6416/// goo(std::make_pair(tmp, ftmp));
6417/// ...
6418/// }
6419///
6420/// Although we already have similar splitting in DAG Combine, we duplicate
6421/// it in CodeGenPrepare to catch the case in which pattern is across
6422/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6423/// during code expansion.
6424static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6425 const TargetLowering &TLI) {
6426 // Handle simple but common cases only.
6427 Type *StoreType = SI.getValueOperand()->getType();
6428 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6429 DL.getTypeSizeInBits(StoreType) == 0)
6430 return false;
6431
6432 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6433 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6434 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6435 DL.getTypeSizeInBits(SplitStoreType))
6436 return false;
6437
6438 // Match the following patterns:
6439 // (store (or (zext LValue to i64),
6440 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6441 // or
6442 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6443 // (zext LValue to i64),
6444 // Expect both operands of OR and the first operand of SHL have only
6445 // one use.
6446 Value *LValue, *HValue;
6447 if (!match(SI.getValueOperand(),
6448 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6449 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6450 m_SpecificInt(HalfValBitSize))))))
6451 return false;
6452
6453 // Check LValue and HValue are int with size less or equal than 32.
6454 if (!LValue->getType()->isIntegerTy() ||
6455 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6456 !HValue->getType()->isIntegerTy() ||
6457 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6458 return false;
6459
6460 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6461 // as the input of target query.
6462 auto *LBC = dyn_cast<BitCastInst>(LValue);
6463 auto *HBC = dyn_cast<BitCastInst>(HValue);
6464 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6465 : EVT::getEVT(LValue->getType());
6466 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6467 : EVT::getEVT(HValue->getType());
6468 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6469 return false;
6470
6471 // Start to split store.
6472 IRBuilder<> Builder(SI.getContext());
6473 Builder.SetInsertPoint(&SI);
6474
6475 // If LValue/HValue is a bitcast in another BB, create a new one in current
6476 // BB so it may be merged with the splitted stores by dag combiner.
6477 if (LBC && LBC->getParent() != SI.getParent())
6478 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6479 if (HBC && HBC->getParent() != SI.getParent())
6480 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6481
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006482 bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
Wei Mia2f0b592016-12-22 19:44:45 +00006483 auto CreateSplitStore = [&](Value *V, bool Upper) {
6484 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6485 Value *Addr = Builder.CreateBitCast(
6486 SI.getOperand(1),
6487 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
Jonas Paulsson5612bb22018-03-13 08:36:20 +00006488 if ((IsLE && Upper) || (!IsLE && !Upper))
Wei Mia2f0b592016-12-22 19:44:45 +00006489 Addr = Builder.CreateGEP(
6490 SplitStoreType, Addr,
6491 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6492 Builder.CreateAlignedStore(
6493 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6494 };
6495
6496 CreateSplitStore(LValue, false);
6497 CreateSplitStore(HValue, true);
6498
6499 // Delete the old store.
6500 SI.eraseFromParent();
6501 return true;
6502}
6503
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006504// Return true if the GEP has two operands, the first operand is of a sequential
6505// type, and the second operand is a constant.
6506static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6507 gep_type_iterator I = gep_type_begin(*GEP);
6508 return GEP->getNumOperands() == 2 &&
6509 I.isSequential() &&
6510 isa<ConstantInt>(GEP->getOperand(1));
6511}
6512
6513// Try unmerging GEPs to reduce liveness interference (register pressure) across
6514// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6515// reducing liveness interference across those edges benefits global register
6516// allocation. Currently handles only certain cases.
6517//
6518// For example, unmerge %GEPI and %UGEPI as below.
6519//
6520// ---------- BEFORE ----------
6521// SrcBlock:
6522// ...
6523// %GEPIOp = ...
6524// ...
6525// %GEPI = gep %GEPIOp, Idx
6526// ...
6527// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6528// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6529// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6530// %UGEPI)
6531//
6532// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6533// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6534// ...
6535//
6536// DstBi:
6537// ...
6538// %UGEPI = gep %GEPIOp, UIdx
6539// ...
6540// ---------------------------
6541//
6542// ---------- AFTER ----------
6543// SrcBlock:
6544// ... (same as above)
6545// (* %GEPI is still alive on the indirectbr edges)
6546// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6547// unmerging)
6548// ...
6549//
6550// DstBi:
6551// ...
6552// %UGEPI = gep %GEPI, (UIdx-Idx)
6553// ...
6554// ---------------------------
6555//
6556// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6557// no longer alive on them.
6558//
6559// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6560// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6561// not to disable further simplications and optimizations as a result of GEP
6562// merging.
6563//
6564// Note this unmerging may increase the length of the data flow critical path
6565// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6566// between the register pressure and the length of data-flow critical
6567// path. Restricting this to the uncommon IndirectBr case would minimize the
6568// impact of potentially longer critical path, if any, and the impact on compile
6569// time.
6570static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6571 const TargetTransformInfo *TTI) {
6572 BasicBlock *SrcBlock = GEPI->getParent();
6573 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6574 // (non-IndirectBr) cases exit early here.
6575 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6576 return false;
6577 // Check that GEPI is a simple gep with a single constant index.
6578 if (!GEPSequentialConstIndexed(GEPI))
6579 return false;
6580 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6581 // Check that GEPI is a cheap one.
6582 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6583 > TargetTransformInfo::TCC_Basic)
6584 return false;
6585 Value *GEPIOp = GEPI->getOperand(0);
6586 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6587 if (!isa<Instruction>(GEPIOp))
6588 return false;
6589 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6590 if (GEPIOpI->getParent() != SrcBlock)
6591 return false;
6592 // Check that GEP is used outside the block, meaning it's alive on the
6593 // IndirectBr edge(s).
6594 if (find_if(GEPI->users(), [&](User *Usr) {
6595 if (auto *I = dyn_cast<Instruction>(Usr)) {
6596 if (I->getParent() != SrcBlock) {
6597 return true;
6598 }
6599 }
6600 return false;
6601 }) == GEPI->users().end())
6602 return false;
6603 // The second elements of the GEP chains to be unmerged.
6604 std::vector<GetElementPtrInst *> UGEPIs;
6605 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6606 // on IndirectBr edges.
6607 for (User *Usr : GEPIOp->users()) {
6608 if (Usr == GEPI) continue;
6609 // Check if Usr is an Instruction. If not, give up.
6610 if (!isa<Instruction>(Usr))
6611 return false;
6612 auto *UI = cast<Instruction>(Usr);
6613 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6614 if (UI->getParent() == SrcBlock)
6615 continue;
6616 // Check if Usr is a GEP. If not, give up.
6617 if (!isa<GetElementPtrInst>(Usr))
6618 return false;
6619 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6620 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6621 // the pointer operand to it. If so, record it in the vector. If not, give
6622 // up.
6623 if (!GEPSequentialConstIndexed(UGEPI))
6624 return false;
6625 if (UGEPI->getOperand(0) != GEPIOp)
6626 return false;
6627 if (GEPIIdx->getType() !=
6628 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6629 return false;
6630 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6631 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6632 > TargetTransformInfo::TCC_Basic)
6633 return false;
6634 UGEPIs.push_back(UGEPI);
6635 }
6636 if (UGEPIs.size() == 0)
6637 return false;
6638 // Check the materializing cost of (Uidx-Idx).
6639 for (GetElementPtrInst *UGEPI : UGEPIs) {
6640 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6641 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6642 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6643 if (ImmCost > TargetTransformInfo::TCC_Basic)
6644 return false;
6645 }
6646 // Now unmerge between GEPI and UGEPIs.
6647 for (GetElementPtrInst *UGEPI : UGEPIs) {
6648 UGEPI->setOperand(0, GEPI);
6649 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6650 Constant *NewUGEPIIdx =
6651 ConstantInt::get(GEPIIdx->getType(),
6652 UGEPIIdx->getValue() - GEPIIdx->getValue());
6653 UGEPI->setOperand(1, NewUGEPIIdx);
6654 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6655 // inbounds to avoid UB.
6656 if (!GEPI->isInBounds()) {
6657 UGEPI->setIsInBounds(false);
6658 }
6659 }
6660 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6661 // alive on IndirectBr edges).
6662 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6663 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6664 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6665 return true;
6666}
6667
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006668bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006669 // Bail out if we inserted the instruction to prevent optimizations from
6670 // stepping on each other's toes.
6671 if (InsertedInsts.count(I))
6672 return false;
6673
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006674 if (PHINode *P = dyn_cast<PHINode>(I)) {
6675 // It is possible for very late stage optimizations (such as SimplifyCFG)
6676 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6677 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006678 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006679 P->replaceAllUsesWith(V);
6680 P->eraseFromParent();
6681 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006682 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006683 }
Chris Lattneree588de2011-01-15 07:29:01 +00006684 return false;
6685 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006686
Chris Lattneree588de2011-01-15 07:29:01 +00006687 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006688 // If the source of the cast is a constant, then this should have
6689 // already been constant folded. The only reason NOT to constant fold
6690 // it is if something (e.g. LSR) was careful to place the constant
6691 // evaluation in a block other than then one that uses it (e.g. to hoist
6692 // the address of globals out of a loop). If this is the case, we don't
6693 // want to forward-subst the cast.
6694 if (isa<Constant>(CI->getOperand(0)))
6695 return false;
6696
Mehdi Amini44ede332015-07-09 02:09:04 +00006697 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006698 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006699
Chris Lattneree588de2011-01-15 07:29:01 +00006700 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006701 /// Sink a zext or sext into its user blocks if the target type doesn't
6702 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006703 if (TLI &&
6704 TLI->getTypeAction(CI->getContext(),
6705 TLI->getValueType(*DL, CI->getType())) ==
6706 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006707 return SinkCast(CI);
6708 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006709 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006710 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006711 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006712 }
Chris Lattneree588de2011-01-15 07:29:01 +00006713 return false;
6714 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006715
Chris Lattneree588de2011-01-15 07:29:01 +00006716 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006717 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006718 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006719
Chris Lattneree588de2011-01-15 07:29:01 +00006720 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006721 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006722 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006723 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006724 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006725 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6726 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006727 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006728 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006729 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006730
Chris Lattneree588de2011-01-15 07:29:01 +00006731 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006732 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6733 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006734 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006735 if (TLI) {
6736 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006737 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006738 SI->getOperand(0)->getType(), AS);
6739 }
Chris Lattneree588de2011-01-15 07:29:01 +00006740 return false;
6741 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006742
Matt Arsenault02d915b2017-03-15 22:35:20 +00006743 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6744 unsigned AS = RMW->getPointerAddressSpace();
6745 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6746 RMW->getType(), AS);
6747 }
6748
6749 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6750 unsigned AS = CmpX->getPointerAddressSpace();
6751 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6752 CmpX->getCompareOperand()->getType(), AS);
6753 }
6754
Yi Jiangd069f632014-04-21 19:34:27 +00006755 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6756
Geoff Berry5d534b62017-02-21 18:53:14 +00006757 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6758 EnableAndCmpSinking && TLI)
6759 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6760
Yi Jiangd069f632014-04-21 19:34:27 +00006761 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6762 BinOp->getOpcode() == Instruction::LShr)) {
6763 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6764 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006765 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006766
6767 return false;
6768 }
6769
Chris Lattneree588de2011-01-15 07:29:01 +00006770 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006771 if (GEPI->hasAllZeroIndices()) {
6772 /// The GEP operand must be a pointer, so must its result -> BitCast
6773 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6774 GEPI->getName(), GEPI);
Vedant Kumar40399a22018-05-24 23:00:21 +00006775 NC->setDebugLoc(GEPI->getDebugLoc());
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006776 GEPI->replaceAllUsesWith(NC);
6777 GEPI->eraseFromParent();
6778 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006779 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006780 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006781 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006782 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6783 return true;
6784 }
Chris Lattneree588de2011-01-15 07:29:01 +00006785 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006786 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006787
Chris Lattneree588de2011-01-15 07:29:01 +00006788 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006789 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006790
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006791 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006792 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006793
Tim Northoveraeb8e062014-02-19 10:02:43 +00006794 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006795 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006796
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006797 if (auto *Switch = dyn_cast<SwitchInst>(I))
6798 return optimizeSwitchInst(Switch);
6799
Quentin Colombetc32615d2014-10-31 17:52:53 +00006800 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006801 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006802
Chris Lattneree588de2011-01-15 07:29:01 +00006803 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006804}
6805
James Molloyf01488e2016-01-15 09:20:19 +00006806/// Given an OR instruction, check to see if this is a bitreverse
6807/// idiom. If so, insert the new intrinsic and return true.
6808static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6809 const TargetLowering &TLI) {
6810 if (!I.getType()->isIntegerTy() ||
6811 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6812 TLI.getValueType(DL, I.getType(), true)))
6813 return false;
6814
6815 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006816 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006817 return false;
6818 Instruction *LastInst = Insts.back();
6819 I.replaceAllUsesWith(LastInst);
6820 RecursivelyDeleteTriviallyDeadInstructions(&I);
6821 return true;
6822}
6823
Chris Lattnerf2836d12007-03-31 04:06:36 +00006824// In this pass we look for GEP and cast instructions that are used
6825// across basic blocks and rewrite them to improve basic-block-at-a-time
6826// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006827bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006828 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006829 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006830
Chris Lattner7a277142011-01-15 07:14:54 +00006831 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006832 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006833 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006834 if (ModifiedDT)
6835 return true;
6836 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006837
James Molloyf01488e2016-01-15 09:20:19 +00006838 bool MadeBitReverse = true;
6839 while (TLI && MadeBitReverse) {
6840 MadeBitReverse = false;
6841 for (auto &I : reverse(BB)) {
6842 if (makeBitReverse(I, *DL, *TLI)) {
6843 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006844 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006845 break;
6846 }
6847 }
6848 }
James Molloy3ef84c42016-01-15 10:36:01 +00006849 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006850
Chris Lattnerf2836d12007-03-31 04:06:36 +00006851 return MadeChange;
6852}
Devang Patel53771ba2011-08-18 00:50:51 +00006853
6854// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006855// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006856// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006857bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006858 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006859 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006860 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006861 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006862 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006863 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006864 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006865 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006866 // being taken. They should not be moved next to the alloca
6867 // (and to the beginning of the scope), but rather stay close to
6868 // where said address is used.
6869 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006870 PrevNonDbgInst = Insn;
6871 continue;
6872 }
6873
6874 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6875 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006876 // If VI is a phi in a block with an EHPad terminator, we can't insert
6877 // after it.
6878 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6879 continue;
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006880 LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
6881 << *DVI << ' ' << *VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006882 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006883 if (isa<PHINode>(VI))
6884 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6885 else
6886 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006887 MadeChange = true;
6888 ++NumDbgValueMoved;
6889 }
6890 }
6891 }
6892 return MadeChange;
6893}
Tim Northovercea0abb2014-03-29 08:22:29 +00006894
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006895/// Scale down both weights to fit into uint32_t.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006896static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6897 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006898 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006899 NewTrue = NewTrue / Scale;
6900 NewFalse = NewFalse / Scale;
6901}
6902
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00006903/// Some targets prefer to split a conditional branch like:
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006904/// \code
6905/// %0 = icmp ne i32 %a, 0
6906/// %1 = icmp ne i32 %b, 0
6907/// %or.cond = or i1 %0, %1
6908/// br i1 %or.cond, label %TrueBB, label %FalseBB
6909/// \endcode
6910/// into multiple branch instructions like:
6911/// \code
6912/// bb1:
6913/// %0 = icmp ne i32 %a, 0
6914/// br i1 %0, label %TrueBB, label %bb2
6915/// bb2:
6916/// %1 = icmp ne i32 %b, 0
6917/// br i1 %1, label %TrueBB, label %FalseBB
6918/// \endcode
6919/// This usually allows instruction selection to do even further optimizations
6920/// and combine the compare with the branch instruction. Currently this is
6921/// applied for targets which have "cheap" jump instructions.
6922///
6923/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6924///
6925bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006926 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006927 return false;
6928
6929 bool MadeChange = false;
6930 for (auto &BB : F) {
6931 // Does this BB end with the following?
6932 // %cond1 = icmp|fcmp|binary instruction ...
6933 // %cond2 = icmp|fcmp|binary instruction ...
6934 // %cond.or = or|and i1 %cond1, cond2
6935 // br i1 %cond.or label %dest1, label %dest2"
6936 BinaryOperator *LogicOp;
6937 BasicBlock *TBB, *FBB;
6938 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6939 continue;
6940
Sanjay Patel42574202015-09-02 19:23:23 +00006941 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6942 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6943 continue;
6944
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006945 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006946 Value *Cond1, *Cond2;
6947 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6948 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006949 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006950 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6951 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006952 Opc = Instruction::Or;
6953 else
6954 continue;
6955
6956 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6957 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6958 continue;
6959
Nicola Zaghend34e60c2018-05-14 12:53:11 +00006960 LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006961
6962 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006963 auto TmpBB =
6964 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6965 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006966
6967 // Update original basic block by using the first condition directly by the
6968 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006969 Br1->setCondition(Cond1);
6970 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006971
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00006972 // Depending on the condition we have to either replace the true or the
6973 // false successor of the original branch instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006974 if (Opc == Instruction::And)
6975 Br1->setSuccessor(0, TmpBB);
6976 else
6977 Br1->setSuccessor(1, TmpBB);
6978
6979 // Fill in the new basic block.
6980 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006981 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6982 I->removeFromParent();
6983 I->insertBefore(Br2);
6984 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006985
6986 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006987 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006988 // the newly generated BB (NewBB). In the other successor we need to add one
6989 // incoming edge to the PHI nodes, because both branch instructions target
6990 // now the same successor. Depending on the original branch condition
6991 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006992 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006993 // This doesn't change the successor order of the just created branch
6994 // instruction (or any other instruction).
6995 if (Opc == Instruction::Or)
6996 std::swap(TBB, FBB);
6997
6998 // Replace the old BB with the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00006999 for (PHINode &PN : TBB->phis()) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007000 int i;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007001 while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
7002 PN.setIncomingBlock(i, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007003 }
7004
7005 // Add another incoming edge form the new BB.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +00007006 for (PHINode &PN : FBB->phis()) {
7007 auto *Val = PN.getIncomingValueForBlock(&BB);
7008 PN.addIncoming(Val, TmpBB);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007009 }
7010
7011 // Update the branch weights (from SelectionDAGBuilder::
7012 // FindMergedConditions).
7013 if (Opc == Instruction::Or) {
7014 // Codegen X | Y as:
7015 // BB1:
7016 // jmp_if_X TBB
7017 // jmp TmpBB
7018 // TmpBB:
7019 // jmp_if_Y TBB
7020 // jmp FBB
7021 //
7022
7023 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
7024 // The requirement is that
7025 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007026 // = TrueProb for original BB.
7027 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007028 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
7029 // assumes that
7030 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
7031 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
7032 // TmpBB, but the math is more complicated.
7033 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007034 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007035 uint64_t NewTrueWeight = TrueWeight;
7036 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
7037 scaleWeights(NewTrueWeight, NewFalseWeight);
7038 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7039 .createBranchWeights(TrueWeight, FalseWeight));
7040
7041 NewTrueWeight = TrueWeight;
7042 NewFalseWeight = 2 * FalseWeight;
7043 scaleWeights(NewTrueWeight, NewFalseWeight);
7044 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7045 .createBranchWeights(TrueWeight, FalseWeight));
7046 }
7047 } else {
7048 // Codegen X & Y as:
7049 // BB1:
7050 // jmp_if_X TmpBB
7051 // jmp FBB
7052 // TmpBB:
7053 // jmp_if_Y TBB
7054 // jmp FBB
7055 //
7056 // This requires creation of TmpBB after CurBB.
7057
7058 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
7059 // The requirement is that
7060 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
Hiroshi Inouec73b6d62018-06-20 05:29:26 +00007061 // = FalseProb for original BB.
7062 // Assuming the original weights are A and B, one choice is to set BB1's
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007063 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
7064 // assumes that
7065 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
7066 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00007067 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007068 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
7069 uint64_t NewFalseWeight = FalseWeight;
7070 scaleWeights(NewTrueWeight, NewFalseWeight);
7071 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
7072 .createBranchWeights(TrueWeight, FalseWeight));
7073
7074 NewTrueWeight = 2 * TrueWeight;
7075 NewFalseWeight = FalseWeight;
7076 scaleWeights(NewTrueWeight, NewFalseWeight);
7077 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
7078 .createBranchWeights(TrueWeight, FalseWeight));
7079 }
7080 }
7081
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007082 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00007083 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007084 ModifiedDT = true;
7085
7086 MadeChange = true;
7087
Nicola Zaghend34e60c2018-05-14 12:53:11 +00007088 LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
7089 TmpBB->dump());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00007090 }
7091 return MadeChange;
7092}