blob: 9d3e7230ed00ad753135c692d8bca63a1e320b0d [file] [log] [blame]
Chris Lattnerf2836d12007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerf2836d12007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksen829046b2008-05-08 17:46:35 +000011// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
Chris Lattnerf2836d12007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
Eugene Zelenko900b6332017-08-29 22:32:07 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000019#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000021#include "llvm/ADT/SetVector.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000022#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000025#include "llvm/Analysis/BlockFrequencyInfo.h"
26#include "llvm/Analysis/BranchProbabilityInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000027#include "llvm/Analysis/ConstantFolding.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000029#include "llvm/Analysis/LoopInfo.h"
Zaara Syeda3a7578c2017-05-31 17:12:38 +000030#include "llvm/Analysis/MemoryBuiltins.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000031#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000032#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000033#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000034#include "llvm/Analysis/ValueTracking.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000035#include "llvm/CodeGen/Analysis.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000036#include "llvm/CodeGen/ISDOpcodes.h"
37#include "llvm/CodeGen/MachineValueType.h"
38#include "llvm/CodeGen/SelectionDAGNodes.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000039#include "llvm/CodeGen/TargetLowering.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000040#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000041#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000042#include "llvm/CodeGen/ValueTypes.h"
43#include "llvm/IR/Argument.h"
44#include "llvm/IR/Attributes.h"
45#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000046#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000047#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000048#include "llvm/IR/Constants.h"
49#include "llvm/IR/DataLayout.h"
50#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000051#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000052#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000053#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000054#include "llvm/IR/GlobalValue.h"
55#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000056#include "llvm/IR/IRBuilder.h"
57#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000058#include "llvm/IR/InstrTypes.h"
59#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000060#include "llvm/IR/Instructions.h"
61#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000062#include "llvm/IR/Intrinsics.h"
63#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000064#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000065#include "llvm/IR/Module.h"
66#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000067#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000068#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000069#include "llvm/IR/Type.h"
70#include "llvm/IR/Use.h"
71#include "llvm/IR/User.h"
72#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000073#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000074#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000075#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000076#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000077#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000078#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000079#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000080#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000081#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000082#include "llvm/Support/ErrorHandling.h"
83#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"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000089#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000090#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000091#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000092#include "llvm/Transforms/Utils/ValueMapper.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000093#include <algorithm>
94#include <cassert>
95#include <cstdint>
96#include <iterator>
97#include <limits>
98#include <memory>
99#include <utility>
100#include <vector>
Zaara Syeda3a7578c2017-05-31 17:12:38 +0000101
Chris Lattnerf2836d12007-03-31 04:06:36 +0000102using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +0000103using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000104
Chandler Carruth1b9dde02014-04-22 02:02:50 +0000105#define DEBUG_TYPE "codegenprepare"
106
Cameron Zwarichced753f2011-01-05 17:27:27 +0000107STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +0000108STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
109STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +0000110STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
111 "sunken Cmps");
112STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
113 "of sunken Casts");
114STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
115 "computations were sunk");
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000116STATISTIC(NumMemoryInstsPhiCreated,
117 "Number of phis created when address "
118 "computations were sunk to memory instructions");
119STATISTIC(NumMemoryInstsSelectCreated,
120 "Number of select created when address "
121 "computations were sunk to memory instructions");
Evan Cheng0663f232011-03-21 01:19:09 +0000122STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
123STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +0000124STATISTIC(NumAndsAdded,
125 "Number of and mask instructions added to form ext loads");
126STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +0000127STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +0000128STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000129STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +0000130STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +0000131
Cameron Zwarich338d3622011-03-11 21:52:04 +0000132static cl::opt<bool> DisableBranchOpts(
133 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
134 cl::desc("Disable branch optimizations in CodeGenPrepare"));
135
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000136static cl::opt<bool>
137 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
138 cl::desc("Disable GC optimizations in CodeGenPrepare"));
139
Benjamin Kramer3d38c172012-05-06 14:25:16 +0000140static cl::opt<bool> DisableSelectToBranch(
141 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
142 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000143
Hal Finkelc3998302014-04-12 00:59:48 +0000144static cl::opt<bool> AddrSinkUsingGEPs(
Eli Friedman5fba1e52017-04-06 22:42:18 +0000145 "addr-sink-using-gep", cl::Hidden, cl::init(true),
Hal Finkelc3998302014-04-12 00:59:48 +0000146 cl::desc("Address sinking in CGP using GEPs."));
147
Tim Northovercea0abb2014-03-29 08:22:29 +0000148static cl::opt<bool> EnableAndCmpSinking(
149 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
150 cl::desc("Enable sinkinig and/cmp into branches."));
151
Quentin Colombetc32615d2014-10-31 17:52:53 +0000152static cl::opt<bool> DisableStoreExtract(
153 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
154 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
155
156static cl::opt<bool> StressStoreExtract(
157 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
158 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
159
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000160static cl::opt<bool> DisableExtLdPromotion(
161 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
162 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
163 "CodeGenPrepare"));
164
165static cl::opt<bool> StressExtLdPromotion(
166 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
167 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
168 "optimization in CodeGenPrepare"));
169
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000170static cl::opt<bool> DisablePreheaderProtect(
171 "disable-preheader-prot", cl::Hidden, cl::init(false),
172 cl::desc("Disable protection against removing loop preheaders"));
173
Dehao Chen302b69c2016-10-18 20:42:47 +0000174static cl::opt<bool> ProfileGuidedSectionPrefix(
David Callahan5960d9b12017-06-14 20:35:33 +0000175 "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
Dehao Chen302b69c2016-10-18 20:42:47 +0000176 cl::desc("Use profile info to add section prefix for hot/cold functions"));
177
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000178static cl::opt<unsigned> FreqRatioToSkipMerge(
179 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
180 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
181 "(frequency of destination block) is greater than this ratio"));
182
Wei Mia2f0b592016-12-22 19:44:45 +0000183static cl::opt<bool> ForceSplitStore(
184 "force-split-store", cl::Hidden, cl::init(false),
185 cl::desc("Force store splitting no matter what the target query says."));
186
Jun Bum Limdee55652017-04-03 19:20:07 +0000187static cl::opt<bool>
188EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
189 cl::desc("Enable merging of redundant sexts when one is dominating"
190 " the other."), cl::init(true));
191
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000192static cl::opt<bool> DisableComplexAddrModes(
Serguei Katkovd4df7442017-11-29 09:48:50 +0000193 "disable-complex-addr-modes", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000194 cl::desc("Disables combining addressing modes with different parts "
195 "in optimizeMemoryInst."));
196
197static cl::opt<bool>
198AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
199 cl::desc("Allow creation of Phis in Address sinking."));
200
201static cl::opt<bool>
Serguei Katkov36520022017-11-07 09:43:08 +0000202AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(false),
Serguei Katkovd5d8d542017-11-05 05:50:33 +0000203 cl::desc("Allow creation of selects in Address sinking."));
204
John Brawn70cdb5b2017-11-24 14:10:45 +0000205static cl::opt<bool> AddrSinkCombineBaseReg(
206 "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
207 cl::desc("Allow combining of BaseReg field in Address sinking."));
208
209static cl::opt<bool> AddrSinkCombineBaseGV(
210 "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
211 cl::desc("Allow combining of BaseGV field in Address sinking."));
212
213static cl::opt<bool> AddrSinkCombineBaseOffs(
214 "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
215 cl::desc("Allow combining of BaseOffs field in Address sinking."));
216
217static cl::opt<bool> AddrSinkCombineScaledReg(
218 "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
219 cl::desc("Allow combining of ScaledReg field in Address sinking."));
220
Eric Christopherc1ea1492008-09-24 05:32:41 +0000221namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000222
223using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
224using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
225using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
226using SExts = SmallVector<Instruction *, 16>;
227using ValueToSExts = DenseMap<Value *, SExts>;
228
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000229class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000230
Chris Lattner2dd09db2009-09-02 06:11:42 +0000231 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000232 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000233 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000234 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000235 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000236 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000237 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000238 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000239 std::unique_ptr<BlockFrequencyInfo> BFI;
240 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000241
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000242 /// As we scan instructions optimizing them, this is the next instruction
243 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000244 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000245
Evan Cheng0663f232011-03-21 01:19:09 +0000246 /// Keeps track of non-local addresses that have been sunk into a block.
247 /// This allows us to avoid inserting duplicate code for blocks with
Simon Dardis230f4532017-11-24 16:45:28 +0000248 /// multiple load/stores of the same address. The usage of WeakTrackingVH
249 /// enables SunkAddrs to be treated as a cache whose entries can be
250 /// invalidated if a sunken address computation has been erased.
251 ValueMap<Value*, WeakTrackingVH> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000252
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000253 /// Keeps track of all instructions inserted for the current function.
254 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000255
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000256 /// Keeps track of the type of the related instruction before their
257 /// promotion for the current function.
258 InstrToOrigTy PromotedInsts;
259
Jun Bum Limdee55652017-04-03 19:20:07 +0000260 /// Keep track of instructions removed during promotion.
261 SetOfInstrs RemovedInsts;
262
263 /// Keep track of sext chains based on their initial value.
264 DenseMap<Value *, Instruction *> SeenChainsForSExt;
265
266 /// Keep track of SExt promoted.
267 ValueToSExts ValToSExtendedUses;
268
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000269 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000270 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000271
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000272 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000273 bool OptSize;
274
Mehdi Amini4fe37982015-07-07 18:45:17 +0000275 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000276 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000277
Chris Lattnerf2836d12007-03-31 04:06:36 +0000278 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000279 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000280
281 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000282 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
283 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000284
Craig Topper4584cd52014-03-07 09:26:03 +0000285 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000286
Mehdi Amini117296c2016-10-01 02:56:57 +0000287 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000288
Craig Topper4584cd52014-03-07 09:26:03 +0000289 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000290 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000291 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000292 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000293 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000294 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000295 }
296
Chris Lattnerf2836d12007-03-31 04:06:36 +0000297 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000298 bool eliminateFallThrough(Function &F);
299 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000300 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000301 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
302 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000303 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
304 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000305 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
306 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000307 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000308 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000309 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000310 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000311 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000312 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000313 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000314 bool optimizeSelectInst(SelectInst *SI);
315 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000316 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000317 bool optimizeExtractElementInst(Instruction *Inst);
318 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
319 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000320 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
321 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
322 bool tryToPromoteExts(TypePromotionTransaction &TPT,
323 const SmallVectorImpl<Instruction *> &Exts,
324 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
325 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000326 bool mergeSExts(Function &F);
327 bool performAddressTypePromotion(
328 Instruction *&Inst,
329 bool AllowPromotionWithoutCommonHeader,
330 bool HasPromoted, TypePromotionTransaction &TPT,
331 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000332 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000333 bool simplifyOffsetableRelocate(Instruction &I);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000334 bool splitIndirectCriticalEdges(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000335 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000336
337} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000338
Devang Patel8c78a0b2007-05-03 01:11:54 +0000339char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000340
Matthias Braun1527baa2017-05-25 21:26:32 +0000341INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000342 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000343INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000344INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000345 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000346
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000347FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000348
Chris Lattnerf2836d12007-03-31 04:06:36 +0000349bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000350 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000351 return false;
352
Mehdi Amini4fe37982015-07-07 18:45:17 +0000353 DL = &F.getParent()->getDataLayout();
354
Chris Lattnerf2836d12007-03-31 04:06:36 +0000355 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000356 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000357 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000358 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000359 BFI.reset();
360 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000361
Devang Patel8f606d72011-03-24 15:35:25 +0000362 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000363 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
364 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000365 SubtargetInfo = TM->getSubtargetImpl(F);
366 TLI = SubtargetInfo->getTargetLowering();
367 TRI = SubtargetInfo->getRegisterInfo();
368 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000369 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000370 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000371 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000372 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000373
Easwaran Raman0d55b552017-11-14 19:31:51 +0000374 ProfileSummaryInfo *PSI =
375 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen302b69c2016-10-18 20:42:47 +0000376 if (ProfileGuidedSectionPrefix) {
Dehao Chen775341a2017-03-23 23:14:11 +0000377 if (PSI->isFunctionHotInCallGraph(&F))
Dehao Chen302b69c2016-10-18 20:42:47 +0000378 F.setSectionPrefix(".hot");
Dehao Chen775341a2017-03-23 23:14:11 +0000379 else if (PSI->isFunctionColdInCallGraph(&F))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000380 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000381 }
382
Preston Gurdcdf540d2012-09-04 18:22:17 +0000383 /// This optimization identifies DIV instructions that can be
384 /// profitably bypassed and carried out with a shorter, faster divide.
Easwaran Raman0d55b552017-11-14 19:31:51 +0000385 if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
386 TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000387 const DenseMap<unsigned int, unsigned int> &BypassWidths =
388 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000389 BasicBlock* BB = &*F.begin();
390 while (BB != nullptr) {
391 // bypassSlowDivision may create new BBs, but we don't want to reapply the
392 // optimization to those blocks.
393 BasicBlock* Next = BB->getNextNode();
394 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
395 BB = Next;
396 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000397 }
398
399 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000400 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000401 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000402
Devang Patel53771ba2011-08-18 00:50:51 +0000403 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000404 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000405 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000406 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000407
Geoff Berry5d534b62017-02-21 18:53:14 +0000408 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000409 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000410
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000411 // Split some critical edges where one of the sources is an indirect branch,
412 // to help generate sane code for PHIs involving such edges.
413 EverMadeChange |= splitIndirectCriticalEdges(F);
414
Chris Lattnerc3748562007-04-02 01:35:34 +0000415 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000416 while (MadeChange) {
417 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000418 SeenChainsForSExt.clear();
419 ValToSExtendedUses.clear();
420 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000421 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000422 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000423 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000424 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000425
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000426 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000427 if (ModifiedDTOnIteration)
428 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000429 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000430 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
431 MadeChange |= mergeSExts(F);
432
433 // Really free removed instructions during promotion.
434 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000435 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000436
Chris Lattnerf2836d12007-03-31 04:06:36 +0000437 EverMadeChange |= MadeChange;
438 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000439
440 SunkAddrs.clear();
441
Cameron Zwarich338d3622011-03-11 21:52:04 +0000442 if (!DisableBranchOpts) {
443 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000444 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000445 for (BasicBlock &BB : F) {
446 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
447 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000448 if (!MadeChange) continue;
449
450 for (SmallVectorImpl<BasicBlock*>::iterator
451 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
452 if (pred_begin(*II) == pred_end(*II))
453 WorkList.insert(*II);
454 }
455
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000456 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000457 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000458 while (!WorkList.empty()) {
459 BasicBlock *BB = *WorkList.begin();
460 WorkList.erase(BB);
461 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
462
463 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000464
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000465 for (SmallVectorImpl<BasicBlock*>::iterator
466 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
467 if (pred_begin(*II) == pred_end(*II))
468 WorkList.insert(*II);
469 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000470
Nadav Rotem70409992012-08-14 05:19:07 +0000471 // Merge pairs of basic blocks with unconditional branches, connected by
472 // a single edge.
473 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000474 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000475
Cameron Zwarich338d3622011-03-11 21:52:04 +0000476 EverMadeChange |= MadeChange;
477 }
478
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000479 if (!DisableGCOpts) {
480 SmallVector<Instruction *, 2> Statepoints;
481 for (BasicBlock &BB : F)
482 for (Instruction &I : BB)
483 if (isStatepoint(I))
484 Statepoints.push_back(&I);
485 for (auto &I : Statepoints)
486 EverMadeChange |= simplifyOffsetableRelocate(*I);
487 }
488
Chris Lattnerf2836d12007-03-31 04:06:36 +0000489 return EverMadeChange;
490}
491
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000492/// Merge basic blocks which are connected by a single edge, where one of the
493/// basic blocks has a single successor pointing to the other basic block,
494/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000495bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000496 bool Changed = false;
497 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000498 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000499 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000500 // If the destination block has a single pred, then this is a trivial
501 // edge, just collapse it.
502 BasicBlock *SinglePred = BB->getSinglePredecessor();
503
Evan Cheng64a223a2012-09-28 23:58:57 +0000504 // Don't merge if BB's address is taken.
505 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000506
507 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
508 if (Term && !Term->isConditional()) {
509 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000510 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000511 // Remember if SinglePred was the entry block of the function.
512 // If so, we will need to move BB back to the entry position.
513 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000514 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000515
516 if (isEntry && BB != &BB->getParent()->getEntryBlock())
517 BB->moveBefore(&BB->getParent()->getEntryBlock());
518
519 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000520 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000521 }
522 }
523 return Changed;
524}
525
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000526/// Find a destination block from BB if BB is mergeable empty block.
527BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
528 // If this block doesn't end with an uncond branch, ignore it.
529 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
530 if (!BI || !BI->isUnconditional())
531 return nullptr;
532
533 // If the instruction before the branch (skipping debug info) isn't a phi
534 // node, then other stuff is happening here.
535 BasicBlock::iterator BBI = BI->getIterator();
536 if (BBI != BB->begin()) {
537 --BBI;
538 while (isa<DbgInfoIntrinsic>(BBI)) {
539 if (BBI == BB->begin())
540 break;
541 --BBI;
542 }
543 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
544 return nullptr;
545 }
546
547 // Do not break infinite loops.
548 BasicBlock *DestBB = BI->getSuccessor(0);
549 if (DestBB == BB)
550 return nullptr;
551
552 if (!canMergeBlocks(BB, DestBB))
553 DestBB = nullptr;
554
555 return DestBB;
556}
557
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000558// Return the unique indirectbr predecessor of a block. This may return null
559// even if such a predecessor exists, if it's not useful for splitting.
560// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
561// predecessors of BB.
562static BasicBlock *
563findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
564 // If the block doesn't have any PHIs, we don't care about it, since there's
565 // no point in splitting it.
566 PHINode *PN = dyn_cast<PHINode>(BB->begin());
567 if (!PN)
568 return nullptr;
569
570 // Verify we have exactly one IBR predecessor.
571 // Conservatively bail out if one of the other predecessors is not a "regular"
572 // terminator (that is, not a switch or a br).
573 BasicBlock *IBB = nullptr;
574 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
575 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
576 TerminatorInst *PredTerm = PredBB->getTerminator();
577 switch (PredTerm->getOpcode()) {
578 case Instruction::IndirectBr:
579 if (IBB)
580 return nullptr;
581 IBB = PredBB;
582 break;
583 case Instruction::Br:
584 case Instruction::Switch:
585 OtherPreds.push_back(PredBB);
586 continue;
587 default:
588 return nullptr;
589 }
590 }
591
592 return IBB;
593}
594
595// Split critical edges where the source of the edge is an indirectbr
596// instruction. This isn't always possible, but we can handle some easy cases.
597// This is useful because MI is unable to split such critical edges,
598// which means it will not be able to sink instructions along those edges.
599// This is especially painful for indirect branches with many successors, where
600// we end up having to prepare all outgoing values in the origin block.
601//
602// Our normal algorithm for splitting critical edges requires us to update
603// the outgoing edges of the edge origin block, but for an indirectbr this
604// is hard, since it would require finding and updating the block addresses
605// the indirect branch uses. But if a block only has a single indirectbr
606// predecessor, with the others being regular branches, we can do it in a
607// different way.
608// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
609// We can split D into D0 and D1, where D0 contains only the PHIs from D,
610// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
611// create the following structure:
612// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
613bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
614 // Check whether the function has any indirectbrs, and collect which blocks
615 // they may jump to. Since most functions don't have indirect branches,
616 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
617 SmallSetVector<BasicBlock *, 16> Targets;
618 for (auto &BB : F) {
619 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
620 if (!IBI)
621 continue;
622
623 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
624 Targets.insert(IBI->getSuccessor(Succ));
625 }
626
627 if (Targets.empty())
628 return false;
629
630 bool Changed = false;
631 for (BasicBlock *Target : Targets) {
632 SmallVector<BasicBlock *, 16> OtherPreds;
633 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
634 // If we did not found an indirectbr, or the indirectbr is the only
635 // incoming edge, this isn't the kind of edge we're looking for.
636 if (!IBRPred || OtherPreds.empty())
637 continue;
638
639 // Don't even think about ehpads/landingpads.
640 Instruction *FirstNonPHI = Target->getFirstNonPHI();
641 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
642 continue;
643
644 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
645 // It's possible Target was its own successor through an indirectbr.
646 // In this case, the indirectbr now comes from BodyBlock.
647 if (IBRPred == Target)
648 IBRPred = BodyBlock;
649
650 // At this point Target only has PHIs, and BodyBlock has the rest of the
651 // block's body. Create a copy of Target that will be used by the "direct"
652 // preds.
653 ValueToValueMapTy VMap;
654 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
655
Brendon Cahoon7769a082017-04-17 19:11:04 +0000656 for (BasicBlock *Pred : OtherPreds) {
657 // If the target is a loop to itself, then the terminator of the split
658 // block needs to be updated.
659 if (Pred == Target)
660 BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
661 else
662 Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
663 }
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000664
665 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
666 // they are clones, so the number of PHIs are the same.
667 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
668 // (b) Leave that as the only edge in the "Indirect" PHI.
669 // (c) Merge the two in the body block.
670 BasicBlock::iterator Indirect = Target->begin(),
671 End = Target->getFirstNonPHI()->getIterator();
672 BasicBlock::iterator Direct = DirectSucc->begin();
673 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
674
675 assert(&*End == Target->getTerminator() &&
676 "Block was expected to only contain PHIs");
677
678 while (Indirect != End) {
679 PHINode *DirPHI = cast<PHINode>(Direct);
680 PHINode *IndPHI = cast<PHINode>(Indirect);
681
682 // Now, clean up - the direct block shouldn't get the indirect value,
683 // and vice versa.
684 DirPHI->removeIncomingValue(IBRPred);
685 Direct++;
686
687 // Advance the pointer here, to avoid invalidation issues when the old
688 // PHI is erased.
689 Indirect++;
690
691 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
692 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
693 IBRPred);
694
695 // Create a PHI in the body block, to merge the direct and indirect
696 // predecessors.
697 PHINode *MergePHI =
698 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
699 MergePHI->addIncoming(NewIndPHI, Target);
700 MergePHI->addIncoming(DirPHI, DirectSucc);
701
702 IndPHI->replaceAllUsesWith(MergePHI);
703 IndPHI->eraseFromParent();
704 }
705
706 Changed = true;
707 }
708
709 return Changed;
710}
711
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000712/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
713/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
714/// edges in ways that are non-optimal for isel. Start by eliminating these
715/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000716bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000717 SmallPtrSet<BasicBlock *, 16> Preheaders;
718 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
719 while (!LoopList.empty()) {
720 Loop *L = LoopList.pop_back_val();
721 LoopList.insert(LoopList.end(), L->begin(), L->end());
722 if (BasicBlock *Preheader = L->getLoopPreheader())
723 Preheaders.insert(Preheader);
724 }
725
Chris Lattnerc3748562007-04-02 01:35:34 +0000726 bool MadeChange = false;
727 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000728 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000729 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000730 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
731 if (!DestBB ||
732 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000733 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000734
Sanjay Patelfc580a62015-09-21 23:03:16 +0000735 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000736 MadeChange = true;
737 }
738 return MadeChange;
739}
740
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000741bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
742 BasicBlock *DestBB,
743 bool isPreheader) {
744 // Do not delete loop preheaders if doing so would create a critical edge.
745 // Loop preheaders can be good locations to spill registers. If the
746 // preheader is deleted and we create a critical edge, registers may be
747 // spilled in the loop body instead.
748 if (!DisablePreheaderProtect && isPreheader &&
749 !(BB->getSinglePredecessor() &&
750 BB->getSinglePredecessor()->getSingleSuccessor()))
751 return false;
752
753 // Try to skip merging if the unique predecessor of BB is terminated by a
754 // switch or indirect branch instruction, and BB is used as an incoming block
755 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
756 // add COPY instructions in the predecessor of BB instead of BB (if it is not
757 // merged). Note that the critical edge created by merging such blocks wont be
758 // split in MachineSink because the jump table is not analyzable. By keeping
759 // such empty block (BB), ISel will place COPY instructions in BB, not in the
760 // predecessor of BB.
761 BasicBlock *Pred = BB->getUniquePredecessor();
762 if (!Pred ||
763 !(isa<SwitchInst>(Pred->getTerminator()) ||
764 isa<IndirectBrInst>(Pred->getTerminator())))
765 return true;
766
767 if (BB->getTerminator() != BB->getFirstNonPHI())
768 return true;
769
770 // We use a simple cost heuristic which determine skipping merging is
771 // profitable if the cost of skipping merging is less than the cost of
772 // merging : Cost(skipping merging) < Cost(merging BB), where the
773 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
774 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
775 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
776 // Freq(Pred) / Freq(BB) > 2.
777 // Note that if there are multiple empty blocks sharing the same incoming
778 // value for the PHIs in the DestBB, we consider them together. In such
779 // case, Cost(merging BB) will be the sum of their frequencies.
780
781 if (!isa<PHINode>(DestBB->begin()))
782 return true;
783
784 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
785
786 // Find all other incoming blocks from which incoming values of all PHIs in
787 // DestBB are the same as the ones from BB.
788 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
789 ++PI) {
790 BasicBlock *DestBBPred = *PI;
791 if (DestBBPred == BB)
792 continue;
793
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000794 bool HasAllSameValue = true;
795 BasicBlock::const_iterator DestBBI = DestBB->begin();
796 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
797 if (DestPN->getIncomingValueForBlock(BB) !=
798 DestPN->getIncomingValueForBlock(DestBBPred)) {
799 HasAllSameValue = false;
800 break;
801 }
802 }
803 if (HasAllSameValue)
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000804 SameIncomingValueBBs.insert(DestBBPred);
805 }
806
807 // See if all BB's incoming values are same as the value from Pred. In this
808 // case, no reason to skip merging because COPYs are expected to be place in
809 // Pred already.
810 if (SameIncomingValueBBs.count(Pred))
811 return true;
812
813 if (!BFI) {
814 Function &F = *BB->getParent();
815 LoopInfo LI{DominatorTree(F)};
816 BPI.reset(new BranchProbabilityInfo(F, LI));
817 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
818 }
819
820 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
821 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
822
823 for (auto SameValueBB : SameIncomingValueBBs)
824 if (SameValueBB->getUniquePredecessor() == Pred &&
825 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
826 BBFreq += BFI->getBlockFreq(SameValueBB);
827
828 return PredFreq.getFrequency() <=
829 BBFreq.getFrequency() * FreqRatioToSkipMerge;
830}
831
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000832/// Return true if we can merge BB into DestBB if there is a single
833/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000834/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000835bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000836 const BasicBlock *DestBB) const {
837 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
838 // the successor. If there are more complex condition (e.g. preheaders),
839 // don't mess around with them.
840 BasicBlock::const_iterator BBI = BB->begin();
841 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000842 for (const User *U : PN->users()) {
843 const Instruction *UI = cast<Instruction>(U);
844 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000845 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000846 // If User is inside DestBB block and it is a PHINode then check
847 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000848 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000849 if (UI->getParent() == DestBB) {
850 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000851 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
852 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
853 if (Insn && Insn->getParent() == BB &&
854 Insn->getParent() != UPN->getIncomingBlock(I))
855 return false;
856 }
857 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000858 }
859 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000860
Chris Lattnerc3748562007-04-02 01:35:34 +0000861 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
862 // and DestBB may have conflicting incoming values for the block. If so, we
863 // can't merge the block.
864 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
865 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000866
Chris Lattnerc3748562007-04-02 01:35:34 +0000867 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000868 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000869 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
870 // It is faster to get preds from a PHI than with pred_iterator.
871 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
872 BBPreds.insert(BBPN->getIncomingBlock(i));
873 } else {
874 BBPreds.insert(pred_begin(BB), pred_end(BB));
875 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000876
Chris Lattnerc3748562007-04-02 01:35:34 +0000877 // Walk the preds of DestBB.
878 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
879 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
880 if (BBPreds.count(Pred)) { // Common predecessor?
881 BBI = DestBB->begin();
882 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
883 const Value *V1 = PN->getIncomingValueForBlock(Pred);
884 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000885
Chris Lattnerc3748562007-04-02 01:35:34 +0000886 // If V2 is a phi node in BB, look up what the mapped value will be.
887 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
888 if (V2PN->getParent() == BB)
889 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000890
Chris Lattnerc3748562007-04-02 01:35:34 +0000891 // If there is a conflict, bail out.
892 if (V1 != V2) return false;
893 }
894 }
895 }
896
897 return true;
898}
899
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000900/// Eliminate a basic block that has only phi's and an unconditional branch in
901/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000902void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000903 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
904 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000905
David Greene74e2d492010-01-05 01:27:11 +0000906 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000907
Chris Lattnerc3748562007-04-02 01:35:34 +0000908 // If the destination block has a single pred, then this is a trivial edge,
909 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000910 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000911 if (SinglePred != DestBB) {
912 // Remember if SinglePred was the entry block of the function. If so, we
913 // will need to move BB back to the entry position.
914 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000915 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000916
Chris Lattner8a172da2008-11-28 19:54:49 +0000917 if (isEntry && BB != &BB->getParent()->getEntryBlock())
918 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000919
David Greene74e2d492010-01-05 01:27:11 +0000920 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000921 return;
922 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000923 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000924
Chris Lattnerc3748562007-04-02 01:35:34 +0000925 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
926 // to handle the new incoming edges it is about to have.
927 PHINode *PN;
928 for (BasicBlock::iterator BBI = DestBB->begin();
929 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
930 // Remove the incoming value for BB, and remember it.
931 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000932
Chris Lattnerc3748562007-04-02 01:35:34 +0000933 // Two options: either the InVal is a phi node defined in BB or it is some
934 // value that dominates BB.
935 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
936 if (InValPhi && InValPhi->getParent() == BB) {
937 // Add all of the input values of the input PHI as inputs of this phi.
938 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
939 PN->addIncoming(InValPhi->getIncomingValue(i),
940 InValPhi->getIncomingBlock(i));
941 } else {
942 // Otherwise, add one instance of the dominating value for each edge that
943 // we will be adding.
944 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
945 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
946 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
947 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000948 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
949 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000950 }
951 }
952 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000953
Chris Lattnerc3748562007-04-02 01:35:34 +0000954 // The PHIs are now updated, change everything that refers to BB to use
955 // DestBB and remove BB.
956 BB->replaceAllUsesWith(DestBB);
957 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000958 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000959
David Greene74e2d492010-01-05 01:27:11 +0000960 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000961}
962
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000963// Computes a map of base pointer relocation instructions to corresponding
964// derived pointer relocation instructions given a vector of all relocate calls
965static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000966 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
967 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
968 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000969 // Collect information in two maps: one primarily for locating the base object
970 // while filling the second map; the second map is the final structure holding
971 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000972 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
973 for (auto *ThisRelocate : AllRelocateCalls) {
974 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
975 ThisRelocate->getDerivedPtrIndex());
976 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000977 }
978 for (auto &Item : RelocateIdxMap) {
979 std::pair<unsigned, unsigned> Key = Item.first;
980 if (Key.first == Key.second)
981 // Base relocation: nothing to insert
982 continue;
983
Manuel Jacob83eefa62016-01-05 04:03:00 +0000984 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000985 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000986
987 // We're iterating over RelocateIdxMap so we cannot modify it.
988 auto MaybeBase = RelocateIdxMap.find(BaseKey);
989 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000990 // TODO: We might want to insert a new base object relocate and gep off
991 // that, if there are enough derived object relocates.
992 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000993
994 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000995 }
996}
997
998// Accepts a GEP and extracts the operands into a vector provided they're all
999// small integer constants
1000static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
1001 SmallVectorImpl<Value *> &OffsetV) {
1002 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
1003 // Only accept small constant integer operands
1004 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
1005 if (!Op || Op->getZExtValue() > 20)
1006 return false;
1007 }
1008
1009 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
1010 OffsetV.push_back(GEP->getOperand(i));
1011 return true;
1012}
1013
1014// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
1015// replace, computes a replacement, and affects it.
1016static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +00001017simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
1018 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001019 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +00001020 // We must ensure the relocation of derived pointer is defined after
1021 // relocation of base pointer. If we find a relocation corresponding to base
1022 // defined earlier than relocation of base then we move relocation of base
1023 // right before found relocation. We consider only relocation in the same
1024 // basic block as relocation of base. Relocations from other basic block will
1025 // be skipped by optimization and we do not care about them.
1026 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1027 &*R != RelocatedBase; ++R)
1028 if (auto RI = dyn_cast<GCRelocateInst>(R))
1029 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1030 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1031 RelocatedBase->moveBefore(RI);
1032 break;
1033 }
1034
Manuel Jacob83eefa62016-01-05 04:03:00 +00001035 for (GCRelocateInst *ToReplace : Targets) {
1036 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001037 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001038 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001039 // A duplicate relocate call. TODO: coalesce duplicates.
1040 continue;
1041 }
1042
Igor Laevskyf637b4a2015-11-03 18:37:40 +00001043 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1044 // Base and derived relocates are in different basic blocks.
1045 // In this case transform is only valid when base dominates derived
1046 // relocate. However it would be too expensive to check dominance
1047 // for each such relocate, so we skip the whole transformation.
1048 continue;
1049 }
1050
Manuel Jacob83eefa62016-01-05 04:03:00 +00001051 Value *Base = ToReplace->getBasePtr();
1052 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001053 if (!Derived || Derived->getPointerOperand() != Base)
1054 continue;
1055
1056 SmallVector<Value *, 2> OffsetV;
1057 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1058 continue;
1059
1060 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +00001061 assert(RelocatedBase->getNextNode() &&
1062 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +00001063
1064 // Insert after RelocatedBase
1065 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001066 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +00001067
1068 // If gc_relocate does not match the actual type, cast it to the right type.
1069 // In theory, there must be a bitcast after gc_relocate if the type does not
1070 // match, and we should reuse it to get the derived pointer. But it could be
1071 // cases like this:
1072 // bb1:
1073 // ...
1074 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1075 // br label %merge
1076 //
1077 // bb2:
1078 // ...
1079 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1080 // br label %merge
1081 //
1082 // merge:
1083 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1084 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1085 //
1086 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1087 // no matter there is already one or not. In this way, we can handle all cases, and
1088 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001089 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +00001090 if (RelocatedBase->getType() != Base->getType()) {
1091 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001092 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001093 }
David Blaikie68d535c2015-03-24 22:38:16 +00001094 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +00001095 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001096 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +00001097 // If the newly generated derived pointer's type does not match the original derived
1098 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001099 Value *ActualReplacement = Replacement;
1100 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +00001101 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001102 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001103 }
1104 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001105 ToReplace->eraseFromParent();
1106
1107 MadeChange = true;
1108 }
1109 return MadeChange;
1110}
1111
1112// Turns this:
1113//
1114// %base = ...
1115// %ptr = gep %base + 15
1116// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1117// %base' = relocate(%tok, i32 4, i32 4)
1118// %ptr' = relocate(%tok, i32 4, i32 5)
1119// %val = load %ptr'
1120//
1121// into this:
1122//
1123// %base = ...
1124// %ptr = gep %base + 15
1125// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1126// %base' = gc.relocate(%tok, i32 4, i32 4)
1127// %ptr' = gep %base' + 15
1128// %val = load %ptr'
1129bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1130 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001131 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001132
1133 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001134 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001135 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001136 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001137
1138 // We need atleast one base pointer relocation + one derived pointer
1139 // relocation to mangle
1140 if (AllRelocateCalls.size() < 2)
1141 return false;
1142
1143 // RelocateInstMap is a mapping from the base relocate instruction to the
1144 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001145 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001146 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1147 if (RelocateInstMap.empty())
1148 return false;
1149
1150 for (auto &Item : RelocateInstMap)
1151 // Item.first is the RelocatedBase to offset against
1152 // Item.second is the vector of Targets to replace
1153 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1154 return MadeChange;
1155}
1156
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001157/// SinkCast - Sink the specified cast instruction into its user blocks
1158static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001159 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001160
Chris Lattnerf2836d12007-03-31 04:06:36 +00001161 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001162 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001163
Chris Lattnerf2836d12007-03-31 04:06:36 +00001164 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001165 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001166 UI != E; ) {
1167 Use &TheUse = UI.getUse();
1168 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001169
Chris Lattnerf2836d12007-03-31 04:06:36 +00001170 // Figure out which BB this cast is used in. For PHI's this is the
1171 // appropriate predecessor block.
1172 BasicBlock *UserBB = User->getParent();
1173 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001174 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001175 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001176
Chris Lattnerf2836d12007-03-31 04:06:36 +00001177 // Preincrement use iterator so we don't invalidate it.
1178 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001179
David Majnemer0c80e2e2016-04-27 19:36:38 +00001180 // The first insertion point of a block containing an EH pad is after the
1181 // pad. If the pad is the user, we cannot sink the cast past the pad.
1182 if (User->isEHPad())
1183 continue;
1184
Andrew Kaylord0430e82015-11-23 19:16:15 +00001185 // If the block selected to receive the cast is an EH pad that does not
1186 // allow non-PHI instructions before the terminator, we can't sink the
1187 // cast.
1188 if (UserBB->getTerminator()->isEHPad())
1189 continue;
1190
Chris Lattnerf2836d12007-03-31 04:06:36 +00001191 // If this user is in the same block as the cast, don't change the cast.
1192 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001193
Chris Lattnerf2836d12007-03-31 04:06:36 +00001194 // If we have already inserted a cast into this block, use it.
1195 CastInst *&InsertedCast = InsertedCasts[UserBB];
1196
1197 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001198 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001199 assert(InsertPt != UserBB->end());
1200 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1201 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001202 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001203
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001204 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001205 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001206 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001207 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001208 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001209
Chris Lattnerf2836d12007-03-31 04:06:36 +00001210 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001211 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001212 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001213 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001214 MadeChange = true;
1215 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001216
Chris Lattnerf2836d12007-03-31 04:06:36 +00001217 return MadeChange;
1218}
1219
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001220/// If the specified cast instruction is a noop copy (e.g. it's casting from
1221/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1222/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001223///
1224/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001225static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1226 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001227 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1228 // than sinking only nop casts, but is helpful on some platforms.
1229 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1230 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1231 ASC->getDestAddressSpace()))
1232 return false;
1233 }
1234
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001235 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001236 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1237 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001238
1239 // This is an fp<->int conversion?
1240 if (SrcVT.isInteger() != DstVT.isInteger())
1241 return false;
1242
1243 // If this is an extension, it will be a zero or sign extension, which
1244 // isn't a noop.
1245 if (SrcVT.bitsLT(DstVT)) return false;
1246
1247 // If these values will be promoted, find out what they will be promoted
1248 // to. This helps us consider truncates on PPC as noop copies when they
1249 // are.
1250 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1251 TargetLowering::TypePromoteInteger)
1252 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1253 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1254 TargetLowering::TypePromoteInteger)
1255 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1256
1257 // If, after promotion, these are the same types, this is a noop copy.
1258 if (SrcVT != DstVT)
1259 return false;
1260
1261 return SinkCast(CI);
1262}
1263
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001264/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1265/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001266///
1267/// Return true if any changes were made.
1268static bool CombineUAddWithOverflow(CmpInst *CI) {
1269 Value *A, *B;
1270 Instruction *AddI;
1271 if (!match(CI,
1272 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1273 return false;
1274
1275 Type *Ty = AddI->getType();
1276 if (!isa<IntegerType>(Ty))
1277 return false;
1278
1279 // We don't want to move around uses of condition values this late, so we we
1280 // check if it is legal to create the call to the intrinsic in the basic
1281 // block containing the icmp:
1282
1283 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1284 return false;
1285
1286#ifndef NDEBUG
1287 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1288 // for now:
1289 if (AddI->hasOneUse())
1290 assert(*AddI->user_begin() == CI && "expected!");
1291#endif
1292
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001293 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001294 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1295
1296 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1297
1298 auto *UAddWithOverflow =
1299 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1300 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1301 auto *Overflow =
1302 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1303
1304 CI->replaceAllUsesWith(Overflow);
1305 AddI->replaceAllUsesWith(UAdd);
1306 CI->eraseFromParent();
1307 AddI->eraseFromParent();
1308 return true;
1309}
1310
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001311/// Sink the given CmpInst into user blocks to reduce the number of virtual
1312/// registers that must be created and coalesced. This is a clear win except on
1313/// targets with multiple condition code registers (PowerPC), where it might
1314/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001315///
1316/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001317static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001318 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001319
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001320 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001321 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001322 return false;
1323
1324 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001325 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001326
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001327 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001328 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001329 UI != E; ) {
1330 Use &TheUse = UI.getUse();
1331 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001332
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001333 // Preincrement use iterator so we don't invalidate it.
1334 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001335
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001336 // Don't bother for PHI nodes.
1337 if (isa<PHINode>(User))
1338 continue;
1339
1340 // Figure out which BB this cmp is used in.
1341 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001342
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001343 // If this user is in the same block as the cmp, don't change the cmp.
1344 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001345
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001346 // If we have already inserted a cmp into this block, use it.
1347 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1348
1349 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001350 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001351 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001352 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001353 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1354 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001355 // Propagate the debug info.
1356 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001357 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001358
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001359 // Replace a use of the cmp with a use of the new cmp.
1360 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001361 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001362 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001363 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001364
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001365 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001366 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001367 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001368 MadeChange = true;
1369 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001370
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001371 return MadeChange;
1372}
1373
Peter Zotovf87e5502016-04-03 17:11:53 +00001374static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001375 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001376 return true;
1377
1378 if (CombineUAddWithOverflow(CI))
1379 return true;
1380
1381 return false;
1382}
1383
Geoff Berry5d534b62017-02-21 18:53:14 +00001384/// Duplicate and sink the given 'and' instruction into user blocks where it is
1385/// used in a compare to allow isel to generate better code for targets where
1386/// this operation can be combined.
1387///
1388/// Return true if any changes are made.
1389static bool sinkAndCmp0Expression(Instruction *AndI,
1390 const TargetLowering &TLI,
1391 SetOfInstrs &InsertedInsts) {
1392 // Double-check that we're not trying to optimize an instruction that was
1393 // already optimized by some other part of this pass.
1394 assert(!InsertedInsts.count(AndI) &&
1395 "Attempting to optimize already optimized and instruction");
1396 (void) InsertedInsts;
1397
1398 // Nothing to do for single use in same basic block.
1399 if (AndI->hasOneUse() &&
1400 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1401 return false;
1402
1403 // Try to avoid cases where sinking/duplicating is likely to increase register
1404 // pressure.
1405 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1406 !isa<ConstantInt>(AndI->getOperand(1)) &&
1407 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1408 return false;
1409
1410 for (auto *U : AndI->users()) {
1411 Instruction *User = cast<Instruction>(U);
1412
1413 // Only sink for and mask feeding icmp with 0.
1414 if (!isa<ICmpInst>(User))
1415 return false;
1416
1417 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1418 if (!CmpC || !CmpC->isZero())
1419 return false;
1420 }
1421
1422 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1423 return false;
1424
1425 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1426 DEBUG(AndI->getParent()->dump());
1427
1428 // Push the 'and' into the same block as the icmp 0. There should only be
1429 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1430 // others, so we don't need to keep track of which BBs we insert into.
1431 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1432 UI != E; ) {
1433 Use &TheUse = UI.getUse();
1434 Instruction *User = cast<Instruction>(*UI);
1435
1436 // Preincrement use iterator so we don't invalidate it.
1437 ++UI;
1438
1439 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1440
1441 // Keep the 'and' in the same place if the use is already in the same block.
1442 Instruction *InsertPt =
1443 User->getParent() == AndI->getParent() ? AndI : User;
1444 Instruction *InsertedAnd =
1445 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1446 AndI->getOperand(1), "", InsertPt);
1447 // Propagate the debug info.
1448 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1449
1450 // Replace a use of the 'and' with a use of the new 'and'.
1451 TheUse = InsertedAnd;
1452 ++NumAndUses;
1453 DEBUG(User->getParent()->dump());
1454 }
1455
1456 // We removed all uses, nuke the and.
1457 AndI->eraseFromParent();
1458 return true;
1459}
1460
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001461/// Check if the candidates could be combined with a shift instruction, which
1462/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001463/// 1. Truncate instruction
1464/// 2. And instruction and the imm is a mask of the low bits:
1465/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001466static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001467 if (!isa<TruncInst>(User)) {
1468 if (User->getOpcode() != Instruction::And ||
1469 !isa<ConstantInt>(User->getOperand(1)))
1470 return false;
1471
Quentin Colombetd4f44692014-04-22 01:20:34 +00001472 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001473
Quentin Colombetd4f44692014-04-22 01:20:34 +00001474 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001475 return false;
1476 }
1477 return true;
1478}
1479
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001480/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001481static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001482SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1483 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001484 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001485 BasicBlock *UserBB = User->getParent();
1486 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1487 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1488 bool MadeChange = false;
1489
1490 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1491 TruncE = TruncI->user_end();
1492 TruncUI != TruncE;) {
1493
1494 Use &TruncTheUse = TruncUI.getUse();
1495 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1496 // Preincrement use iterator so we don't invalidate it.
1497
1498 ++TruncUI;
1499
1500 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1501 if (!ISDOpcode)
1502 continue;
1503
Tim Northovere2239ff2014-07-29 10:20:22 +00001504 // If the use is actually a legal node, there will not be an
1505 // implicit truncate.
1506 // FIXME: always querying the result type is just an
1507 // approximation; some nodes' legality is determined by the
1508 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001509 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001510 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001511 continue;
1512
1513 // Don't bother for PHI nodes.
1514 if (isa<PHINode>(TruncUser))
1515 continue;
1516
1517 BasicBlock *TruncUserBB = TruncUser->getParent();
1518
1519 if (UserBB == TruncUserBB)
1520 continue;
1521
1522 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1523 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1524
1525 if (!InsertedShift && !InsertedTrunc) {
1526 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001527 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001528 // Sink the shift
1529 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001530 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1531 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001532 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001533 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1534 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001535
1536 // Sink the trunc
1537 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1538 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001539 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001540
1541 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001542 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001543
1544 MadeChange = true;
1545
1546 TruncTheUse = InsertedTrunc;
1547 }
1548 }
1549 return MadeChange;
1550}
1551
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001552/// Sink the shift *right* instruction into user blocks if the uses could
1553/// potentially be combined with this shift instruction and generate BitExtract
1554/// instruction. It will only be applied if the architecture supports BitExtract
1555/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001556/// BB1:
1557/// %x.extract.shift = lshr i64 %arg1, 32
1558/// BB2:
1559/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1560/// ==>
1561///
1562/// BB2:
1563/// %x.extract.shift.1 = lshr i64 %arg1, 32
1564/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1565///
1566/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1567/// instruction.
1568/// Return true if any changes are made.
1569static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001570 const TargetLowering &TLI,
1571 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001572 BasicBlock *DefBB = ShiftI->getParent();
1573
1574 /// Only insert instructions in each block once.
1575 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1576
Mehdi Amini44ede332015-07-09 02:09:04 +00001577 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001578
1579 bool MadeChange = false;
1580 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1581 UI != E;) {
1582 Use &TheUse = UI.getUse();
1583 Instruction *User = cast<Instruction>(*UI);
1584 // Preincrement use iterator so we don't invalidate it.
1585 ++UI;
1586
1587 // Don't bother for PHI nodes.
1588 if (isa<PHINode>(User))
1589 continue;
1590
1591 if (!isExtractBitsCandidateUse(User))
1592 continue;
1593
1594 BasicBlock *UserBB = User->getParent();
1595
1596 if (UserBB == DefBB) {
1597 // If the shift and truncate instruction are in the same BB. The use of
1598 // the truncate(TruncUse) may still introduce another truncate if not
1599 // legal. In this case, we would like to sink both shift and truncate
1600 // instruction to the BB of TruncUse.
1601 // for example:
1602 // BB1:
1603 // i64 shift.result = lshr i64 opnd, imm
1604 // trunc.result = trunc shift.result to i16
1605 //
1606 // BB2:
1607 // ----> We will have an implicit truncate here if the architecture does
1608 // not have i16 compare.
1609 // cmp i16 trunc.result, opnd2
1610 //
1611 if (isa<TruncInst>(User) && shiftIsLegal
1612 // If the type of the truncate is legal, no trucate will be
1613 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001614 &&
1615 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001616 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001617 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001618
1619 continue;
1620 }
1621 // If we have already inserted a shift into this block, use it.
1622 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1623
1624 if (!InsertedShift) {
1625 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001626 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001627
1628 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001629 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1630 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001631 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001632 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1633 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001634
1635 MadeChange = true;
1636 }
1637
1638 // Replace a use of the shift with a use of the new shift.
1639 TheUse = InsertedShift;
1640 }
1641
1642 // If we removed all uses, nuke the shift.
1643 if (ShiftI->use_empty())
1644 ShiftI->eraseFromParent();
1645
1646 return MadeChange;
1647}
1648
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001649/// If counting leading or trailing zeros is an expensive operation and a zero
1650/// input is defined, add a check for zero to avoid calling the intrinsic.
1651///
1652/// We want to transform:
1653/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1654///
1655/// into:
1656/// entry:
1657/// %cmpz = icmp eq i64 %A, 0
1658/// br i1 %cmpz, label %cond.end, label %cond.false
1659/// cond.false:
1660/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1661/// br label %cond.end
1662/// cond.end:
1663/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1664///
1665/// If the transform is performed, return true and set ModifiedDT to true.
1666static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1667 const TargetLowering *TLI,
1668 const DataLayout *DL,
1669 bool &ModifiedDT) {
1670 if (!TLI || !DL)
1671 return false;
1672
1673 // If a zero input is undefined, it doesn't make sense to despeculate that.
1674 if (match(CountZeros->getOperand(1), m_One()))
1675 return false;
1676
1677 // If it's cheap to speculate, there's nothing to do.
1678 auto IntrinsicID = CountZeros->getIntrinsicID();
1679 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1680 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1681 return false;
1682
1683 // Only handle legal scalar cases. Anything else requires too much work.
1684 Type *Ty = CountZeros->getType();
1685 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001686 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001687 return false;
1688
1689 // The intrinsic will be sunk behind a compare against zero and branch.
1690 BasicBlock *StartBlock = CountZeros->getParent();
1691 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1692
1693 // Create another block after the count zero intrinsic. A PHI will be added
1694 // in this block to select the result of the intrinsic or the bit-width
1695 // constant if the input to the intrinsic is zero.
1696 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1697 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1698
1699 // Set up a builder to create a compare, conditional branch, and PHI.
1700 IRBuilder<> Builder(CountZeros->getContext());
1701 Builder.SetInsertPoint(StartBlock->getTerminator());
1702 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1703
1704 // Replace the unconditional branch that was created by the first split with
1705 // a compare against zero and a conditional branch.
1706 Value *Zero = Constant::getNullValue(Ty);
1707 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1708 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1709 StartBlock->getTerminator()->eraseFromParent();
1710
1711 // Create a PHI in the end block to select either the output of the intrinsic
1712 // or the bit width of the operand.
1713 Builder.SetInsertPoint(&EndBlock->front());
1714 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1715 CountZeros->replaceAllUsesWith(PN);
1716 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1717 PN->addIncoming(BitWidth, StartBlock);
1718 PN->addIncoming(CountZeros, CallBlock);
1719
1720 // We are explicitly handling the zero case, so we can set the intrinsic's
1721 // undefined zero argument to 'true'. This will also prevent reprocessing the
1722 // intrinsic; we only despeculate when a zero input is defined.
1723 CountZeros->setArgOperand(1, Builder.getTrue());
1724 ModifiedDT = true;
1725 return true;
1726}
1727
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001728bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001729 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001730
Chris Lattner7a277142011-01-15 07:14:54 +00001731 // Lower inline assembly if we can.
1732 // If we found an inline asm expession, and if the target knows how to
1733 // lower it to normal LLVM code, do so now.
1734 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1735 if (TLI->ExpandInlineAsm(CI)) {
1736 // Avoid invalidating the iterator.
1737 CurInstIterator = BB->begin();
1738 // Avoid processing instructions out of order, which could cause
1739 // reuse before a value is defined.
1740 SunkAddrs.clear();
1741 return true;
1742 }
1743 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001744 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001745 return true;
1746 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001747
John Brawn0dbcd652015-03-18 12:01:59 +00001748 // Align the pointer arguments to this call if the target thinks it's a good
1749 // idea
1750 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001751 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001752 for (auto &Arg : CI->arg_operands()) {
1753 // We want to align both objects whose address is used directly and
1754 // objects whose address is used in casts and GEPs, though it only makes
1755 // sense for GEPs if the offset is a multiple of the desired alignment and
1756 // if size - offset meets the size threshold.
1757 if (!Arg->getType()->isPointerTy())
1758 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001759 APInt Offset(DL->getPointerSizeInBits(
1760 cast<PointerType>(Arg->getType())->getAddressSpace()),
1761 0);
1762 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001763 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001764 if ((Offset2 & (PrefAlign-1)) != 0)
1765 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001766 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001767 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1768 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001769 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001770 // Global variables can only be aligned if they are defined in this
1771 // object (i.e. they are uniquely initialized in this object), and
1772 // over-aligning global variables that have an explicit section is
1773 // forbidden.
1774 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001775 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001776 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001777 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001778 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001779 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001780 }
1781 // If this is a memcpy (or similar) then we may be able to improve the
1782 // alignment
1783 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001784 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001785 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001786 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001787 if (Align > MI->getAlignment())
1788 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001789 }
1790 }
1791
Philip Reamesac115ed2016-03-09 23:13:12 +00001792 // If we have a cold call site, try to sink addressing computation into the
1793 // cold block. This interacts with our handling for loads and stores to
1794 // ensure that we can fold all uses of a potential addressing computation
1795 // into their uses. TODO: generalize this to work over profiling data
1796 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1797 for (auto &Arg : CI->arg_operands()) {
1798 if (!Arg->getType()->isPointerTy())
1799 continue;
1800 unsigned AS = Arg->getType()->getPointerAddressSpace();
1801 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1802 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001803
Eric Christopher4b7948e2010-03-11 02:41:03 +00001804 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001805 if (II) {
1806 switch (II->getIntrinsicID()) {
1807 default: break;
1808 case Intrinsic::objectsize: {
1809 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001810 ConstantInt *RetVal =
1811 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001812 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001813 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1814 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001815 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001816 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001817 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001818
Sanjay Patel545a4562016-01-20 18:59:16 +00001819 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001820
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001821 // If the iterator instruction was recursively deleted, start over at the
1822 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001823 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001824 CurInstIterator = BB->begin();
1825 SunkAddrs.clear();
1826 }
1827 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001828 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001829 case Intrinsic::aarch64_stlxr:
1830 case Intrinsic::aarch64_stxr: {
1831 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1832 if (!ExtVal || !ExtVal->hasOneUse() ||
1833 ExtVal->getParent() == CI->getParent())
1834 return false;
1835 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1836 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001837 // Mark this instruction as "inserted by CGP", so that other
1838 // optimizations don't touch it.
1839 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001840 return true;
1841 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001842 case Intrinsic::invariant_group_barrier:
1843 II->replaceAllUsesWith(II->getArgOperand(0));
1844 II->eraseFromParent();
1845 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001846
1847 case Intrinsic::cttz:
1848 case Intrinsic::ctlz:
1849 // If counting zeros is expensive, try to avoid it.
1850 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001851 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001852
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001853 if (TLI) {
1854 SmallVector<Value*, 2> PtrOps;
1855 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001856 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1857 while (!PtrOps.empty()) {
1858 Value *PtrVal = PtrOps.pop_back_val();
1859 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1860 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001861 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001862 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001863 }
Pete Cooper615fd892012-03-13 20:59:56 +00001864 }
1865
Eric Christopher4b7948e2010-03-11 02:41:03 +00001866 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001867 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001868
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001869 // Lower all default uses of _chk calls. This is very similar
1870 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001871 // to fortified library functions (e.g. __memcpy_chk) that have the default
1872 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001873 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001874 if (Value *V = Simplifier.optimizeCall(CI)) {
1875 CI->replaceAllUsesWith(V);
1876 CI->eraseFromParent();
1877 return true;
1878 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001879
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001880 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001881}
Chris Lattner1b93be52011-01-15 07:25:29 +00001882
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001883/// Look for opportunities to duplicate return instructions to the predecessor
1884/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001885/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001886/// bb0:
1887/// %tmp0 = tail call i32 @f0()
1888/// br label %return
1889/// bb1:
1890/// %tmp1 = tail call i32 @f1()
1891/// br label %return
1892/// bb2:
1893/// %tmp2 = tail call i32 @f2()
1894/// br label %return
1895/// return:
1896/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1897/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001898/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001899///
1900/// =>
1901///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001902/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001903/// bb0:
1904/// %tmp0 = tail call i32 @f0()
1905/// ret i32 %tmp0
1906/// bb1:
1907/// %tmp1 = tail call i32 @f1()
1908/// ret i32 %tmp1
1909/// bb2:
1910/// %tmp2 = tail call i32 @f2()
1911/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001912/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001913bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001914 if (!TLI)
1915 return false;
1916
Michael Kuperstein71321562016-09-07 20:29:49 +00001917 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1918 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001919 return false;
1920
Craig Topperc0196b12014-04-14 00:51:57 +00001921 PHINode *PN = nullptr;
1922 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001923 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001924 if (V) {
1925 BCI = dyn_cast<BitCastInst>(V);
1926 if (BCI)
1927 V = BCI->getOperand(0);
1928
1929 PN = dyn_cast<PHINode>(V);
1930 if (!PN)
1931 return false;
1932 }
Evan Cheng0663f232011-03-21 01:19:09 +00001933
Cameron Zwarich4649f172011-03-24 04:52:10 +00001934 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001935 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001936
Cameron Zwarich4649f172011-03-24 04:52:10 +00001937 // Make sure there are no instructions between the PHI and return, or that the
1938 // return is the first instruction in the block.
1939 if (PN) {
1940 BasicBlock::iterator BI = BB->begin();
1941 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001942 if (&*BI == BCI)
1943 // Also skip over the bitcast.
1944 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001945 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001946 return false;
1947 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001948 BasicBlock::iterator BI = BB->begin();
1949 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001950 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001951 return false;
1952 }
Evan Cheng0663f232011-03-21 01:19:09 +00001953
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001954 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1955 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001956 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001957 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001958 if (PN) {
1959 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1960 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1961 // Make sure the phi value is indeed produced by the tail call.
1962 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001963 TLI->mayBeEmittedAsTailCall(CI) &&
1964 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001965 TailCalls.push_back(CI);
1966 }
1967 } else {
1968 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001969 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001970 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001971 continue;
1972
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001973 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001974 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1975 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001976 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1977 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001978 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001979
Cameron Zwarich4649f172011-03-24 04:52:10 +00001980 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001981 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1982 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001983 TailCalls.push_back(CI);
1984 }
Evan Cheng0663f232011-03-21 01:19:09 +00001985 }
1986
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001987 bool Changed = false;
1988 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1989 CallInst *CI = TailCalls[i];
1990 CallSite CS(CI);
1991
1992 // Conservatively require the attributes of the call to match those of the
1993 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001994 AttributeList CalleeAttrs = CS.getAttributes();
1995 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1996 .removeAttribute(Attribute::NoAlias) !=
1997 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1998 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001999 continue;
2000
2001 // Make sure the call instruction is followed by an unconditional branch to
2002 // the return block.
2003 BasicBlock *CallBB = CI->getParent();
2004 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2005 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2006 continue;
2007
2008 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002009 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002010 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002011 ++NumRetsDup;
2012 }
2013
2014 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002015 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002016 BB->eraseFromParent();
2017
2018 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002019}
2020
Chris Lattner728f9022008-11-25 07:09:13 +00002021//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002022// Memory Optimization
2023//===----------------------------------------------------------------------===//
2024
Chandler Carruthc8925912013-01-05 02:09:22 +00002025namespace {
2026
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002027/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002028/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002029struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002030 Value *BaseReg = nullptr;
2031 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00002032 Value *OriginalValue = nullptr;
2033
2034 enum FieldName {
2035 NoField = 0x00,
2036 BaseRegField = 0x01,
2037 BaseGVField = 0x02,
2038 BaseOffsField = 0x04,
2039 ScaledRegField = 0x08,
2040 ScaleField = 0x10,
2041 MultipleFields = 0xff
2042 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00002043
2044 ExtAddrMode() = default;
2045
Chandler Carruthc8925912013-01-05 02:09:22 +00002046 void print(raw_ostream &OS) const;
2047 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002048
John Brawn736bf002017-10-03 13:08:22 +00002049 FieldName compare(const ExtAddrMode &other) {
2050 // First check that the types are the same on each field, as differing types
2051 // is something we can't cope with later on.
2052 if (BaseReg && other.BaseReg &&
2053 BaseReg->getType() != other.BaseReg->getType())
2054 return MultipleFields;
2055 if (BaseGV && other.BaseGV &&
2056 BaseGV->getType() != other.BaseGV->getType())
2057 return MultipleFields;
2058 if (ScaledReg && other.ScaledReg &&
2059 ScaledReg->getType() != other.ScaledReg->getType())
2060 return MultipleFields;
2061
2062 // Check each field to see if it differs.
2063 unsigned Result = NoField;
2064 if (BaseReg != other.BaseReg)
2065 Result |= BaseRegField;
2066 if (BaseGV != other.BaseGV)
2067 Result |= BaseGVField;
2068 if (BaseOffs != other.BaseOffs)
2069 Result |= BaseOffsField;
2070 if (ScaledReg != other.ScaledReg)
2071 Result |= ScaledRegField;
2072 // Don't count 0 as being a different scale, because that actually means
2073 // unscaled (which will already be counted by having no ScaledReg).
2074 if (Scale && other.Scale && Scale != other.Scale)
2075 Result |= ScaleField;
2076
2077 if (countPopulation(Result) > 1)
2078 return MultipleFields;
2079 else
2080 return static_cast<FieldName>(Result);
2081 }
2082
John Brawn4b476482017-11-27 11:29:15 +00002083 // An AddrMode is trivial if it involves no calculation i.e. it is just a base
2084 // with no offset.
John Brawn736bf002017-10-03 13:08:22 +00002085 bool isTrivial() {
John Brawn4b476482017-11-27 11:29:15 +00002086 // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
2087 // trivial if at most one of these terms is nonzero, except that BaseGV and
2088 // BaseReg both being zero actually means a null pointer value, which we
2089 // consider to be 'non-zero' here.
2090 return !BaseOffs && !Scale && !(BaseGV && BaseReg);
Chandler Carruthc8925912013-01-05 02:09:22 +00002091 }
John Brawn70cdb5b2017-11-24 14:10:45 +00002092
2093 Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
2094 switch (Field) {
2095 default:
2096 return nullptr;
2097 case BaseRegField:
2098 return BaseReg;
2099 case BaseGVField:
2100 return BaseGV;
2101 case ScaledRegField:
2102 return ScaledReg;
2103 case BaseOffsField:
2104 return ConstantInt::get(IntPtrTy, BaseOffs);
2105 }
2106 }
2107
2108 void SetCombinedField(FieldName Field, Value *V,
2109 const SmallVectorImpl<ExtAddrMode> &AddrModes) {
2110 switch (Field) {
2111 default:
2112 llvm_unreachable("Unhandled fields are expected to be rejected earlier");
2113 break;
2114 case ExtAddrMode::BaseRegField:
2115 BaseReg = V;
2116 break;
2117 case ExtAddrMode::BaseGVField:
2118 // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
2119 // in the BaseReg field.
2120 assert(BaseReg == nullptr);
2121 BaseReg = V;
2122 BaseGV = nullptr;
2123 break;
2124 case ExtAddrMode::ScaledRegField:
2125 ScaledReg = V;
2126 // If we have a mix of scaled and unscaled addrmodes then we want scale
2127 // to be the scale and not zero.
2128 if (!Scale)
2129 for (const ExtAddrMode &AM : AddrModes)
2130 if (AM.Scale) {
2131 Scale = AM.Scale;
2132 break;
2133 }
2134 break;
2135 case ExtAddrMode::BaseOffsField:
2136 // The offset is no longer a constant, so it goes in ScaledReg with a
2137 // scale of 1.
2138 assert(ScaledReg == nullptr);
2139 ScaledReg = V;
2140 Scale = 1;
2141 BaseOffs = 0;
2142 break;
2143 }
2144 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002145};
2146
Eugene Zelenko900b6332017-08-29 22:32:07 +00002147} // end anonymous namespace
2148
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002149#ifndef NDEBUG
2150static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2151 AM.print(OS);
2152 return OS;
2153}
2154#endif
2155
Aaron Ballman615eb472017-10-15 14:32:27 +00002156#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002157void ExtAddrMode::print(raw_ostream &OS) const {
2158 bool NeedPlus = false;
2159 OS << "[";
2160 if (BaseGV) {
2161 OS << (NeedPlus ? " + " : "")
2162 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002163 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002164 NeedPlus = true;
2165 }
2166
Richard Trieuc0f91212014-05-30 03:15:17 +00002167 if (BaseOffs) {
2168 OS << (NeedPlus ? " + " : "")
2169 << BaseOffs;
2170 NeedPlus = true;
2171 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002172
2173 if (BaseReg) {
2174 OS << (NeedPlus ? " + " : "")
2175 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002176 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002177 NeedPlus = true;
2178 }
2179 if (Scale) {
2180 OS << (NeedPlus ? " + " : "")
2181 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002182 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002183 }
2184
2185 OS << ']';
2186}
2187
Yaron Kereneb2a2542016-01-29 20:50:44 +00002188LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002189 print(dbgs());
2190 dbgs() << '\n';
2191}
2192#endif
2193
Eugene Zelenko900b6332017-08-29 22:32:07 +00002194namespace {
2195
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002196/// \brief This class provides transaction based operation on the IR.
2197/// Every change made through this class is recorded in the internal state and
2198/// can be undone (rollback) until commit is called.
2199class TypePromotionTransaction {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002200 /// \brief This represents the common interface of the individual transaction.
2201 /// Each class implements the logic for doing one specific modification on
2202 /// the IR via the TypePromotionTransaction.
2203 class TypePromotionAction {
2204 protected:
2205 /// The Instruction modified.
2206 Instruction *Inst;
2207
2208 public:
2209 /// \brief Constructor of the action.
2210 /// The constructor performs the related action on the IR.
2211 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2212
Eugene Zelenko900b6332017-08-29 22:32:07 +00002213 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002214
2215 /// \brief Undo the modification done by this action.
2216 /// When this method is called, the IR must be in the same state as it was
2217 /// before this action was applied.
2218 /// \pre Undoing the action works if and only if the IR is in the exact same
2219 /// state as it was directly after this action was applied.
2220 virtual void undo() = 0;
2221
2222 /// \brief Advocate every change made by this action.
2223 /// When the results on the IR of the action are to be kept, it is important
2224 /// to call this function, otherwise hidden information may be kept forever.
2225 virtual void commit() {
2226 // Nothing to be done, this action is not doing anything.
2227 }
2228 };
2229
2230 /// \brief Utility to remember the position of an instruction.
2231 class InsertionHandler {
2232 /// Position of an instruction.
2233 /// Either an instruction:
2234 /// - Is the first in a basic block: BB is used.
2235 /// - Has a previous instructon: PrevInst is used.
2236 union {
2237 Instruction *PrevInst;
2238 BasicBlock *BB;
2239 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002240
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002241 /// Remember whether or not the instruction had a previous instruction.
2242 bool HasPrevInstruction;
2243
2244 public:
2245 /// \brief Record the position of \p Inst.
2246 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002247 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002248 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2249 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002250 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002251 else
2252 Point.BB = Inst->getParent();
2253 }
2254
2255 /// \brief Insert \p Inst at the recorded position.
2256 void insert(Instruction *Inst) {
2257 if (HasPrevInstruction) {
2258 if (Inst->getParent())
2259 Inst->removeFromParent();
2260 Inst->insertAfter(Point.PrevInst);
2261 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002262 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002263 if (Inst->getParent())
2264 Inst->moveBefore(Position);
2265 else
2266 Inst->insertBefore(Position);
2267 }
2268 }
2269 };
2270
2271 /// \brief Move an instruction before another.
2272 class InstructionMoveBefore : public TypePromotionAction {
2273 /// Original position of the instruction.
2274 InsertionHandler Position;
2275
2276 public:
2277 /// \brief Move \p Inst before \p Before.
2278 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2279 : TypePromotionAction(Inst), Position(Inst) {
2280 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2281 Inst->moveBefore(Before);
2282 }
2283
2284 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002285 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002286 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2287 Position.insert(Inst);
2288 }
2289 };
2290
2291 /// \brief Set the operand of an instruction with a new value.
2292 class OperandSetter : public TypePromotionAction {
2293 /// Original operand of the instruction.
2294 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002295
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296 /// Index of the modified instruction.
2297 unsigned Idx;
2298
2299 public:
2300 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2301 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2302 : TypePromotionAction(Inst), Idx(Idx) {
2303 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2304 << "for:" << *Inst << "\n"
2305 << "with:" << *NewVal << "\n");
2306 Origin = Inst->getOperand(Idx);
2307 Inst->setOperand(Idx, NewVal);
2308 }
2309
2310 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002311 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2313 << "for: " << *Inst << "\n"
2314 << "with: " << *Origin << "\n");
2315 Inst->setOperand(Idx, Origin);
2316 }
2317 };
2318
2319 /// \brief Hide the operands of an instruction.
2320 /// Do as if this instruction was not using any of its operands.
2321 class OperandsHider : public TypePromotionAction {
2322 /// The list of original operands.
2323 SmallVector<Value *, 4> OriginalValues;
2324
2325 public:
2326 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2327 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2328 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2329 unsigned NumOpnds = Inst->getNumOperands();
2330 OriginalValues.reserve(NumOpnds);
2331 for (unsigned It = 0; It < NumOpnds; ++It) {
2332 // Save the current operand.
2333 Value *Val = Inst->getOperand(It);
2334 OriginalValues.push_back(Val);
2335 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002336 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002337 // that we are not willing to pay.
2338 Inst->setOperand(It, UndefValue::get(Val->getType()));
2339 }
2340 }
2341
2342 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002343 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002344 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2345 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2346 Inst->setOperand(It, OriginalValues[It]);
2347 }
2348 };
2349
2350 /// \brief Build a truncate instruction.
2351 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002352 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002353
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002354 public:
2355 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2356 /// result.
2357 /// trunc Opnd to Ty.
2358 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2359 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002360 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2361 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002362 }
2363
Quentin Colombetac55b152014-09-16 22:36:07 +00002364 /// \brief Get the built value.
2365 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002366
2367 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002368 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002369 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2370 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2371 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002372 }
2373 };
2374
2375 /// \brief Build a sign extension instruction.
2376 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002377 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002378
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002379 public:
2380 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2381 /// result.
2382 /// sext Opnd to Ty.
2383 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002384 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002385 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002386 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2387 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002388 }
2389
Quentin Colombetac55b152014-09-16 22:36:07 +00002390 /// \brief Get the built value.
2391 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392
2393 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002394 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002395 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2396 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2397 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002398 }
2399 };
2400
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002401 /// \brief Build a zero extension instruction.
2402 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002403 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002404
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002405 public:
2406 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2407 /// result.
2408 /// zext Opnd to Ty.
2409 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002410 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002411 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002412 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2413 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002414 }
2415
Quentin Colombetac55b152014-09-16 22:36:07 +00002416 /// \brief Get the built value.
2417 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002418
2419 /// \brief Remove the built instruction.
2420 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002421 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2422 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2423 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002424 }
2425 };
2426
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002427 /// \brief Mutate an instruction to another type.
2428 class TypeMutator : public TypePromotionAction {
2429 /// Record the original type.
2430 Type *OrigTy;
2431
2432 public:
2433 /// \brief Mutate the type of \p Inst into \p NewTy.
2434 TypeMutator(Instruction *Inst, Type *NewTy)
2435 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2436 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2437 << "\n");
2438 Inst->mutateType(NewTy);
2439 }
2440
2441 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002442 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2444 << "\n");
2445 Inst->mutateType(OrigTy);
2446 }
2447 };
2448
2449 /// \brief Replace the uses of an instruction by another instruction.
2450 class UsesReplacer : public TypePromotionAction {
2451 /// Helper structure to keep track of the replaced uses.
2452 struct InstructionAndIdx {
2453 /// The instruction using the instruction.
2454 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002455
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456 /// The index where this instruction is used for Inst.
2457 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002458
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2460 : Inst(Inst), Idx(Idx) {}
2461 };
2462
2463 /// Keep track of the original uses (pair Instruction, Index).
2464 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002465
2466 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002467
2468 public:
2469 /// \brief Replace all the use of \p Inst by \p New.
2470 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2471 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2472 << "\n");
2473 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002474 for (Use &U : Inst->uses()) {
2475 Instruction *UserI = cast<Instruction>(U.getUser());
2476 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002477 }
2478 // Now, we can replace the uses.
2479 Inst->replaceAllUsesWith(New);
2480 }
2481
2482 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002483 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002484 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2485 for (use_iterator UseIt = OriginalUses.begin(),
2486 EndIt = OriginalUses.end();
2487 UseIt != EndIt; ++UseIt) {
2488 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2489 }
2490 }
2491 };
2492
2493 /// \brief Remove an instruction from the IR.
2494 class InstructionRemover : public TypePromotionAction {
2495 /// Original position of the instruction.
2496 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002497
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002498 /// Helper structure to hide all the link to the instruction. In other
2499 /// words, this helps to do as if the instruction was removed.
2500 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002501
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002502 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002503 UsesReplacer *Replacer = nullptr;
2504
Jun Bum Limdee55652017-04-03 19:20:07 +00002505 /// Keep track of instructions removed.
2506 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002507
2508 public:
2509 /// \brief Remove all reference of \p Inst and optinally replace all its
2510 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002511 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002512 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002513 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2514 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002515 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002516 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002517 if (New)
2518 Replacer = new UsesReplacer(Inst, New);
2519 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002520 RemovedInsts.insert(Inst);
2521 /// The instructions removed here will be freed after completing
2522 /// optimizeBlock() for all blocks as we need to keep track of the
2523 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002524 Inst->removeFromParent();
2525 }
2526
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002527 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002528
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002529 /// \brief Resurrect the instruction and reassign it to the proper uses if
2530 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002531 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002532 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2533 Inserter.insert(Inst);
2534 if (Replacer)
2535 Replacer->undo();
2536 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002537 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002538 }
2539 };
2540
2541public:
2542 /// Restoration point.
2543 /// The restoration point is a pointer to an action instead of an iterator
2544 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002545 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002546
2547 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2548 : RemovedInsts(RemovedInsts) {}
2549
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002550 /// Advocate every changes made in that transaction.
2551 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002552
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002553 /// Undo all the changes made after the given point.
2554 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002555
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002556 /// Get the current restoration point.
2557 ConstRestorationPt getRestorationPoint() const;
2558
2559 /// \name API for IR modification with state keeping to support rollback.
2560 /// @{
2561 /// Same as Instruction::setOperand.
2562 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002563
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002564 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002565 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002566
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002567 /// Same as Value::replaceAllUsesWith.
2568 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002569
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002570 /// Same as Value::mutateType.
2571 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002572
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002573 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002574 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002575
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002576 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002577 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002578
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002579 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002580 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002581
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582 /// Same as Instruction::moveBefore.
2583 void moveBefore(Instruction *Inst, Instruction *Before);
2584 /// @}
2585
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002586private:
2587 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002588 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002589
2590 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2591
Jun Bum Limdee55652017-04-03 19:20:07 +00002592 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002593};
2594
Eugene Zelenko900b6332017-08-29 22:32:07 +00002595} // end anonymous namespace
2596
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002597void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2598 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002599 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2600 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002601}
2602
2603void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2604 Value *NewVal) {
2605 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002606 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2607 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002608}
2609
2610void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2611 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002612 Actions.push_back(
2613 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002614}
2615
2616void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002617 Actions.push_back(
2618 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002619}
2620
Quentin Colombetac55b152014-09-16 22:36:07 +00002621Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2622 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002623 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002624 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002625 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002626 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002627}
2628
Quentin Colombetac55b152014-09-16 22:36:07 +00002629Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2630 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002631 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002632 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002633 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002634 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002635}
2636
Quentin Colombetac55b152014-09-16 22:36:07 +00002637Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2638 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002639 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002640 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002641 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002642 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002643}
2644
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002645void TypePromotionTransaction::moveBefore(Instruction *Inst,
2646 Instruction *Before) {
2647 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002648 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2649 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002650}
2651
2652TypePromotionTransaction::ConstRestorationPt
2653TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002654 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002655}
2656
2657void TypePromotionTransaction::commit() {
2658 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002659 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002660 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002661 Actions.clear();
2662}
2663
2664void TypePromotionTransaction::rollback(
2665 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002666 while (!Actions.empty() && Point != Actions.back().get()) {
2667 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002668 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002669 }
2670}
2671
Eugene Zelenko900b6332017-08-29 22:32:07 +00002672namespace {
2673
Chandler Carruthc8925912013-01-05 02:09:22 +00002674/// \brief A helper class for matching addressing modes.
2675///
2676/// This encapsulates the logic for matching the target-legal addressing modes.
2677class AddressingModeMatcher {
2678 SmallVectorImpl<Instruction*> &AddrModeInsts;
2679 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002680 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002681 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002682
2683 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2684 /// the memory instruction that we're computing this address for.
2685 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002686 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002687 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002688
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002689 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002690 /// part of the return value of this addressing mode matching stuff.
2691 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002692
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002693 /// The instructions inserted by other CodeGenPrepare optimizations.
2694 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002695
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002696 /// A map from the instructions to their type before promotion.
2697 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002698
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002699 /// The ongoing transaction where every action should be registered.
2700 TypePromotionTransaction &TPT;
2701
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002702 /// This is set to true when we should not do profitability checks.
2703 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002704 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002705
Eric Christopherd75c00c2015-02-26 22:38:34 +00002706 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002707 const TargetLowering &TLI,
2708 const TargetRegisterInfo &TRI,
2709 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002710 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002711 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002712 InstrToOrigTy &PromotedInsts,
2713 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002714 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002715 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2716 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2717 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002718 IgnoreProfitability = false;
2719 }
Stephen Lin837bba12013-07-15 17:55:02 +00002720
Eugene Zelenko900b6332017-08-29 22:32:07 +00002721public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002722 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002723 /// give an access type of AccessTy. This returns a list of involved
2724 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002725 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002726 /// optimizations.
2727 /// \p PromotedInsts maps the instructions to their type before promotion.
2728 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002729 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002730 Instruction *MemoryInst,
2731 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002732 const TargetLowering &TLI,
2733 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002734 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002735 InstrToOrigTy &PromotedInsts,
2736 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002737 ExtAddrMode Result;
2738
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002739 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2740 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002741 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002742 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002743 (void)Success; assert(Success && "Couldn't select *anything*?");
2744 return Result;
2745 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002746
Chandler Carruthc8925912013-01-05 02:09:22 +00002747private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002748 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2749 bool matchAddr(Value *V, unsigned Depth);
2750 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002751 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002752 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002753 ExtAddrMode &AMBefore,
2754 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002755 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2756 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002757 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002758};
2759
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002760/// \brief Keep track of simplification of Phi nodes.
2761/// Accept the set of all phi nodes and erase phi node from this set
2762/// if it is simplified.
2763class SimplificationTracker {
2764 DenseMap<Value *, Value *> Storage;
2765 const SimplifyQuery &SQ;
2766 SmallPtrSetImpl<PHINode *> &AllPhiNodes;
2767 SmallPtrSetImpl<SelectInst *> &AllSelectNodes;
2768
2769public:
2770 SimplificationTracker(const SimplifyQuery &sq,
2771 SmallPtrSetImpl<PHINode *> &APN,
2772 SmallPtrSetImpl<SelectInst *> &ASN)
2773 : SQ(sq), AllPhiNodes(APN), AllSelectNodes(ASN) {}
2774
2775 Value *Get(Value *V) {
2776 do {
2777 auto SV = Storage.find(V);
2778 if (SV == Storage.end())
2779 return V;
2780 V = SV->second;
2781 } while (true);
2782 }
2783
2784 Value *Simplify(Value *Val) {
2785 SmallVector<Value *, 32> WorkList;
2786 SmallPtrSet<Value *, 32> Visited;
2787 WorkList.push_back(Val);
2788 while (!WorkList.empty()) {
2789 auto P = WorkList.pop_back_val();
2790 if (!Visited.insert(P).second)
2791 continue;
2792 if (auto *PI = dyn_cast<Instruction>(P))
2793 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2794 for (auto *U : PI->users())
2795 WorkList.push_back(cast<Value>(U));
2796 Put(PI, V);
2797 PI->replaceAllUsesWith(V);
2798 if (auto *PHI = dyn_cast<PHINode>(PI))
2799 AllPhiNodes.erase(PHI);
2800 if (auto *Select = dyn_cast<SelectInst>(PI))
2801 AllSelectNodes.erase(Select);
2802 PI->eraseFromParent();
2803 }
2804 }
2805 return Get(Val);
2806 }
2807
2808 void Put(Value *From, Value *To) {
2809 Storage.insert({ From, To });
2810 }
2811};
2812
John Brawn736bf002017-10-03 13:08:22 +00002813/// \brief A helper class for combining addressing modes.
2814class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002815 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2816 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2817 typedef std::pair<PHINode *, PHINode *> PHIPair;
2818
John Brawn736bf002017-10-03 13:08:22 +00002819private:
2820 /// The addressing modes we've collected.
2821 SmallVector<ExtAddrMode, 16> AddrModes;
2822
2823 /// The field in which the AddrModes differ, when we have more than one.
2824 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2825
2826 /// Are the AddrModes that we have all just equal to their original values?
2827 bool AllAddrModesTrivial = true;
2828
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002829 /// Common Type for all different fields in addressing modes.
2830 Type *CommonType;
2831
2832 /// SimplifyQuery for simplifyInstruction utility.
2833 const SimplifyQuery &SQ;
2834
2835 /// Original Address.
2836 ValueInBB Original;
2837
John Brawn736bf002017-10-03 13:08:22 +00002838public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002839 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2840 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2841
John Brawn736bf002017-10-03 13:08:22 +00002842 /// \brief Get the combined AddrMode
2843 const ExtAddrMode &getAddrMode() const {
2844 return AddrModes[0];
2845 }
2846
2847 /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
2848 /// have.
2849 /// \return True iff we succeeded in doing so.
2850 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2851 // Take note of if we have any non-trivial AddrModes, as we need to detect
2852 // when all AddrModes are trivial as then we would introduce a phi or select
2853 // which just duplicates what's already there.
2854 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2855
2856 // If this is the first addrmode then everything is fine.
2857 if (AddrModes.empty()) {
2858 AddrModes.emplace_back(NewAddrMode);
2859 return true;
2860 }
2861
2862 // Figure out how different this is from the other address modes, which we
2863 // can do just by comparing against the first one given that we only care
2864 // about the cumulative difference.
2865 ExtAddrMode::FieldName ThisDifferentField =
2866 AddrModes[0].compare(NewAddrMode);
2867 if (DifferentField == ExtAddrMode::NoField)
2868 DifferentField = ThisDifferentField;
2869 else if (DifferentField != ThisDifferentField)
2870 DifferentField = ExtAddrMode::MultipleFields;
2871
John Brawn70cdb5b2017-11-24 14:10:45 +00002872 // If NewAddrMode differs in only one dimension, and that dimension isn't
2873 // the amount that ScaledReg is scaled by, then we can handle it by
Serguei Katkov505359f2017-11-20 05:42:36 +00002874 // inserting a phi/select later on. Even if NewAddMode is the same
2875 // we still need to collect it due to original value is different.
2876 // And later we will need all original values as anchors during
2877 // finding the common Phi node.
John Brawn70cdb5b2017-11-24 14:10:45 +00002878 if (DifferentField != ExtAddrMode::MultipleFields &&
2879 DifferentField != ExtAddrMode::ScaleField) {
John Brawn736bf002017-10-03 13:08:22 +00002880 AddrModes.emplace_back(NewAddrMode);
2881 return true;
2882 }
2883
2884 // We couldn't combine NewAddrMode with the rest, so return failure.
2885 AddrModes.clear();
2886 return false;
2887 }
2888
2889 /// \brief Combine the addressing modes we've collected into a single
2890 /// addressing mode.
2891 /// \return True iff we successfully combined them or we only had one so
2892 /// didn't need to combine them anyway.
2893 bool combineAddrModes() {
2894 // If we have no AddrModes then they can't be combined.
2895 if (AddrModes.size() == 0)
2896 return false;
2897
2898 // A single AddrMode can trivially be combined.
Serguei Katkov505359f2017-11-20 05:42:36 +00002899 if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
John Brawn736bf002017-10-03 13:08:22 +00002900 return true;
2901
2902 // If the AddrModes we collected are all just equal to the value they are
2903 // derived from then combining them wouldn't do anything useful.
2904 if (AllAddrModesTrivial)
2905 return false;
2906
John Brawn70cdb5b2017-11-24 14:10:45 +00002907 if (!addrModeCombiningAllowed())
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002908 return false;
2909
2910 // Build a map between <original value, basic block where we saw it> to
2911 // value of base register.
Serguei Katkov50364592017-11-29 05:51:26 +00002912 // Bail out if there is no common type.
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002913 FoldAddrToValueMapping Map;
Serguei Katkov50364592017-11-29 05:51:26 +00002914 if (!initializeMap(Map))
2915 return false;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002916
2917 Value *CommonValue = findCommon(Map);
2918 if (CommonValue)
John Brawn70cdb5b2017-11-24 14:10:45 +00002919 AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002920 return CommonValue != nullptr;
2921 }
2922
2923private:
2924 /// \brief Initialize Map with anchor values. For address seen in some BB
2925 /// we set the value of different field saw in this address.
2926 /// If address is not an instruction than basic block is set to null.
2927 /// At the same time we find a common type for different field we will
2928 /// use to create new Phi/Select nodes. Keep it in CommonType field.
Serguei Katkov50364592017-11-29 05:51:26 +00002929 /// Return false if there is no common type found.
2930 bool initializeMap(FoldAddrToValueMapping &Map) {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002931 // Keep track of keys where the value is null. We will need to replace it
2932 // with constant null when we know the common type.
2933 SmallVector<ValueInBB, 2> NullValue;
John Brawn70cdb5b2017-11-24 14:10:45 +00002934 Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002935 for (auto &AM : AddrModes) {
2936 BasicBlock *BB = nullptr;
2937 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2938 BB = I->getParent();
2939
John Brawn70cdb5b2017-11-24 14:10:45 +00002940 Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002941 if (DV) {
Serguei Katkov50364592017-11-29 05:51:26 +00002942 auto *Type = DV->getType();
2943 if (CommonType && CommonType != Type)
2944 return false;
2945 CommonType = Type;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002946 Map[{ AM.OriginalValue, BB }] = DV;
2947 } else {
2948 NullValue.push_back({ AM.OriginalValue, BB });
2949 }
2950 }
2951 assert(CommonType && "At least one non-null value must be!");
2952 for (auto VIBB : NullValue)
2953 Map[VIBB] = Constant::getNullValue(CommonType);
Serguei Katkov50364592017-11-29 05:51:26 +00002954 return true;
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002955 }
2956
2957 /// \brief We have mapping between value A and basic block where value A
2958 /// seen to other value B where B was a field in addressing mode represented
2959 /// by A. Also we have an original value C representin an address in some
2960 /// basic block. Traversing from C through phi and selects we ended up with
2961 /// A's in a map. This utility function tries to find a value V which is a
2962 /// field in addressing mode C and traversing through phi nodes and selects
2963 /// we will end up in corresponded values B in a map.
2964 /// The utility will create a new Phi/Selects if needed.
2965 // The simple example looks as follows:
2966 // BB1:
2967 // p1 = b1 + 40
2968 // br cond BB2, BB3
2969 // BB2:
2970 // p2 = b2 + 40
2971 // br BB3
2972 // BB3:
2973 // p = phi [p1, BB1], [p2, BB2]
2974 // v = load p
2975 // Map is
2976 // <p1, BB1> -> b1
2977 // <p2, BB2> -> b2
2978 // Request is
2979 // <p, BB3> -> ?
2980 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2981 Value *findCommon(FoldAddrToValueMapping &Map) {
2982 // Tracks of new created Phi nodes.
2983 SmallPtrSet<PHINode *, 32> NewPhiNodes;
2984 // Tracks of new created Select nodes.
2985 SmallPtrSet<SelectInst *, 32> NewSelectNodes;
2986 // Tracks the simplification of new created phi nodes. The reason we use
2987 // this mapping is because we will add new created Phi nodes in AddrToBase.
2988 // Simplification of Phi nodes is recursive, so some Phi node may
2989 // be simplified after we added it to AddrToBase.
2990 // Using this mapping we can find the current value in AddrToBase.
2991 SimplificationTracker ST(SQ, NewPhiNodes, NewSelectNodes);
2992
2993 // First step, DFS to create PHI nodes for all intermediate blocks.
2994 // Also fill traverse order for the second step.
2995 SmallVector<ValueInBB, 32> TraverseOrder;
2996 InsertPlaceholders(Map, TraverseOrder, NewPhiNodes, NewSelectNodes);
2997
2998 // Second Step, fill new nodes by merged values and simplify if possible.
2999 FillPlaceholders(Map, TraverseOrder, ST);
3000
3001 if (!AddrSinkNewSelects && NewSelectNodes.size() > 0) {
3002 DestroyNodes(NewPhiNodes);
3003 DestroyNodes(NewSelectNodes);
3004 return nullptr;
3005 }
3006
3007 // Now we'd like to match New Phi nodes to existed ones.
3008 unsigned PhiNotMatchedCount = 0;
3009 if (!MatchPhiSet(NewPhiNodes, ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
3010 DestroyNodes(NewPhiNodes);
3011 DestroyNodes(NewSelectNodes);
3012 return nullptr;
3013 }
3014
3015 auto *Result = ST.Get(Map.find(Original)->second);
3016 if (Result) {
3017 NumMemoryInstsPhiCreated += NewPhiNodes.size() + PhiNotMatchedCount;
3018 NumMemoryInstsSelectCreated += NewSelectNodes.size();
3019 }
3020 return Result;
3021 }
3022
3023 /// \brief Destroy nodes from a set.
3024 template <typename T> void DestroyNodes(SmallPtrSetImpl<T *> &Instructions) {
3025 // For safe erasing, replace the Phi with dummy value first.
3026 auto Dummy = UndefValue::get(CommonType);
3027 for (auto I : Instructions) {
3028 I->replaceAllUsesWith(Dummy);
3029 I->eraseFromParent();
3030 }
3031 }
3032
3033 /// \brief Try to match PHI node to Candidate.
3034 /// Matcher tracks the matched Phi nodes.
3035 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
3036 DenseSet<PHIPair> &Matcher,
3037 SmallPtrSetImpl<PHINode *> &PhiNodesToMatch) {
3038 SmallVector<PHIPair, 8> WorkList;
3039 Matcher.insert({ PHI, Candidate });
3040 WorkList.push_back({ PHI, Candidate });
3041 SmallSet<PHIPair, 8> Visited;
3042 while (!WorkList.empty()) {
3043 auto Item = WorkList.pop_back_val();
3044 if (!Visited.insert(Item).second)
3045 continue;
3046 // We iterate over all incoming values to Phi to compare them.
3047 // If values are different and both of them Phi and the first one is a
3048 // Phi we added (subject to match) and both of them is in the same basic
3049 // block then we can match our pair if values match. So we state that
3050 // these values match and add it to work list to verify that.
3051 for (auto B : Item.first->blocks()) {
3052 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
3053 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
3054 if (FirstValue == SecondValue)
3055 continue;
3056
3057 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
3058 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
3059
3060 // One of them is not Phi or
3061 // The first one is not Phi node from the set we'd like to match or
3062 // Phi nodes from different basic blocks then
3063 // we will not be able to match.
3064 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
3065 FirstPhi->getParent() != SecondPhi->getParent())
3066 return false;
3067
3068 // If we already matched them then continue.
3069 if (Matcher.count({ FirstPhi, SecondPhi }))
3070 continue;
3071 // So the values are different and does not match. So we need them to
3072 // match.
3073 Matcher.insert({ FirstPhi, SecondPhi });
3074 // But me must check it.
3075 WorkList.push_back({ FirstPhi, SecondPhi });
3076 }
3077 }
3078 return true;
3079 }
3080
3081 /// \brief For the given set of PHI nodes try to find their equivalents.
3082 /// Returns false if this matching fails and creation of new Phi is disabled.
3083 bool MatchPhiSet(SmallPtrSetImpl<PHINode *> &PhiNodesToMatch,
3084 SimplificationTracker &ST, bool AllowNewPhiNodes,
3085 unsigned &PhiNotMatchedCount) {
3086 DenseSet<PHIPair> Matched;
3087 SmallPtrSet<PHINode *, 8> WillNotMatch;
3088 while (PhiNodesToMatch.size()) {
3089 PHINode *PHI = *PhiNodesToMatch.begin();
3090
3091 // Add us, if no Phi nodes in the basic block we do not match.
3092 WillNotMatch.clear();
3093 WillNotMatch.insert(PHI);
3094
3095 // Traverse all Phis until we found equivalent or fail to do that.
3096 bool IsMatched = false;
3097 for (auto &P : PHI->getParent()->phis()) {
3098 if (&P == PHI)
3099 continue;
3100 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3101 break;
3102 // If it does not match, collect all Phi nodes from matcher.
3103 // if we end up with no match, them all these Phi nodes will not match
3104 // later.
3105 for (auto M : Matched)
3106 WillNotMatch.insert(M.first);
3107 Matched.clear();
3108 }
3109 if (IsMatched) {
3110 // Replace all matched values and erase them.
3111 for (auto MV : Matched) {
3112 MV.first->replaceAllUsesWith(MV.second);
3113 PhiNodesToMatch.erase(MV.first);
3114 ST.Put(MV.first, MV.second);
3115 MV.first->eraseFromParent();
3116 }
3117 Matched.clear();
3118 continue;
3119 }
3120 // If we are not allowed to create new nodes then bail out.
3121 if (!AllowNewPhiNodes)
3122 return false;
3123 // Just remove all seen values in matcher. They will not match anything.
3124 PhiNotMatchedCount += WillNotMatch.size();
3125 for (auto *P : WillNotMatch)
3126 PhiNodesToMatch.erase(P);
3127 }
3128 return true;
3129 }
3130 /// \brief Fill the placeholder with values from predecessors and simplify it.
3131 void FillPlaceholders(FoldAddrToValueMapping &Map,
3132 SmallVectorImpl<ValueInBB> &TraverseOrder,
3133 SimplificationTracker &ST) {
3134 while (!TraverseOrder.empty()) {
3135 auto Current = TraverseOrder.pop_back_val();
3136 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3137 Value *CurrentValue = Current.first;
3138 BasicBlock *CurrentBlock = Current.second;
3139 Value *V = Map[Current];
3140
3141 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3142 // CurrentValue also must be Select.
3143 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3144 auto *TrueValue = CurrentSelect->getTrueValue();
3145 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3146 ? CurrentBlock
3147 : nullptr };
3148 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
3149 Select->setTrueValue(Map[TrueItem]);
3150 auto *FalseValue = CurrentSelect->getFalseValue();
3151 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3152 ? CurrentBlock
3153 : nullptr };
3154 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
3155 Select->setFalseValue(Map[FalseItem]);
3156 } else {
3157 // Must be a Phi node then.
3158 PHINode *PHI = cast<PHINode>(V);
3159 // Fill the Phi node with values from predecessors.
3160 bool IsDefinedInThisBB =
3161 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3162 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3163 for (auto B : predecessors(CurrentBlock)) {
3164 Value *PV = IsDefinedInThisBB
3165 ? CurrentPhi->getIncomingValueForBlock(B)
3166 : CurrentValue;
3167 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3168 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3169 PHI->addIncoming(ST.Get(Map[item]), B);
3170 }
3171 }
3172 // Simplify if possible.
3173 Map[Current] = ST.Simplify(V);
3174 }
3175 }
3176
3177 /// Starting from value recursively iterates over predecessors up to known
3178 /// ending values represented in a map. For each traversed block inserts
3179 /// a placeholder Phi or Select.
3180 /// Reports all new created Phi/Select nodes by adding them to set.
3181 /// Also reports and order in what basic blocks have been traversed.
3182 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3183 SmallVectorImpl<ValueInBB> &TraverseOrder,
3184 SmallPtrSetImpl<PHINode *> &NewPhiNodes,
3185 SmallPtrSetImpl<SelectInst *> &NewSelectNodes) {
3186 SmallVector<ValueInBB, 32> Worklist;
3187 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3188 "Address must be a Phi or Select node");
3189 auto *Dummy = UndefValue::get(CommonType);
3190 Worklist.push_back(Original);
3191 while (!Worklist.empty()) {
3192 auto Current = Worklist.pop_back_val();
3193 // If value is not an instruction it is something global, constant,
3194 // parameter and we can say that this value is observable in any block.
3195 // Set block to null to denote it.
3196 // Also please take into account that it is how we build anchors.
3197 if (!isa<Instruction>(Current.first))
3198 Current.second = nullptr;
3199 // if it is already visited or it is an ending value then skip it.
3200 if (Map.find(Current) != Map.end())
3201 continue;
3202 TraverseOrder.push_back(Current);
3203
3204 Value *CurrentValue = Current.first;
3205 BasicBlock *CurrentBlock = Current.second;
3206 // CurrentValue must be a Phi node or select. All others must be covered
3207 // by anchors.
3208 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3209 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3210
3211 unsigned PredCount =
3212 std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3213 // if Current Value is not defined in this basic block we are interested
3214 // in values in predecessors.
3215 if (!IsDefinedInThisBB) {
3216 assert(PredCount && "Unreachable block?!");
3217 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3218 &CurrentBlock->front());
3219 Map[Current] = PHI;
3220 NewPhiNodes.insert(PHI);
3221 // Add all predecessors in work list.
3222 for (auto B : predecessors(CurrentBlock))
3223 Worklist.push_back({ CurrentValue, B });
3224 continue;
3225 }
3226 // Value is defined in this basic block.
3227 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3228 // Is it OK to get metadata from OrigSelect?!
3229 // Create a Select placeholder with dummy value.
3230 SelectInst *Select =
3231 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3232 OrigSelect->getName(), OrigSelect, OrigSelect);
3233 Map[Current] = Select;
3234 NewSelectNodes.insert(Select);
3235 // We are interested in True and False value in this basic block.
3236 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3237 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3238 } else {
3239 // It must be a Phi node then.
3240 auto *CurrentPhi = cast<PHINode>(CurrentI);
3241 // Create new Phi node for merge of bases.
3242 assert(PredCount && "Unreachable block?!");
3243 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3244 &CurrentBlock->front());
3245 Map[Current] = PHI;
3246 NewPhiNodes.insert(PHI);
3247
3248 // Add all predecessors in work list.
3249 for (auto B : predecessors(CurrentBlock))
3250 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3251 }
3252 }
John Brawn736bf002017-10-03 13:08:22 +00003253 }
John Brawn70cdb5b2017-11-24 14:10:45 +00003254
3255 bool addrModeCombiningAllowed() {
3256 if (DisableComplexAddrModes)
3257 return false;
3258 switch (DifferentField) {
3259 default:
3260 return false;
3261 case ExtAddrMode::BaseRegField:
3262 return AddrSinkCombineBaseReg;
3263 case ExtAddrMode::BaseGVField:
3264 return AddrSinkCombineBaseGV;
3265 case ExtAddrMode::BaseOffsField:
3266 return AddrSinkCombineBaseOffs;
3267 case ExtAddrMode::ScaledRegField:
3268 return AddrSinkCombineScaledReg;
3269 }
3270 }
John Brawn736bf002017-10-03 13:08:22 +00003271};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003272} // end anonymous namespace
3273
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003274/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003275/// Return true and update AddrMode if this addr mode is legal for the target,
3276/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003277bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003278 unsigned Depth) {
3279 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3280 // mode. Just process that directly.
3281 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003282 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003283
Chandler Carruthc8925912013-01-05 02:09:22 +00003284 // If the scale is 0, it takes nothing to add this.
3285 if (Scale == 0)
3286 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003287
Chandler Carruthc8925912013-01-05 02:09:22 +00003288 // If we already have a scale of this value, we can add to it, otherwise, we
3289 // need an available scale field.
3290 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3291 return false;
3292
3293 ExtAddrMode TestAddrMode = AddrMode;
3294
3295 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3296 // [A+B + A*7] -> [B+A*8].
3297 TestAddrMode.Scale += Scale;
3298 TestAddrMode.ScaledReg = ScaleReg;
3299
3300 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003301 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003302 return false;
3303
3304 // It was legal, so commit it.
3305 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003306
Chandler Carruthc8925912013-01-05 02:09:22 +00003307 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3308 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3309 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003310 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003311 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3312 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3313 TestAddrMode.ScaledReg = AddLHS;
3314 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003315
Chandler Carruthc8925912013-01-05 02:09:22 +00003316 // If this addressing mode is legal, commit it and remember that we folded
3317 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003318 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003319 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3320 AddrMode = TestAddrMode;
3321 return true;
3322 }
3323 }
3324
3325 // Otherwise, not (x+c)*scale, just return what we have.
3326 return true;
3327}
3328
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003329/// This is a little filter, which returns true if an addressing computation
3330/// involving I might be folded into a load/store accessing it.
3331/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003332/// the set of instructions that MatchOperationAddr can.
3333static bool MightBeFoldableInst(Instruction *I) {
3334 switch (I->getOpcode()) {
3335 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003336 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003337 // Don't touch identity bitcasts.
3338 if (I->getType() == I->getOperand(0)->getType())
3339 return false;
3340 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3341 case Instruction::PtrToInt:
3342 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3343 return true;
3344 case Instruction::IntToPtr:
3345 // We know the input is intptr_t, so this is foldable.
3346 return true;
3347 case Instruction::Add:
3348 return true;
3349 case Instruction::Mul:
3350 case Instruction::Shl:
3351 // Can only handle X*C and X << C.
3352 return isa<ConstantInt>(I->getOperand(1));
3353 case Instruction::GetElementPtr:
3354 return true;
3355 default:
3356 return false;
3357 }
3358}
3359
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003360/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3361/// \note \p Val is assumed to be the product of some type promotion.
3362/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3363/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003364static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3365 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003366 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3367 if (!PromotedInst)
3368 return false;
3369 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3370 // If the ISDOpcode is undefined, it was undefined before the promotion.
3371 if (!ISDOpcode)
3372 return true;
3373 // Otherwise, check if the promoted instruction is legal or not.
3374 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003375 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003376}
3377
Eugene Zelenko900b6332017-08-29 22:32:07 +00003378namespace {
3379
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003380/// \brief Hepler class to perform type promotion.
3381class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003382 /// \brief Utility function to check whether or not a sign or zero extension
3383 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3384 /// either using the operands of \p Inst or promoting \p Inst.
3385 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003386 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003387 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003388 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003389 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003390 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003391 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003392 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003393 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3394 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003395
3396 /// \brief Utility function to determine if \p OpIdx should be promoted when
3397 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003398 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003399 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003400 }
3401
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003402 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003403 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003404 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003405 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003406 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003407 /// Newly added extensions are inserted in \p Exts.
3408 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003409 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003410 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003411 static Value *promoteOperandForTruncAndAnyExt(
3412 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003413 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003414 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003415 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003416
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003417 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003418 /// operand is promotable and is not a supported trunc or sext.
3419 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003420 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003421 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003422 /// Newly added extensions are inserted in \p Exts.
3423 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003424 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003425 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003426 static Value *promoteOperandForOther(Instruction *Ext,
3427 TypePromotionTransaction &TPT,
3428 InstrToOrigTy &PromotedInsts,
3429 unsigned &CreatedInstsCost,
3430 SmallVectorImpl<Instruction *> *Exts,
3431 SmallVectorImpl<Instruction *> *Truncs,
3432 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003433
3434 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003435 static Value *signExtendOperandForOther(
3436 Instruction *Ext, TypePromotionTransaction &TPT,
3437 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3438 SmallVectorImpl<Instruction *> *Exts,
3439 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3440 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3441 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003442 }
3443
3444 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003445 static Value *zeroExtendOperandForOther(
3446 Instruction *Ext, TypePromotionTransaction &TPT,
3447 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3448 SmallVectorImpl<Instruction *> *Exts,
3449 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3450 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3451 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003452 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003453
3454public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003455 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003456 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3457 InstrToOrigTy &PromotedInsts,
3458 unsigned &CreatedInstsCost,
3459 SmallVectorImpl<Instruction *> *Exts,
3460 SmallVectorImpl<Instruction *> *Truncs,
3461 const TargetLowering &TLI);
3462
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003463 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3464 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003465 /// \return NULL if no promotable action is possible with the current
3466 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003467 /// \p InsertedInsts keeps track of all the instructions inserted by the
3468 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003469 /// because we do not want to promote these instructions as CodeGenPrepare
3470 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3471 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003472 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003473 const TargetLowering &TLI,
3474 const InstrToOrigTy &PromotedInsts);
3475};
3476
Eugene Zelenko900b6332017-08-29 22:32:07 +00003477} // end anonymous namespace
3478
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003479bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003480 Type *ConsideredExtType,
3481 const InstrToOrigTy &PromotedInsts,
3482 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003483 // The promotion helper does not know how to deal with vector types yet.
3484 // To be able to fix that, we would need to fix the places where we
3485 // statically extend, e.g., constants and such.
3486 if (Inst->getType()->isVectorTy())
3487 return false;
3488
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003489 // We can always get through zext.
3490 if (isa<ZExtInst>(Inst))
3491 return true;
3492
3493 // sext(sext) is ok too.
3494 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003495 return true;
3496
3497 // We can get through binary operator, if it is legal. In other words, the
3498 // binary operator must have a nuw or nsw flag.
3499 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3500 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003501 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3502 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003503 return true;
3504
3505 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003506 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003507 if (!isa<TruncInst>(Inst))
3508 return false;
3509
3510 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003511 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003512 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003513 if (!OpndVal->getType()->isIntegerTy() ||
3514 OpndVal->getType()->getIntegerBitWidth() >
3515 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003516 return false;
3517
3518 // If the operand of the truncate is not an instruction, we will not have
3519 // any information on the dropped bits.
3520 // (Actually we could for constant but it is not worth the extra logic).
3521 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3522 if (!Opnd)
3523 return false;
3524
3525 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003526 // I.e., check that trunc just drops extended bits of the same kind of
3527 // the extension.
3528 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003529 const Type *OpndType;
3530 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003531 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3532 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003533 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3534 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003535 else
3536 return false;
3537
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003538 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003539 return Inst->getType()->getIntegerBitWidth() >=
3540 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003541}
3542
3543TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003544 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003545 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003546 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3547 "Unexpected instruction type");
3548 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3549 Type *ExtTy = Ext->getType();
3550 bool IsSExt = isa<SExtInst>(Ext);
3551 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003552 // get through.
3553 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003554 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003555 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003556
3557 // Do not promote if the operand has been added by codegenprepare.
3558 // Otherwise, it means we are undoing an optimization that is likely to be
3559 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003560 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003561 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003562
3563 // SExt or Trunc instructions.
3564 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003565 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3566 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003567 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003568
3569 // Regular instruction.
3570 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003571 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003572 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003573 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003574}
3575
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003576Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003577 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003578 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003579 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003580 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003581 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3582 // get through it and this method should not be called.
3583 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003584 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003585 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003586 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003587 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003588 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003589 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003590 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003591 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3592 TPT.replaceAllUsesWith(SExt, ZExt);
3593 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003594 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003595 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003596 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3597 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003598 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3599 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003600 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003601
3602 // Remove dead code.
3603 if (SExtOpnd->use_empty())
3604 TPT.eraseInstruction(SExtOpnd);
3605
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003606 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003607 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003608 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003609 if (ExtInst) {
3610 if (Exts)
3611 Exts->push_back(ExtInst);
3612 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3613 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003614 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003615 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003616
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003617 // At this point we have: ext ty opnd to ty.
3618 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3619 Value *NextVal = ExtInst->getOperand(0);
3620 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003621 return NextVal;
3622}
3623
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003624Value *TypePromotionHelper::promoteOperandForOther(
3625 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003626 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003627 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003628 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3629 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003630 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003631 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003632 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003633 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003634 if (!ExtOpnd->hasOneUse()) {
3635 // ExtOpnd will be promoted.
3636 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003637 // promoted version.
3638 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003639 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003640 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003641 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003642 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003643 if (Truncs)
3644 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003645 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003646
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003647 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003648 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003649 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003650 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003651 }
3652
3653 // Get through the Instruction:
3654 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003655 // 2. Replace the uses of Ext by Inst.
3656 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003657
3658 // Remember the original type of the instruction before promotion.
3659 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003660 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3661 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003662 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003663 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003664 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003665 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003666 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003667 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003668
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003669 DEBUG(dbgs() << "Propagate Ext to operands\n");
3670 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003671 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003672 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3673 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3674 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003675 DEBUG(dbgs() << "No need to propagate\n");
3676 continue;
3677 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003678 // Check if we can statically extend the operand.
3679 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003680 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003681 DEBUG(dbgs() << "Statically extend\n");
3682 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3683 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3684 : Cst->getValue().zext(BitWidth);
3685 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003686 continue;
3687 }
3688 // UndefValue are typed, so we have to statically sign extend them.
3689 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003690 DEBUG(dbgs() << "Statically extend\n");
3691 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003692 continue;
3693 }
3694
3695 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003696 // Check if Ext was reused to extend an operand.
3697 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003698 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003699 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003700 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3701 : TPT.createZExt(Ext, Opnd, Ext->getType());
3702 if (!isa<Instruction>(ValForExtOpnd)) {
3703 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3704 continue;
3705 }
3706 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003707 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003708 if (Exts)
3709 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003710 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003711
3712 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003713 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3714 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003715 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003716 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003717 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003718 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003719 if (ExtForOpnd == Ext) {
3720 DEBUG(dbgs() << "Extension is useless now\n");
3721 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003722 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003723 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003724}
3725
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003726/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003727/// \p NewCost gives the cost of extension instructions created by the
3728/// promotion.
3729/// \p OldCost gives the cost of extension instructions before the promotion
3730/// plus the number of instructions that have been
3731/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003732/// \p PromotedOperand is the value that has been promoted.
3733/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003734bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003735 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3736 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3737 // The cost of the new extensions is greater than the cost of the
3738 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003739 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003740 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003741 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003742 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003743 return true;
3744 // The promotion is neutral but it may help folding the sign extension in
3745 // loads for instance.
3746 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003747 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003748}
3749
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003750/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003751/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003752/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003753/// If \p MovedAway is not NULL, it contains the information of whether or
3754/// not AddrInst has to be folded into the addressing mode on success.
3755/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3756/// because it has been moved away.
3757/// Thus AddrInst must not be added in the matched instructions.
3758/// This state can happen when AddrInst is a sext, since it may be moved away.
3759/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3760/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003761bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003762 unsigned Depth,
3763 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003764 // Avoid exponential behavior on extremely deep expression trees.
3765 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003766
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003767 // By default, all matched instructions stay in place.
3768 if (MovedAway)
3769 *MovedAway = false;
3770
Chandler Carruthc8925912013-01-05 02:09:22 +00003771 switch (Opcode) {
3772 case Instruction::PtrToInt:
3773 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003774 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003775 case Instruction::IntToPtr: {
3776 auto AS = AddrInst->getType()->getPointerAddressSpace();
3777 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003778 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003779 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003780 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003781 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003782 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003783 case Instruction::BitCast:
3784 // BitCast is always a noop, and we can handle it as long as it is
3785 // int->int or pointer->pointer (we don't want int<->fp or something).
3786 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3787 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3788 // Don't touch identity bitcasts. These were probably put here by LSR,
3789 // and we don't want to mess around with them. Assume it knows what it
3790 // is doing.
3791 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003792 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003793 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003794 case Instruction::AddrSpaceCast: {
3795 unsigned SrcAS
3796 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3797 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3798 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003799 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003800 return false;
3801 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003802 case Instruction::Add: {
3803 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3804 ExtAddrMode BackupAddrMode = AddrMode;
3805 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003806 // Start a transaction at this point.
3807 // The LHS may match but not the RHS.
3808 // Therefore, we need a higher level restoration point to undo partially
3809 // matched operation.
3810 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3811 TPT.getRestorationPoint();
3812
Sanjay Patelfc580a62015-09-21 23:03:16 +00003813 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3814 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003815 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003816
Chandler Carruthc8925912013-01-05 02:09:22 +00003817 // Restore the old addr mode info.
3818 AddrMode = BackupAddrMode;
3819 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003820 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003821
Chandler Carruthc8925912013-01-05 02:09:22 +00003822 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003823 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3824 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003825 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003826
Chandler Carruthc8925912013-01-05 02:09:22 +00003827 // Otherwise we definitely can't merge the ADD in.
3828 AddrMode = BackupAddrMode;
3829 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003830 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003831 break;
3832 }
3833 //case Instruction::Or:
3834 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3835 //break;
3836 case Instruction::Mul:
3837 case Instruction::Shl: {
3838 // Can only handle X*C and X << C.
3839 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003840 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003841 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003842 int64_t Scale = RHS->getSExtValue();
3843 if (Opcode == Instruction::Shl)
3844 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003845
Sanjay Patelfc580a62015-09-21 23:03:16 +00003846 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003847 }
3848 case Instruction::GetElementPtr: {
3849 // Scan the GEP. We check it if it contains constant offsets and at most
3850 // one variable offset.
3851 int VariableOperand = -1;
3852 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003853
Chandler Carruthc8925912013-01-05 02:09:22 +00003854 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003855 gep_type_iterator GTI = gep_type_begin(AddrInst);
3856 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003857 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003858 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003859 unsigned Idx =
3860 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3861 ConstantOffset += SL->getElementOffset(Idx);
3862 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003863 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003864 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3865 ConstantOffset += CI->getSExtValue()*TypeSize;
3866 } else if (TypeSize) { // Scales of zero don't do anything.
3867 // We only allow one variable index at the moment.
3868 if (VariableOperand != -1)
3869 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003870
Chandler Carruthc8925912013-01-05 02:09:22 +00003871 // Remember the variable index.
3872 VariableOperand = i;
3873 VariableScale = TypeSize;
3874 }
3875 }
3876 }
Stephen Lin837bba12013-07-15 17:55:02 +00003877
Chandler Carruthc8925912013-01-05 02:09:22 +00003878 // A common case is for the GEP to only do a constant offset. In this case,
3879 // just add it to the disp field and check validity.
3880 if (VariableOperand == -1) {
3881 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003882 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003883 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003884 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003885 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003886 return true;
3887 }
3888 AddrMode.BaseOffs -= ConstantOffset;
3889 return false;
3890 }
3891
3892 // Save the valid addressing mode in case we can't match.
3893 ExtAddrMode BackupAddrMode = AddrMode;
3894 unsigned OldSize = AddrModeInsts.size();
3895
3896 // See if the scale and offset amount is valid for this target.
3897 AddrMode.BaseOffs += ConstantOffset;
3898
3899 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003900 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003901 // If it couldn't be matched, just stuff the value in a register.
3902 if (AddrMode.HasBaseReg) {
3903 AddrMode = BackupAddrMode;
3904 AddrModeInsts.resize(OldSize);
3905 return false;
3906 }
3907 AddrMode.HasBaseReg = true;
3908 AddrMode.BaseReg = AddrInst->getOperand(0);
3909 }
3910
3911 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003912 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003913 Depth)) {
3914 // If it couldn't be matched, try stuffing the base into a register
3915 // instead of matching it, and retrying the match of the scale.
3916 AddrMode = BackupAddrMode;
3917 AddrModeInsts.resize(OldSize);
3918 if (AddrMode.HasBaseReg)
3919 return false;
3920 AddrMode.HasBaseReg = true;
3921 AddrMode.BaseReg = AddrInst->getOperand(0);
3922 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003923 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003924 VariableScale, Depth)) {
3925 // If even that didn't work, bail.
3926 AddrMode = BackupAddrMode;
3927 AddrModeInsts.resize(OldSize);
3928 return false;
3929 }
3930 }
3931
3932 return true;
3933 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003934 case Instruction::SExt:
3935 case Instruction::ZExt: {
3936 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3937 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003938 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003939
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003940 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003941 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003942 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003943 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003944 if (!TPH)
3945 return false;
3946
3947 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3948 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003949 unsigned CreatedInstsCost = 0;
3950 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003951 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003952 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003953 // SExt has been moved away.
3954 // Thus either it will be rematched later in the recursive calls or it is
3955 // gone. Anyway, we must not fold it into the addressing mode at this point.
3956 // E.g.,
3957 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003958 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003959 // addr = gep base, idx
3960 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003961 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003962 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3963 // addr = gep base, op <- match
3964 if (MovedAway)
3965 *MovedAway = true;
3966
3967 assert(PromotedOperand &&
3968 "TypePromotionHelper should have filtered out those cases");
3969
3970 ExtAddrMode BackupAddrMode = AddrMode;
3971 unsigned OldSize = AddrModeInsts.size();
3972
Sanjay Patelfc580a62015-09-21 23:03:16 +00003973 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003974 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003975 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003976 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003977 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003978 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003979 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003980 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003981 AddrMode = BackupAddrMode;
3982 AddrModeInsts.resize(OldSize);
3983 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3984 TPT.rollback(LastKnownGood);
3985 return false;
3986 }
3987 return true;
3988 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003989 }
3990 return false;
3991}
3992
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003993/// If we can, try to add the value of 'Addr' into the current addressing mode.
3994/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3995/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3996/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003997///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003998bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003999 // Start a transaction at this point that we will rollback if the matching
4000 // fails.
4001 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4002 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00004003 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
4004 // Fold in immediates if legal for the target.
4005 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004006 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004007 return true;
4008 AddrMode.BaseOffs -= CI->getSExtValue();
4009 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
4010 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00004011 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004012 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004013 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004014 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00004015 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004016 }
4017 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
4018 ExtAddrMode BackupAddrMode = AddrMode;
4019 unsigned OldSize = AddrModeInsts.size();
4020
4021 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004022 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004023 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004024 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004025 // to check here.
4026 if (MovedAway)
4027 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004028 // Okay, it's possible to fold this. Check to see if it is actually
4029 // *profitable* to do so. We use a simple cost model to avoid increasing
4030 // register pressure too much.
4031 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00004032 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004033 AddrModeInsts.push_back(I);
4034 return true;
4035 }
Stephen Lin837bba12013-07-15 17:55:02 +00004036
Chandler Carruthc8925912013-01-05 02:09:22 +00004037 // It isn't profitable to do this, roll back.
4038 //cerr << "NOT FOLDING: " << *I;
4039 AddrMode = BackupAddrMode;
4040 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004041 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004042 }
4043 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004044 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00004045 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004046 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004047 } else if (isa<ConstantPointerNull>(Addr)) {
4048 // Null pointer gets folded without affecting the addressing mode.
4049 return true;
4050 }
4051
4052 // Worse case, the target should support [reg] addressing modes. :)
4053 if (!AddrMode.HasBaseReg) {
4054 AddrMode.HasBaseReg = true;
4055 AddrMode.BaseReg = Addr;
4056 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004057 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004058 return true;
4059 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00004060 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004061 }
4062
4063 // If the base register is already taken, see if we can do [r+r].
4064 if (AddrMode.Scale == 0) {
4065 AddrMode.Scale = 1;
4066 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00004067 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00004068 return true;
4069 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00004070 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004071 }
4072 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004073 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00004074 return false;
4075}
4076
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004077/// Check to see if all uses of OpVal by the specified inline asm call are due
4078/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00004079static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004080 const TargetLowering &TLI,
4081 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00004082 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004083 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004084 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004085 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004086
Chandler Carruthc8925912013-01-05 02:09:22 +00004087 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4088 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004089
Chandler Carruthc8925912013-01-05 02:09:22 +00004090 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004091 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004092
4093 // If this asm operand is our Value*, and if it isn't an indirect memory
4094 // operand, we can't fold it!
4095 if (OpInfo.CallOperandVal == OpVal &&
4096 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4097 !OpInfo.isIndirect))
4098 return false;
4099 }
4100
4101 return true;
4102}
4103
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004104// Max number of memory uses to look at before aborting the search to conserve
4105// compile time.
4106static constexpr int MaxMemoryUsesToScan = 20;
4107
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004108/// Recursively walk all the uses of I until we find a memory use.
4109/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004110/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004111static bool FindAllMemoryUses(
4112 Instruction *I,
4113 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004114 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4115 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004116 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004117 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004118 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004119
Chandler Carruthc8925912013-01-05 02:09:22 +00004120 // If this is an obviously unfoldable instruction, bail out.
4121 if (!MightBeFoldableInst(I))
4122 return true;
4123
Philip Reamesac115ed2016-03-09 23:13:12 +00004124 const bool OptSize = I->getFunction()->optForSize();
4125
Chandler Carruthc8925912013-01-05 02:09:22 +00004126 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004127 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004128 // Conservatively return true if we're seeing a large number or a deep chain
4129 // of users. This avoids excessive compilation times in pathological cases.
4130 if (SeenInsts++ >= MaxMemoryUsesToScan)
4131 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004132
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004133 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004134 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4135 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004136 continue;
4137 }
Stephen Lin837bba12013-07-15 17:55:02 +00004138
Chandler Carruthcdf47882014-03-09 03:16:01 +00004139 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4140 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004141 if (opNo != StoreInst::getPointerOperandIndex())
4142 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004143 MemoryUses.push_back(std::make_pair(SI, opNo));
4144 continue;
4145 }
Stephen Lin837bba12013-07-15 17:55:02 +00004146
Matt Arsenault02d915b2017-03-15 22:35:20 +00004147 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4148 unsigned opNo = U.getOperandNo();
4149 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4150 return true; // Storing addr, not into addr.
4151 MemoryUses.push_back(std::make_pair(RMW, opNo));
4152 continue;
4153 }
4154
4155 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4156 unsigned opNo = U.getOperandNo();
4157 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4158 return true; // Storing addr, not into addr.
4159 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4160 continue;
4161 }
4162
Chandler Carruthcdf47882014-03-09 03:16:01 +00004163 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004164 // If this is a cold call, we can sink the addressing calculation into
4165 // the cold path. See optimizeCallInst
4166 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4167 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004168
Chandler Carruthc8925912013-01-05 02:09:22 +00004169 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4170 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004171
Chandler Carruthc8925912013-01-05 02:09:22 +00004172 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004173 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004174 return true;
4175 continue;
4176 }
Stephen Lin837bba12013-07-15 17:55:02 +00004177
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004178 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4179 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004180 return true;
4181 }
4182
4183 return false;
4184}
4185
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004186/// Return true if Val is already known to be live at the use site that we're
4187/// folding it into. If so, there is no cost to include it in the addressing
4188/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4189/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004190bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004191 Value *KnownLive2) {
4192 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004193 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004194 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004195
Chandler Carruthc8925912013-01-05 02:09:22 +00004196 // All values other than instructions and arguments (e.g. constants) are live.
4197 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004198
Chandler Carruthc8925912013-01-05 02:09:22 +00004199 // If Val is a constant sized alloca in the entry block, it is live, this is
4200 // true because it is just a reference to the stack/frame pointer, which is
4201 // live for the whole function.
4202 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4203 if (AI->isStaticAlloca())
4204 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004205
Chandler Carruthc8925912013-01-05 02:09:22 +00004206 // Check to see if this value is already used in the memory instruction's
4207 // block. If so, it's already live into the block at the very least, so we
4208 // can reasonably fold it.
4209 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4210}
4211
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004212/// It is possible for the addressing mode of the machine to fold the specified
4213/// instruction into a load or store that ultimately uses it.
4214/// However, the specified instruction has multiple uses.
4215/// Given this, it may actually increase register pressure to fold it
4216/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004217///
4218/// X = ...
4219/// Y = X+1
4220/// use(Y) -> nonload/store
4221/// Z = Y+1
4222/// load Z
4223///
4224/// In this case, Y has multiple uses, and can be folded into the load of Z
4225/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4226/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4227/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4228/// number of computations either.
4229///
4230/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4231/// X was live across 'load Z' for other reasons, we actually *would* want to
4232/// fold the addressing mode in the Z case. This would make Y die earlier.
4233bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004234isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004235 ExtAddrMode &AMAfter) {
4236 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004237
Chandler Carruthc8925912013-01-05 02:09:22 +00004238 // AMBefore is the addressing mode before this instruction was folded into it,
4239 // and AMAfter is the addressing mode after the instruction was folded. Get
4240 // the set of registers referenced by AMAfter and subtract out those
4241 // referenced by AMBefore: this is the set of values which folding in this
4242 // address extends the lifetime of.
4243 //
4244 // Note that there are only two potential values being referenced here,
4245 // BaseReg and ScaleReg (global addresses are always available, as are any
4246 // folded immediates).
4247 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004248
Chandler Carruthc8925912013-01-05 02:09:22 +00004249 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4250 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004251 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004252 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004253 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004254 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004255
4256 // If folding this instruction (and it's subexprs) didn't extend any live
4257 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004258 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004259 return true;
4260
Philip Reamesac115ed2016-03-09 23:13:12 +00004261 // If all uses of this instruction can have the address mode sunk into them,
4262 // we can remove the addressing mode and effectively trade one live register
4263 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004264 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004265 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4266 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004267 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004268 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004269
Chandler Carruthc8925912013-01-05 02:09:22 +00004270 // Now that we know that all uses of this instruction are part of a chain of
4271 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004272 // into a memory use, loop over each of these memory operation uses and see
4273 // if they could *actually* fold the instruction. The assumption is that
4274 // addressing modes are cheap and that duplicating the computation involved
4275 // many times is worthwhile, even on a fastpath. For sinking candidates
4276 // (i.e. cold call sites), this serves as a way to prevent excessive code
4277 // growth since most architectures have some reasonable small and fast way to
4278 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004279 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4280 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4281 Instruction *User = MemoryUses[i].first;
4282 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004283
Chandler Carruthc8925912013-01-05 02:09:22 +00004284 // Get the access type of this use. If the use isn't a pointer, we don't
4285 // know what it accesses.
4286 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004287 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4288 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004289 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004290 Type *AddressAccessTy = AddrTy->getElementType();
4291 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004292
Chandler Carruthc8925912013-01-05 02:09:22 +00004293 // Do a match against the root of this address, ignoring profitability. This
4294 // will tell us if the addressing mode for the memory operation will
4295 // *actually* cover the shared instruction.
4296 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004297 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4298 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004299 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4300 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004301 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004302 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004303 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004304 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004305 (void)Success; assert(Success && "Couldn't select *anything*?");
4306
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004307 // The match was to check the profitability, the changes made are not
4308 // part of the original matcher. Therefore, they should be dropped
4309 // otherwise the original matcher will not present the right state.
4310 TPT.rollback(LastKnownGood);
4311
Chandler Carruthc8925912013-01-05 02:09:22 +00004312 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004313 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004314 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004315
Chandler Carruthc8925912013-01-05 02:09:22 +00004316 MatchedAddrModeInsts.clear();
4317 }
Stephen Lin837bba12013-07-15 17:55:02 +00004318
Chandler Carruthc8925912013-01-05 02:09:22 +00004319 return true;
4320}
4321
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004322/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004323/// different basic block than BB.
4324static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4325 if (Instruction *I = dyn_cast<Instruction>(V))
4326 return I->getParent() != BB;
4327 return false;
4328}
4329
Philip Reamesac115ed2016-03-09 23:13:12 +00004330/// Sink addressing mode computation immediate before MemoryInst if doing so
4331/// can be done without increasing register pressure. The need for the
4332/// register pressure constraint means this can end up being an all or nothing
4333/// decision for all uses of the same addressing computation.
4334///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004335/// Load and Store Instructions often have addressing modes that can do
4336/// significant amounts of computation. As such, instruction selection will try
4337/// to get the load or store to do as much computation as possible for the
4338/// program. The problem is that isel can only see within a single block. As
4339/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004340///
4341/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004342/// operands. It's also used to sink addressing computations feeding into cold
4343/// call sites into their (cold) basic block.
4344///
4345/// The motivation for handling sinking into cold blocks is that doing so can
4346/// both enable other address mode sinking (by satisfying the register pressure
4347/// constraint above), and reduce register pressure globally (by removing the
4348/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004349bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004350 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004351 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004352
4353 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004354 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004355 SmallVector<Value*, 8> worklist;
4356 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004357 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004358
John Brawneb83c752017-10-03 13:04:15 +00004359 // Use a worklist to iteratively look through PHI and select nodes, and
4360 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004361 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004362 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004363 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004364 const SimplifyQuery SQ(*DL, TLInfo);
4365 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004366 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004367 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4368 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004369 while (!worklist.empty()) {
4370 Value *V = worklist.back();
4371 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004372
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004373 // We allow traversing cyclic Phi nodes.
4374 // In case of success after this loop we ensure that traversing through
4375 // Phi nodes ends up with all cases to compute address of the form
4376 // BaseGV + Base + Scale * Index + Offset
4377 // where Scale and Offset are constans and BaseGV, Base and Index
4378 // are exactly the same Values in all cases.
4379 // It means that BaseGV, Scale and Offset dominate our memory instruction
4380 // and have the same value as they had in address computation represented
4381 // as Phi. So we can safely sink address computation to memory instruction.
4382 if (!Visited.insert(V).second)
4383 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004384
Owen Anderson8ba5f392010-11-27 08:15:55 +00004385 // For a PHI node, push all of its incoming values.
4386 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004387 for (Value *IncValue : P->incoming_values())
4388 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004389 PhiOrSelectSeen = true;
4390 continue;
4391 }
4392 // Similar for select.
4393 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4394 worklist.push_back(SI->getFalseValue());
4395 worklist.push_back(SI->getTrueValue());
4396 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004397 continue;
4398 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004399
Philip Reamesac115ed2016-03-09 23:13:12 +00004400 // For non-PHIs, determine the addressing mode being computed. Note that
4401 // the result may differ depending on what other uses our candidate
4402 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004403 AddrModeInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004404 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004405 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4406 InsertedInsts, PromotedInsts, TPT);
John Brawn736bf002017-10-03 13:08:22 +00004407 NewAddrMode.OriginalValue = V;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004408
John Brawn736bf002017-10-03 13:08:22 +00004409 if (!AddrModes.addNewAddrMode(NewAddrMode))
4410 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004411 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004412
John Brawn736bf002017-10-03 13:08:22 +00004413 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4414 // or we have multiple but either couldn't combine them or combining them
4415 // wouldn't do anything useful, bail out now.
4416 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004417 TPT.rollback(LastKnownGood);
4418 return false;
4419 }
4420 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004421
John Brawn736bf002017-10-03 13:08:22 +00004422 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4423 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4424
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004425 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004426 // If we saw a Phi node then it is not local definitely, and if we saw a select
4427 // then we want to push the address calculation past it even if it's already
4428 // in this BB.
4429 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004430 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004431 })) {
David Greene74e2d492010-01-05 01:27:11 +00004432 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004433 return false;
4434 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004435
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004436 // Insert this computation right after this user. Since our caller is
4437 // scanning from the top of the BB to the bottom, reuse of the expr are
4438 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004439 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004440
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004441 // Now that we determined the addressing expression we want to use and know
4442 // that we have to sink it into this block. Check to see if we have already
Simon Dardis230f4532017-11-24 16:45:28 +00004443 // done this for some other load/store instr in this block. If so, reuse
4444 // the computation. Before attempting reuse, check if the address is valid
4445 // as it may have been erased.
4446
4447 WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
4448
4449 Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004450 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004451 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004452 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004453 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004454 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004455 } else if (AddrSinkUsingGEPs ||
4456 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004457 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004458 // By default, we use the GEP-based method when AA is used later. This
4459 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4460 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004461 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004462 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004463 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004464
4465 // First, find the pointer.
4466 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4467 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004468 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004469 }
4470
4471 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4472 // We can't add more than one pointer together, nor can we scale a
4473 // pointer (both of which seem meaningless).
4474 if (ResultPtr || AddrMode.Scale != 1)
4475 return false;
4476
4477 ResultPtr = AddrMode.ScaledReg;
4478 AddrMode.Scale = 0;
4479 }
4480
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004481 // It is only safe to sign extend the BaseReg if we know that the math
4482 // required to create it did not overflow before we extend it. Since
4483 // the original IR value was tossed in favor of a constant back when
4484 // the AddrMode was created we need to bail out gracefully if widths
4485 // do not match instead of extending it.
4486 //
4487 // (See below for code to add the scale.)
4488 if (AddrMode.Scale) {
4489 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4490 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4491 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4492 return false;
4493 }
4494
Hal Finkelc3998302014-04-12 00:59:48 +00004495 if (AddrMode.BaseGV) {
4496 if (ResultPtr)
4497 return false;
4498
4499 ResultPtr = AddrMode.BaseGV;
4500 }
4501
4502 // If the real base value actually came from an inttoptr, then the matcher
4503 // will look through it and provide only the integer value. In that case,
4504 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004505 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4506 if (!ResultPtr && AddrMode.BaseReg) {
4507 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4508 "sunkaddr");
4509 AddrMode.BaseReg = nullptr;
4510 } else if (!ResultPtr && AddrMode.Scale == 1) {
4511 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4512 "sunkaddr");
4513 AddrMode.Scale = 0;
4514 }
Hal Finkelc3998302014-04-12 00:59:48 +00004515 }
4516
4517 if (!ResultPtr &&
4518 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4519 SunkAddr = Constant::getNullValue(Addr->getType());
4520 } else if (!ResultPtr) {
4521 return false;
4522 } else {
4523 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004524 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4525 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004526
4527 // Start with the base register. Do this first so that subsequent address
4528 // matching finds it last, which will prevent it from trying to match it
4529 // as the scaled value in case it happens to be a mul. That would be
4530 // problematic if we've sunk a different mul for the scale, because then
4531 // we'd end up sinking both muls.
4532 if (AddrMode.BaseReg) {
4533 Value *V = AddrMode.BaseReg;
4534 if (V->getType() != IntPtrTy)
4535 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4536
4537 ResultIndex = V;
4538 }
4539
4540 // Add the scale value.
4541 if (AddrMode.Scale) {
4542 Value *V = AddrMode.ScaledReg;
4543 if (V->getType() == IntPtrTy) {
4544 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004545 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004546 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4547 cast<IntegerType>(V->getType())->getBitWidth() &&
4548 "We can't transform if ScaledReg is too narrow");
4549 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004550 }
4551
4552 if (AddrMode.Scale != 1)
4553 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4554 "sunkaddr");
4555 if (ResultIndex)
4556 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4557 else
4558 ResultIndex = V;
4559 }
4560
4561 // Add in the Base Offset if present.
4562 if (AddrMode.BaseOffs) {
4563 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4564 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004565 // We need to add this separately from the scale above to help with
4566 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004567 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004568 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004569 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004570 }
4571
4572 ResultIndex = V;
4573 }
4574
4575 if (!ResultIndex) {
4576 SunkAddr = ResultPtr;
4577 } else {
4578 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004579 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004580 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004581 }
4582
4583 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004584 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004585 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004586 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004587 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4588 // non-integral pointers, so in that case bail out now.
4589 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4590 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4591 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4592 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4593 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4594 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4595 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4596 (AddrMode.BaseGV &&
4597 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4598 return false;
4599
David Greene74e2d492010-01-05 01:27:11 +00004600 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004601 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004602 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004603 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004604
4605 // Start with the base register. Do this first so that subsequent address
4606 // matching finds it last, which will prevent it from trying to match it
4607 // as the scaled value in case it happens to be a mul. That would be
4608 // problematic if we've sunk a different mul for the scale, because then
4609 // we'd end up sinking both muls.
4610 if (AddrMode.BaseReg) {
4611 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004612 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004613 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004614 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004615 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004616 Result = V;
4617 }
4618
4619 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004620 if (AddrMode.Scale) {
4621 Value *V = AddrMode.ScaledReg;
4622 if (V->getType() == IntPtrTy) {
4623 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004624 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004625 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004626 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4627 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004628 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004629 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004630 // It is only safe to sign extend the BaseReg if we know that the math
4631 // required to create it did not overflow before we extend it. Since
4632 // the original IR value was tossed in favor of a constant back when
4633 // the AddrMode was created we need to bail out gracefully if widths
4634 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004635 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004636 if (I && (Result != AddrMode.BaseReg))
4637 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004638 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004639 }
4640 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004641 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4642 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004643 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004644 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004645 else
4646 Result = V;
4647 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004648
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004649 // Add in the BaseGV if present.
4650 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004651 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004652 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004653 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004654 else
4655 Result = V;
4656 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004657
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004658 // Add in the Base Offset if present.
4659 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004660 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004661 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004662 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004663 else
4664 Result = V;
4665 }
4666
Craig Topperc0196b12014-04-14 00:51:57 +00004667 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004668 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004669 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004670 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004671 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004672
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004673 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Simon Dardis230f4532017-11-24 16:45:28 +00004674 // Store the newly computed address into the cache. In the case we reused a
4675 // value, this should be idempotent.
4676 SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004677
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004678 // If we have no uses, recursively delete the value and all dead instructions
4679 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004680 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004681 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004682 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004683 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004684 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004685 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004686
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004687 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004688
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004689 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004690 // If the iterator instruction was recursively deleted, start over at the
4691 // start of the block.
4692 CurInstIterator = BB->begin();
4693 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004694 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004695 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004696 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004697 return true;
4698}
4699
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004700/// If there are any memory operands, use OptimizeMemoryInst to sink their
4701/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004702bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004703 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004704
Eric Christopher11e4df72015-02-26 22:38:43 +00004705 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004706 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004707 TargetLowering::AsmOperandInfoVector TargetConstraints =
4708 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004709 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004710 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4711 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004712
Evan Cheng1da25002008-02-26 02:42:37 +00004713 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004714 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004715
Eli Friedman666bbe32008-02-26 18:37:49 +00004716 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4717 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004718 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004719 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004720 } else if (OpInfo.Type == InlineAsm::isInput)
4721 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004722 }
4723
4724 return MadeChange;
4725}
4726
Jun Bum Lim42301012017-03-17 19:05:21 +00004727/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004728/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004729static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4730 assert(!Val->use_empty() && "Input must have at least one use");
4731 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004732 bool IsSExt = isa<SExtInst>(FirstUser);
4733 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004734 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004735 const Instruction *UI = cast<Instruction>(U);
4736 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4737 return false;
4738 Type *CurTy = UI->getType();
4739 // Same input and output types: Same instruction after CSE.
4740 if (CurTy == ExtTy)
4741 continue;
4742
4743 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004744 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004745 // b = sext ty1 a to ty2
4746 // c = sext ty1 a to ty3
4747 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004748 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004749 // b = sext ty1 a to ty2
4750 // c = sext ty2 b to ty3
4751 // However, the last sext is not free.
4752 if (IsSExt)
4753 return false;
4754
4755 // This is a ZExt, maybe this is free to extend from one type to another.
4756 // In that case, we would not account for a different use.
4757 Type *NarrowTy;
4758 Type *LargeTy;
4759 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4760 CurTy->getScalarType()->getIntegerBitWidth()) {
4761 NarrowTy = CurTy;
4762 LargeTy = ExtTy;
4763 } else {
4764 NarrowTy = ExtTy;
4765 LargeTy = CurTy;
4766 }
4767
4768 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4769 return false;
4770 }
4771 // All uses are the same or can be derived from one another for free.
4772 return true;
4773}
4774
Jun Bum Lim42301012017-03-17 19:05:21 +00004775/// \brief Try to speculatively promote extensions in \p Exts and continue
4776/// promoting through newly promoted operands recursively as far as doing so is
4777/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4778/// When some promotion happened, \p TPT contains the proper state to revert
4779/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004780///
Jun Bum Lim42301012017-03-17 19:05:21 +00004781/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004782bool CodeGenPrepare::tryToPromoteExts(
4783 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4784 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4785 unsigned CreatedInstsCost) {
4786 bool Promoted = false;
4787
4788 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004789 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004790 // Early check if we directly have ext(load).
4791 if (isa<LoadInst>(I->getOperand(0))) {
4792 ProfitablyMovedExts.push_back(I);
4793 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004794 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004795
4796 // Check whether or not we want to do any promotion. The reason we have
4797 // this check inside the for loop is to catch the case where an extension
4798 // is directly fed by a load because in such case the extension can be moved
4799 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004800 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004801 return false;
4802
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004803 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004804 TypePromotionHelper::Action TPH =
4805 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004806 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004807 if (!TPH) {
4808 // Save the current extension as we cannot move up through its operand.
4809 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004810 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004811 }
4812
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004813 // Save the current state.
4814 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4815 TPT.getRestorationPoint();
4816 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004817 unsigned NewCreatedInstsCost = 0;
4818 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004819 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004820 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4821 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004822 assert(PromotedVal &&
4823 "TypePromotionHelper should have filtered out those cases");
4824
4825 // We would be able to merge only one extension in a load.
4826 // Therefore, if we have more than 1 new extension we heuristically
4827 // cut this search path, because it means we degrade the code quality.
4828 // With exactly 2, the transformation is neutral, because we will merge
4829 // one extension but leave one. However, we optimistically keep going,
4830 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004831 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004832 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004833 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004834 TotalCreatedInstsCost =
4835 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004836 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004837 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004838 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004839 // This promotion is not profitable, rollback to the previous state, and
4840 // save the current extension in ProfitablyMovedExts as the latest
4841 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004842 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004843 ProfitablyMovedExts.push_back(I);
4844 continue;
4845 }
4846 // Continue promoting NewExts as far as doing so is profitable.
4847 SmallVector<Instruction *, 2> NewlyMovedExts;
4848 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4849 bool NewPromoted = false;
4850 for (auto ExtInst : NewlyMovedExts) {
4851 Instruction *MovedExt = cast<Instruction>(ExtInst);
4852 Value *ExtOperand = MovedExt->getOperand(0);
4853 // If we have reached to a load, we need this extra profitability check
4854 // as it could potentially be merged into an ext(load).
4855 if (isa<LoadInst>(ExtOperand) &&
4856 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4857 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4858 continue;
4859
4860 ProfitablyMovedExts.push_back(MovedExt);
4861 NewPromoted = true;
4862 }
4863
4864 // If none of speculative promotions for NewExts is profitable, rollback
4865 // and save the current extension (I) as the last profitable extension.
4866 if (!NewPromoted) {
4867 TPT.rollback(LastKnownGood);
4868 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004869 continue;
4870 }
4871 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004872 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004873 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004874 return Promoted;
4875}
4876
Jun Bum Limdee55652017-04-03 19:20:07 +00004877/// Merging redundant sexts when one is dominating the other.
4878bool CodeGenPrepare::mergeSExts(Function &F) {
4879 DominatorTree DT(F);
4880 bool Changed = false;
4881 for (auto &Entry : ValToSExtendedUses) {
4882 SExts &Insts = Entry.second;
4883 SExts CurPts;
4884 for (Instruction *Inst : Insts) {
4885 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4886 Inst->getOperand(0) != Entry.first)
4887 continue;
4888 bool inserted = false;
4889 for (auto &Pt : CurPts) {
4890 if (DT.dominates(Inst, Pt)) {
4891 Pt->replaceAllUsesWith(Inst);
4892 RemovedInsts.insert(Pt);
4893 Pt->removeFromParent();
4894 Pt = Inst;
4895 inserted = true;
4896 Changed = true;
4897 break;
4898 }
4899 if (!DT.dominates(Pt, Inst))
4900 // Give up if we need to merge in a common dominator as the
4901 // expermients show it is not profitable.
4902 continue;
4903 Inst->replaceAllUsesWith(Pt);
4904 RemovedInsts.insert(Inst);
4905 Inst->removeFromParent();
4906 inserted = true;
4907 Changed = true;
4908 break;
4909 }
4910 if (!inserted)
4911 CurPts.push_back(Inst);
4912 }
4913 }
4914 return Changed;
4915}
4916
Jun Bum Lim42301012017-03-17 19:05:21 +00004917/// Return true, if an ext(load) can be formed from an extension in
4918/// \p MovedExts.
4919bool CodeGenPrepare::canFormExtLd(
4920 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4921 Instruction *&Inst, bool HasPromoted) {
4922 for (auto *MovedExtInst : MovedExts) {
4923 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4924 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4925 Inst = MovedExtInst;
4926 break;
4927 }
4928 }
4929 if (!LI)
4930 return false;
4931
4932 // If they're already in the same block, there's nothing to do.
4933 // Make the cheap checks first if we did not promote.
4934 // If we promoted, we need to check if it is indeed profitable.
4935 if (!HasPromoted && LI->getParent() == Inst->getParent())
4936 return false;
4937
Haicheng Wuabdef9e2017-07-15 02:12:16 +00004938 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004939}
4940
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004941/// Move a zext or sext fed by a load into the same basic block as the load,
4942/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4943/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00004944///
Jun Bum Limdee55652017-04-03 19:20:07 +00004945/// E.g.,
4946/// \code
4947/// %ld = load i32* %addr
4948/// %add = add nuw i32 %ld, 4
4949/// %zext = zext i32 %add to i64
4950// \endcode
4951/// =>
4952/// \code
4953/// %ld = load i32* %addr
4954/// %zext = zext i32 %ld to i64
4955/// %add = add nuw i64 %zext, 4
4956/// \encode
4957/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4958/// allow us to match zext(load i32*) to i64.
4959///
4960/// Also, try to promote the computations used to obtain a sign extended
4961/// value used into memory accesses.
4962/// E.g.,
4963/// \code
4964/// a = add nsw i32 b, 3
4965/// d = sext i32 a to i64
4966/// e = getelementptr ..., i64 d
4967/// \endcode
4968/// =>
4969/// \code
4970/// f = sext i32 b to i64
4971/// a = add nsw i64 f, 3
4972/// e = getelementptr ..., i64 a
4973/// \endcode
4974///
4975/// \p Inst[in/out] the extension may be modified during the process if some
4976/// promotions apply.
4977bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4978 // ExtLoad formation and address type promotion infrastructure requires TLI to
4979 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004980 if (!TLI)
4981 return false;
4982
Jun Bum Limdee55652017-04-03 19:20:07 +00004983 bool AllowPromotionWithoutCommonHeader = false;
4984 /// See if it is an interesting sext operations for the address type
4985 /// promotion before trying to promote it, e.g., the ones with the right
4986 /// type and used in memory accesses.
4987 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4988 *Inst, AllowPromotionWithoutCommonHeader);
4989 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004990 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00004991 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004992 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00004993 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4994 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00004995
Jun Bum Limdee55652017-04-03 19:20:07 +00004996 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00004997
Dan Gohman99429a02009-10-16 20:59:35 +00004998 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004999 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00005000 Instruction *ExtFedByLoad;
5001
5002 // Try to promote a chain of computation if it allows to form an extended
5003 // load.
5004 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
5005 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
5006 TPT.commit();
5007 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00005008 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00005009 // CGP does not check if the zext would be speculatively executed when moved
5010 // to the same basic block as the load. Preserving its original location
5011 // would pessimize the debugging experience, as well as negatively impact
5012 // the quality of sample pgo. We don't want to use "line 0" as that has a
5013 // size cost in the line-table section and logically the zext can be seen as
5014 // part of the load. Therefore we conservatively reuse the same debug
5015 // location for the load and the zext.
5016 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
5017 ++NumExtsMoved;
5018 Inst = ExtFedByLoad;
5019 return true;
5020 }
5021
5022 // Continue promoting SExts if known as considerable depending on targets.
5023 if (ATPConsiderable &&
5024 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
5025 HasPromoted, TPT, SpeculativelyMovedExts))
5026 return true;
5027
5028 TPT.rollback(LastKnownGood);
5029 return false;
5030}
5031
5032// Perform address type promotion if doing so is profitable.
5033// If AllowPromotionWithoutCommonHeader == false, we should find other sext
5034// instructions that sign extended the same initial value. However, if
5035// AllowPromotionWithoutCommonHeader == true, we expect promoting the
5036// extension is just profitable.
5037bool CodeGenPrepare::performAddressTypePromotion(
5038 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
5039 bool HasPromoted, TypePromotionTransaction &TPT,
5040 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
5041 bool Promoted = false;
5042 SmallPtrSet<Instruction *, 1> UnhandledExts;
5043 bool AllSeenFirst = true;
5044 for (auto I : SpeculativelyMovedExts) {
5045 Value *HeadOfChain = I->getOperand(0);
5046 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
5047 SeenChainsForSExt.find(HeadOfChain);
5048 // If there is an unhandled SExt which has the same header, try to promote
5049 // it as well.
5050 if (AlreadySeen != SeenChainsForSExt.end()) {
5051 if (AlreadySeen->second != nullptr)
5052 UnhandledExts.insert(AlreadySeen->second);
5053 AllSeenFirst = false;
5054 }
5055 }
5056
5057 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
5058 SpeculativelyMovedExts.size() == 1)) {
5059 TPT.commit();
5060 if (HasPromoted)
5061 Promoted = true;
5062 for (auto I : SpeculativelyMovedExts) {
5063 Value *HeadOfChain = I->getOperand(0);
5064 SeenChainsForSExt[HeadOfChain] = nullptr;
5065 ValToSExtendedUses[HeadOfChain].push_back(I);
5066 }
5067 // Update Inst as promotion happen.
5068 Inst = SpeculativelyMovedExts.pop_back_val();
5069 } else {
5070 // This is the first chain visited from the header, keep the current chain
5071 // as unhandled. Defer to promote this until we encounter another SExt
5072 // chain derived from the same header.
5073 for (auto I : SpeculativelyMovedExts) {
5074 Value *HeadOfChain = I->getOperand(0);
5075 SeenChainsForSExt[HeadOfChain] = Inst;
5076 }
Dan Gohman99429a02009-10-16 20:59:35 +00005077 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00005078 }
Dan Gohman99429a02009-10-16 20:59:35 +00005079
Jun Bum Limdee55652017-04-03 19:20:07 +00005080 if (!AllSeenFirst && !UnhandledExts.empty())
5081 for (auto VisitedSExt : UnhandledExts) {
5082 if (RemovedInsts.count(VisitedSExt))
5083 continue;
5084 TypePromotionTransaction TPT(RemovedInsts);
5085 SmallVector<Instruction *, 1> Exts;
5086 SmallVector<Instruction *, 2> Chains;
5087 Exts.push_back(VisitedSExt);
5088 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
5089 TPT.commit();
5090 if (HasPromoted)
5091 Promoted = true;
5092 for (auto I : Chains) {
5093 Value *HeadOfChain = I->getOperand(0);
5094 // Mark this as handled.
5095 SeenChainsForSExt[HeadOfChain] = nullptr;
5096 ValToSExtendedUses[HeadOfChain].push_back(I);
5097 }
5098 }
5099 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005100}
5101
Sanjay Patelfc580a62015-09-21 23:03:16 +00005102bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005103 BasicBlock *DefBB = I->getParent();
5104
Bob Wilsonff714f92010-09-21 21:44:14 +00005105 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005106 // other uses of the source with result of extension.
5107 Value *Src = I->getOperand(0);
5108 if (Src->hasOneUse())
5109 return false;
5110
Evan Cheng2011df42007-12-13 07:50:36 +00005111 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005112 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005113 return false;
5114
Evan Cheng7bc89422007-12-12 00:51:06 +00005115 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005116 // this block.
5117 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005118 return false;
5119
Evan Chengd3d80172007-12-05 23:58:20 +00005120 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005121 for (User *U : I->users()) {
5122 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005123
5124 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005125 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005126 if (UserBB == DefBB) continue;
5127 DefIsLiveOut = true;
5128 break;
5129 }
5130 if (!DefIsLiveOut)
5131 return false;
5132
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005133 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005134 for (User *U : Src->users()) {
5135 Instruction *UI = cast<Instruction>(U);
5136 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005137 if (UserBB == DefBB) continue;
5138 // Be conservative. We don't want this xform to end up introducing
5139 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005140 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005141 return false;
5142 }
5143
Evan Chengd3d80172007-12-05 23:58:20 +00005144 // InsertedTruncs - Only insert one trunc in each block once.
5145 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5146
5147 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005148 for (Use &U : Src->uses()) {
5149 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005150
5151 // Figure out which BB this ext is used in.
5152 BasicBlock *UserBB = User->getParent();
5153 if (UserBB == DefBB) continue;
5154
5155 // Both src and def are live in this block. Rewrite the use.
5156 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5157
5158 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005159 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005160 assert(InsertPt != UserBB->end());
5161 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005162 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005163 }
5164
5165 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005166 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005167 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005168 MadeChange = true;
5169 }
5170
5171 return MadeChange;
5172}
5173
Geoff Berry5256fca2015-11-20 22:34:39 +00005174// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5175// just after the load if the target can fold this into one extload instruction,
5176// with the hope of eliminating some of the other later "and" instructions using
5177// the loaded value. "and"s that are made trivially redundant by the insertion
5178// of the new "and" are removed by this function, while others (e.g. those whose
5179// path from the load goes through a phi) are left for isel to potentially
5180// remove.
5181//
5182// For example:
5183//
5184// b0:
5185// x = load i32
5186// ...
5187// b1:
5188// y = and x, 0xff
5189// z = use y
5190//
5191// becomes:
5192//
5193// b0:
5194// x = load i32
5195// x' = and x, 0xff
5196// ...
5197// b1:
5198// z = use x'
5199//
5200// whereas:
5201//
5202// b0:
5203// x1 = load i32
5204// ...
5205// b1:
5206// x2 = load i32
5207// ...
5208// b2:
5209// x = phi x1, x2
5210// y = and x, 0xff
5211//
5212// becomes (after a call to optimizeLoadExt for each load):
5213//
5214// b0:
5215// x1 = load i32
5216// x1' = and x1, 0xff
5217// ...
5218// b1:
5219// x2 = load i32
5220// x2' = and x2, 0xff
5221// ...
5222// b2:
5223// x = phi x1', x2'
5224// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005225bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005226 if (!Load->isSimple() ||
5227 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5228 return false;
5229
Geoff Berry5d534b62017-02-21 18:53:14 +00005230 // Skip loads we've already transformed.
5231 if (Load->hasOneUse() &&
5232 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5233 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005234
5235 // Look at all uses of Load, looking through phis, to determine how many bits
5236 // of the loaded value are needed.
5237 SmallVector<Instruction *, 8> WorkList;
5238 SmallPtrSet<Instruction *, 16> Visited;
5239 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5240 for (auto *U : Load->users())
5241 WorkList.push_back(cast<Instruction>(U));
5242
5243 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5244 unsigned BitWidth = LoadResultVT.getSizeInBits();
5245 APInt DemandBits(BitWidth, 0);
5246 APInt WidestAndBits(BitWidth, 0);
5247
5248 while (!WorkList.empty()) {
5249 Instruction *I = WorkList.back();
5250 WorkList.pop_back();
5251
5252 // Break use-def graph loops.
5253 if (!Visited.insert(I).second)
5254 continue;
5255
5256 // For a PHI node, push all of its users.
5257 if (auto *Phi = dyn_cast<PHINode>(I)) {
5258 for (auto *U : Phi->users())
5259 WorkList.push_back(cast<Instruction>(U));
5260 continue;
5261 }
5262
5263 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005264 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005265 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5266 if (!AndC)
5267 return false;
5268 APInt AndBits = AndC->getValue();
5269 DemandBits |= AndBits;
5270 // Keep track of the widest and mask we see.
5271 if (AndBits.ugt(WidestAndBits))
5272 WidestAndBits = AndBits;
5273 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5274 AndsToMaybeRemove.push_back(I);
5275 break;
5276 }
5277
Eugene Zelenko900b6332017-08-29 22:32:07 +00005278 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005279 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5280 if (!ShlC)
5281 return false;
5282 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005283 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005284 break;
5285 }
5286
Eugene Zelenko900b6332017-08-29 22:32:07 +00005287 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005288 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5289 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005290 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005291 break;
5292 }
5293
5294 default:
5295 return false;
5296 }
5297 }
5298
5299 uint32_t ActiveBits = DemandBits.getActiveBits();
5300 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5301 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5302 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5303 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5304 // followed by an AND.
5305 // TODO: Look into removing this restriction by fixing backends to either
5306 // return false for isLoadExtLegal for i1 or have them select this pattern to
5307 // a single instruction.
5308 //
5309 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5310 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005311 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005312 WidestAndBits != DemandBits)
5313 return false;
5314
5315 LLVMContext &Ctx = Load->getType()->getContext();
5316 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5317 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5318
5319 // Reject cases that won't be matched as extloads.
5320 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5321 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5322 return false;
5323
5324 IRBuilder<> Builder(Load->getNextNode());
5325 auto *NewAnd = dyn_cast<Instruction>(
5326 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005327 // Mark this instruction as "inserted by CGP", so that other
5328 // optimizations don't touch it.
5329 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005330
5331 // Replace all uses of load with new and (except for the use of load in the
5332 // new and itself).
5333 Load->replaceAllUsesWith(NewAnd);
5334 NewAnd->setOperand(0, Load);
5335
5336 // Remove any and instructions that are now redundant.
5337 for (auto *And : AndsToMaybeRemove)
5338 // Check that the and mask is the same as the one we decided to put on the
5339 // new and.
5340 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5341 And->replaceAllUsesWith(NewAnd);
5342 if (&*CurInstIterator == And)
5343 CurInstIterator = std::next(And->getIterator());
5344 And->eraseFromParent();
5345 ++NumAndUses;
5346 }
5347
5348 ++NumAndsAdded;
5349 return true;
5350}
5351
Sanjay Patel69a50a12015-10-19 21:59:12 +00005352/// Check if V (an operand of a select instruction) is an expensive instruction
5353/// that is only used once.
5354static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5355 auto *I = dyn_cast<Instruction>(V);
5356 // If it's safe to speculatively execute, then it should not have side
5357 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005358 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5359 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005360}
5361
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005362/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005363static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005364 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005365 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005366 // If even a predictable select is cheap, then a branch can't be cheaper.
5367 if (!TLI->isPredictableSelectExpensive())
5368 return false;
5369
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005370 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005371 // whether a select is better represented as a branch.
5372
5373 // If metadata tells us that the select condition is obviously predictable,
5374 // then we want to replace the select with a branch.
5375 uint64_t TrueWeight, FalseWeight;
5376 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5377 uint64_t Max = std::max(TrueWeight, FalseWeight);
5378 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005379 if (Sum != 0) {
5380 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5381 if (Probability > TLI->getPredictableBranchThreshold())
5382 return true;
5383 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005384 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005385
5386 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5387
Sanjay Patel4e652762015-09-28 22:14:51 +00005388 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5389 // comparison condition. If the compare has more than one use, there's
5390 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005391 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005392 return false;
5393
Sanjay Patel69a50a12015-10-19 21:59:12 +00005394 // If either operand of the select is expensive and only needed on one side
5395 // of the select, we should form a branch.
5396 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5397 sinkSelectOperand(TTI, SI->getFalseValue()))
5398 return true;
5399
5400 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005401}
5402
Dehao Chen9bbb9412016-09-12 20:23:28 +00005403/// If \p isTrue is true, return the true value of \p SI, otherwise return
5404/// false value of \p SI. If the true/false value of \p SI is defined by any
5405/// select instructions in \p Selects, look through the defining select
5406/// instruction until the true/false value is not defined in \p Selects.
5407static Value *getTrueOrFalseValue(
5408 SelectInst *SI, bool isTrue,
5409 const SmallPtrSet<const Instruction *, 2> &Selects) {
5410 Value *V;
5411
5412 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5413 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005414 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005415 "The condition of DefSI does not match with SI");
5416 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5417 }
5418 return V;
5419}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005420
Nadav Rotem9d832022012-09-02 12:10:19 +00005421/// If we have a SelectInst that will likely profit from branch prediction,
5422/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005423bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005424 // Find all consecutive select instructions that share the same condition.
5425 SmallVector<SelectInst *, 2> ASI;
5426 ASI.push_back(SI);
5427 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5428 It != SI->getParent()->end(); ++It) {
5429 SelectInst *I = dyn_cast<SelectInst>(&*It);
5430 if (I && SI->getCondition() == I->getCondition()) {
5431 ASI.push_back(I);
5432 } else {
5433 break;
5434 }
5435 }
5436
5437 SelectInst *LastSI = ASI.back();
5438 // Increment the current iterator to skip all the rest of select instructions
5439 // because they will be either "not lowered" or "all lowered" to branch.
5440 CurInstIterator = std::next(LastSI->getIterator());
5441
Nadav Rotem9d832022012-09-02 12:10:19 +00005442 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5443
5444 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005445 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5446 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005447 return false;
5448
Nadav Rotem9d832022012-09-02 12:10:19 +00005449 TargetLowering::SelectSupportKind SelectKind;
5450 if (VectorCond)
5451 SelectKind = TargetLowering::VectorMaskSelect;
5452 else if (SI->getType()->isVectorTy())
5453 SelectKind = TargetLowering::ScalarCondVectorVal;
5454 else
5455 SelectKind = TargetLowering::ScalarValSelect;
5456
Sanjay Pateld66607b2016-04-26 17:11:17 +00005457 if (TLI->isSelectSupported(SelectKind) &&
5458 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5459 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005460
5461 ModifiedDT = true;
5462
Sanjay Patel69a50a12015-10-19 21:59:12 +00005463 // Transform a sequence like this:
5464 // start:
5465 // %cmp = cmp uge i32 %a, %b
5466 // %sel = select i1 %cmp, i32 %c, i32 %d
5467 //
5468 // Into:
5469 // start:
5470 // %cmp = cmp uge i32 %a, %b
5471 // br i1 %cmp, label %select.true, label %select.false
5472 // select.true:
5473 // br label %select.end
5474 // select.false:
5475 // br label %select.end
5476 // select.end:
5477 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5478 //
5479 // In addition, we may sink instructions that produce %c or %d from
5480 // the entry block into the destination(s) of the new branch.
5481 // If the true or false blocks do not contain a sunken instruction, that
5482 // block and its branch may be optimized away. In that case, one side of the
5483 // first branch will point directly to select.end, and the corresponding PHI
5484 // predecessor block will be the start block.
5485
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005486 // First, we split the block containing the select into 2 blocks.
5487 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005488 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005489 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005490
Sanjay Patel69a50a12015-10-19 21:59:12 +00005491 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005492 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005493
5494 // These are the new basic blocks for the conditional branch.
5495 // At least one will become an actual new basic block.
5496 BasicBlock *TrueBlock = nullptr;
5497 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005498 BranchInst *TrueBranch = nullptr;
5499 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005500
5501 // Sink expensive instructions into the conditional blocks to avoid executing
5502 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005503 for (SelectInst *SI : ASI) {
5504 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5505 if (TrueBlock == nullptr) {
5506 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5507 EndBlock->getParent(), EndBlock);
5508 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5509 }
5510 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5511 TrueInst->moveBefore(TrueBranch);
5512 }
5513 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5514 if (FalseBlock == nullptr) {
5515 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5516 EndBlock->getParent(), EndBlock);
5517 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5518 }
5519 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5520 FalseInst->moveBefore(FalseBranch);
5521 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005522 }
5523
5524 // If there was nothing to sink, then arbitrarily choose the 'false' side
5525 // for a new input value to the PHI.
5526 if (TrueBlock == FalseBlock) {
5527 assert(TrueBlock == nullptr &&
5528 "Unexpected basic block transform while optimizing select");
5529
5530 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5531 EndBlock->getParent(), EndBlock);
5532 BranchInst::Create(EndBlock, FalseBlock);
5533 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005534
5535 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005536 // If we did not create a new block for one of the 'true' or 'false' paths
5537 // of the condition, it means that side of the branch goes to the end block
5538 // directly and the path originates from the start block from the point of
5539 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005540 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005541 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005542 TT = EndBlock;
5543 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005544 TrueBlock = StartBlock;
5545 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005546 TT = TrueBlock;
5547 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005548 FalseBlock = StartBlock;
5549 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005550 TT = TrueBlock;
5551 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005552 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005553 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005554
Dehao Chen9bbb9412016-09-12 20:23:28 +00005555 SmallPtrSet<const Instruction *, 2> INS;
5556 INS.insert(ASI.begin(), ASI.end());
5557 // Use reverse iterator because later select may use the value of the
5558 // earlier select, and we need to propagate value through earlier select
5559 // to get the PHI operand.
5560 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5561 SelectInst *SI = *It;
5562 // The select itself is replaced with a PHI Node.
5563 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5564 PN->takeName(SI);
5565 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5566 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005567
Dehao Chen9bbb9412016-09-12 20:23:28 +00005568 SI->replaceAllUsesWith(PN);
5569 SI->eraseFromParent();
5570 INS.erase(SI);
5571 ++NumSelectsExpanded;
5572 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005573
5574 // Instruct OptimizeBlock to skip to the next block.
5575 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005576 return true;
5577}
5578
Benjamin Kramer573ff362014-03-01 17:24:40 +00005579static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005580 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5581 int SplatElem = -1;
5582 for (unsigned i = 0; i < Mask.size(); ++i) {
5583 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5584 return false;
5585 SplatElem = Mask[i];
5586 }
5587
5588 return true;
5589}
5590
5591/// Some targets have expensive vector shifts if the lanes aren't all the same
5592/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5593/// it's often worth sinking a shufflevector splat down to its use so that
5594/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005595bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005596 BasicBlock *DefBB = SVI->getParent();
5597
5598 // Only do this xform if variable vector shifts are particularly expensive.
5599 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5600 return false;
5601
5602 // We only expect better codegen by sinking a shuffle if we can recognise a
5603 // constant splat.
5604 if (!isBroadcastShuffle(SVI))
5605 return false;
5606
5607 // InsertedShuffles - Only insert a shuffle in each block once.
5608 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5609
5610 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005611 for (User *U : SVI->users()) {
5612 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005613
5614 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005615 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005616 if (UserBB == DefBB) continue;
5617
5618 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005619 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005620
5621 // Everything checks out, sink the shuffle if the user's block doesn't
5622 // already have a copy.
5623 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5624
5625 if (!InsertedShuffle) {
5626 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005627 assert(InsertPt != UserBB->end());
5628 InsertedShuffle =
5629 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5630 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005631 }
5632
Chandler Carruthcdf47882014-03-09 03:16:01 +00005633 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005634 MadeChange = true;
5635 }
5636
5637 // If we removed all uses, nuke the shuffle.
5638 if (SVI->use_empty()) {
5639 SVI->eraseFromParent();
5640 MadeChange = true;
5641 }
5642
5643 return MadeChange;
5644}
5645
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005646bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5647 if (!TLI || !DL)
5648 return false;
5649
5650 Value *Cond = SI->getCondition();
5651 Type *OldType = Cond->getType();
5652 LLVMContext &Context = Cond->getContext();
5653 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5654 unsigned RegWidth = RegType.getSizeInBits();
5655
5656 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5657 return false;
5658
5659 // If the register width is greater than the type width, expand the condition
5660 // of the switch instruction and each case constant to the width of the
5661 // register. By widening the type of the switch condition, subsequent
5662 // comparisons (for case comparisons) will not need to be extended to the
5663 // preferred register width, so we will potentially eliminate N-1 extends,
5664 // where N is the number of cases in the switch.
5665 auto *NewType = Type::getIntNTy(Context, RegWidth);
5666
5667 // Zero-extend the switch condition and case constants unless the switch
5668 // condition is a function argument that is already being sign-extended.
5669 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5670 // everything instead.
5671 Instruction::CastOps ExtType = Instruction::ZExt;
5672 if (auto *Arg = dyn_cast<Argument>(Cond))
5673 if (Arg->hasSExtAttr())
5674 ExtType = Instruction::SExt;
5675
5676 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5677 ExtInst->insertBefore(SI);
5678 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005679 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005680 APInt NarrowConst = Case.getCaseValue()->getValue();
5681 APInt WideConst = (ExtType == Instruction::ZExt) ?
5682 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5683 Case.setValue(ConstantInt::get(Context, WideConst));
5684 }
5685
5686 return true;
5687}
5688
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005689
Quentin Colombetc32615d2014-10-31 17:52:53 +00005690namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005691
Quentin Colombetc32615d2014-10-31 17:52:53 +00005692/// \brief Helper class to promote a scalar operation to a vector one.
5693/// This class is used to move downward extractelement transition.
5694/// E.g.,
5695/// a = vector_op <2 x i32>
5696/// b = extractelement <2 x i32> a, i32 0
5697/// c = scalar_op b
5698/// store c
5699///
5700/// =>
5701/// a = vector_op <2 x i32>
5702/// c = vector_op a (equivalent to scalar_op on the related lane)
5703/// * d = extractelement <2 x i32> c, i32 0
5704/// * store d
5705/// Assuming both extractelement and store can be combine, we get rid of the
5706/// transition.
5707class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005708 /// DataLayout associated with the current module.
5709 const DataLayout &DL;
5710
Quentin Colombetc32615d2014-10-31 17:52:53 +00005711 /// Used to perform some checks on the legality of vector operations.
5712 const TargetLowering &TLI;
5713
5714 /// Used to estimated the cost of the promoted chain.
5715 const TargetTransformInfo &TTI;
5716
5717 /// The transition being moved downwards.
5718 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005719
Quentin Colombetc32615d2014-10-31 17:52:53 +00005720 /// The sequence of instructions to be promoted.
5721 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005722
Quentin Colombetc32615d2014-10-31 17:52:53 +00005723 /// Cost of combining a store and an extract.
5724 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005725
Quentin Colombetc32615d2014-10-31 17:52:53 +00005726 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005727 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005728
5729 /// \brief The instruction that represents the current end of the transition.
5730 /// Since we are faking the promotion until we reach the end of the chain
5731 /// of computation, we need a way to get the current end of the transition.
5732 Instruction *getEndOfTransition() const {
5733 if (InstsToBePromoted.empty())
5734 return Transition;
5735 return InstsToBePromoted.back();
5736 }
5737
5738 /// \brief Return the index of the original value in the transition.
5739 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5740 /// c, is at index 0.
5741 unsigned getTransitionOriginalValueIdx() const {
5742 assert(isa<ExtractElementInst>(Transition) &&
5743 "Other kind of transitions are not supported yet");
5744 return 0;
5745 }
5746
5747 /// \brief Return the index of the index in the transition.
5748 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5749 /// is at index 1.
5750 unsigned getTransitionIdx() const {
5751 assert(isa<ExtractElementInst>(Transition) &&
5752 "Other kind of transitions are not supported yet");
5753 return 1;
5754 }
5755
5756 /// \brief Get the type of the transition.
5757 /// This is the type of the original value.
5758 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5759 /// transition is <2 x i32>.
5760 Type *getTransitionType() const {
5761 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5762 }
5763
5764 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5765 /// I.e., we have the following sequence:
5766 /// Def = Transition <ty1> a to <ty2>
5767 /// b = ToBePromoted <ty2> Def, ...
5768 /// =>
5769 /// b = ToBePromoted <ty1> a, ...
5770 /// Def = Transition <ty1> ToBePromoted to <ty2>
5771 void promoteImpl(Instruction *ToBePromoted);
5772
5773 /// \brief Check whether or not it is profitable to promote all the
5774 /// instructions enqueued to be promoted.
5775 bool isProfitableToPromote() {
5776 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5777 unsigned Index = isa<ConstantInt>(ValIdx)
5778 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5779 : -1;
5780 Type *PromotedType = getTransitionType();
5781
5782 StoreInst *ST = cast<StoreInst>(CombineInst);
5783 unsigned AS = ST->getPointerAddressSpace();
5784 unsigned Align = ST->getAlignment();
5785 // Check if this store is supported.
5786 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005787 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5788 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005789 // If this is not supported, there is no way we can combine
5790 // the extract with the store.
5791 return false;
5792 }
5793
5794 // The scalar chain of computation has to pay for the transition
5795 // scalar to vector.
5796 // The vector chain has to account for the combining cost.
5797 uint64_t ScalarCost =
5798 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5799 uint64_t VectorCost = StoreExtractCombineCost;
5800 for (const auto &Inst : InstsToBePromoted) {
5801 // Compute the cost.
5802 // By construction, all instructions being promoted are arithmetic ones.
5803 // Moreover, one argument is a constant that can be viewed as a splat
5804 // constant.
5805 Value *Arg0 = Inst->getOperand(0);
5806 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5807 isa<ConstantFP>(Arg0);
5808 TargetTransformInfo::OperandValueKind Arg0OVK =
5809 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5810 : TargetTransformInfo::OK_AnyValue;
5811 TargetTransformInfo::OperandValueKind Arg1OVK =
5812 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5813 : TargetTransformInfo::OK_AnyValue;
5814 ScalarCost += TTI.getArithmeticInstrCost(
5815 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5816 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5817 Arg0OVK, Arg1OVK);
5818 }
5819 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5820 << ScalarCost << "\nVector: " << VectorCost << '\n');
5821 return ScalarCost > VectorCost;
5822 }
5823
5824 /// \brief Generate a constant vector with \p Val with the same
5825 /// number of elements as the transition.
5826 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005827 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005828 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5829 /// otherwise we generate a vector with as many undef as possible:
5830 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5831 /// used at the index of the extract.
5832 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005833 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005834 if (!UseSplat) {
5835 // If we cannot determine where the constant must be, we have to
5836 // use a splat constant.
5837 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5838 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5839 ExtractIdx = CstVal->getSExtValue();
5840 else
5841 UseSplat = true;
5842 }
5843
5844 unsigned End = getTransitionType()->getVectorNumElements();
5845 if (UseSplat)
5846 return ConstantVector::getSplat(End, Val);
5847
5848 SmallVector<Constant *, 4> ConstVec;
5849 UndefValue *UndefVal = UndefValue::get(Val->getType());
5850 for (unsigned Idx = 0; Idx != End; ++Idx) {
5851 if (Idx == ExtractIdx)
5852 ConstVec.push_back(Val);
5853 else
5854 ConstVec.push_back(UndefVal);
5855 }
5856 return ConstantVector::get(ConstVec);
5857 }
5858
5859 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5860 /// in \p Use can trigger undefined behavior.
5861 static bool canCauseUndefinedBehavior(const Instruction *Use,
5862 unsigned OperandIdx) {
5863 // This is not safe to introduce undef when the operand is on
5864 // the right hand side of a division-like instruction.
5865 if (OperandIdx != 1)
5866 return false;
5867 switch (Use->getOpcode()) {
5868 default:
5869 return false;
5870 case Instruction::SDiv:
5871 case Instruction::UDiv:
5872 case Instruction::SRem:
5873 case Instruction::URem:
5874 return true;
5875 case Instruction::FDiv:
5876 case Instruction::FRem:
5877 return !Use->hasNoNaNs();
5878 }
5879 llvm_unreachable(nullptr);
5880 }
5881
5882public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005883 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5884 const TargetTransformInfo &TTI, Instruction *Transition,
5885 unsigned CombineCost)
5886 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00005887 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005888 assert(Transition && "Do not know how to promote null");
5889 }
5890
5891 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5892 bool canPromote(const Instruction *ToBePromoted) const {
5893 // We could support CastInst too.
5894 return isa<BinaryOperator>(ToBePromoted);
5895 }
5896
5897 /// \brief Check if it is profitable to promote \p ToBePromoted
5898 /// by moving downward the transition through.
5899 bool shouldPromote(const Instruction *ToBePromoted) const {
5900 // Promote only if all the operands can be statically expanded.
5901 // Indeed, we do not want to introduce any new kind of transitions.
5902 for (const Use &U : ToBePromoted->operands()) {
5903 const Value *Val = U.get();
5904 if (Val == getEndOfTransition()) {
5905 // If the use is a division and the transition is on the rhs,
5906 // we cannot promote the operation, otherwise we may create a
5907 // division by zero.
5908 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5909 return false;
5910 continue;
5911 }
5912 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5913 !isa<ConstantFP>(Val))
5914 return false;
5915 }
5916 // Check that the resulting operation is legal.
5917 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5918 if (!ISDOpcode)
5919 return false;
5920 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005921 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005922 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005923 }
5924
5925 /// \brief Check whether or not \p Use can be combined
5926 /// with the transition.
5927 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5928 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5929
5930 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5931 void enqueueForPromotion(Instruction *ToBePromoted) {
5932 InstsToBePromoted.push_back(ToBePromoted);
5933 }
5934
5935 /// \brief Set the instruction that will be combined with the transition.
5936 void recordCombineInstruction(Instruction *ToBeCombined) {
5937 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5938 CombineInst = ToBeCombined;
5939 }
5940
5941 /// \brief Promote all the instructions enqueued for promotion if it is
5942 /// is profitable.
5943 /// \return True if the promotion happened, false otherwise.
5944 bool promote() {
5945 // Check if there is something to promote.
5946 // Right now, if we do not have anything to combine with,
5947 // we assume the promotion is not profitable.
5948 if (InstsToBePromoted.empty() || !CombineInst)
5949 return false;
5950
5951 // Check cost.
5952 if (!StressStoreExtract && !isProfitableToPromote())
5953 return false;
5954
5955 // Promote.
5956 for (auto &ToBePromoted : InstsToBePromoted)
5957 promoteImpl(ToBePromoted);
5958 InstsToBePromoted.clear();
5959 return true;
5960 }
5961};
Eugene Zelenko900b6332017-08-29 22:32:07 +00005962
5963} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00005964
5965void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5966 // At this point, we know that all the operands of ToBePromoted but Def
5967 // can be statically promoted.
5968 // For Def, we need to use its parameter in ToBePromoted:
5969 // b = ToBePromoted ty1 a
5970 // Def = Transition ty1 b to ty2
5971 // Move the transition down.
5972 // 1. Replace all uses of the promoted operation by the transition.
5973 // = ... b => = ... Def.
5974 assert(ToBePromoted->getType() == Transition->getType() &&
5975 "The type of the result of the transition does not match "
5976 "the final type");
5977 ToBePromoted->replaceAllUsesWith(Transition);
5978 // 2. Update the type of the uses.
5979 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5980 Type *TransitionTy = getTransitionType();
5981 ToBePromoted->mutateType(TransitionTy);
5982 // 3. Update all the operands of the promoted operation with promoted
5983 // operands.
5984 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5985 for (Use &U : ToBePromoted->operands()) {
5986 Value *Val = U.get();
5987 Value *NewVal = nullptr;
5988 if (Val == Transition)
5989 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5990 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5991 isa<ConstantFP>(Val)) {
5992 // Use a splat constant if it is not safe to use undef.
5993 NewVal = getConstantVector(
5994 cast<Constant>(Val),
5995 isa<UndefValue>(Val) ||
5996 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5997 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005998 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5999 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00006000 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
6001 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00006002 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006003 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
6004}
6005
6006/// Some targets can do store(extractelement) with one instruction.
6007/// Try to push the extractelement towards the stores when the target
6008/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006009bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00006010 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00006011 if (DisableStoreExtract || !TLI ||
6012 (!StressStoreExtract &&
6013 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
6014 Inst->getOperand(1), CombineCost)))
6015 return false;
6016
6017 // At this point we know that Inst is a vector to scalar transition.
6018 // Try to move it down the def-use chain, until:
6019 // - We can combine the transition with its single use
6020 // => we got rid of the transition.
6021 // - We escape the current basic block
6022 // => we would need to check that we are moving it at a cheaper place and
6023 // we do not do that for now.
6024 BasicBlock *Parent = Inst->getParent();
6025 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00006026 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006027 // If the transition has more than one use, assume this is not going to be
6028 // beneficial.
6029 while (Inst->hasOneUse()) {
6030 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
6031 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
6032
6033 if (ToBePromoted->getParent() != Parent) {
6034 DEBUG(dbgs() << "Instruction to promote is in a different block ("
6035 << ToBePromoted->getParent()->getName()
6036 << ") than the transition (" << Parent->getName() << ").\n");
6037 return false;
6038 }
6039
6040 if (VPH.canCombine(ToBePromoted)) {
6041 DEBUG(dbgs() << "Assume " << *Inst << '\n'
6042 << "will be combined with: " << *ToBePromoted << '\n');
6043 VPH.recordCombineInstruction(ToBePromoted);
6044 bool Changed = VPH.promote();
6045 NumStoreExtractExposed += Changed;
6046 return Changed;
6047 }
6048
6049 DEBUG(dbgs() << "Try promoting.\n");
6050 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
6051 return false;
6052
6053 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
6054
6055 VPH.enqueueForPromotion(ToBePromoted);
6056 Inst = ToBePromoted;
6057 }
6058 return false;
6059}
6060
Wei Mia2f0b592016-12-22 19:44:45 +00006061/// For the instruction sequence of store below, F and I values
6062/// are bundled together as an i64 value before being stored into memory.
6063/// Sometimes it is more efficent to generate separate stores for F and I,
6064/// which can remove the bitwise instructions or sink them to colder places.
6065///
6066/// (store (or (zext (bitcast F to i32) to i64),
6067/// (shl (zext I to i64), 32)), addr) -->
6068/// (store F, addr) and (store I, addr+4)
6069///
6070/// Similarly, splitting for other merged store can also be beneficial, like:
6071/// For pair of {i32, i32}, i64 store --> two i32 stores.
6072/// For pair of {i32, i16}, i64 store --> two i32 stores.
6073/// For pair of {i16, i16}, i32 store --> two i16 stores.
6074/// For pair of {i16, i8}, i32 store --> two i16 stores.
6075/// For pair of {i8, i8}, i16 store --> two i8 stores.
6076///
6077/// We allow each target to determine specifically which kind of splitting is
6078/// supported.
6079///
6080/// The store patterns are commonly seen from the simple code snippet below
6081/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
6082/// void goo(const std::pair<int, float> &);
6083/// hoo() {
6084/// ...
6085/// goo(std::make_pair(tmp, ftmp));
6086/// ...
6087/// }
6088///
6089/// Although we already have similar splitting in DAG Combine, we duplicate
6090/// it in CodeGenPrepare to catch the case in which pattern is across
6091/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6092/// during code expansion.
6093static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6094 const TargetLowering &TLI) {
6095 // Handle simple but common cases only.
6096 Type *StoreType = SI.getValueOperand()->getType();
6097 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6098 DL.getTypeSizeInBits(StoreType) == 0)
6099 return false;
6100
6101 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6102 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6103 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6104 DL.getTypeSizeInBits(SplitStoreType))
6105 return false;
6106
6107 // Match the following patterns:
6108 // (store (or (zext LValue to i64),
6109 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6110 // or
6111 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6112 // (zext LValue to i64),
6113 // Expect both operands of OR and the first operand of SHL have only
6114 // one use.
6115 Value *LValue, *HValue;
6116 if (!match(SI.getValueOperand(),
6117 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6118 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6119 m_SpecificInt(HalfValBitSize))))))
6120 return false;
6121
6122 // Check LValue and HValue are int with size less or equal than 32.
6123 if (!LValue->getType()->isIntegerTy() ||
6124 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6125 !HValue->getType()->isIntegerTy() ||
6126 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6127 return false;
6128
6129 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6130 // as the input of target query.
6131 auto *LBC = dyn_cast<BitCastInst>(LValue);
6132 auto *HBC = dyn_cast<BitCastInst>(HValue);
6133 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6134 : EVT::getEVT(LValue->getType());
6135 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6136 : EVT::getEVT(HValue->getType());
6137 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6138 return false;
6139
6140 // Start to split store.
6141 IRBuilder<> Builder(SI.getContext());
6142 Builder.SetInsertPoint(&SI);
6143
6144 // If LValue/HValue is a bitcast in another BB, create a new one in current
6145 // BB so it may be merged with the splitted stores by dag combiner.
6146 if (LBC && LBC->getParent() != SI.getParent())
6147 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6148 if (HBC && HBC->getParent() != SI.getParent())
6149 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6150
6151 auto CreateSplitStore = [&](Value *V, bool Upper) {
6152 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6153 Value *Addr = Builder.CreateBitCast(
6154 SI.getOperand(1),
6155 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6156 if (Upper)
6157 Addr = Builder.CreateGEP(
6158 SplitStoreType, Addr,
6159 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6160 Builder.CreateAlignedStore(
6161 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6162 };
6163
6164 CreateSplitStore(LValue, false);
6165 CreateSplitStore(HValue, true);
6166
6167 // Delete the old store.
6168 SI.eraseFromParent();
6169 return true;
6170}
6171
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006172// Return true if the GEP has two operands, the first operand is of a sequential
6173// type, and the second operand is a constant.
6174static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6175 gep_type_iterator I = gep_type_begin(*GEP);
6176 return GEP->getNumOperands() == 2 &&
6177 I.isSequential() &&
6178 isa<ConstantInt>(GEP->getOperand(1));
6179}
6180
6181// Try unmerging GEPs to reduce liveness interference (register pressure) across
6182// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6183// reducing liveness interference across those edges benefits global register
6184// allocation. Currently handles only certain cases.
6185//
6186// For example, unmerge %GEPI and %UGEPI as below.
6187//
6188// ---------- BEFORE ----------
6189// SrcBlock:
6190// ...
6191// %GEPIOp = ...
6192// ...
6193// %GEPI = gep %GEPIOp, Idx
6194// ...
6195// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6196// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6197// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6198// %UGEPI)
6199//
6200// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6201// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6202// ...
6203//
6204// DstBi:
6205// ...
6206// %UGEPI = gep %GEPIOp, UIdx
6207// ...
6208// ---------------------------
6209//
6210// ---------- AFTER ----------
6211// SrcBlock:
6212// ... (same as above)
6213// (* %GEPI is still alive on the indirectbr edges)
6214// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6215// unmerging)
6216// ...
6217//
6218// DstBi:
6219// ...
6220// %UGEPI = gep %GEPI, (UIdx-Idx)
6221// ...
6222// ---------------------------
6223//
6224// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6225// no longer alive on them.
6226//
6227// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6228// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6229// not to disable further simplications and optimizations as a result of GEP
6230// merging.
6231//
6232// Note this unmerging may increase the length of the data flow critical path
6233// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6234// between the register pressure and the length of data-flow critical
6235// path. Restricting this to the uncommon IndirectBr case would minimize the
6236// impact of potentially longer critical path, if any, and the impact on compile
6237// time.
6238static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6239 const TargetTransformInfo *TTI) {
6240 BasicBlock *SrcBlock = GEPI->getParent();
6241 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6242 // (non-IndirectBr) cases exit early here.
6243 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6244 return false;
6245 // Check that GEPI is a simple gep with a single constant index.
6246 if (!GEPSequentialConstIndexed(GEPI))
6247 return false;
6248 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6249 // Check that GEPI is a cheap one.
6250 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6251 > TargetTransformInfo::TCC_Basic)
6252 return false;
6253 Value *GEPIOp = GEPI->getOperand(0);
6254 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6255 if (!isa<Instruction>(GEPIOp))
6256 return false;
6257 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6258 if (GEPIOpI->getParent() != SrcBlock)
6259 return false;
6260 // Check that GEP is used outside the block, meaning it's alive on the
6261 // IndirectBr edge(s).
6262 if (find_if(GEPI->users(), [&](User *Usr) {
6263 if (auto *I = dyn_cast<Instruction>(Usr)) {
6264 if (I->getParent() != SrcBlock) {
6265 return true;
6266 }
6267 }
6268 return false;
6269 }) == GEPI->users().end())
6270 return false;
6271 // The second elements of the GEP chains to be unmerged.
6272 std::vector<GetElementPtrInst *> UGEPIs;
6273 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6274 // on IndirectBr edges.
6275 for (User *Usr : GEPIOp->users()) {
6276 if (Usr == GEPI) continue;
6277 // Check if Usr is an Instruction. If not, give up.
6278 if (!isa<Instruction>(Usr))
6279 return false;
6280 auto *UI = cast<Instruction>(Usr);
6281 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6282 if (UI->getParent() == SrcBlock)
6283 continue;
6284 // Check if Usr is a GEP. If not, give up.
6285 if (!isa<GetElementPtrInst>(Usr))
6286 return false;
6287 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6288 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6289 // the pointer operand to it. If so, record it in the vector. If not, give
6290 // up.
6291 if (!GEPSequentialConstIndexed(UGEPI))
6292 return false;
6293 if (UGEPI->getOperand(0) != GEPIOp)
6294 return false;
6295 if (GEPIIdx->getType() !=
6296 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6297 return false;
6298 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6299 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6300 > TargetTransformInfo::TCC_Basic)
6301 return false;
6302 UGEPIs.push_back(UGEPI);
6303 }
6304 if (UGEPIs.size() == 0)
6305 return false;
6306 // Check the materializing cost of (Uidx-Idx).
6307 for (GetElementPtrInst *UGEPI : UGEPIs) {
6308 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6309 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6310 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6311 if (ImmCost > TargetTransformInfo::TCC_Basic)
6312 return false;
6313 }
6314 // Now unmerge between GEPI and UGEPIs.
6315 for (GetElementPtrInst *UGEPI : UGEPIs) {
6316 UGEPI->setOperand(0, GEPI);
6317 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6318 Constant *NewUGEPIIdx =
6319 ConstantInt::get(GEPIIdx->getType(),
6320 UGEPIIdx->getValue() - GEPIIdx->getValue());
6321 UGEPI->setOperand(1, NewUGEPIIdx);
6322 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6323 // inbounds to avoid UB.
6324 if (!GEPI->isInBounds()) {
6325 UGEPI->setIsInBounds(false);
6326 }
6327 }
6328 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6329 // alive on IndirectBr edges).
6330 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6331 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6332 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6333 return true;
6334}
6335
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006336bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006337 // Bail out if we inserted the instruction to prevent optimizations from
6338 // stepping on each other's toes.
6339 if (InsertedInsts.count(I))
6340 return false;
6341
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006342 if (PHINode *P = dyn_cast<PHINode>(I)) {
6343 // It is possible for very late stage optimizations (such as SimplifyCFG)
6344 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6345 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006346 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006347 P->replaceAllUsesWith(V);
6348 P->eraseFromParent();
6349 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006350 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006351 }
Chris Lattneree588de2011-01-15 07:29:01 +00006352 return false;
6353 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006354
Chris Lattneree588de2011-01-15 07:29:01 +00006355 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006356 // If the source of the cast is a constant, then this should have
6357 // already been constant folded. The only reason NOT to constant fold
6358 // it is if something (e.g. LSR) was careful to place the constant
6359 // evaluation in a block other than then one that uses it (e.g. to hoist
6360 // the address of globals out of a loop). If this is the case, we don't
6361 // want to forward-subst the cast.
6362 if (isa<Constant>(CI->getOperand(0)))
6363 return false;
6364
Mehdi Amini44ede332015-07-09 02:09:04 +00006365 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006366 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006367
Chris Lattneree588de2011-01-15 07:29:01 +00006368 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006369 /// Sink a zext or sext into its user blocks if the target type doesn't
6370 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006371 if (TLI &&
6372 TLI->getTypeAction(CI->getContext(),
6373 TLI->getValueType(*DL, CI->getType())) ==
6374 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006375 return SinkCast(CI);
6376 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006377 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006378 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006379 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006380 }
Chris Lattneree588de2011-01-15 07:29:01 +00006381 return false;
6382 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006383
Chris Lattneree588de2011-01-15 07:29:01 +00006384 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006385 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006386 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006387
Chris Lattneree588de2011-01-15 07:29:01 +00006388 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006389 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006390 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006391 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006392 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006393 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6394 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006395 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006396 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006397 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006398
Chris Lattneree588de2011-01-15 07:29:01 +00006399 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006400 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6401 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006402 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006403 if (TLI) {
6404 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006405 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006406 SI->getOperand(0)->getType(), AS);
6407 }
Chris Lattneree588de2011-01-15 07:29:01 +00006408 return false;
6409 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006410
Matt Arsenault02d915b2017-03-15 22:35:20 +00006411 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6412 unsigned AS = RMW->getPointerAddressSpace();
6413 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6414 RMW->getType(), AS);
6415 }
6416
6417 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6418 unsigned AS = CmpX->getPointerAddressSpace();
6419 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6420 CmpX->getCompareOperand()->getType(), AS);
6421 }
6422
Yi Jiangd069f632014-04-21 19:34:27 +00006423 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6424
Geoff Berry5d534b62017-02-21 18:53:14 +00006425 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6426 EnableAndCmpSinking && TLI)
6427 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6428
Yi Jiangd069f632014-04-21 19:34:27 +00006429 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6430 BinOp->getOpcode() == Instruction::LShr)) {
6431 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6432 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006433 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006434
6435 return false;
6436 }
6437
Chris Lattneree588de2011-01-15 07:29:01 +00006438 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006439 if (GEPI->hasAllZeroIndices()) {
6440 /// The GEP operand must be a pointer, so must its result -> BitCast
6441 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6442 GEPI->getName(), GEPI);
6443 GEPI->replaceAllUsesWith(NC);
6444 GEPI->eraseFromParent();
6445 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006446 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006447 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006448 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006449 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6450 return true;
6451 }
Chris Lattneree588de2011-01-15 07:29:01 +00006452 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006453 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006454
Chris Lattneree588de2011-01-15 07:29:01 +00006455 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006456 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006457
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006458 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006459 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006460
Tim Northoveraeb8e062014-02-19 10:02:43 +00006461 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006462 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006463
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006464 if (auto *Switch = dyn_cast<SwitchInst>(I))
6465 return optimizeSwitchInst(Switch);
6466
Quentin Colombetc32615d2014-10-31 17:52:53 +00006467 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006468 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006469
Chris Lattneree588de2011-01-15 07:29:01 +00006470 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006471}
6472
James Molloyf01488e2016-01-15 09:20:19 +00006473/// Given an OR instruction, check to see if this is a bitreverse
6474/// idiom. If so, insert the new intrinsic and return true.
6475static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6476 const TargetLowering &TLI) {
6477 if (!I.getType()->isIntegerTy() ||
6478 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6479 TLI.getValueType(DL, I.getType(), true)))
6480 return false;
6481
6482 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006483 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006484 return false;
6485 Instruction *LastInst = Insts.back();
6486 I.replaceAllUsesWith(LastInst);
6487 RecursivelyDeleteTriviallyDeadInstructions(&I);
6488 return true;
6489}
6490
Chris Lattnerf2836d12007-03-31 04:06:36 +00006491// In this pass we look for GEP and cast instructions that are used
6492// across basic blocks and rewrite them to improve basic-block-at-a-time
6493// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006494bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006495 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006496 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006497
Chris Lattner7a277142011-01-15 07:14:54 +00006498 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006499 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006500 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006501 if (ModifiedDT)
6502 return true;
6503 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006504
James Molloyf01488e2016-01-15 09:20:19 +00006505 bool MadeBitReverse = true;
6506 while (TLI && MadeBitReverse) {
6507 MadeBitReverse = false;
6508 for (auto &I : reverse(BB)) {
6509 if (makeBitReverse(I, *DL, *TLI)) {
6510 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006511 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006512 break;
6513 }
6514 }
6515 }
James Molloy3ef84c42016-01-15 10:36:01 +00006516 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006517
Chris Lattnerf2836d12007-03-31 04:06:36 +00006518 return MadeChange;
6519}
Devang Patel53771ba2011-08-18 00:50:51 +00006520
6521// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006522// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006523// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006524bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006525 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006526 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006527 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006528 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006529 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006530 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006531 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006532 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006533 // being taken. They should not be moved next to the alloca
6534 // (and to the beginning of the scope), but rather stay close to
6535 // where said address is used.
6536 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006537 PrevNonDbgInst = Insn;
6538 continue;
6539 }
6540
6541 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6542 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006543 // If VI is a phi in a block with an EHPad terminator, we can't insert
6544 // after it.
6545 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6546 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00006547 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6548 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006549 if (isa<PHINode>(VI))
6550 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6551 else
6552 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006553 MadeChange = true;
6554 ++NumDbgValueMoved;
6555 }
6556 }
6557 }
6558 return MadeChange;
6559}
Tim Northovercea0abb2014-03-29 08:22:29 +00006560
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006561/// \brief Scale down both weights to fit into uint32_t.
6562static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6563 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006564 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006565 NewTrue = NewTrue / Scale;
6566 NewFalse = NewFalse / Scale;
6567}
6568
6569/// \brief Some targets prefer to split a conditional branch like:
6570/// \code
6571/// %0 = icmp ne i32 %a, 0
6572/// %1 = icmp ne i32 %b, 0
6573/// %or.cond = or i1 %0, %1
6574/// br i1 %or.cond, label %TrueBB, label %FalseBB
6575/// \endcode
6576/// into multiple branch instructions like:
6577/// \code
6578/// bb1:
6579/// %0 = icmp ne i32 %a, 0
6580/// br i1 %0, label %TrueBB, label %bb2
6581/// bb2:
6582/// %1 = icmp ne i32 %b, 0
6583/// br i1 %1, label %TrueBB, label %FalseBB
6584/// \endcode
6585/// This usually allows instruction selection to do even further optimizations
6586/// and combine the compare with the branch instruction. Currently this is
6587/// applied for targets which have "cheap" jump instructions.
6588///
6589/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6590///
6591bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006592 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006593 return false;
6594
6595 bool MadeChange = false;
6596 for (auto &BB : F) {
6597 // Does this BB end with the following?
6598 // %cond1 = icmp|fcmp|binary instruction ...
6599 // %cond2 = icmp|fcmp|binary instruction ...
6600 // %cond.or = or|and i1 %cond1, cond2
6601 // br i1 %cond.or label %dest1, label %dest2"
6602 BinaryOperator *LogicOp;
6603 BasicBlock *TBB, *FBB;
6604 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6605 continue;
6606
Sanjay Patel42574202015-09-02 19:23:23 +00006607 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6608 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6609 continue;
6610
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006611 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006612 Value *Cond1, *Cond2;
6613 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6614 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006615 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006616 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6617 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006618 Opc = Instruction::Or;
6619 else
6620 continue;
6621
6622 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6623 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6624 continue;
6625
6626 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6627
6628 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006629 auto TmpBB =
6630 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6631 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006632
6633 // Update original basic block by using the first condition directly by the
6634 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006635 Br1->setCondition(Cond1);
6636 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006637
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006638 // Depending on the conditon we have to either replace the true or the false
6639 // successor of the original branch instruction.
6640 if (Opc == Instruction::And)
6641 Br1->setSuccessor(0, TmpBB);
6642 else
6643 Br1->setSuccessor(1, TmpBB);
6644
6645 // Fill in the new basic block.
6646 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006647 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6648 I->removeFromParent();
6649 I->insertBefore(Br2);
6650 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006651
6652 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006653 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006654 // the newly generated BB (NewBB). In the other successor we need to add one
6655 // incoming edge to the PHI nodes, because both branch instructions target
6656 // now the same successor. Depending on the original branch condition
6657 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006658 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006659 // This doesn't change the successor order of the just created branch
6660 // instruction (or any other instruction).
6661 if (Opc == Instruction::Or)
6662 std::swap(TBB, FBB);
6663
6664 // Replace the old BB with the new BB.
6665 for (auto &I : *TBB) {
6666 PHINode *PN = dyn_cast<PHINode>(&I);
6667 if (!PN)
6668 break;
6669 int i;
6670 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6671 PN->setIncomingBlock(i, TmpBB);
6672 }
6673
6674 // Add another incoming edge form the new BB.
6675 for (auto &I : *FBB) {
6676 PHINode *PN = dyn_cast<PHINode>(&I);
6677 if (!PN)
6678 break;
6679 auto *Val = PN->getIncomingValueForBlock(&BB);
6680 PN->addIncoming(Val, TmpBB);
6681 }
6682
6683 // Update the branch weights (from SelectionDAGBuilder::
6684 // FindMergedConditions).
6685 if (Opc == Instruction::Or) {
6686 // Codegen X | Y as:
6687 // BB1:
6688 // jmp_if_X TBB
6689 // jmp TmpBB
6690 // TmpBB:
6691 // jmp_if_Y TBB
6692 // jmp FBB
6693 //
6694
6695 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6696 // The requirement is that
6697 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6698 // = TrueProb for orignal BB.
6699 // Assuming the orignal weights are A and B, one choice is to set BB1's
6700 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6701 // assumes that
6702 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6703 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6704 // TmpBB, but the math is more complicated.
6705 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006706 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006707 uint64_t NewTrueWeight = TrueWeight;
6708 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6709 scaleWeights(NewTrueWeight, NewFalseWeight);
6710 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6711 .createBranchWeights(TrueWeight, FalseWeight));
6712
6713 NewTrueWeight = TrueWeight;
6714 NewFalseWeight = 2 * FalseWeight;
6715 scaleWeights(NewTrueWeight, NewFalseWeight);
6716 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6717 .createBranchWeights(TrueWeight, FalseWeight));
6718 }
6719 } else {
6720 // Codegen X & Y as:
6721 // BB1:
6722 // jmp_if_X TmpBB
6723 // jmp FBB
6724 // TmpBB:
6725 // jmp_if_Y TBB
6726 // jmp FBB
6727 //
6728 // This requires creation of TmpBB after CurBB.
6729
6730 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6731 // The requirement is that
6732 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6733 // = FalseProb for orignal BB.
6734 // Assuming the orignal weights are A and B, one choice is to set BB1's
6735 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6736 // assumes that
6737 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6738 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006739 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006740 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6741 uint64_t NewFalseWeight = FalseWeight;
6742 scaleWeights(NewTrueWeight, NewFalseWeight);
6743 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6744 .createBranchWeights(TrueWeight, FalseWeight));
6745
6746 NewTrueWeight = 2 * TrueWeight;
6747 NewFalseWeight = FalseWeight;
6748 scaleWeights(NewTrueWeight, NewFalseWeight);
6749 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6750 .createBranchWeights(TrueWeight, FalseWeight));
6751 }
6752 }
6753
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006754 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006755 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006756 ModifiedDT = true;
6757
6758 MadeChange = true;
6759
6760 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6761 TmpBB->dump());
6762 }
6763 return MadeChange;
6764}