blob: d6633a508f5d5bbc428f0f10ef3f69bc9cc490db [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"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000039#include "llvm/CodeGen/TargetPassConfig.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000040#include "llvm/CodeGen/ValueTypes.h"
41#include "llvm/IR/Argument.h"
42#include "llvm/IR/Attributes.h"
43#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000044#include "llvm/IR/CallSite.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000045#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000046#include "llvm/IR/Constants.h"
47#include "llvm/IR/DataLayout.h"
48#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000049#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000050#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000051#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000052#include "llvm/IR/GlobalValue.h"
53#include "llvm/IR/GlobalVariable.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000054#include "llvm/IR/IRBuilder.h"
55#include "llvm/IR/InlineAsm.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000056#include "llvm/IR/InstrTypes.h"
57#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Instructions.h"
59#include "llvm/IR/IntrinsicInst.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000060#include "llvm/IR/Intrinsics.h"
61#include "llvm/IR/LLVMContext.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000062#include "llvm/IR/MDBuilder.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000063#include "llvm/IR/Module.h"
64#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000065#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000066#include "llvm/IR/Statepoint.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000067#include "llvm/IR/Type.h"
68#include "llvm/IR/Use.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000071#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000072#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000073#include "llvm/Pass.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000074#include "llvm/Support/BlockFrequency.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000075#include "llvm/Support/BranchProbability.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000076#include "llvm/Support/Casting.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000077#include "llvm/Support/CommandLine.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000078#include "llvm/Support/Compiler.h"
Evan Chengd3d80172007-12-05 23:58:20 +000079#include "llvm/Support/Debug.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000080#include "llvm/Support/ErrorHandling.h"
81#include "llvm/Support/MathExtras.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000082#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000083#include "llvm/Target/TargetLowering.h"
Eugene Zelenko900b6332017-08-29 22:32:07 +000084#include "llvm/Target/TargetMachine.h"
85#include "llvm/Target/TargetOptions.h"
Hal Finkelc3998302014-04-12 00:59:48 +000086#include "llvm/Target/TargetSubtargetInfo.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 Katkov3664aa82017-11-08 05:38:54 +0000193 "disable-complex-addr-modes", cl::Hidden, cl::init(true),
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
Eric Christopherc1ea1492008-09-24 05:32:41 +0000205namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000206
207using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
208using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
209using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
210using SExts = SmallVector<Instruction *, 16>;
211using ValueToSExts = DenseMap<Value *, SExts>;
212
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000213class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000214
Chris Lattner2dd09db2009-09-02 06:11:42 +0000215 class CodeGenPrepare : public FunctionPass {
Eugene Zelenko900b6332017-08-29 22:32:07 +0000216 const TargetMachine *TM = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000217 const TargetSubtargetInfo *SubtargetInfo;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000218 const TargetLowering *TLI = nullptr;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000219 const TargetRegisterInfo *TRI;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000220 const TargetTransformInfo *TTI = nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000221 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000222 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000223 std::unique_ptr<BlockFrequencyInfo> BFI;
224 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000225
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000226 /// As we scan instructions optimizing them, this is the next instruction
227 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000228 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000229
Evan Cheng0663f232011-03-21 01:19:09 +0000230 /// Keeps track of non-local addresses that have been sunk into a block.
231 /// This allows us to avoid inserting duplicate code for blocks with
232 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000233 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000234
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000235 /// Keeps track of all instructions inserted for the current function.
236 SetOfInstrs InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000237
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000238 /// Keeps track of the type of the related instruction before their
239 /// promotion for the current function.
240 InstrToOrigTy PromotedInsts;
241
Jun Bum Limdee55652017-04-03 19:20:07 +0000242 /// Keep track of instructions removed during promotion.
243 SetOfInstrs RemovedInsts;
244
245 /// Keep track of sext chains based on their initial value.
246 DenseMap<Value *, Instruction *> SeenChainsForSExt;
247
248 /// Keep track of SExt promoted.
249 ValueToSExts ValToSExtendedUses;
250
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000251 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000252 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000253
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000254 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000255 bool OptSize;
256
Mehdi Amini4fe37982015-07-07 18:45:17 +0000257 /// DataLayout for the Function being processed.
Eugene Zelenko900b6332017-08-29 22:32:07 +0000258 const DataLayout *DL = nullptr;
Mehdi Amini4fe37982015-07-07 18:45:17 +0000259
Chris Lattnerf2836d12007-03-31 04:06:36 +0000260 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000261 static char ID; // Pass identification, replacement for typeid
Eugene Zelenko900b6332017-08-29 22:32:07 +0000262
263 CodeGenPrepare() : FunctionPass(ID) {
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000264 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
265 }
Eugene Zelenko900b6332017-08-29 22:32:07 +0000266
Craig Topper4584cd52014-03-07 09:26:03 +0000267 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000268
Mehdi Amini117296c2016-10-01 02:56:57 +0000269 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000270
Craig Topper4584cd52014-03-07 09:26:03 +0000271 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000272 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000273 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000274 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000275 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000276 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000277 }
278
Chris Lattnerf2836d12007-03-31 04:06:36 +0000279 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000280 bool eliminateFallThrough(Function &F);
281 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000282 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000283 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
284 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000285 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
286 bool isPreheader);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000287 bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
288 bool optimizeInst(Instruction *I, bool &ModifiedDT);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000289 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000290 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000291 bool optimizeInlineAsmInst(CallInst *CS);
Sanjay Patel3b8974b2017-06-08 20:00:09 +0000292 bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
Jun Bum Limdee55652017-04-03 19:20:07 +0000293 bool optimizeExt(Instruction *&I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000294 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000295 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000296 bool optimizeSelectInst(SelectInst *SI);
297 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000298 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000299 bool optimizeExtractElementInst(Instruction *Inst);
300 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
301 bool placeDbgValues(Function &F);
Jun Bum Lim42301012017-03-17 19:05:21 +0000302 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
303 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
304 bool tryToPromoteExts(TypePromotionTransaction &TPT,
305 const SmallVectorImpl<Instruction *> &Exts,
306 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
307 unsigned CreatedInstsCost = 0);
Jun Bum Limdee55652017-04-03 19:20:07 +0000308 bool mergeSExts(Function &F);
309 bool performAddressTypePromotion(
310 Instruction *&Inst,
311 bool AllowPromotionWithoutCommonHeader,
312 bool HasPromoted, TypePromotionTransaction &TPT,
313 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000314 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000315 bool simplifyOffsetableRelocate(Instruction &I);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000316 bool splitIndirectCriticalEdges(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000317 };
Eugene Zelenko900b6332017-08-29 22:32:07 +0000318
319} // end anonymous namespace
Devang Patel09f162c2007-05-01 21:15:47 +0000320
Devang Patel8c78a0b2007-05-03 01:11:54 +0000321char CodeGenPrepare::ID = 0;
Eugene Zelenko900b6332017-08-29 22:32:07 +0000322
Matthias Braun1527baa2017-05-25 21:26:32 +0000323INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000324 "Optimize for code generation", false, false)
Dehao Chen302b69c2016-10-18 20:42:47 +0000325INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
Matthias Braun1527baa2017-05-25 21:26:32 +0000326INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000327 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000328
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000329FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000330
Chris Lattnerf2836d12007-03-31 04:06:36 +0000331bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000332 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000333 return false;
334
Mehdi Amini4fe37982015-07-07 18:45:17 +0000335 DL = &F.getParent()->getDataLayout();
336
Chris Lattnerf2836d12007-03-31 04:06:36 +0000337 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000338 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000339 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000340 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000341 BFI.reset();
342 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000343
Devang Patel8f606d72011-03-24 15:35:25 +0000344 ModifiedDT = false;
Francis Visoiu Mistrih8b617642017-05-18 17:21:13 +0000345 if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
346 TM = &TPC->getTM<TargetMachine>();
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000347 SubtargetInfo = TM->getSubtargetImpl(F);
348 TLI = SubtargetInfo->getTargetLowering();
349 TRI = SubtargetInfo->getRegisterInfo();
350 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000351 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000352 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000353 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000354 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000355
Dehao Chen302b69c2016-10-18 20:42:47 +0000356 if (ProfileGuidedSectionPrefix) {
357 ProfileSummaryInfo *PSI =
358 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Dehao Chen775341a2017-03-23 23:14:11 +0000359 if (PSI->isFunctionHotInCallGraph(&F))
Dehao Chen302b69c2016-10-18 20:42:47 +0000360 F.setSectionPrefix(".hot");
Dehao Chen775341a2017-03-23 23:14:11 +0000361 else if (PSI->isFunctionColdInCallGraph(&F))
Teresa Johnson720d9b42017-05-09 01:43:24 +0000362 F.setSectionPrefix(".unlikely");
Dehao Chen302b69c2016-10-18 20:42:47 +0000363 }
364
Preston Gurdcdf540d2012-09-04 18:22:17 +0000365 /// This optimization identifies DIV instructions that can be
366 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000367 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000368 const DenseMap<unsigned int, unsigned int> &BypassWidths =
369 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000370 BasicBlock* BB = &*F.begin();
371 while (BB != nullptr) {
372 // bypassSlowDivision may create new BBs, but we don't want to reapply the
373 // optimization to those blocks.
374 BasicBlock* Next = BB->getNextNode();
375 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
376 BB = Next;
377 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000378 }
379
380 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000381 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000382 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000383
Devang Patel53771ba2011-08-18 00:50:51 +0000384 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000385 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000386 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000387 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000388
Geoff Berry5d534b62017-02-21 18:53:14 +0000389 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000390 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000391
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000392 // Split some critical edges where one of the sources is an indirect branch,
393 // to help generate sane code for PHIs involving such edges.
394 EverMadeChange |= splitIndirectCriticalEdges(F);
395
Chris Lattnerc3748562007-04-02 01:35:34 +0000396 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000397 while (MadeChange) {
398 MadeChange = false;
Jun Bum Limdee55652017-04-03 19:20:07 +0000399 SeenChainsForSExt.clear();
400 ValToSExtendedUses.clear();
401 RemovedInsts.clear();
Hans Wennborg02fbc712012-09-19 07:48:16 +0000402 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000403 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000404 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000405 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000406
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000407 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000408 if (ModifiedDTOnIteration)
409 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000410 }
Jun Bum Limdee55652017-04-03 19:20:07 +0000411 if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
412 MadeChange |= mergeSExts(F);
413
414 // Really free removed instructions during promotion.
415 for (Instruction *I : RemovedInsts)
Reid Kleckner96ab8722017-05-18 17:24:10 +0000416 I->deleteValue();
Jun Bum Limdee55652017-04-03 19:20:07 +0000417
Chris Lattnerf2836d12007-03-31 04:06:36 +0000418 EverMadeChange |= MadeChange;
419 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000420
421 SunkAddrs.clear();
422
Cameron Zwarich338d3622011-03-11 21:52:04 +0000423 if (!DisableBranchOpts) {
424 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000425 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000426 for (BasicBlock &BB : F) {
427 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
428 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000429 if (!MadeChange) continue;
430
431 for (SmallVectorImpl<BasicBlock*>::iterator
432 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
433 if (pred_begin(*II) == pred_end(*II))
434 WorkList.insert(*II);
435 }
436
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000437 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000438 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000439 while (!WorkList.empty()) {
440 BasicBlock *BB = *WorkList.begin();
441 WorkList.erase(BB);
442 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
443
444 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000445
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000446 for (SmallVectorImpl<BasicBlock*>::iterator
447 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
448 if (pred_begin(*II) == pred_end(*II))
449 WorkList.insert(*II);
450 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000451
Nadav Rotem70409992012-08-14 05:19:07 +0000452 // Merge pairs of basic blocks with unconditional branches, connected by
453 // a single edge.
454 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000455 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000456
Cameron Zwarich338d3622011-03-11 21:52:04 +0000457 EverMadeChange |= MadeChange;
458 }
459
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000460 if (!DisableGCOpts) {
461 SmallVector<Instruction *, 2> Statepoints;
462 for (BasicBlock &BB : F)
463 for (Instruction &I : BB)
464 if (isStatepoint(I))
465 Statepoints.push_back(&I);
466 for (auto &I : Statepoints)
467 EverMadeChange |= simplifyOffsetableRelocate(*I);
468 }
469
Chris Lattnerf2836d12007-03-31 04:06:36 +0000470 return EverMadeChange;
471}
472
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000473/// Merge basic blocks which are connected by a single edge, where one of the
474/// basic blocks has a single successor pointing to the other basic block,
475/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000476bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000477 bool Changed = false;
478 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000479 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000480 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000481 // If the destination block has a single pred, then this is a trivial
482 // edge, just collapse it.
483 BasicBlock *SinglePred = BB->getSinglePredecessor();
484
Evan Cheng64a223a2012-09-28 23:58:57 +0000485 // Don't merge if BB's address is taken.
486 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000487
488 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
489 if (Term && !Term->isConditional()) {
490 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000491 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000492 // Remember if SinglePred was the entry block of the function.
493 // If so, we will need to move BB back to the entry position.
494 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000495 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000496
497 if (isEntry && BB != &BB->getParent()->getEntryBlock())
498 BB->moveBefore(&BB->getParent()->getEntryBlock());
499
500 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000501 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000502 }
503 }
504 return Changed;
505}
506
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000507/// Find a destination block from BB if BB is mergeable empty block.
508BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
509 // If this block doesn't end with an uncond branch, ignore it.
510 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
511 if (!BI || !BI->isUnconditional())
512 return nullptr;
513
514 // If the instruction before the branch (skipping debug info) isn't a phi
515 // node, then other stuff is happening here.
516 BasicBlock::iterator BBI = BI->getIterator();
517 if (BBI != BB->begin()) {
518 --BBI;
519 while (isa<DbgInfoIntrinsic>(BBI)) {
520 if (BBI == BB->begin())
521 break;
522 --BBI;
523 }
524 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
525 return nullptr;
526 }
527
528 // Do not break infinite loops.
529 BasicBlock *DestBB = BI->getSuccessor(0);
530 if (DestBB == BB)
531 return nullptr;
532
533 if (!canMergeBlocks(BB, DestBB))
534 DestBB = nullptr;
535
536 return DestBB;
537}
538
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000539// Return the unique indirectbr predecessor of a block. This may return null
540// even if such a predecessor exists, if it's not useful for splitting.
541// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
542// predecessors of BB.
543static BasicBlock *
544findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
545 // If the block doesn't have any PHIs, we don't care about it, since there's
546 // no point in splitting it.
547 PHINode *PN = dyn_cast<PHINode>(BB->begin());
548 if (!PN)
549 return nullptr;
550
551 // Verify we have exactly one IBR predecessor.
552 // Conservatively bail out if one of the other predecessors is not a "regular"
553 // terminator (that is, not a switch or a br).
554 BasicBlock *IBB = nullptr;
555 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
556 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
557 TerminatorInst *PredTerm = PredBB->getTerminator();
558 switch (PredTerm->getOpcode()) {
559 case Instruction::IndirectBr:
560 if (IBB)
561 return nullptr;
562 IBB = PredBB;
563 break;
564 case Instruction::Br:
565 case Instruction::Switch:
566 OtherPreds.push_back(PredBB);
567 continue;
568 default:
569 return nullptr;
570 }
571 }
572
573 return IBB;
574}
575
576// Split critical edges where the source of the edge is an indirectbr
577// instruction. This isn't always possible, but we can handle some easy cases.
578// This is useful because MI is unable to split such critical edges,
579// which means it will not be able to sink instructions along those edges.
580// This is especially painful for indirect branches with many successors, where
581// we end up having to prepare all outgoing values in the origin block.
582//
583// Our normal algorithm for splitting critical edges requires us to update
584// the outgoing edges of the edge origin block, but for an indirectbr this
585// is hard, since it would require finding and updating the block addresses
586// the indirect branch uses. But if a block only has a single indirectbr
587// predecessor, with the others being regular branches, we can do it in a
588// different way.
589// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
590// We can split D into D0 and D1, where D0 contains only the PHIs from D,
591// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
592// create the following structure:
593// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
594bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
595 // Check whether the function has any indirectbrs, and collect which blocks
596 // they may jump to. Since most functions don't have indirect branches,
597 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
598 SmallSetVector<BasicBlock *, 16> Targets;
599 for (auto &BB : F) {
600 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
601 if (!IBI)
602 continue;
603
604 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
605 Targets.insert(IBI->getSuccessor(Succ));
606 }
607
608 if (Targets.empty())
609 return false;
610
611 bool Changed = false;
612 for (BasicBlock *Target : Targets) {
613 SmallVector<BasicBlock *, 16> OtherPreds;
614 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
615 // If we did not found an indirectbr, or the indirectbr is the only
616 // incoming edge, this isn't the kind of edge we're looking for.
617 if (!IBRPred || OtherPreds.empty())
618 continue;
619
620 // Don't even think about ehpads/landingpads.
621 Instruction *FirstNonPHI = Target->getFirstNonPHI();
622 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
623 continue;
624
625 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
626 // It's possible Target was its own successor through an indirectbr.
627 // In this case, the indirectbr now comes from BodyBlock.
628 if (IBRPred == Target)
629 IBRPred = BodyBlock;
630
631 // At this point Target only has PHIs, and BodyBlock has the rest of the
632 // block's body. Create a copy of Target that will be used by the "direct"
633 // preds.
634 ValueToValueMapTy VMap;
635 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
636
Brendon Cahoon7769a082017-04-17 19:11:04 +0000637 for (BasicBlock *Pred : OtherPreds) {
638 // If the target is a loop to itself, then the terminator of the split
639 // block needs to be updated.
640 if (Pred == Target)
641 BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
642 else
643 Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
644 }
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000645
646 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
647 // they are clones, so the number of PHIs are the same.
648 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
649 // (b) Leave that as the only edge in the "Indirect" PHI.
650 // (c) Merge the two in the body block.
651 BasicBlock::iterator Indirect = Target->begin(),
652 End = Target->getFirstNonPHI()->getIterator();
653 BasicBlock::iterator Direct = DirectSucc->begin();
654 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
655
656 assert(&*End == Target->getTerminator() &&
657 "Block was expected to only contain PHIs");
658
659 while (Indirect != End) {
660 PHINode *DirPHI = cast<PHINode>(Direct);
661 PHINode *IndPHI = cast<PHINode>(Indirect);
662
663 // Now, clean up - the direct block shouldn't get the indirect value,
664 // and vice versa.
665 DirPHI->removeIncomingValue(IBRPred);
666 Direct++;
667
668 // Advance the pointer here, to avoid invalidation issues when the old
669 // PHI is erased.
670 Indirect++;
671
672 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
673 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
674 IBRPred);
675
676 // Create a PHI in the body block, to merge the direct and indirect
677 // predecessors.
678 PHINode *MergePHI =
679 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
680 MergePHI->addIncoming(NewIndPHI, Target);
681 MergePHI->addIncoming(DirPHI, DirectSucc);
682
683 IndPHI->replaceAllUsesWith(MergePHI);
684 IndPHI->eraseFromParent();
685 }
686
687 Changed = true;
688 }
689
690 return Changed;
691}
692
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000693/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
694/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
695/// edges in ways that are non-optimal for isel. Start by eliminating these
696/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000697bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000698 SmallPtrSet<BasicBlock *, 16> Preheaders;
699 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
700 while (!LoopList.empty()) {
701 Loop *L = LoopList.pop_back_val();
702 LoopList.insert(LoopList.end(), L->begin(), L->end());
703 if (BasicBlock *Preheader = L->getLoopPreheader())
704 Preheaders.insert(Preheader);
705 }
706
Chris Lattnerc3748562007-04-02 01:35:34 +0000707 bool MadeChange = false;
708 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000709 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000710 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000711 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
712 if (!DestBB ||
713 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000714 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000715
Sanjay Patelfc580a62015-09-21 23:03:16 +0000716 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000717 MadeChange = true;
718 }
719 return MadeChange;
720}
721
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000722bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
723 BasicBlock *DestBB,
724 bool isPreheader) {
725 // Do not delete loop preheaders if doing so would create a critical edge.
726 // Loop preheaders can be good locations to spill registers. If the
727 // preheader is deleted and we create a critical edge, registers may be
728 // spilled in the loop body instead.
729 if (!DisablePreheaderProtect && isPreheader &&
730 !(BB->getSinglePredecessor() &&
731 BB->getSinglePredecessor()->getSingleSuccessor()))
732 return false;
733
734 // Try to skip merging if the unique predecessor of BB is terminated by a
735 // switch or indirect branch instruction, and BB is used as an incoming block
736 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
737 // add COPY instructions in the predecessor of BB instead of BB (if it is not
738 // merged). Note that the critical edge created by merging such blocks wont be
739 // split in MachineSink because the jump table is not analyzable. By keeping
740 // such empty block (BB), ISel will place COPY instructions in BB, not in the
741 // predecessor of BB.
742 BasicBlock *Pred = BB->getUniquePredecessor();
743 if (!Pred ||
744 !(isa<SwitchInst>(Pred->getTerminator()) ||
745 isa<IndirectBrInst>(Pred->getTerminator())))
746 return true;
747
748 if (BB->getTerminator() != BB->getFirstNonPHI())
749 return true;
750
751 // We use a simple cost heuristic which determine skipping merging is
752 // profitable if the cost of skipping merging is less than the cost of
753 // merging : Cost(skipping merging) < Cost(merging BB), where the
754 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
755 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
756 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
757 // Freq(Pred) / Freq(BB) > 2.
758 // Note that if there are multiple empty blocks sharing the same incoming
759 // value for the PHIs in the DestBB, we consider them together. In such
760 // case, Cost(merging BB) will be the sum of their frequencies.
761
762 if (!isa<PHINode>(DestBB->begin()))
763 return true;
764
765 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
766
767 // Find all other incoming blocks from which incoming values of all PHIs in
768 // DestBB are the same as the ones from BB.
769 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
770 ++PI) {
771 BasicBlock *DestBBPred = *PI;
772 if (DestBBPred == BB)
773 continue;
774
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000775 bool HasAllSameValue = true;
776 BasicBlock::const_iterator DestBBI = DestBB->begin();
777 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
778 if (DestPN->getIncomingValueForBlock(BB) !=
779 DestPN->getIncomingValueForBlock(DestBBPred)) {
780 HasAllSameValue = false;
781 break;
782 }
783 }
784 if (HasAllSameValue)
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000785 SameIncomingValueBBs.insert(DestBBPred);
786 }
787
788 // See if all BB's incoming values are same as the value from Pred. In this
789 // case, no reason to skip merging because COPYs are expected to be place in
790 // Pred already.
791 if (SameIncomingValueBBs.count(Pred))
792 return true;
793
794 if (!BFI) {
795 Function &F = *BB->getParent();
796 LoopInfo LI{DominatorTree(F)};
797 BPI.reset(new BranchProbabilityInfo(F, LI));
798 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
799 }
800
801 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
802 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
803
804 for (auto SameValueBB : SameIncomingValueBBs)
805 if (SameValueBB->getUniquePredecessor() == Pred &&
806 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
807 BBFreq += BFI->getBlockFreq(SameValueBB);
808
809 return PredFreq.getFrequency() <=
810 BBFreq.getFrequency() * FreqRatioToSkipMerge;
811}
812
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000813/// Return true if we can merge BB into DestBB if there is a single
814/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000815/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000816bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000817 const BasicBlock *DestBB) const {
818 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
819 // the successor. If there are more complex condition (e.g. preheaders),
820 // don't mess around with them.
821 BasicBlock::const_iterator BBI = BB->begin();
822 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000823 for (const User *U : PN->users()) {
824 const Instruction *UI = cast<Instruction>(U);
825 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000826 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000827 // If User is inside DestBB block and it is a PHINode then check
828 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000829 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000830 if (UI->getParent() == DestBB) {
831 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000832 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
833 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
834 if (Insn && Insn->getParent() == BB &&
835 Insn->getParent() != UPN->getIncomingBlock(I))
836 return false;
837 }
838 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000839 }
840 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000841
Chris Lattnerc3748562007-04-02 01:35:34 +0000842 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
843 // and DestBB may have conflicting incoming values for the block. If so, we
844 // can't merge the block.
845 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
846 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000847
Chris Lattnerc3748562007-04-02 01:35:34 +0000848 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000849 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000850 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
851 // It is faster to get preds from a PHI than with pred_iterator.
852 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
853 BBPreds.insert(BBPN->getIncomingBlock(i));
854 } else {
855 BBPreds.insert(pred_begin(BB), pred_end(BB));
856 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000857
Chris Lattnerc3748562007-04-02 01:35:34 +0000858 // Walk the preds of DestBB.
859 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
860 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
861 if (BBPreds.count(Pred)) { // Common predecessor?
862 BBI = DestBB->begin();
863 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
864 const Value *V1 = PN->getIncomingValueForBlock(Pred);
865 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000866
Chris Lattnerc3748562007-04-02 01:35:34 +0000867 // If V2 is a phi node in BB, look up what the mapped value will be.
868 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
869 if (V2PN->getParent() == BB)
870 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000871
Chris Lattnerc3748562007-04-02 01:35:34 +0000872 // If there is a conflict, bail out.
873 if (V1 != V2) return false;
874 }
875 }
876 }
877
878 return true;
879}
880
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000881/// Eliminate a basic block that has only phi's and an unconditional branch in
882/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000883void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000884 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
885 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000886
David Greene74e2d492010-01-05 01:27:11 +0000887 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000888
Chris Lattnerc3748562007-04-02 01:35:34 +0000889 // If the destination block has a single pred, then this is a trivial edge,
890 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000891 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000892 if (SinglePred != DestBB) {
893 // Remember if SinglePred was the entry block of the function. If so, we
894 // will need to move BB back to the entry position.
895 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Balaram Makam32bcb5d2017-10-27 00:35:18 +0000896 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000897
Chris Lattner8a172da2008-11-28 19:54:49 +0000898 if (isEntry && BB != &BB->getParent()->getEntryBlock())
899 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000900
David Greene74e2d492010-01-05 01:27:11 +0000901 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000902 return;
903 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000904 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000905
Chris Lattnerc3748562007-04-02 01:35:34 +0000906 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
907 // to handle the new incoming edges it is about to have.
908 PHINode *PN;
909 for (BasicBlock::iterator BBI = DestBB->begin();
910 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
911 // Remove the incoming value for BB, and remember it.
912 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000913
Chris Lattnerc3748562007-04-02 01:35:34 +0000914 // Two options: either the InVal is a phi node defined in BB or it is some
915 // value that dominates BB.
916 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
917 if (InValPhi && InValPhi->getParent() == BB) {
918 // Add all of the input values of the input PHI as inputs of this phi.
919 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
920 PN->addIncoming(InValPhi->getIncomingValue(i),
921 InValPhi->getIncomingBlock(i));
922 } else {
923 // Otherwise, add one instance of the dominating value for each edge that
924 // we will be adding.
925 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
926 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
927 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
928 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000929 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
930 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000931 }
932 }
933 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000934
Chris Lattnerc3748562007-04-02 01:35:34 +0000935 // The PHIs are now updated, change everything that refers to BB to use
936 // DestBB and remove BB.
937 BB->replaceAllUsesWith(DestBB);
938 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000939 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000940
David Greene74e2d492010-01-05 01:27:11 +0000941 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000942}
943
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000944// Computes a map of base pointer relocation instructions to corresponding
945// derived pointer relocation instructions given a vector of all relocate calls
946static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000947 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
948 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
949 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000950 // Collect information in two maps: one primarily for locating the base object
951 // while filling the second map; the second map is the final structure holding
952 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000953 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
954 for (auto *ThisRelocate : AllRelocateCalls) {
955 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
956 ThisRelocate->getDerivedPtrIndex());
957 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000958 }
959 for (auto &Item : RelocateIdxMap) {
960 std::pair<unsigned, unsigned> Key = Item.first;
961 if (Key.first == Key.second)
962 // Base relocation: nothing to insert
963 continue;
964
Manuel Jacob83eefa62016-01-05 04:03:00 +0000965 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000966 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000967
968 // We're iterating over RelocateIdxMap so we cannot modify it.
969 auto MaybeBase = RelocateIdxMap.find(BaseKey);
970 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000971 // TODO: We might want to insert a new base object relocate and gep off
972 // that, if there are enough derived object relocates.
973 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000974
975 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000976 }
977}
978
979// Accepts a GEP and extracts the operands into a vector provided they're all
980// small integer constants
981static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
982 SmallVectorImpl<Value *> &OffsetV) {
983 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
984 // Only accept small constant integer operands
985 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
986 if (!Op || Op->getZExtValue() > 20)
987 return false;
988 }
989
990 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
991 OffsetV.push_back(GEP->getOperand(i));
992 return true;
993}
994
995// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
996// replace, computes a replacement, and affects it.
997static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000998simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
999 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001000 bool MadeChange = false;
Serguei Katkov9e5604d2017-08-17 05:48:30 +00001001 // We must ensure the relocation of derived pointer is defined after
1002 // relocation of base pointer. If we find a relocation corresponding to base
1003 // defined earlier than relocation of base then we move relocation of base
1004 // right before found relocation. We consider only relocation in the same
1005 // basic block as relocation of base. Relocations from other basic block will
1006 // be skipped by optimization and we do not care about them.
1007 for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
1008 &*R != RelocatedBase; ++R)
1009 if (auto RI = dyn_cast<GCRelocateInst>(R))
1010 if (RI->getStatepoint() == RelocatedBase->getStatepoint())
1011 if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
1012 RelocatedBase->moveBefore(RI);
1013 break;
1014 }
1015
Manuel Jacob83eefa62016-01-05 04:03:00 +00001016 for (GCRelocateInst *ToReplace : Targets) {
1017 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001018 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +00001019 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001020 // A duplicate relocate call. TODO: coalesce duplicates.
1021 continue;
1022 }
1023
Igor Laevskyf637b4a2015-11-03 18:37:40 +00001024 if (RelocatedBase->getParent() != ToReplace->getParent()) {
1025 // Base and derived relocates are in different basic blocks.
1026 // In this case transform is only valid when base dominates derived
1027 // relocate. However it would be too expensive to check dominance
1028 // for each such relocate, so we skip the whole transformation.
1029 continue;
1030 }
1031
Manuel Jacob83eefa62016-01-05 04:03:00 +00001032 Value *Base = ToReplace->getBasePtr();
1033 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001034 if (!Derived || Derived->getPointerOperand() != Base)
1035 continue;
1036
1037 SmallVector<Value *, 2> OffsetV;
1038 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
1039 continue;
1040
1041 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +00001042 assert(RelocatedBase->getNextNode() &&
1043 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +00001044
1045 // Insert after RelocatedBase
1046 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001047 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +00001048
1049 // If gc_relocate does not match the actual type, cast it to the right type.
1050 // In theory, there must be a bitcast after gc_relocate if the type does not
1051 // match, and we should reuse it to get the derived pointer. But it could be
1052 // cases like this:
1053 // bb1:
1054 // ...
1055 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1056 // br label %merge
1057 //
1058 // bb2:
1059 // ...
1060 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
1061 // br label %merge
1062 //
1063 // merge:
1064 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
1065 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
1066 //
1067 // In this case, we can not find the bitcast any more. So we insert a new bitcast
1068 // no matter there is already one or not. In this way, we can handle all cases, and
1069 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001070 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +00001071 if (RelocatedBase->getType() != Base->getType()) {
1072 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001073 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001074 }
David Blaikie68d535c2015-03-24 22:38:16 +00001075 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +00001076 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001077 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +00001078 // If the newly generated derived pointer's type does not match the original derived
1079 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +00001080 Value *ActualReplacement = Replacement;
1081 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +00001082 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +00001083 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +00001084 }
1085 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001086 ToReplace->eraseFromParent();
1087
1088 MadeChange = true;
1089 }
1090 return MadeChange;
1091}
1092
1093// Turns this:
1094//
1095// %base = ...
1096// %ptr = gep %base + 15
1097// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1098// %base' = relocate(%tok, i32 4, i32 4)
1099// %ptr' = relocate(%tok, i32 4, i32 5)
1100// %val = load %ptr'
1101//
1102// into this:
1103//
1104// %base = ...
1105// %ptr = gep %base + 15
1106// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
1107// %base' = gc.relocate(%tok, i32 4, i32 4)
1108// %ptr' = gep %base' + 15
1109// %val = load %ptr'
1110bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
1111 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +00001112 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001113
1114 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +00001115 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001116 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001117 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001118
1119 // We need atleast one base pointer relocation + one derived pointer
1120 // relocation to mangle
1121 if (AllRelocateCalls.size() < 2)
1122 return false;
1123
1124 // RelocateInstMap is a mapping from the base relocate instruction to the
1125 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001126 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001127 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1128 if (RelocateInstMap.empty())
1129 return false;
1130
1131 for (auto &Item : RelocateInstMap)
1132 // Item.first is the RelocatedBase to offset against
1133 // Item.second is the vector of Targets to replace
1134 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1135 return MadeChange;
1136}
1137
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001138/// SinkCast - Sink the specified cast instruction into its user blocks
1139static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001140 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001141
Chris Lattnerf2836d12007-03-31 04:06:36 +00001142 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001143 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001144
Chris Lattnerf2836d12007-03-31 04:06:36 +00001145 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001146 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001147 UI != E; ) {
1148 Use &TheUse = UI.getUse();
1149 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001150
Chris Lattnerf2836d12007-03-31 04:06:36 +00001151 // Figure out which BB this cast is used in. For PHI's this is the
1152 // appropriate predecessor block.
1153 BasicBlock *UserBB = User->getParent();
1154 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001155 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001156 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001157
Chris Lattnerf2836d12007-03-31 04:06:36 +00001158 // Preincrement use iterator so we don't invalidate it.
1159 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001160
David Majnemer0c80e2e2016-04-27 19:36:38 +00001161 // The first insertion point of a block containing an EH pad is after the
1162 // pad. If the pad is the user, we cannot sink the cast past the pad.
1163 if (User->isEHPad())
1164 continue;
1165
Andrew Kaylord0430e82015-11-23 19:16:15 +00001166 // If the block selected to receive the cast is an EH pad that does not
1167 // allow non-PHI instructions before the terminator, we can't sink the
1168 // cast.
1169 if (UserBB->getTerminator()->isEHPad())
1170 continue;
1171
Chris Lattnerf2836d12007-03-31 04:06:36 +00001172 // If this user is in the same block as the cast, don't change the cast.
1173 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001174
Chris Lattnerf2836d12007-03-31 04:06:36 +00001175 // If we have already inserted a cast into this block, use it.
1176 CastInst *&InsertedCast = InsertedCasts[UserBB];
1177
1178 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001179 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001180 assert(InsertPt != UserBB->end());
1181 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1182 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001183 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001184
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001185 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001186 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001187 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001188 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001189 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001190
Chris Lattnerf2836d12007-03-31 04:06:36 +00001191 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001192 if (CI->use_empty()) {
Adrian Prantl261ac8b2017-11-03 21:55:03 +00001193 salvageDebugInfo(*CI);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001194 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001195 MadeChange = true;
1196 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001197
Chris Lattnerf2836d12007-03-31 04:06:36 +00001198 return MadeChange;
1199}
1200
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001201/// If the specified cast instruction is a noop copy (e.g. it's casting from
1202/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1203/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001204///
1205/// Return true if any changes are made.
Mehdi Amini44ede332015-07-09 02:09:04 +00001206static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1207 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001208 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1209 // than sinking only nop casts, but is helpful on some platforms.
1210 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1211 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1212 ASC->getDestAddressSpace()))
1213 return false;
1214 }
1215
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001216 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001217 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1218 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001219
1220 // This is an fp<->int conversion?
1221 if (SrcVT.isInteger() != DstVT.isInteger())
1222 return false;
1223
1224 // If this is an extension, it will be a zero or sign extension, which
1225 // isn't a noop.
1226 if (SrcVT.bitsLT(DstVT)) return false;
1227
1228 // If these values will be promoted, find out what they will be promoted
1229 // to. This helps us consider truncates on PPC as noop copies when they
1230 // are.
1231 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1232 TargetLowering::TypePromoteInteger)
1233 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1234 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1235 TargetLowering::TypePromoteInteger)
1236 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1237
1238 // If, after promotion, these are the same types, this is a noop copy.
1239 if (SrcVT != DstVT)
1240 return false;
1241
1242 return SinkCast(CI);
1243}
1244
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001245/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1246/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001247///
1248/// Return true if any changes were made.
1249static bool CombineUAddWithOverflow(CmpInst *CI) {
1250 Value *A, *B;
1251 Instruction *AddI;
1252 if (!match(CI,
1253 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1254 return false;
1255
1256 Type *Ty = AddI->getType();
1257 if (!isa<IntegerType>(Ty))
1258 return false;
1259
1260 // We don't want to move around uses of condition values this late, so we we
1261 // check if it is legal to create the call to the intrinsic in the basic
1262 // block containing the icmp:
1263
1264 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1265 return false;
1266
1267#ifndef NDEBUG
1268 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1269 // for now:
1270 if (AddI->hasOneUse())
1271 assert(*AddI->user_begin() == CI && "expected!");
1272#endif
1273
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001274 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001275 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1276
1277 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1278
1279 auto *UAddWithOverflow =
1280 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1281 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1282 auto *Overflow =
1283 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1284
1285 CI->replaceAllUsesWith(Overflow);
1286 AddI->replaceAllUsesWith(UAdd);
1287 CI->eraseFromParent();
1288 AddI->eraseFromParent();
1289 return true;
1290}
1291
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001292/// Sink the given CmpInst into user blocks to reduce the number of virtual
1293/// registers that must be created and coalesced. This is a clear win except on
1294/// targets with multiple condition code registers (PowerPC), where it might
1295/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001296///
1297/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001298static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001299 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001300
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001301 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001302 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001303 return false;
1304
1305 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001306 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001307
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001308 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001309 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001310 UI != E; ) {
1311 Use &TheUse = UI.getUse();
1312 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001313
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001314 // Preincrement use iterator so we don't invalidate it.
1315 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001316
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001317 // Don't bother for PHI nodes.
1318 if (isa<PHINode>(User))
1319 continue;
1320
1321 // Figure out which BB this cmp is used in.
1322 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001323
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001324 // If this user is in the same block as the cmp, don't change the cmp.
1325 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001326
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001327 // If we have already inserted a cmp into this block, use it.
1328 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1329
1330 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001331 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001332 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001333 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001334 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1335 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001336 // Propagate the debug info.
1337 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001338 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001339
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001340 // Replace a use of the cmp with a use of the new cmp.
1341 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001342 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001343 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001344 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001345
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001346 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001347 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001348 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001349 MadeChange = true;
1350 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001351
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001352 return MadeChange;
1353}
1354
Peter Zotovf87e5502016-04-03 17:11:53 +00001355static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001356 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001357 return true;
1358
1359 if (CombineUAddWithOverflow(CI))
1360 return true;
1361
1362 return false;
1363}
1364
Geoff Berry5d534b62017-02-21 18:53:14 +00001365/// Duplicate and sink the given 'and' instruction into user blocks where it is
1366/// used in a compare to allow isel to generate better code for targets where
1367/// this operation can be combined.
1368///
1369/// Return true if any changes are made.
1370static bool sinkAndCmp0Expression(Instruction *AndI,
1371 const TargetLowering &TLI,
1372 SetOfInstrs &InsertedInsts) {
1373 // Double-check that we're not trying to optimize an instruction that was
1374 // already optimized by some other part of this pass.
1375 assert(!InsertedInsts.count(AndI) &&
1376 "Attempting to optimize already optimized and instruction");
1377 (void) InsertedInsts;
1378
1379 // Nothing to do for single use in same basic block.
1380 if (AndI->hasOneUse() &&
1381 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1382 return false;
1383
1384 // Try to avoid cases where sinking/duplicating is likely to increase register
1385 // pressure.
1386 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1387 !isa<ConstantInt>(AndI->getOperand(1)) &&
1388 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1389 return false;
1390
1391 for (auto *U : AndI->users()) {
1392 Instruction *User = cast<Instruction>(U);
1393
1394 // Only sink for and mask feeding icmp with 0.
1395 if (!isa<ICmpInst>(User))
1396 return false;
1397
1398 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1399 if (!CmpC || !CmpC->isZero())
1400 return false;
1401 }
1402
1403 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1404 return false;
1405
1406 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1407 DEBUG(AndI->getParent()->dump());
1408
1409 // Push the 'and' into the same block as the icmp 0. There should only be
1410 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1411 // others, so we don't need to keep track of which BBs we insert into.
1412 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1413 UI != E; ) {
1414 Use &TheUse = UI.getUse();
1415 Instruction *User = cast<Instruction>(*UI);
1416
1417 // Preincrement use iterator so we don't invalidate it.
1418 ++UI;
1419
1420 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1421
1422 // Keep the 'and' in the same place if the use is already in the same block.
1423 Instruction *InsertPt =
1424 User->getParent() == AndI->getParent() ? AndI : User;
1425 Instruction *InsertedAnd =
1426 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1427 AndI->getOperand(1), "", InsertPt);
1428 // Propagate the debug info.
1429 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1430
1431 // Replace a use of the 'and' with a use of the new 'and'.
1432 TheUse = InsertedAnd;
1433 ++NumAndUses;
1434 DEBUG(User->getParent()->dump());
1435 }
1436
1437 // We removed all uses, nuke the and.
1438 AndI->eraseFromParent();
1439 return true;
1440}
1441
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001442/// Check if the candidates could be combined with a shift instruction, which
1443/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001444/// 1. Truncate instruction
1445/// 2. And instruction and the imm is a mask of the low bits:
1446/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001447static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001448 if (!isa<TruncInst>(User)) {
1449 if (User->getOpcode() != Instruction::And ||
1450 !isa<ConstantInt>(User->getOperand(1)))
1451 return false;
1452
Quentin Colombetd4f44692014-04-22 01:20:34 +00001453 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001454
Quentin Colombetd4f44692014-04-22 01:20:34 +00001455 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001456 return false;
1457 }
1458 return true;
1459}
1460
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001461/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001462static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001463SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1464 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001465 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001466 BasicBlock *UserBB = User->getParent();
1467 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1468 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1469 bool MadeChange = false;
1470
1471 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1472 TruncE = TruncI->user_end();
1473 TruncUI != TruncE;) {
1474
1475 Use &TruncTheUse = TruncUI.getUse();
1476 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1477 // Preincrement use iterator so we don't invalidate it.
1478
1479 ++TruncUI;
1480
1481 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1482 if (!ISDOpcode)
1483 continue;
1484
Tim Northovere2239ff2014-07-29 10:20:22 +00001485 // If the use is actually a legal node, there will not be an
1486 // implicit truncate.
1487 // FIXME: always querying the result type is just an
1488 // approximation; some nodes' legality is determined by the
1489 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001490 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001491 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001492 continue;
1493
1494 // Don't bother for PHI nodes.
1495 if (isa<PHINode>(TruncUser))
1496 continue;
1497
1498 BasicBlock *TruncUserBB = TruncUser->getParent();
1499
1500 if (UserBB == TruncUserBB)
1501 continue;
1502
1503 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1504 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1505
1506 if (!InsertedShift && !InsertedTrunc) {
1507 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001508 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001509 // Sink the shift
1510 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001511 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1512 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001513 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001514 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1515 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001516
1517 // Sink the trunc
1518 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1519 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001520 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001521
1522 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001523 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001524
1525 MadeChange = true;
1526
1527 TruncTheUse = InsertedTrunc;
1528 }
1529 }
1530 return MadeChange;
1531}
1532
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001533/// Sink the shift *right* instruction into user blocks if the uses could
1534/// potentially be combined with this shift instruction and generate BitExtract
1535/// instruction. It will only be applied if the architecture supports BitExtract
1536/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001537/// BB1:
1538/// %x.extract.shift = lshr i64 %arg1, 32
1539/// BB2:
1540/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1541/// ==>
1542///
1543/// BB2:
1544/// %x.extract.shift.1 = lshr i64 %arg1, 32
1545/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1546///
1547/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1548/// instruction.
1549/// Return true if any changes are made.
1550static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001551 const TargetLowering &TLI,
1552 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001553 BasicBlock *DefBB = ShiftI->getParent();
1554
1555 /// Only insert instructions in each block once.
1556 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1557
Mehdi Amini44ede332015-07-09 02:09:04 +00001558 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001559
1560 bool MadeChange = false;
1561 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1562 UI != E;) {
1563 Use &TheUse = UI.getUse();
1564 Instruction *User = cast<Instruction>(*UI);
1565 // Preincrement use iterator so we don't invalidate it.
1566 ++UI;
1567
1568 // Don't bother for PHI nodes.
1569 if (isa<PHINode>(User))
1570 continue;
1571
1572 if (!isExtractBitsCandidateUse(User))
1573 continue;
1574
1575 BasicBlock *UserBB = User->getParent();
1576
1577 if (UserBB == DefBB) {
1578 // If the shift and truncate instruction are in the same BB. The use of
1579 // the truncate(TruncUse) may still introduce another truncate if not
1580 // legal. In this case, we would like to sink both shift and truncate
1581 // instruction to the BB of TruncUse.
1582 // for example:
1583 // BB1:
1584 // i64 shift.result = lshr i64 opnd, imm
1585 // trunc.result = trunc shift.result to i16
1586 //
1587 // BB2:
1588 // ----> We will have an implicit truncate here if the architecture does
1589 // not have i16 compare.
1590 // cmp i16 trunc.result, opnd2
1591 //
1592 if (isa<TruncInst>(User) && shiftIsLegal
1593 // If the type of the truncate is legal, no trucate will be
1594 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001595 &&
1596 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001597 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001598 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001599
1600 continue;
1601 }
1602 // If we have already inserted a shift into this block, use it.
1603 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1604
1605 if (!InsertedShift) {
1606 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001607 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001608
1609 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001610 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1611 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001612 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001613 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1614 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001615
1616 MadeChange = true;
1617 }
1618
1619 // Replace a use of the shift with a use of the new shift.
1620 TheUse = InsertedShift;
1621 }
1622
1623 // If we removed all uses, nuke the shift.
1624 if (ShiftI->use_empty())
1625 ShiftI->eraseFromParent();
1626
1627 return MadeChange;
1628}
1629
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001630/// If counting leading or trailing zeros is an expensive operation and a zero
1631/// input is defined, add a check for zero to avoid calling the intrinsic.
1632///
1633/// We want to transform:
1634/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1635///
1636/// into:
1637/// entry:
1638/// %cmpz = icmp eq i64 %A, 0
1639/// br i1 %cmpz, label %cond.end, label %cond.false
1640/// cond.false:
1641/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1642/// br label %cond.end
1643/// cond.end:
1644/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1645///
1646/// If the transform is performed, return true and set ModifiedDT to true.
1647static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1648 const TargetLowering *TLI,
1649 const DataLayout *DL,
1650 bool &ModifiedDT) {
1651 if (!TLI || !DL)
1652 return false;
1653
1654 // If a zero input is undefined, it doesn't make sense to despeculate that.
1655 if (match(CountZeros->getOperand(1), m_One()))
1656 return false;
1657
1658 // If it's cheap to speculate, there's nothing to do.
1659 auto IntrinsicID = CountZeros->getIntrinsicID();
1660 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1661 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1662 return false;
1663
1664 // Only handle legal scalar cases. Anything else requires too much work.
1665 Type *Ty = CountZeros->getType();
1666 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001667 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001668 return false;
1669
1670 // The intrinsic will be sunk behind a compare against zero and branch.
1671 BasicBlock *StartBlock = CountZeros->getParent();
1672 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1673
1674 // Create another block after the count zero intrinsic. A PHI will be added
1675 // in this block to select the result of the intrinsic or the bit-width
1676 // constant if the input to the intrinsic is zero.
1677 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1678 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1679
1680 // Set up a builder to create a compare, conditional branch, and PHI.
1681 IRBuilder<> Builder(CountZeros->getContext());
1682 Builder.SetInsertPoint(StartBlock->getTerminator());
1683 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1684
1685 // Replace the unconditional branch that was created by the first split with
1686 // a compare against zero and a conditional branch.
1687 Value *Zero = Constant::getNullValue(Ty);
1688 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1689 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1690 StartBlock->getTerminator()->eraseFromParent();
1691
1692 // Create a PHI in the end block to select either the output of the intrinsic
1693 // or the bit width of the operand.
1694 Builder.SetInsertPoint(&EndBlock->front());
1695 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1696 CountZeros->replaceAllUsesWith(PN);
1697 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1698 PN->addIncoming(BitWidth, StartBlock);
1699 PN->addIncoming(CountZeros, CallBlock);
1700
1701 // We are explicitly handling the zero case, so we can set the intrinsic's
1702 // undefined zero argument to 'true'. This will also prevent reprocessing the
1703 // intrinsic; we only despeculate when a zero input is defined.
1704 CountZeros->setArgOperand(1, Builder.getTrue());
1705 ModifiedDT = true;
1706 return true;
1707}
1708
Sanjay Patel3b8974b2017-06-08 20:00:09 +00001709bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001710 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001711
Chris Lattner7a277142011-01-15 07:14:54 +00001712 // Lower inline assembly if we can.
1713 // If we found an inline asm expession, and if the target knows how to
1714 // lower it to normal LLVM code, do so now.
1715 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1716 if (TLI->ExpandInlineAsm(CI)) {
1717 // Avoid invalidating the iterator.
1718 CurInstIterator = BB->begin();
1719 // Avoid processing instructions out of order, which could cause
1720 // reuse before a value is defined.
1721 SunkAddrs.clear();
1722 return true;
1723 }
1724 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001725 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001726 return true;
1727 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001728
John Brawn0dbcd652015-03-18 12:01:59 +00001729 // Align the pointer arguments to this call if the target thinks it's a good
1730 // idea
1731 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001732 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001733 for (auto &Arg : CI->arg_operands()) {
1734 // We want to align both objects whose address is used directly and
1735 // objects whose address is used in casts and GEPs, though it only makes
1736 // sense for GEPs if the offset is a multiple of the desired alignment and
1737 // if size - offset meets the size threshold.
1738 if (!Arg->getType()->isPointerTy())
1739 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001740 APInt Offset(DL->getPointerSizeInBits(
1741 cast<PointerType>(Arg->getType())->getAddressSpace()),
1742 0);
1743 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001744 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001745 if ((Offset2 & (PrefAlign-1)) != 0)
1746 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001747 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001748 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1749 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001750 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001751 // Global variables can only be aligned if they are defined in this
1752 // object (i.e. they are uniquely initialized in this object), and
1753 // over-aligning global variables that have an explicit section is
1754 // forbidden.
1755 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001756 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001757 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001758 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001759 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001760 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001761 }
1762 // If this is a memcpy (or similar) then we may be able to improve the
1763 // alignment
1764 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001765 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001766 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001767 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001768 if (Align > MI->getAlignment())
1769 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001770 }
1771 }
1772
Philip Reamesac115ed2016-03-09 23:13:12 +00001773 // If we have a cold call site, try to sink addressing computation into the
1774 // cold block. This interacts with our handling for loads and stores to
1775 // ensure that we can fold all uses of a potential addressing computation
1776 // into their uses. TODO: generalize this to work over profiling data
1777 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1778 for (auto &Arg : CI->arg_operands()) {
1779 if (!Arg->getType()->isPointerTy())
1780 continue;
1781 unsigned AS = Arg->getType()->getPointerAddressSpace();
1782 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1783 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001784
Eric Christopher4b7948e2010-03-11 02:41:03 +00001785 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001786 if (II) {
1787 switch (II->getIntrinsicID()) {
1788 default: break;
1789 case Intrinsic::objectsize: {
1790 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001791 ConstantInt *RetVal =
1792 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001793 // Substituting this can cause recursive simplifications, which can
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001794 // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
1795 // this
Sanjoy Das2cbeb002017-04-26 16:37:05 +00001796 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001797 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00001798 WeakTrackingVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001799
Sanjay Patel545a4562016-01-20 18:59:16 +00001800 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001801
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001802 // If the iterator instruction was recursively deleted, start over at the
1803 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001804 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001805 CurInstIterator = BB->begin();
1806 SunkAddrs.clear();
1807 }
1808 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001809 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001810 case Intrinsic::aarch64_stlxr:
1811 case Intrinsic::aarch64_stxr: {
1812 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1813 if (!ExtVal || !ExtVal->hasOneUse() ||
1814 ExtVal->getParent() == CI->getParent())
1815 return false;
1816 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1817 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001818 // Mark this instruction as "inserted by CGP", so that other
1819 // optimizations don't touch it.
1820 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001821 return true;
1822 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001823 case Intrinsic::invariant_group_barrier:
1824 II->replaceAllUsesWith(II->getArgOperand(0));
1825 II->eraseFromParent();
1826 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001827
1828 case Intrinsic::cttz:
1829 case Intrinsic::ctlz:
1830 // If counting zeros is expensive, try to avoid it.
1831 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001832 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001833
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001834 if (TLI) {
1835 SmallVector<Value*, 2> PtrOps;
1836 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001837 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
1838 while (!PtrOps.empty()) {
1839 Value *PtrVal = PtrOps.pop_back_val();
1840 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
1841 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001842 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00001843 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001844 }
Pete Cooper615fd892012-03-13 20:59:56 +00001845 }
1846
Eric Christopher4b7948e2010-03-11 02:41:03 +00001847 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001848 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001849
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001850 // Lower all default uses of _chk calls. This is very similar
1851 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001852 // to fortified library functions (e.g. __memcpy_chk) that have the default
1853 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001854 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001855 if (Value *V = Simplifier.optimizeCall(CI)) {
1856 CI->replaceAllUsesWith(V);
1857 CI->eraseFromParent();
1858 return true;
1859 }
Zaara Syeda3a7578c2017-05-31 17:12:38 +00001860
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001861 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001862}
Chris Lattner1b93be52011-01-15 07:25:29 +00001863
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001864/// Look for opportunities to duplicate return instructions to the predecessor
1865/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001866/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001867/// bb0:
1868/// %tmp0 = tail call i32 @f0()
1869/// br label %return
1870/// bb1:
1871/// %tmp1 = tail call i32 @f1()
1872/// br label %return
1873/// bb2:
1874/// %tmp2 = tail call i32 @f2()
1875/// br label %return
1876/// return:
1877/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1878/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001879/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001880///
1881/// =>
1882///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001883/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001884/// bb0:
1885/// %tmp0 = tail call i32 @f0()
1886/// ret i32 %tmp0
1887/// bb1:
1888/// %tmp1 = tail call i32 @f1()
1889/// ret i32 %tmp1
1890/// bb2:
1891/// %tmp2 = tail call i32 @f2()
1892/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001893/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001894bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001895 if (!TLI)
1896 return false;
1897
Michael Kuperstein71321562016-09-07 20:29:49 +00001898 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1899 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001900 return false;
1901
Craig Topperc0196b12014-04-14 00:51:57 +00001902 PHINode *PN = nullptr;
1903 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00001904 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001905 if (V) {
1906 BCI = dyn_cast<BitCastInst>(V);
1907 if (BCI)
1908 V = BCI->getOperand(0);
1909
1910 PN = dyn_cast<PHINode>(V);
1911 if (!PN)
1912 return false;
1913 }
Evan Cheng0663f232011-03-21 01:19:09 +00001914
Cameron Zwarich4649f172011-03-24 04:52:10 +00001915 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001916 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001917
Cameron Zwarich4649f172011-03-24 04:52:10 +00001918 // Make sure there are no instructions between the PHI and return, or that the
1919 // return is the first instruction in the block.
1920 if (PN) {
1921 BasicBlock::iterator BI = BB->begin();
1922 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001923 if (&*BI == BCI)
1924 // Also skip over the bitcast.
1925 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001926 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001927 return false;
1928 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001929 BasicBlock::iterator BI = BB->begin();
1930 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00001931 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001932 return false;
1933 }
Evan Cheng0663f232011-03-21 01:19:09 +00001934
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001935 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1936 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001937 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001938 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001939 if (PN) {
1940 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1941 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1942 // Make sure the phi value is indeed produced by the tail call.
1943 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001944 TLI->mayBeEmittedAsTailCall(CI) &&
1945 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001946 TailCalls.push_back(CI);
1947 }
1948 } else {
1949 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001950 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001951 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001952 continue;
1953
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001954 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001955 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1956 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001957 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1958 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001959 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001960
Cameron Zwarich4649f172011-03-24 04:52:10 +00001961 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00001962 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
1963 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001964 TailCalls.push_back(CI);
1965 }
Evan Cheng0663f232011-03-21 01:19:09 +00001966 }
1967
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001968 bool Changed = false;
1969 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1970 CallInst *CI = TailCalls[i];
1971 CallSite CS(CI);
1972
1973 // Conservatively require the attributes of the call to match those of the
1974 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00001975 AttributeList CalleeAttrs = CS.getAttributes();
1976 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1977 .removeAttribute(Attribute::NoAlias) !=
1978 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
1979 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001980 continue;
1981
1982 // Make sure the call instruction is followed by an unconditional branch to
1983 // the return block.
1984 BasicBlock *CallBB = CI->getParent();
1985 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1986 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1987 continue;
1988
1989 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00001990 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001991 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001992 ++NumRetsDup;
1993 }
1994
1995 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001996 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001997 BB->eraseFromParent();
1998
1999 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002000}
2001
Chris Lattner728f9022008-11-25 07:09:13 +00002002//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002003// Memory Optimization
2004//===----------------------------------------------------------------------===//
2005
Chandler Carruthc8925912013-01-05 02:09:22 +00002006namespace {
2007
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002008/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002009/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002010struct ExtAddrMode : public TargetLowering::AddrMode {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002011 Value *BaseReg = nullptr;
2012 Value *ScaledReg = nullptr;
John Brawn736bf002017-10-03 13:08:22 +00002013 Value *OriginalValue = nullptr;
2014
2015 enum FieldName {
2016 NoField = 0x00,
2017 BaseRegField = 0x01,
2018 BaseGVField = 0x02,
2019 BaseOffsField = 0x04,
2020 ScaledRegField = 0x08,
2021 ScaleField = 0x10,
2022 MultipleFields = 0xff
2023 };
Eugene Zelenko900b6332017-08-29 22:32:07 +00002024
2025 ExtAddrMode() = default;
2026
Chandler Carruthc8925912013-01-05 02:09:22 +00002027 void print(raw_ostream &OS) const;
2028 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002029
John Brawn736bf002017-10-03 13:08:22 +00002030 FieldName compare(const ExtAddrMode &other) {
2031 // First check that the types are the same on each field, as differing types
2032 // is something we can't cope with later on.
2033 if (BaseReg && other.BaseReg &&
2034 BaseReg->getType() != other.BaseReg->getType())
2035 return MultipleFields;
2036 if (BaseGV && other.BaseGV &&
2037 BaseGV->getType() != other.BaseGV->getType())
2038 return MultipleFields;
2039 if (ScaledReg && other.ScaledReg &&
2040 ScaledReg->getType() != other.ScaledReg->getType())
2041 return MultipleFields;
2042
2043 // Check each field to see if it differs.
2044 unsigned Result = NoField;
2045 if (BaseReg != other.BaseReg)
2046 Result |= BaseRegField;
2047 if (BaseGV != other.BaseGV)
2048 Result |= BaseGVField;
2049 if (BaseOffs != other.BaseOffs)
2050 Result |= BaseOffsField;
2051 if (ScaledReg != other.ScaledReg)
2052 Result |= ScaledRegField;
2053 // Don't count 0 as being a different scale, because that actually means
2054 // unscaled (which will already be counted by having no ScaledReg).
2055 if (Scale && other.Scale && Scale != other.Scale)
2056 Result |= ScaleField;
2057
2058 if (countPopulation(Result) > 1)
2059 return MultipleFields;
2060 else
2061 return static_cast<FieldName>(Result);
2062 }
2063
Serguei Katkovf66a59e2017-10-31 07:01:35 +00002064 // AddrModes with a baseReg or gv where the reg/gv is
2065 // the only populated field are trivial.
John Brawn736bf002017-10-03 13:08:22 +00002066 bool isTrivial() {
Serguei Katkovf66a59e2017-10-31 07:01:35 +00002067 if (BaseGV && !BaseOffs && !Scale && !BaseReg)
2068 return true;
2069
2070 if (!BaseGV && !BaseOffs && !Scale && BaseReg)
2071 return true;
2072
2073 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002074 }
2075};
2076
Eugene Zelenko900b6332017-08-29 22:32:07 +00002077} // end anonymous namespace
2078
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002079#ifndef NDEBUG
2080static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2081 AM.print(OS);
2082 return OS;
2083}
2084#endif
2085
Aaron Ballman615eb472017-10-15 14:32:27 +00002086#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chandler Carruthc8925912013-01-05 02:09:22 +00002087void ExtAddrMode::print(raw_ostream &OS) const {
2088 bool NeedPlus = false;
2089 OS << "[";
2090 if (BaseGV) {
2091 OS << (NeedPlus ? " + " : "")
2092 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002093 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002094 NeedPlus = true;
2095 }
2096
Richard Trieuc0f91212014-05-30 03:15:17 +00002097 if (BaseOffs) {
2098 OS << (NeedPlus ? " + " : "")
2099 << BaseOffs;
2100 NeedPlus = true;
2101 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002102
2103 if (BaseReg) {
2104 OS << (NeedPlus ? " + " : "")
2105 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002106 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002107 NeedPlus = true;
2108 }
2109 if (Scale) {
2110 OS << (NeedPlus ? " + " : "")
2111 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002112 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002113 }
2114
2115 OS << ']';
2116}
2117
Yaron Kereneb2a2542016-01-29 20:50:44 +00002118LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002119 print(dbgs());
2120 dbgs() << '\n';
2121}
2122#endif
2123
Eugene Zelenko900b6332017-08-29 22:32:07 +00002124namespace {
2125
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002126/// \brief This class provides transaction based operation on the IR.
2127/// Every change made through this class is recorded in the internal state and
2128/// can be undone (rollback) until commit is called.
2129class TypePromotionTransaction {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002130 /// \brief This represents the common interface of the individual transaction.
2131 /// Each class implements the logic for doing one specific modification on
2132 /// the IR via the TypePromotionTransaction.
2133 class TypePromotionAction {
2134 protected:
2135 /// The Instruction modified.
2136 Instruction *Inst;
2137
2138 public:
2139 /// \brief Constructor of the action.
2140 /// The constructor performs the related action on the IR.
2141 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2142
Eugene Zelenko900b6332017-08-29 22:32:07 +00002143 virtual ~TypePromotionAction() = default;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002144
2145 /// \brief Undo the modification done by this action.
2146 /// When this method is called, the IR must be in the same state as it was
2147 /// before this action was applied.
2148 /// \pre Undoing the action works if and only if the IR is in the exact same
2149 /// state as it was directly after this action was applied.
2150 virtual void undo() = 0;
2151
2152 /// \brief Advocate every change made by this action.
2153 /// When the results on the IR of the action are to be kept, it is important
2154 /// to call this function, otherwise hidden information may be kept forever.
2155 virtual void commit() {
2156 // Nothing to be done, this action is not doing anything.
2157 }
2158 };
2159
2160 /// \brief Utility to remember the position of an instruction.
2161 class InsertionHandler {
2162 /// Position of an instruction.
2163 /// Either an instruction:
2164 /// - Is the first in a basic block: BB is used.
2165 /// - Has a previous instructon: PrevInst is used.
2166 union {
2167 Instruction *PrevInst;
2168 BasicBlock *BB;
2169 } Point;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002170
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002171 /// Remember whether or not the instruction had a previous instruction.
2172 bool HasPrevInstruction;
2173
2174 public:
2175 /// \brief Record the position of \p Inst.
2176 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002177 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002178 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2179 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002180 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002181 else
2182 Point.BB = Inst->getParent();
2183 }
2184
2185 /// \brief Insert \p Inst at the recorded position.
2186 void insert(Instruction *Inst) {
2187 if (HasPrevInstruction) {
2188 if (Inst->getParent())
2189 Inst->removeFromParent();
2190 Inst->insertAfter(Point.PrevInst);
2191 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002192 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002193 if (Inst->getParent())
2194 Inst->moveBefore(Position);
2195 else
2196 Inst->insertBefore(Position);
2197 }
2198 }
2199 };
2200
2201 /// \brief Move an instruction before another.
2202 class InstructionMoveBefore : public TypePromotionAction {
2203 /// Original position of the instruction.
2204 InsertionHandler Position;
2205
2206 public:
2207 /// \brief Move \p Inst before \p Before.
2208 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2209 : TypePromotionAction(Inst), Position(Inst) {
2210 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2211 Inst->moveBefore(Before);
2212 }
2213
2214 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002215 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002216 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2217 Position.insert(Inst);
2218 }
2219 };
2220
2221 /// \brief Set the operand of an instruction with a new value.
2222 class OperandSetter : public TypePromotionAction {
2223 /// Original operand of the instruction.
2224 Value *Origin;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002225
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002226 /// Index of the modified instruction.
2227 unsigned Idx;
2228
2229 public:
2230 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2231 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2232 : TypePromotionAction(Inst), Idx(Idx) {
2233 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2234 << "for:" << *Inst << "\n"
2235 << "with:" << *NewVal << "\n");
2236 Origin = Inst->getOperand(Idx);
2237 Inst->setOperand(Idx, NewVal);
2238 }
2239
2240 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002241 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002242 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2243 << "for: " << *Inst << "\n"
2244 << "with: " << *Origin << "\n");
2245 Inst->setOperand(Idx, Origin);
2246 }
2247 };
2248
2249 /// \brief Hide the operands of an instruction.
2250 /// Do as if this instruction was not using any of its operands.
2251 class OperandsHider : public TypePromotionAction {
2252 /// The list of original operands.
2253 SmallVector<Value *, 4> OriginalValues;
2254
2255 public:
2256 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2257 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2258 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2259 unsigned NumOpnds = Inst->getNumOperands();
2260 OriginalValues.reserve(NumOpnds);
2261 for (unsigned It = 0; It < NumOpnds; ++It) {
2262 // Save the current operand.
2263 Value *Val = Inst->getOperand(It);
2264 OriginalValues.push_back(Val);
2265 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002266 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002267 // that we are not willing to pay.
2268 Inst->setOperand(It, UndefValue::get(Val->getType()));
2269 }
2270 }
2271
2272 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002273 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002274 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2275 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2276 Inst->setOperand(It, OriginalValues[It]);
2277 }
2278 };
2279
2280 /// \brief Build a truncate instruction.
2281 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002282 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002283
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284 public:
2285 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2286 /// result.
2287 /// trunc Opnd to Ty.
2288 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2289 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002290 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2291 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002292 }
2293
Quentin Colombetac55b152014-09-16 22:36:07 +00002294 /// \brief Get the built value.
2295 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002296
2297 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002298 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002299 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2300 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2301 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002302 }
2303 };
2304
2305 /// \brief Build a sign extension instruction.
2306 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002307 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002308
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002309 public:
2310 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2311 /// result.
2312 /// sext Opnd to Ty.
2313 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002314 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002315 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002316 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2317 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002318 }
2319
Quentin Colombetac55b152014-09-16 22:36:07 +00002320 /// \brief Get the built value.
2321 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322
2323 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002324 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002325 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2326 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2327 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002328 }
2329 };
2330
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002331 /// \brief Build a zero extension instruction.
2332 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002333 Value *Val;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002334
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002335 public:
2336 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2337 /// result.
2338 /// zext Opnd to Ty.
2339 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002340 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002341 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002342 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2343 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002344 }
2345
Quentin Colombetac55b152014-09-16 22:36:07 +00002346 /// \brief Get the built value.
2347 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002348
2349 /// \brief Remove the built instruction.
2350 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002351 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2352 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2353 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002354 }
2355 };
2356
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002357 /// \brief Mutate an instruction to another type.
2358 class TypeMutator : public TypePromotionAction {
2359 /// Record the original type.
2360 Type *OrigTy;
2361
2362 public:
2363 /// \brief Mutate the type of \p Inst into \p NewTy.
2364 TypeMutator(Instruction *Inst, Type *NewTy)
2365 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2366 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2367 << "\n");
2368 Inst->mutateType(NewTy);
2369 }
2370
2371 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002372 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002373 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2374 << "\n");
2375 Inst->mutateType(OrigTy);
2376 }
2377 };
2378
2379 /// \brief Replace the uses of an instruction by another instruction.
2380 class UsesReplacer : public TypePromotionAction {
2381 /// Helper structure to keep track of the replaced uses.
2382 struct InstructionAndIdx {
2383 /// The instruction using the instruction.
2384 Instruction *Inst;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002385
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002386 /// The index where this instruction is used for Inst.
2387 unsigned Idx;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002388
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002389 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2390 : Inst(Inst), Idx(Idx) {}
2391 };
2392
2393 /// Keep track of the original uses (pair Instruction, Index).
2394 SmallVector<InstructionAndIdx, 4> OriginalUses;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002395
2396 using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002397
2398 public:
2399 /// \brief Replace all the use of \p Inst by \p New.
2400 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2401 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2402 << "\n");
2403 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002404 for (Use &U : Inst->uses()) {
2405 Instruction *UserI = cast<Instruction>(U.getUser());
2406 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002407 }
2408 // Now, we can replace the uses.
2409 Inst->replaceAllUsesWith(New);
2410 }
2411
2412 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002413 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002414 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2415 for (use_iterator UseIt = OriginalUses.begin(),
2416 EndIt = OriginalUses.end();
2417 UseIt != EndIt; ++UseIt) {
2418 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2419 }
2420 }
2421 };
2422
2423 /// \brief Remove an instruction from the IR.
2424 class InstructionRemover : public TypePromotionAction {
2425 /// Original position of the instruction.
2426 InsertionHandler Inserter;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002427
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002428 /// Helper structure to hide all the link to the instruction. In other
2429 /// words, this helps to do as if the instruction was removed.
2430 OperandsHider Hider;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002431
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002432 /// Keep track of the uses replaced, if any.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002433 UsesReplacer *Replacer = nullptr;
2434
Jun Bum Limdee55652017-04-03 19:20:07 +00002435 /// Keep track of instructions removed.
2436 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002437
2438 public:
2439 /// \brief Remove all reference of \p Inst and optinally replace all its
2440 /// uses with New.
Jun Bum Limdee55652017-04-03 19:20:07 +00002441 /// \p RemovedInsts Keep track of the instructions removed by this Action.
Craig Topperc0196b12014-04-14 00:51:57 +00002442 /// \pre If !Inst->use_empty(), then New != nullptr
Jun Bum Limdee55652017-04-03 19:20:07 +00002443 InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
2444 Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Eugene Zelenko900b6332017-08-29 22:32:07 +00002446 RemovedInsts(RemovedInsts) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002447 if (New)
2448 Replacer = new UsesReplacer(Inst, New);
2449 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
Jun Bum Limdee55652017-04-03 19:20:07 +00002450 RemovedInsts.insert(Inst);
2451 /// The instructions removed here will be freed after completing
2452 /// optimizeBlock() for all blocks as we need to keep track of the
2453 /// removed instructions during promotion.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002454 Inst->removeFromParent();
2455 }
2456
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002457 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002458
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459 /// \brief Resurrect the instruction and reassign it to the proper uses if
2460 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002461 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002462 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2463 Inserter.insert(Inst);
2464 if (Replacer)
2465 Replacer->undo();
2466 Hider.undo();
Jun Bum Limdee55652017-04-03 19:20:07 +00002467 RemovedInsts.erase(Inst);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002468 }
2469 };
2470
2471public:
2472 /// Restoration point.
2473 /// The restoration point is a pointer to an action instead of an iterator
2474 /// because the iterator may be invalidated but not the pointer.
Eugene Zelenko900b6332017-08-29 22:32:07 +00002475 using ConstRestorationPt = const TypePromotionAction *;
Jun Bum Limdee55652017-04-03 19:20:07 +00002476
2477 TypePromotionTransaction(SetOfInstrs &RemovedInsts)
2478 : RemovedInsts(RemovedInsts) {}
2479
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002480 /// Advocate every changes made in that transaction.
2481 void commit();
Eugene Zelenko900b6332017-08-29 22:32:07 +00002482
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002483 /// Undo all the changes made after the given point.
2484 void rollback(ConstRestorationPt Point);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002485
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002486 /// Get the current restoration point.
2487 ConstRestorationPt getRestorationPoint() const;
2488
2489 /// \name API for IR modification with state keeping to support rollback.
2490 /// @{
2491 /// Same as Instruction::setOperand.
2492 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002493
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002494 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002495 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002496
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497 /// Same as Value::replaceAllUsesWith.
2498 void replaceAllUsesWith(Instruction *Inst, Value *New);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002499
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002500 /// Same as Value::mutateType.
2501 void mutateType(Instruction *Inst, Type *NewTy);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002502
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002503 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002504 Value *createTrunc(Instruction *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002505
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002506 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002507 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002508
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002509 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002510 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Eugene Zelenko900b6332017-08-29 22:32:07 +00002511
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002512 /// Same as Instruction::moveBefore.
2513 void moveBefore(Instruction *Inst, Instruction *Before);
2514 /// @}
2515
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002516private:
2517 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002518 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002519
2520 using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
2521
Jun Bum Limdee55652017-04-03 19:20:07 +00002522 SetOfInstrs &RemovedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002523};
2524
Eugene Zelenko900b6332017-08-29 22:32:07 +00002525} // end anonymous namespace
2526
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002527void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2528 Value *NewVal) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002529 Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
2530 Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002531}
2532
2533void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2534 Value *NewVal) {
2535 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002536 llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
2537 Inst, RemovedInsts, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002538}
2539
2540void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2541 Value *New) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002542 Actions.push_back(
2543 llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002544}
2545
2546void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00002547 Actions.push_back(
2548 llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002549}
2550
Quentin Colombetac55b152014-09-16 22:36:07 +00002551Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2552 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002553 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002554 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002555 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002556 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002557}
2558
Quentin Colombetac55b152014-09-16 22:36:07 +00002559Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2560 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002561 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002562 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002563 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002564 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002565}
2566
Quentin Colombetac55b152014-09-16 22:36:07 +00002567Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2568 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002569 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002570 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002571 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002572 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002573}
2574
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002575void TypePromotionTransaction::moveBefore(Instruction *Inst,
2576 Instruction *Before) {
2577 Actions.push_back(
Eugene Zelenko900b6332017-08-29 22:32:07 +00002578 llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
2579 Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002580}
2581
2582TypePromotionTransaction::ConstRestorationPt
2583TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002584 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002585}
2586
2587void TypePromotionTransaction::commit() {
2588 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002589 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002590 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002591 Actions.clear();
2592}
2593
2594void TypePromotionTransaction::rollback(
2595 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002596 while (!Actions.empty() && Point != Actions.back().get()) {
2597 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002598 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599 }
2600}
2601
Eugene Zelenko900b6332017-08-29 22:32:07 +00002602namespace {
2603
Chandler Carruthc8925912013-01-05 02:09:22 +00002604/// \brief A helper class for matching addressing modes.
2605///
2606/// This encapsulates the logic for matching the target-legal addressing modes.
2607class AddressingModeMatcher {
2608 SmallVectorImpl<Instruction*> &AddrModeInsts;
2609 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002610 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002611 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002612
2613 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2614 /// the memory instruction that we're computing this address for.
2615 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002616 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002617 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002618
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002619 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002620 /// part of the return value of this addressing mode matching stuff.
2621 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002622
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002623 /// The instructions inserted by other CodeGenPrepare optimizations.
2624 const SetOfInstrs &InsertedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002625
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002626 /// A map from the instructions to their type before promotion.
2627 InstrToOrigTy &PromotedInsts;
Eugene Zelenko900b6332017-08-29 22:32:07 +00002628
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002629 /// The ongoing transaction where every action should be registered.
2630 TypePromotionTransaction &TPT;
2631
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002632 /// This is set to true when we should not do profitability checks.
2633 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002634 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002635
Eric Christopherd75c00c2015-02-26 22:38:34 +00002636 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002637 const TargetLowering &TLI,
2638 const TargetRegisterInfo &TRI,
2639 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002640 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002641 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002642 InstrToOrigTy &PromotedInsts,
2643 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002644 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002645 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2646 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2647 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002648 IgnoreProfitability = false;
2649 }
Stephen Lin837bba12013-07-15 17:55:02 +00002650
Eugene Zelenko900b6332017-08-29 22:32:07 +00002651public:
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002652 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002653 /// give an access type of AccessTy. This returns a list of involved
2654 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002655 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002656 /// optimizations.
2657 /// \p PromotedInsts maps the instructions to their type before promotion.
2658 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002659 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002660 Instruction *MemoryInst,
2661 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002662 const TargetLowering &TLI,
2663 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002664 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002665 InstrToOrigTy &PromotedInsts,
2666 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002667 ExtAddrMode Result;
2668
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002669 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2670 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002671 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002672 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002673 (void)Success; assert(Success && "Couldn't select *anything*?");
2674 return Result;
2675 }
Eugene Zelenko900b6332017-08-29 22:32:07 +00002676
Chandler Carruthc8925912013-01-05 02:09:22 +00002677private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002678 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2679 bool matchAddr(Value *V, unsigned Depth);
2680 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002681 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002682 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002683 ExtAddrMode &AMBefore,
2684 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002685 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2686 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002687 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002688};
2689
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002690/// \brief Keep track of simplification of Phi nodes.
2691/// Accept the set of all phi nodes and erase phi node from this set
2692/// if it is simplified.
2693class SimplificationTracker {
2694 DenseMap<Value *, Value *> Storage;
2695 const SimplifyQuery &SQ;
2696 SmallPtrSetImpl<PHINode *> &AllPhiNodes;
2697 SmallPtrSetImpl<SelectInst *> &AllSelectNodes;
2698
2699public:
2700 SimplificationTracker(const SimplifyQuery &sq,
2701 SmallPtrSetImpl<PHINode *> &APN,
2702 SmallPtrSetImpl<SelectInst *> &ASN)
2703 : SQ(sq), AllPhiNodes(APN), AllSelectNodes(ASN) {}
2704
2705 Value *Get(Value *V) {
2706 do {
2707 auto SV = Storage.find(V);
2708 if (SV == Storage.end())
2709 return V;
2710 V = SV->second;
2711 } while (true);
2712 }
2713
2714 Value *Simplify(Value *Val) {
2715 SmallVector<Value *, 32> WorkList;
2716 SmallPtrSet<Value *, 32> Visited;
2717 WorkList.push_back(Val);
2718 while (!WorkList.empty()) {
2719 auto P = WorkList.pop_back_val();
2720 if (!Visited.insert(P).second)
2721 continue;
2722 if (auto *PI = dyn_cast<Instruction>(P))
2723 if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
2724 for (auto *U : PI->users())
2725 WorkList.push_back(cast<Value>(U));
2726 Put(PI, V);
2727 PI->replaceAllUsesWith(V);
2728 if (auto *PHI = dyn_cast<PHINode>(PI))
2729 AllPhiNodes.erase(PHI);
2730 if (auto *Select = dyn_cast<SelectInst>(PI))
2731 AllSelectNodes.erase(Select);
2732 PI->eraseFromParent();
2733 }
2734 }
2735 return Get(Val);
2736 }
2737
2738 void Put(Value *From, Value *To) {
2739 Storage.insert({ From, To });
2740 }
2741};
2742
John Brawn736bf002017-10-03 13:08:22 +00002743/// \brief A helper class for combining addressing modes.
2744class AddressingModeCombiner {
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002745 typedef std::pair<Value *, BasicBlock *> ValueInBB;
2746 typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
2747 typedef std::pair<PHINode *, PHINode *> PHIPair;
2748
John Brawn736bf002017-10-03 13:08:22 +00002749private:
2750 /// The addressing modes we've collected.
2751 SmallVector<ExtAddrMode, 16> AddrModes;
2752
2753 /// The field in which the AddrModes differ, when we have more than one.
2754 ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
2755
2756 /// Are the AddrModes that we have all just equal to their original values?
2757 bool AllAddrModesTrivial = true;
2758
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002759 /// Common Type for all different fields in addressing modes.
2760 Type *CommonType;
2761
2762 /// SimplifyQuery for simplifyInstruction utility.
2763 const SimplifyQuery &SQ;
2764
2765 /// Original Address.
2766 ValueInBB Original;
2767
John Brawn736bf002017-10-03 13:08:22 +00002768public:
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002769 AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
2770 : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
2771
John Brawn736bf002017-10-03 13:08:22 +00002772 /// \brief Get the combined AddrMode
2773 const ExtAddrMode &getAddrMode() const {
2774 return AddrModes[0];
2775 }
2776
2777 /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
2778 /// have.
2779 /// \return True iff we succeeded in doing so.
2780 bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
2781 // Take note of if we have any non-trivial AddrModes, as we need to detect
2782 // when all AddrModes are trivial as then we would introduce a phi or select
2783 // which just duplicates what's already there.
2784 AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
2785
2786 // If this is the first addrmode then everything is fine.
2787 if (AddrModes.empty()) {
2788 AddrModes.emplace_back(NewAddrMode);
2789 return true;
2790 }
2791
2792 // Figure out how different this is from the other address modes, which we
2793 // can do just by comparing against the first one given that we only care
2794 // about the cumulative difference.
2795 ExtAddrMode::FieldName ThisDifferentField =
2796 AddrModes[0].compare(NewAddrMode);
2797 if (DifferentField == ExtAddrMode::NoField)
2798 DifferentField = ThisDifferentField;
2799 else if (DifferentField != ThisDifferentField)
2800 DifferentField = ExtAddrMode::MultipleFields;
2801
2802 // If this AddrMode is the same as all the others then everything is fine
2803 // (which should only happen when there is actually only one AddrMode).
2804 if (DifferentField == ExtAddrMode::NoField) {
2805 assert(AddrModes.size() == 1);
2806 return true;
2807 }
2808
2809 // If NewAddrMode differs in only one dimension then we can handle it by
2810 // inserting a phi/select later on.
2811 if (DifferentField != ExtAddrMode::MultipleFields) {
2812 AddrModes.emplace_back(NewAddrMode);
2813 return true;
2814 }
2815
2816 // We couldn't combine NewAddrMode with the rest, so return failure.
2817 AddrModes.clear();
2818 return false;
2819 }
2820
2821 /// \brief Combine the addressing modes we've collected into a single
2822 /// addressing mode.
2823 /// \return True iff we successfully combined them or we only had one so
2824 /// didn't need to combine them anyway.
2825 bool combineAddrModes() {
2826 // If we have no AddrModes then they can't be combined.
2827 if (AddrModes.size() == 0)
2828 return false;
2829
2830 // A single AddrMode can trivially be combined.
2831 if (AddrModes.size() == 1)
2832 return true;
2833
2834 // If the AddrModes we collected are all just equal to the value they are
2835 // derived from then combining them wouldn't do anything useful.
2836 if (AllAddrModesTrivial)
2837 return false;
2838
Serguei Katkovd5d8d542017-11-05 05:50:33 +00002839 if (DisableComplexAddrModes)
2840 return false;
2841
2842 // For now we support only different base registers.
2843 // TODO: enable others.
2844 if (DifferentField != ExtAddrMode::BaseRegField)
2845 return false;
2846
2847 // Build a map between <original value, basic block where we saw it> to
2848 // value of base register.
2849 FoldAddrToValueMapping Map;
2850 initializeMap(Map);
2851
2852 Value *CommonValue = findCommon(Map);
2853 if (CommonValue)
2854 AddrModes[0].BaseReg = CommonValue;
2855 return CommonValue != nullptr;
2856 }
2857
2858private:
2859 /// \brief Initialize Map with anchor values. For address seen in some BB
2860 /// we set the value of different field saw in this address.
2861 /// If address is not an instruction than basic block is set to null.
2862 /// At the same time we find a common type for different field we will
2863 /// use to create new Phi/Select nodes. Keep it in CommonType field.
2864 void initializeMap(FoldAddrToValueMapping &Map) {
2865 // Keep track of keys where the value is null. We will need to replace it
2866 // with constant null when we know the common type.
2867 SmallVector<ValueInBB, 2> NullValue;
2868 for (auto &AM : AddrModes) {
2869 BasicBlock *BB = nullptr;
2870 if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
2871 BB = I->getParent();
2872
2873 // For now we support only base register as different field.
2874 // TODO: Enable others.
2875 Value *DV = AM.BaseReg;
2876 if (DV) {
2877 if (CommonType)
2878 assert(CommonType == DV->getType() && "Different types detected!");
2879 else
2880 CommonType = DV->getType();
2881 Map[{ AM.OriginalValue, BB }] = DV;
2882 } else {
2883 NullValue.push_back({ AM.OriginalValue, BB });
2884 }
2885 }
2886 assert(CommonType && "At least one non-null value must be!");
2887 for (auto VIBB : NullValue)
2888 Map[VIBB] = Constant::getNullValue(CommonType);
2889 }
2890
2891 /// \brief We have mapping between value A and basic block where value A
2892 /// seen to other value B where B was a field in addressing mode represented
2893 /// by A. Also we have an original value C representin an address in some
2894 /// basic block. Traversing from C through phi and selects we ended up with
2895 /// A's in a map. This utility function tries to find a value V which is a
2896 /// field in addressing mode C and traversing through phi nodes and selects
2897 /// we will end up in corresponded values B in a map.
2898 /// The utility will create a new Phi/Selects if needed.
2899 // The simple example looks as follows:
2900 // BB1:
2901 // p1 = b1 + 40
2902 // br cond BB2, BB3
2903 // BB2:
2904 // p2 = b2 + 40
2905 // br BB3
2906 // BB3:
2907 // p = phi [p1, BB1], [p2, BB2]
2908 // v = load p
2909 // Map is
2910 // <p1, BB1> -> b1
2911 // <p2, BB2> -> b2
2912 // Request is
2913 // <p, BB3> -> ?
2914 // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
2915 Value *findCommon(FoldAddrToValueMapping &Map) {
2916 // Tracks of new created Phi nodes.
2917 SmallPtrSet<PHINode *, 32> NewPhiNodes;
2918 // Tracks of new created Select nodes.
2919 SmallPtrSet<SelectInst *, 32> NewSelectNodes;
2920 // Tracks the simplification of new created phi nodes. The reason we use
2921 // this mapping is because we will add new created Phi nodes in AddrToBase.
2922 // Simplification of Phi nodes is recursive, so some Phi node may
2923 // be simplified after we added it to AddrToBase.
2924 // Using this mapping we can find the current value in AddrToBase.
2925 SimplificationTracker ST(SQ, NewPhiNodes, NewSelectNodes);
2926
2927 // First step, DFS to create PHI nodes for all intermediate blocks.
2928 // Also fill traverse order for the second step.
2929 SmallVector<ValueInBB, 32> TraverseOrder;
2930 InsertPlaceholders(Map, TraverseOrder, NewPhiNodes, NewSelectNodes);
2931
2932 // Second Step, fill new nodes by merged values and simplify if possible.
2933 FillPlaceholders(Map, TraverseOrder, ST);
2934
2935 if (!AddrSinkNewSelects && NewSelectNodes.size() > 0) {
2936 DestroyNodes(NewPhiNodes);
2937 DestroyNodes(NewSelectNodes);
2938 return nullptr;
2939 }
2940
2941 // Now we'd like to match New Phi nodes to existed ones.
2942 unsigned PhiNotMatchedCount = 0;
2943 if (!MatchPhiSet(NewPhiNodes, ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
2944 DestroyNodes(NewPhiNodes);
2945 DestroyNodes(NewSelectNodes);
2946 return nullptr;
2947 }
2948
2949 auto *Result = ST.Get(Map.find(Original)->second);
2950 if (Result) {
2951 NumMemoryInstsPhiCreated += NewPhiNodes.size() + PhiNotMatchedCount;
2952 NumMemoryInstsSelectCreated += NewSelectNodes.size();
2953 }
2954 return Result;
2955 }
2956
2957 /// \brief Destroy nodes from a set.
2958 template <typename T> void DestroyNodes(SmallPtrSetImpl<T *> &Instructions) {
2959 // For safe erasing, replace the Phi with dummy value first.
2960 auto Dummy = UndefValue::get(CommonType);
2961 for (auto I : Instructions) {
2962 I->replaceAllUsesWith(Dummy);
2963 I->eraseFromParent();
2964 }
2965 }
2966
2967 /// \brief Try to match PHI node to Candidate.
2968 /// Matcher tracks the matched Phi nodes.
2969 bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
2970 DenseSet<PHIPair> &Matcher,
2971 SmallPtrSetImpl<PHINode *> &PhiNodesToMatch) {
2972 SmallVector<PHIPair, 8> WorkList;
2973 Matcher.insert({ PHI, Candidate });
2974 WorkList.push_back({ PHI, Candidate });
2975 SmallSet<PHIPair, 8> Visited;
2976 while (!WorkList.empty()) {
2977 auto Item = WorkList.pop_back_val();
2978 if (!Visited.insert(Item).second)
2979 continue;
2980 // We iterate over all incoming values to Phi to compare them.
2981 // If values are different and both of them Phi and the first one is a
2982 // Phi we added (subject to match) and both of them is in the same basic
2983 // block then we can match our pair if values match. So we state that
2984 // these values match and add it to work list to verify that.
2985 for (auto B : Item.first->blocks()) {
2986 Value *FirstValue = Item.first->getIncomingValueForBlock(B);
2987 Value *SecondValue = Item.second->getIncomingValueForBlock(B);
2988 if (FirstValue == SecondValue)
2989 continue;
2990
2991 PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
2992 PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
2993
2994 // One of them is not Phi or
2995 // The first one is not Phi node from the set we'd like to match or
2996 // Phi nodes from different basic blocks then
2997 // we will not be able to match.
2998 if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
2999 FirstPhi->getParent() != SecondPhi->getParent())
3000 return false;
3001
3002 // If we already matched them then continue.
3003 if (Matcher.count({ FirstPhi, SecondPhi }))
3004 continue;
3005 // So the values are different and does not match. So we need them to
3006 // match.
3007 Matcher.insert({ FirstPhi, SecondPhi });
3008 // But me must check it.
3009 WorkList.push_back({ FirstPhi, SecondPhi });
3010 }
3011 }
3012 return true;
3013 }
3014
3015 /// \brief For the given set of PHI nodes try to find their equivalents.
3016 /// Returns false if this matching fails and creation of new Phi is disabled.
3017 bool MatchPhiSet(SmallPtrSetImpl<PHINode *> &PhiNodesToMatch,
3018 SimplificationTracker &ST, bool AllowNewPhiNodes,
3019 unsigned &PhiNotMatchedCount) {
3020 DenseSet<PHIPair> Matched;
3021 SmallPtrSet<PHINode *, 8> WillNotMatch;
3022 while (PhiNodesToMatch.size()) {
3023 PHINode *PHI = *PhiNodesToMatch.begin();
3024
3025 // Add us, if no Phi nodes in the basic block we do not match.
3026 WillNotMatch.clear();
3027 WillNotMatch.insert(PHI);
3028
3029 // Traverse all Phis until we found equivalent or fail to do that.
3030 bool IsMatched = false;
3031 for (auto &P : PHI->getParent()->phis()) {
3032 if (&P == PHI)
3033 continue;
3034 if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
3035 break;
3036 // If it does not match, collect all Phi nodes from matcher.
3037 // if we end up with no match, them all these Phi nodes will not match
3038 // later.
3039 for (auto M : Matched)
3040 WillNotMatch.insert(M.first);
3041 Matched.clear();
3042 }
3043 if (IsMatched) {
3044 // Replace all matched values and erase them.
3045 for (auto MV : Matched) {
3046 MV.first->replaceAllUsesWith(MV.second);
3047 PhiNodesToMatch.erase(MV.first);
3048 ST.Put(MV.first, MV.second);
3049 MV.first->eraseFromParent();
3050 }
3051 Matched.clear();
3052 continue;
3053 }
3054 // If we are not allowed to create new nodes then bail out.
3055 if (!AllowNewPhiNodes)
3056 return false;
3057 // Just remove all seen values in matcher. They will not match anything.
3058 PhiNotMatchedCount += WillNotMatch.size();
3059 for (auto *P : WillNotMatch)
3060 PhiNodesToMatch.erase(P);
3061 }
3062 return true;
3063 }
3064 /// \brief Fill the placeholder with values from predecessors and simplify it.
3065 void FillPlaceholders(FoldAddrToValueMapping &Map,
3066 SmallVectorImpl<ValueInBB> &TraverseOrder,
3067 SimplificationTracker &ST) {
3068 while (!TraverseOrder.empty()) {
3069 auto Current = TraverseOrder.pop_back_val();
3070 assert(Map.find(Current) != Map.end() && "No node to fill!!!");
3071 Value *CurrentValue = Current.first;
3072 BasicBlock *CurrentBlock = Current.second;
3073 Value *V = Map[Current];
3074
3075 if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
3076 // CurrentValue also must be Select.
3077 auto *CurrentSelect = cast<SelectInst>(CurrentValue);
3078 auto *TrueValue = CurrentSelect->getTrueValue();
3079 ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
3080 ? CurrentBlock
3081 : nullptr };
3082 assert(Map.find(TrueItem) != Map.end() && "No True Value!");
3083 Select->setTrueValue(Map[TrueItem]);
3084 auto *FalseValue = CurrentSelect->getFalseValue();
3085 ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
3086 ? CurrentBlock
3087 : nullptr };
3088 assert(Map.find(FalseItem) != Map.end() && "No False Value!");
3089 Select->setFalseValue(Map[FalseItem]);
3090 } else {
3091 // Must be a Phi node then.
3092 PHINode *PHI = cast<PHINode>(V);
3093 // Fill the Phi node with values from predecessors.
3094 bool IsDefinedInThisBB =
3095 cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
3096 auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
3097 for (auto B : predecessors(CurrentBlock)) {
3098 Value *PV = IsDefinedInThisBB
3099 ? CurrentPhi->getIncomingValueForBlock(B)
3100 : CurrentValue;
3101 ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
3102 assert(Map.find(item) != Map.end() && "No predecessor Value!");
3103 PHI->addIncoming(ST.Get(Map[item]), B);
3104 }
3105 }
3106 // Simplify if possible.
3107 Map[Current] = ST.Simplify(V);
3108 }
3109 }
3110
3111 /// Starting from value recursively iterates over predecessors up to known
3112 /// ending values represented in a map. For each traversed block inserts
3113 /// a placeholder Phi or Select.
3114 /// Reports all new created Phi/Select nodes by adding them to set.
3115 /// Also reports and order in what basic blocks have been traversed.
3116 void InsertPlaceholders(FoldAddrToValueMapping &Map,
3117 SmallVectorImpl<ValueInBB> &TraverseOrder,
3118 SmallPtrSetImpl<PHINode *> &NewPhiNodes,
3119 SmallPtrSetImpl<SelectInst *> &NewSelectNodes) {
3120 SmallVector<ValueInBB, 32> Worklist;
3121 assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
3122 "Address must be a Phi or Select node");
3123 auto *Dummy = UndefValue::get(CommonType);
3124 Worklist.push_back(Original);
3125 while (!Worklist.empty()) {
3126 auto Current = Worklist.pop_back_val();
3127 // If value is not an instruction it is something global, constant,
3128 // parameter and we can say that this value is observable in any block.
3129 // Set block to null to denote it.
3130 // Also please take into account that it is how we build anchors.
3131 if (!isa<Instruction>(Current.first))
3132 Current.second = nullptr;
3133 // if it is already visited or it is an ending value then skip it.
3134 if (Map.find(Current) != Map.end())
3135 continue;
3136 TraverseOrder.push_back(Current);
3137
3138 Value *CurrentValue = Current.first;
3139 BasicBlock *CurrentBlock = Current.second;
3140 // CurrentValue must be a Phi node or select. All others must be covered
3141 // by anchors.
3142 Instruction *CurrentI = cast<Instruction>(CurrentValue);
3143 bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
3144
3145 unsigned PredCount =
3146 std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
3147 // if Current Value is not defined in this basic block we are interested
3148 // in values in predecessors.
3149 if (!IsDefinedInThisBB) {
3150 assert(PredCount && "Unreachable block?!");
3151 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3152 &CurrentBlock->front());
3153 Map[Current] = PHI;
3154 NewPhiNodes.insert(PHI);
3155 // Add all predecessors in work list.
3156 for (auto B : predecessors(CurrentBlock))
3157 Worklist.push_back({ CurrentValue, B });
3158 continue;
3159 }
3160 // Value is defined in this basic block.
3161 if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
3162 // Is it OK to get metadata from OrigSelect?!
3163 // Create a Select placeholder with dummy value.
3164 SelectInst *Select =
3165 SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
3166 OrigSelect->getName(), OrigSelect, OrigSelect);
3167 Map[Current] = Select;
3168 NewSelectNodes.insert(Select);
3169 // We are interested in True and False value in this basic block.
3170 Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
3171 Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
3172 } else {
3173 // It must be a Phi node then.
3174 auto *CurrentPhi = cast<PHINode>(CurrentI);
3175 // Create new Phi node for merge of bases.
3176 assert(PredCount && "Unreachable block?!");
3177 PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
3178 &CurrentBlock->front());
3179 Map[Current] = PHI;
3180 NewPhiNodes.insert(PHI);
3181
3182 // Add all predecessors in work list.
3183 for (auto B : predecessors(CurrentBlock))
3184 Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
3185 }
3186 }
John Brawn736bf002017-10-03 13:08:22 +00003187 }
3188};
Eugene Zelenko900b6332017-08-29 22:32:07 +00003189} // end anonymous namespace
3190
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003191/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003192/// Return true and update AddrMode if this addr mode is legal for the target,
3193/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003194bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003195 unsigned Depth) {
3196 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3197 // mode. Just process that directly.
3198 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003199 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003200
Chandler Carruthc8925912013-01-05 02:09:22 +00003201 // If the scale is 0, it takes nothing to add this.
3202 if (Scale == 0)
3203 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003204
Chandler Carruthc8925912013-01-05 02:09:22 +00003205 // If we already have a scale of this value, we can add to it, otherwise, we
3206 // need an available scale field.
3207 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3208 return false;
3209
3210 ExtAddrMode TestAddrMode = AddrMode;
3211
3212 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3213 // [A+B + A*7] -> [B+A*8].
3214 TestAddrMode.Scale += Scale;
3215 TestAddrMode.ScaledReg = ScaleReg;
3216
3217 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003218 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003219 return false;
3220
3221 // It was legal, so commit it.
3222 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003223
Chandler Carruthc8925912013-01-05 02:09:22 +00003224 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3225 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3226 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003227 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003228 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3229 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3230 TestAddrMode.ScaledReg = AddLHS;
3231 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003232
Chandler Carruthc8925912013-01-05 02:09:22 +00003233 // If this addressing mode is legal, commit it and remember that we folded
3234 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003235 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003236 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3237 AddrMode = TestAddrMode;
3238 return true;
3239 }
3240 }
3241
3242 // Otherwise, not (x+c)*scale, just return what we have.
3243 return true;
3244}
3245
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003246/// This is a little filter, which returns true if an addressing computation
3247/// involving I might be folded into a load/store accessing it.
3248/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003249/// the set of instructions that MatchOperationAddr can.
3250static bool MightBeFoldableInst(Instruction *I) {
3251 switch (I->getOpcode()) {
3252 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003253 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003254 // Don't touch identity bitcasts.
3255 if (I->getType() == I->getOperand(0)->getType())
3256 return false;
3257 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3258 case Instruction::PtrToInt:
3259 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3260 return true;
3261 case Instruction::IntToPtr:
3262 // We know the input is intptr_t, so this is foldable.
3263 return true;
3264 case Instruction::Add:
3265 return true;
3266 case Instruction::Mul:
3267 case Instruction::Shl:
3268 // Can only handle X*C and X << C.
3269 return isa<ConstantInt>(I->getOperand(1));
3270 case Instruction::GetElementPtr:
3271 return true;
3272 default:
3273 return false;
3274 }
3275}
3276
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003277/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3278/// \note \p Val is assumed to be the product of some type promotion.
3279/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3280/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003281static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3282 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003283 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3284 if (!PromotedInst)
3285 return false;
3286 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3287 // If the ISDOpcode is undefined, it was undefined before the promotion.
3288 if (!ISDOpcode)
3289 return true;
3290 // Otherwise, check if the promoted instruction is legal or not.
3291 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003292 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003293}
3294
Eugene Zelenko900b6332017-08-29 22:32:07 +00003295namespace {
3296
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003297/// \brief Hepler class to perform type promotion.
3298class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003299 /// \brief Utility function to check whether or not a sign or zero extension
3300 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3301 /// either using the operands of \p Inst or promoting \p Inst.
3302 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003303 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003304 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003305 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003306 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003307 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003308 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003309 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003310 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3311 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003312
3313 /// \brief Utility function to determine if \p OpIdx should be promoted when
3314 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003315 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003316 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003317 }
3318
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003319 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003320 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003321 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003322 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003323 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003324 /// Newly added extensions are inserted in \p Exts.
3325 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003326 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003327 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003328 static Value *promoteOperandForTruncAndAnyExt(
3329 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003330 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003331 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003332 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003333
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003334 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003335 /// operand is promotable and is not a supported trunc or sext.
3336 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003337 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003338 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003339 /// Newly added extensions are inserted in \p Exts.
3340 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003341 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003342 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003343 static Value *promoteOperandForOther(Instruction *Ext,
3344 TypePromotionTransaction &TPT,
3345 InstrToOrigTy &PromotedInsts,
3346 unsigned &CreatedInstsCost,
3347 SmallVectorImpl<Instruction *> *Exts,
3348 SmallVectorImpl<Instruction *> *Truncs,
3349 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003350
3351 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003352 static Value *signExtendOperandForOther(
3353 Instruction *Ext, TypePromotionTransaction &TPT,
3354 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3355 SmallVectorImpl<Instruction *> *Exts,
3356 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3357 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3358 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003359 }
3360
3361 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003362 static Value *zeroExtendOperandForOther(
3363 Instruction *Ext, TypePromotionTransaction &TPT,
3364 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3365 SmallVectorImpl<Instruction *> *Exts,
3366 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3367 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3368 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003369 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003370
3371public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003372 /// Type for the utility function that promotes the operand of Ext.
Eugene Zelenko900b6332017-08-29 22:32:07 +00003373 using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
3374 InstrToOrigTy &PromotedInsts,
3375 unsigned &CreatedInstsCost,
3376 SmallVectorImpl<Instruction *> *Exts,
3377 SmallVectorImpl<Instruction *> *Truncs,
3378 const TargetLowering &TLI);
3379
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003380 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3381 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003382 /// \return NULL if no promotable action is possible with the current
3383 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003384 /// \p InsertedInsts keeps track of all the instructions inserted by the
3385 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003386 /// because we do not want to promote these instructions as CodeGenPrepare
3387 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3388 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003389 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003390 const TargetLowering &TLI,
3391 const InstrToOrigTy &PromotedInsts);
3392};
3393
Eugene Zelenko900b6332017-08-29 22:32:07 +00003394} // end anonymous namespace
3395
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003396bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003397 Type *ConsideredExtType,
3398 const InstrToOrigTy &PromotedInsts,
3399 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003400 // The promotion helper does not know how to deal with vector types yet.
3401 // To be able to fix that, we would need to fix the places where we
3402 // statically extend, e.g., constants and such.
3403 if (Inst->getType()->isVectorTy())
3404 return false;
3405
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003406 // We can always get through zext.
3407 if (isa<ZExtInst>(Inst))
3408 return true;
3409
3410 // sext(sext) is ok too.
3411 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003412 return true;
3413
3414 // We can get through binary operator, if it is legal. In other words, the
3415 // binary operator must have a nuw or nsw flag.
3416 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3417 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003418 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3419 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003420 return true;
3421
3422 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003423 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003424 if (!isa<TruncInst>(Inst))
3425 return false;
3426
3427 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003428 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003429 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003430 if (!OpndVal->getType()->isIntegerTy() ||
3431 OpndVal->getType()->getIntegerBitWidth() >
3432 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003433 return false;
3434
3435 // If the operand of the truncate is not an instruction, we will not have
3436 // any information on the dropped bits.
3437 // (Actually we could for constant but it is not worth the extra logic).
3438 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3439 if (!Opnd)
3440 return false;
3441
3442 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003443 // I.e., check that trunc just drops extended bits of the same kind of
3444 // the extension.
3445 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003446 const Type *OpndType;
3447 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003448 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3449 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003450 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3451 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003452 else
3453 return false;
3454
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003455 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003456 return Inst->getType()->getIntegerBitWidth() >=
3457 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003458}
3459
3460TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003461 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003462 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003463 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3464 "Unexpected instruction type");
3465 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3466 Type *ExtTy = Ext->getType();
3467 bool IsSExt = isa<SExtInst>(Ext);
3468 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003469 // get through.
3470 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003471 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003472 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003473
3474 // Do not promote if the operand has been added by codegenprepare.
3475 // Otherwise, it means we are undoing an optimization that is likely to be
3476 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003477 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003478 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003479
3480 // SExt or Trunc instructions.
3481 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003482 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3483 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003484 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003485
3486 // Regular instruction.
3487 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003488 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003489 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003490 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003491}
3492
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003493Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Eugene Zelenko900b6332017-08-29 22:32:07 +00003494 Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003495 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003496 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003497 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003498 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3499 // get through it and this method should not be called.
3500 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003501 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003502 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003503 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003504 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003505 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003506 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003507 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003508 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3509 TPT.replaceAllUsesWith(SExt, ZExt);
3510 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003511 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003512 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003513 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3514 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003515 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3516 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003517 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003518
3519 // Remove dead code.
3520 if (SExtOpnd->use_empty())
3521 TPT.eraseInstruction(SExtOpnd);
3522
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003523 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003524 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003525 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003526 if (ExtInst) {
3527 if (Exts)
3528 Exts->push_back(ExtInst);
3529 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3530 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003531 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003532 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003533
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003534 // At this point we have: ext ty opnd to ty.
3535 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3536 Value *NextVal = ExtInst->getOperand(0);
3537 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003538 return NextVal;
3539}
3540
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003541Value *TypePromotionHelper::promoteOperandForOther(
3542 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003543 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003544 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003545 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3546 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003547 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003548 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003549 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003550 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003551 if (!ExtOpnd->hasOneUse()) {
3552 // ExtOpnd will be promoted.
3553 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003554 // promoted version.
3555 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003556 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003557 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
Quentin Colombetac55b152014-09-16 22:36:07 +00003558 // Insert it just after the definition.
Sanjay Patel674d2c22017-08-29 14:07:48 +00003559 ITrunc->moveAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003560 if (Truncs)
3561 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003562 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003563
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003564 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003565 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003566 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003567 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003568 }
3569
3570 // Get through the Instruction:
3571 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003572 // 2. Replace the uses of Ext by Inst.
3573 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003574
3575 // Remember the original type of the instruction before promotion.
3576 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003577 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3578 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003579 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003580 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003581 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003582 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003583 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003584 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003585
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003586 DEBUG(dbgs() << "Propagate Ext to operands\n");
3587 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003588 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003589 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3590 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3591 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003592 DEBUG(dbgs() << "No need to propagate\n");
3593 continue;
3594 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003595 // Check if we can statically extend the operand.
3596 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003597 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003598 DEBUG(dbgs() << "Statically extend\n");
3599 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3600 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3601 : Cst->getValue().zext(BitWidth);
3602 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003603 continue;
3604 }
3605 // UndefValue are typed, so we have to statically sign extend them.
3606 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003607 DEBUG(dbgs() << "Statically extend\n");
3608 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003609 continue;
3610 }
3611
3612 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003613 // Check if Ext was reused to extend an operand.
3614 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003615 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003616 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003617 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3618 : TPT.createZExt(Ext, Opnd, Ext->getType());
3619 if (!isa<Instruction>(ValForExtOpnd)) {
3620 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3621 continue;
3622 }
3623 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003624 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003625 if (Exts)
3626 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003627 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003628
3629 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003630 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3631 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003632 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003633 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003634 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003635 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003636 if (ExtForOpnd == Ext) {
3637 DEBUG(dbgs() << "Extension is useless now\n");
3638 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003639 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003640 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003641}
3642
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003643/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003644/// \p NewCost gives the cost of extension instructions created by the
3645/// promotion.
3646/// \p OldCost gives the cost of extension instructions before the promotion
3647/// plus the number of instructions that have been
3648/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003649/// \p PromotedOperand is the value that has been promoted.
3650/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003651bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003652 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3653 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3654 // The cost of the new extensions is greater than the cost of the
3655 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003656 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003657 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003658 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003659 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003660 return true;
3661 // The promotion is neutral but it may help folding the sign extension in
3662 // loads for instance.
3663 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003664 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003665}
3666
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003667/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003668/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003669/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003670/// If \p MovedAway is not NULL, it contains the information of whether or
3671/// not AddrInst has to be folded into the addressing mode on success.
3672/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3673/// because it has been moved away.
3674/// Thus AddrInst must not be added in the matched instructions.
3675/// This state can happen when AddrInst is a sext, since it may be moved away.
3676/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3677/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003678bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003679 unsigned Depth,
3680 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003681 // Avoid exponential behavior on extremely deep expression trees.
3682 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003683
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003684 // By default, all matched instructions stay in place.
3685 if (MovedAway)
3686 *MovedAway = false;
3687
Chandler Carruthc8925912013-01-05 02:09:22 +00003688 switch (Opcode) {
3689 case Instruction::PtrToInt:
3690 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003691 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003692 case Instruction::IntToPtr: {
3693 auto AS = AddrInst->getType()->getPointerAddressSpace();
3694 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003695 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003696 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003697 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003698 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003699 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003700 case Instruction::BitCast:
3701 // BitCast is always a noop, and we can handle it as long as it is
3702 // int->int or pointer->pointer (we don't want int<->fp or something).
3703 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3704 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3705 // Don't touch identity bitcasts. These were probably put here by LSR,
3706 // and we don't want to mess around with them. Assume it knows what it
3707 // is doing.
3708 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003709 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003710 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003711 case Instruction::AddrSpaceCast: {
3712 unsigned SrcAS
3713 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3714 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3715 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003716 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003717 return false;
3718 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003719 case Instruction::Add: {
3720 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3721 ExtAddrMode BackupAddrMode = AddrMode;
3722 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003723 // Start a transaction at this point.
3724 // The LHS may match but not the RHS.
3725 // Therefore, we need a higher level restoration point to undo partially
3726 // matched operation.
3727 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3728 TPT.getRestorationPoint();
3729
Sanjay Patelfc580a62015-09-21 23:03:16 +00003730 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3731 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003732 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003733
Chandler Carruthc8925912013-01-05 02:09:22 +00003734 // Restore the old addr mode info.
3735 AddrMode = BackupAddrMode;
3736 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003737 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003738
Chandler Carruthc8925912013-01-05 02:09:22 +00003739 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003740 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3741 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003742 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003743
Chandler Carruthc8925912013-01-05 02:09:22 +00003744 // Otherwise we definitely can't merge the ADD in.
3745 AddrMode = BackupAddrMode;
3746 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003747 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003748 break;
3749 }
3750 //case Instruction::Or:
3751 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3752 //break;
3753 case Instruction::Mul:
3754 case Instruction::Shl: {
3755 // Can only handle X*C and X << C.
3756 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Philip Reames9c3cbee2017-10-30 23:59:51 +00003757 if (!RHS || RHS->getBitWidth() > 64)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003758 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003759 int64_t Scale = RHS->getSExtValue();
3760 if (Opcode == Instruction::Shl)
3761 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003762
Sanjay Patelfc580a62015-09-21 23:03:16 +00003763 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003764 }
3765 case Instruction::GetElementPtr: {
3766 // Scan the GEP. We check it if it contains constant offsets and at most
3767 // one variable offset.
3768 int VariableOperand = -1;
3769 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003770
Chandler Carruthc8925912013-01-05 02:09:22 +00003771 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003772 gep_type_iterator GTI = gep_type_begin(AddrInst);
3773 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003774 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003775 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003776 unsigned Idx =
3777 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3778 ConstantOffset += SL->getElementOffset(Idx);
3779 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003780 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003781 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3782 ConstantOffset += CI->getSExtValue()*TypeSize;
3783 } else if (TypeSize) { // Scales of zero don't do anything.
3784 // We only allow one variable index at the moment.
3785 if (VariableOperand != -1)
3786 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003787
Chandler Carruthc8925912013-01-05 02:09:22 +00003788 // Remember the variable index.
3789 VariableOperand = i;
3790 VariableScale = TypeSize;
3791 }
3792 }
3793 }
Stephen Lin837bba12013-07-15 17:55:02 +00003794
Chandler Carruthc8925912013-01-05 02:09:22 +00003795 // A common case is for the GEP to only do a constant offset. In this case,
3796 // just add it to the disp field and check validity.
3797 if (VariableOperand == -1) {
3798 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003799 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003800 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003801 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003802 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003803 return true;
3804 }
3805 AddrMode.BaseOffs -= ConstantOffset;
3806 return false;
3807 }
3808
3809 // Save the valid addressing mode in case we can't match.
3810 ExtAddrMode BackupAddrMode = AddrMode;
3811 unsigned OldSize = AddrModeInsts.size();
3812
3813 // See if the scale and offset amount is valid for this target.
3814 AddrMode.BaseOffs += ConstantOffset;
3815
3816 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003817 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003818 // If it couldn't be matched, just stuff the value in a register.
3819 if (AddrMode.HasBaseReg) {
3820 AddrMode = BackupAddrMode;
3821 AddrModeInsts.resize(OldSize);
3822 return false;
3823 }
3824 AddrMode.HasBaseReg = true;
3825 AddrMode.BaseReg = AddrInst->getOperand(0);
3826 }
3827
3828 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003829 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003830 Depth)) {
3831 // If it couldn't be matched, try stuffing the base into a register
3832 // instead of matching it, and retrying the match of the scale.
3833 AddrMode = BackupAddrMode;
3834 AddrModeInsts.resize(OldSize);
3835 if (AddrMode.HasBaseReg)
3836 return false;
3837 AddrMode.HasBaseReg = true;
3838 AddrMode.BaseReg = AddrInst->getOperand(0);
3839 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003840 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003841 VariableScale, Depth)) {
3842 // If even that didn't work, bail.
3843 AddrMode = BackupAddrMode;
3844 AddrModeInsts.resize(OldSize);
3845 return false;
3846 }
3847 }
3848
3849 return true;
3850 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003851 case Instruction::SExt:
3852 case Instruction::ZExt: {
3853 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3854 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003855 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003856
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003857 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003858 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003859 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003860 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003861 if (!TPH)
3862 return false;
3863
3864 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3865 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003866 unsigned CreatedInstsCost = 0;
3867 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003868 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003869 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003870 // SExt has been moved away.
3871 // Thus either it will be rematched later in the recursive calls or it is
3872 // gone. Anyway, we must not fold it into the addressing mode at this point.
3873 // E.g.,
3874 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003875 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003876 // addr = gep base, idx
3877 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003878 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003879 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3880 // addr = gep base, op <- match
3881 if (MovedAway)
3882 *MovedAway = true;
3883
3884 assert(PromotedOperand &&
3885 "TypePromotionHelper should have filtered out those cases");
3886
3887 ExtAddrMode BackupAddrMode = AddrMode;
3888 unsigned OldSize = AddrModeInsts.size();
3889
Sanjay Patelfc580a62015-09-21 23:03:16 +00003890 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003891 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003892 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003893 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003894 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003895 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003896 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003897 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003898 AddrMode = BackupAddrMode;
3899 AddrModeInsts.resize(OldSize);
3900 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3901 TPT.rollback(LastKnownGood);
3902 return false;
3903 }
3904 return true;
3905 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003906 }
3907 return false;
3908}
3909
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003910/// If we can, try to add the value of 'Addr' into the current addressing mode.
3911/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3912/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3913/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003914///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003915bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003916 // Start a transaction at this point that we will rollback if the matching
3917 // fails.
3918 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3919 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003920 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3921 // Fold in immediates if legal for the target.
3922 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003923 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003924 return true;
3925 AddrMode.BaseOffs -= CI->getSExtValue();
3926 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3927 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003928 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003929 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003930 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003931 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003932 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003933 }
3934 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3935 ExtAddrMode BackupAddrMode = AddrMode;
3936 unsigned OldSize = AddrModeInsts.size();
3937
3938 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003939 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003940 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003941 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003942 // to check here.
3943 if (MovedAway)
3944 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003945 // Okay, it's possible to fold this. Check to see if it is actually
3946 // *profitable* to do so. We use a simple cost model to avoid increasing
3947 // register pressure too much.
3948 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003949 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003950 AddrModeInsts.push_back(I);
3951 return true;
3952 }
Stephen Lin837bba12013-07-15 17:55:02 +00003953
Chandler Carruthc8925912013-01-05 02:09:22 +00003954 // It isn't profitable to do this, roll back.
3955 //cerr << "NOT FOLDING: " << *I;
3956 AddrMode = BackupAddrMode;
3957 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003958 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003959 }
3960 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003961 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003962 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003963 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003964 } else if (isa<ConstantPointerNull>(Addr)) {
3965 // Null pointer gets folded without affecting the addressing mode.
3966 return true;
3967 }
3968
3969 // Worse case, the target should support [reg] addressing modes. :)
3970 if (!AddrMode.HasBaseReg) {
3971 AddrMode.HasBaseReg = true;
3972 AddrMode.BaseReg = Addr;
3973 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003974 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003975 return true;
3976 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003977 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003978 }
3979
3980 // If the base register is already taken, see if we can do [r+r].
3981 if (AddrMode.Scale == 0) {
3982 AddrMode.Scale = 1;
3983 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003984 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003985 return true;
3986 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003987 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003988 }
3989 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003990 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003991 return false;
3992}
3993
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003994/// Check to see if all uses of OpVal by the specified inline asm call are due
3995/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003996static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003997 const TargetLowering &TLI,
3998 const TargetRegisterInfo &TRI) {
Sanjay Patel4137d512017-06-07 14:29:52 +00003999 const Function *F = CI->getFunction();
Eric Christopherd75c00c2015-02-26 22:38:34 +00004000 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004001 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004002 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004003
Chandler Carruthc8925912013-01-05 02:09:22 +00004004 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4005 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00004006
Chandler Carruthc8925912013-01-05 02:09:22 +00004007 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004008 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00004009
4010 // If this asm operand is our Value*, and if it isn't an indirect memory
4011 // operand, we can't fold it!
4012 if (OpInfo.CallOperandVal == OpVal &&
4013 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
4014 !OpInfo.isIndirect))
4015 return false;
4016 }
4017
4018 return true;
4019}
4020
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004021// Max number of memory uses to look at before aborting the search to conserve
4022// compile time.
4023static constexpr int MaxMemoryUsesToScan = 20;
4024
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004025/// Recursively walk all the uses of I until we find a memory use.
4026/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00004027/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00004028static bool FindAllMemoryUses(
4029 Instruction *I,
4030 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004031 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
4032 const TargetRegisterInfo &TRI, int SeenInsts = 0) {
Chandler Carruthc8925912013-01-05 02:09:22 +00004033 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00004034 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00004035 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004036
Chandler Carruthc8925912013-01-05 02:09:22 +00004037 // If this is an obviously unfoldable instruction, bail out.
4038 if (!MightBeFoldableInst(I))
4039 return true;
4040
Philip Reamesac115ed2016-03-09 23:13:12 +00004041 const bool OptSize = I->getFunction()->optForSize();
4042
Chandler Carruthc8925912013-01-05 02:09:22 +00004043 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004044 for (Use &U : I->uses()) {
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004045 // Conservatively return true if we're seeing a large number or a deep chain
4046 // of users. This avoids excessive compilation times in pathological cases.
4047 if (SeenInsts++ >= MaxMemoryUsesToScan)
4048 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00004049
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004050 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthcdf47882014-03-09 03:16:01 +00004051 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
4052 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00004053 continue;
4054 }
Stephen Lin837bba12013-07-15 17:55:02 +00004055
Chandler Carruthcdf47882014-03-09 03:16:01 +00004056 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
4057 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00004058 if (opNo != StoreInst::getPointerOperandIndex())
4059 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00004060 MemoryUses.push_back(std::make_pair(SI, opNo));
4061 continue;
4062 }
Stephen Lin837bba12013-07-15 17:55:02 +00004063
Matt Arsenault02d915b2017-03-15 22:35:20 +00004064 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
4065 unsigned opNo = U.getOperandNo();
4066 if (opNo != AtomicRMWInst::getPointerOperandIndex())
4067 return true; // Storing addr, not into addr.
4068 MemoryUses.push_back(std::make_pair(RMW, opNo));
4069 continue;
4070 }
4071
4072 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
4073 unsigned opNo = U.getOperandNo();
4074 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
4075 return true; // Storing addr, not into addr.
4076 MemoryUses.push_back(std::make_pair(CmpX, opNo));
4077 continue;
4078 }
4079
Chandler Carruthcdf47882014-03-09 03:16:01 +00004080 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00004081 // If this is a cold call, we can sink the addressing calculation into
4082 // the cold path. See optimizeCallInst
4083 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
4084 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00004085
Chandler Carruthc8925912013-01-05 02:09:22 +00004086 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
4087 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004088
Chandler Carruthc8925912013-01-05 02:09:22 +00004089 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004090 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004091 return true;
4092 continue;
4093 }
Stephen Lin837bba12013-07-15 17:55:02 +00004094
Benjamin Kramerfc638c12017-07-24 16:18:09 +00004095 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
4096 SeenInsts))
Chandler Carruthc8925912013-01-05 02:09:22 +00004097 return true;
4098 }
4099
4100 return false;
4101}
4102
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00004103/// Return true if Val is already known to be live at the use site that we're
4104/// folding it into. If so, there is no cost to include it in the addressing
4105/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
4106/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004107bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00004108 Value *KnownLive2) {
4109 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00004110 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00004111 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004112
Chandler Carruthc8925912013-01-05 02:09:22 +00004113 // All values other than instructions and arguments (e.g. constants) are live.
4114 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004115
Chandler Carruthc8925912013-01-05 02:09:22 +00004116 // If Val is a constant sized alloca in the entry block, it is live, this is
4117 // true because it is just a reference to the stack/frame pointer, which is
4118 // live for the whole function.
4119 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
4120 if (AI->isStaticAlloca())
4121 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004122
Chandler Carruthc8925912013-01-05 02:09:22 +00004123 // Check to see if this value is already used in the memory instruction's
4124 // block. If so, it's already live into the block at the very least, so we
4125 // can reasonably fold it.
4126 return Val->isUsedInBasicBlock(MemoryInst->getParent());
4127}
4128
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004129/// It is possible for the addressing mode of the machine to fold the specified
4130/// instruction into a load or store that ultimately uses it.
4131/// However, the specified instruction has multiple uses.
4132/// Given this, it may actually increase register pressure to fold it
4133/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00004134///
4135/// X = ...
4136/// Y = X+1
4137/// use(Y) -> nonload/store
4138/// Z = Y+1
4139/// load Z
4140///
4141/// In this case, Y has multiple uses, and can be folded into the load of Z
4142/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
4143/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
4144/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
4145/// number of computations either.
4146///
4147/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
4148/// X was live across 'load Z' for other reasons, we actually *would* want to
4149/// fold the addressing mode in the Z case. This would make Y die earlier.
4150bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00004151isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00004152 ExtAddrMode &AMAfter) {
4153 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00004154
Chandler Carruthc8925912013-01-05 02:09:22 +00004155 // AMBefore is the addressing mode before this instruction was folded into it,
4156 // and AMAfter is the addressing mode after the instruction was folded. Get
4157 // the set of registers referenced by AMAfter and subtract out those
4158 // referenced by AMBefore: this is the set of values which folding in this
4159 // address extends the lifetime of.
4160 //
4161 // Note that there are only two potential values being referenced here,
4162 // BaseReg and ScaleReg (global addresses are always available, as are any
4163 // folded immediates).
4164 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00004165
Chandler Carruthc8925912013-01-05 02:09:22 +00004166 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
4167 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004168 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004169 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004170 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00004171 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00004172
4173 // If folding this instruction (and it's subexprs) didn't extend any live
4174 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00004175 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00004176 return true;
4177
Philip Reamesac115ed2016-03-09 23:13:12 +00004178 // If all uses of this instruction can have the address mode sunk into them,
4179 // we can remove the addressing mode and effectively trade one live register
4180 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00004181 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00004182 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
4183 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004184 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00004185 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004186
Chandler Carruthc8925912013-01-05 02:09:22 +00004187 // Now that we know that all uses of this instruction are part of a chain of
4188 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004189 // into a memory use, loop over each of these memory operation uses and see
4190 // if they could *actually* fold the instruction. The assumption is that
4191 // addressing modes are cheap and that duplicating the computation involved
4192 // many times is worthwhile, even on a fastpath. For sinking candidates
4193 // (i.e. cold call sites), this serves as a way to prevent excessive code
4194 // growth since most architectures have some reasonable small and fast way to
4195 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004196 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4197 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4198 Instruction *User = MemoryUses[i].first;
4199 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004200
Chandler Carruthc8925912013-01-05 02:09:22 +00004201 // Get the access type of this use. If the use isn't a pointer, we don't
4202 // know what it accesses.
4203 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004204 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4205 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004206 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004207 Type *AddressAccessTy = AddrTy->getElementType();
4208 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004209
Chandler Carruthc8925912013-01-05 02:09:22 +00004210 // Do a match against the root of this address, ignoring profitability. This
4211 // will tell us if the addressing mode for the memory operation will
4212 // *actually* cover the shared instruction.
4213 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004214 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4215 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004216 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4217 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004218 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004219 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004220 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004221 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004222 (void)Success; assert(Success && "Couldn't select *anything*?");
4223
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004224 // The match was to check the profitability, the changes made are not
4225 // part of the original matcher. Therefore, they should be dropped
4226 // otherwise the original matcher will not present the right state.
4227 TPT.rollback(LastKnownGood);
4228
Chandler Carruthc8925912013-01-05 02:09:22 +00004229 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004230 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004231 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004232
Chandler Carruthc8925912013-01-05 02:09:22 +00004233 MatchedAddrModeInsts.clear();
4234 }
Stephen Lin837bba12013-07-15 17:55:02 +00004235
Chandler Carruthc8925912013-01-05 02:09:22 +00004236 return true;
4237}
4238
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004239/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004240/// different basic block than BB.
4241static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4242 if (Instruction *I = dyn_cast<Instruction>(V))
4243 return I->getParent() != BB;
4244 return false;
4245}
4246
Philip Reamesac115ed2016-03-09 23:13:12 +00004247/// Sink addressing mode computation immediate before MemoryInst if doing so
4248/// can be done without increasing register pressure. The need for the
4249/// register pressure constraint means this can end up being an all or nothing
4250/// decision for all uses of the same addressing computation.
4251///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004252/// Load and Store Instructions often have addressing modes that can do
4253/// significant amounts of computation. As such, instruction selection will try
4254/// to get the load or store to do as much computation as possible for the
4255/// program. The problem is that isel can only see within a single block. As
4256/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004257///
4258/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004259/// operands. It's also used to sink addressing computations feeding into cold
4260/// call sites into their (cold) basic block.
4261///
4262/// The motivation for handling sinking into cold blocks is that doing so can
4263/// both enable other address mode sinking (by satisfying the register pressure
4264/// constraint above), and reduce register pressure globally (by removing the
4265/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004266bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004267 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004268 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004269
4270 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004271 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004272 SmallVector<Value*, 8> worklist;
4273 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004274 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004275
John Brawneb83c752017-10-03 13:04:15 +00004276 // Use a worklist to iteratively look through PHI and select nodes, and
4277 // ensure that the addressing mode obtained from the non-PHI/select roots of
John Brawn736bf002017-10-03 13:08:22 +00004278 // the graph are compatible.
John Brawneb83c752017-10-03 13:04:15 +00004279 bool PhiOrSelectSeen = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004280 SmallVector<Instruction*, 16> AddrModeInsts;
Serguei Katkovaee63752017-11-05 07:59:02 +00004281 const SimplifyQuery SQ(*DL, TLInfo);
4282 AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
Jun Bum Limdee55652017-04-03 19:20:07 +00004283 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004284 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4285 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004286 while (!worklist.empty()) {
4287 Value *V = worklist.back();
4288 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004289
Serguei Katkov4ea855e2017-07-19 04:49:17 +00004290 // We allow traversing cyclic Phi nodes.
4291 // In case of success after this loop we ensure that traversing through
4292 // Phi nodes ends up with all cases to compute address of the form
4293 // BaseGV + Base + Scale * Index + Offset
4294 // where Scale and Offset are constans and BaseGV, Base and Index
4295 // are exactly the same Values in all cases.
4296 // It means that BaseGV, Scale and Offset dominate our memory instruction
4297 // and have the same value as they had in address computation represented
4298 // as Phi. So we can safely sink address computation to memory instruction.
4299 if (!Visited.insert(V).second)
4300 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00004301
Owen Anderson8ba5f392010-11-27 08:15:55 +00004302 // For a PHI node, push all of its incoming values.
4303 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004304 for (Value *IncValue : P->incoming_values())
4305 worklist.push_back(IncValue);
John Brawneb83c752017-10-03 13:04:15 +00004306 PhiOrSelectSeen = true;
4307 continue;
4308 }
4309 // Similar for select.
4310 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
4311 worklist.push_back(SI->getFalseValue());
4312 worklist.push_back(SI->getTrueValue());
4313 PhiOrSelectSeen = true;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004314 continue;
4315 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004316
Philip Reamesac115ed2016-03-09 23:13:12 +00004317 // For non-PHIs, determine the addressing mode being computed. Note that
4318 // the result may differ depending on what other uses our candidate
4319 // addressing instructions might have.
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004320 AddrModeInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004321 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Serguei Katkova6fba3d2017-07-18 05:16:38 +00004322 V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
4323 InsertedInsts, PromotedInsts, TPT);
John Brawn736bf002017-10-03 13:08:22 +00004324 NewAddrMode.OriginalValue = V;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004325
John Brawn736bf002017-10-03 13:08:22 +00004326 if (!AddrModes.addNewAddrMode(NewAddrMode))
4327 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004328 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004329
John Brawn736bf002017-10-03 13:08:22 +00004330 // Try to combine the AddrModes we've collected. If we couldn't collect any,
4331 // or we have multiple but either couldn't combine them or combining them
4332 // wouldn't do anything useful, bail out now.
4333 if (!AddrModes.combineAddrModes()) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004334 TPT.rollback(LastKnownGood);
4335 return false;
4336 }
4337 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004338
John Brawn736bf002017-10-03 13:08:22 +00004339 // Get the combined AddrMode (or the only AddrMode, if we only had one).
4340 ExtAddrMode AddrMode = AddrModes.getAddrMode();
4341
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004342 // If all the instructions matched are already in this BB, don't do anything.
John Brawneb83c752017-10-03 13:04:15 +00004343 // If we saw a Phi node then it is not local definitely, and if we saw a select
4344 // then we want to push the address calculation past it even if it's already
4345 // in this BB.
4346 if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
Justin Lebar838c7f52016-11-21 22:49:11 +00004347 return IsNonLocalValue(V, MemoryInst->getParent());
Serguei Katkov0b7b59a2017-07-11 06:24:44 +00004348 })) {
David Greene74e2d492010-01-05 01:27:11 +00004349 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004350 return false;
4351 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004352
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004353 // Insert this computation right after this user. Since our caller is
4354 // scanning from the top of the BB to the bottom, reuse of the expr are
4355 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004356 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004357
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004358 // Now that we determined the addressing expression we want to use and know
4359 // that we have to sink it into this block. Check to see if we have already
4360 // done this for some other load/store instr in this block. If so, reuse the
Simon Dardis82221602017-11-13 16:41:17 +00004361 // computation.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004362 Value *&SunkAddr = SunkAddrs[Addr];
4363 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004364 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004365 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004366 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004367 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004368 } else if (AddrSinkUsingGEPs ||
4369 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004370 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004371 // By default, we use the GEP-based method when AA is used later. This
4372 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4373 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004374 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004375 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004376 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004377
4378 // First, find the pointer.
4379 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4380 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004381 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004382 }
4383
4384 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4385 // We can't add more than one pointer together, nor can we scale a
4386 // pointer (both of which seem meaningless).
4387 if (ResultPtr || AddrMode.Scale != 1)
4388 return false;
4389
4390 ResultPtr = AddrMode.ScaledReg;
4391 AddrMode.Scale = 0;
4392 }
4393
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004394 // It is only safe to sign extend the BaseReg if we know that the math
4395 // required to create it did not overflow before we extend it. Since
4396 // the original IR value was tossed in favor of a constant back when
4397 // the AddrMode was created we need to bail out gracefully if widths
4398 // do not match instead of extending it.
4399 //
4400 // (See below for code to add the scale.)
4401 if (AddrMode.Scale) {
4402 Type *ScaledRegTy = AddrMode.ScaledReg->getType();
4403 if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
4404 cast<IntegerType>(ScaledRegTy)->getBitWidth())
4405 return false;
4406 }
4407
Hal Finkelc3998302014-04-12 00:59:48 +00004408 if (AddrMode.BaseGV) {
4409 if (ResultPtr)
4410 return false;
4411
4412 ResultPtr = AddrMode.BaseGV;
4413 }
4414
4415 // If the real base value actually came from an inttoptr, then the matcher
4416 // will look through it and provide only the integer value. In that case,
4417 // use it here.
Keno Fischer05e4ac22017-06-29 20:28:59 +00004418 if (!DL->isNonIntegralPointerType(Addr->getType())) {
4419 if (!ResultPtr && AddrMode.BaseReg) {
4420 ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
4421 "sunkaddr");
4422 AddrMode.BaseReg = nullptr;
4423 } else if (!ResultPtr && AddrMode.Scale == 1) {
4424 ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
4425 "sunkaddr");
4426 AddrMode.Scale = 0;
4427 }
Hal Finkelc3998302014-04-12 00:59:48 +00004428 }
4429
4430 if (!ResultPtr &&
4431 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4432 SunkAddr = Constant::getNullValue(Addr->getType());
4433 } else if (!ResultPtr) {
4434 return false;
4435 } else {
4436 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004437 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4438 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004439
4440 // Start with the base register. Do this first so that subsequent address
4441 // matching finds it last, which will prevent it from trying to match it
4442 // as the scaled value in case it happens to be a mul. That would be
4443 // problematic if we've sunk a different mul for the scale, because then
4444 // we'd end up sinking both muls.
4445 if (AddrMode.BaseReg) {
4446 Value *V = AddrMode.BaseReg;
4447 if (V->getType() != IntPtrTy)
4448 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4449
4450 ResultIndex = V;
4451 }
4452
4453 // Add the scale value.
4454 if (AddrMode.Scale) {
4455 Value *V = AddrMode.ScaledReg;
4456 if (V->getType() == IntPtrTy) {
4457 // done.
Hal Finkelc3998302014-04-12 00:59:48 +00004458 } else {
Eli Friedman6f7c9ad2017-07-12 23:30:02 +00004459 assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
4460 cast<IntegerType>(V->getType())->getBitWidth() &&
4461 "We can't transform if ScaledReg is too narrow");
4462 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004463 }
4464
4465 if (AddrMode.Scale != 1)
4466 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4467 "sunkaddr");
4468 if (ResultIndex)
4469 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4470 else
4471 ResultIndex = V;
4472 }
4473
4474 // Add in the Base Offset if present.
4475 if (AddrMode.BaseOffs) {
4476 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4477 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004478 // We need to add this separately from the scale above to help with
4479 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004480 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004481 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004482 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004483 }
4484
4485 ResultIndex = V;
4486 }
4487
4488 if (!ResultIndex) {
4489 SunkAddr = ResultPtr;
4490 } else {
4491 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004492 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004493 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004494 }
4495
4496 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004497 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004498 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004499 } else {
Keno Fischer05e4ac22017-06-29 20:28:59 +00004500 // We'd require a ptrtoint/inttoptr down the line, which we can't do for
4501 // non-integral pointers, so in that case bail out now.
4502 Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
4503 Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
4504 PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
4505 PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
4506 if (DL->isNonIntegralPointerType(Addr->getType()) ||
4507 (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
4508 (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
4509 (AddrMode.BaseGV &&
4510 DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
4511 return false;
4512
David Greene74e2d492010-01-05 01:27:11 +00004513 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004514 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004515 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004516 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004517
4518 // Start with the base register. Do this first so that subsequent address
4519 // matching finds it last, which will prevent it from trying to match it
4520 // as the scaled value in case it happens to be a mul. That would be
4521 // problematic if we've sunk a different mul for the scale, because then
4522 // we'd end up sinking both muls.
4523 if (AddrMode.BaseReg) {
4524 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004525 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004526 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004527 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004528 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004529 Result = V;
4530 }
4531
4532 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004533 if (AddrMode.Scale) {
4534 Value *V = AddrMode.ScaledReg;
4535 if (V->getType() == IntPtrTy) {
4536 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004537 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004538 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004539 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4540 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004541 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004542 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004543 // It is only safe to sign extend the BaseReg if we know that the math
4544 // required to create it did not overflow before we extend it. Since
4545 // the original IR value was tossed in favor of a constant back when
4546 // the AddrMode was created we need to bail out gracefully if widths
4547 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004548 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004549 if (I && (Result != AddrMode.BaseReg))
4550 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004551 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004552 }
4553 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004554 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4555 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004556 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004557 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004558 else
4559 Result = V;
4560 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004561
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004562 // Add in the BaseGV if present.
4563 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004564 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004565 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004566 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004567 else
4568 Result = V;
4569 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004570
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004571 // Add in the Base Offset if present.
4572 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004573 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004574 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004575 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004576 else
4577 Result = V;
4578 }
4579
Craig Topperc0196b12014-04-14 00:51:57 +00004580 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004581 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004582 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004583 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004584 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004585
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004586 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004587
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004588 // If we have no uses, recursively delete the value and all dead instructions
4589 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004590 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004591 // This can cause recursive deletion, which can invalidate our iterator.
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004592 // Use a WeakTrackingVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004593 Value *CurValue = &*CurInstIterator;
Sanjoy Dase6bca0e2017-05-01 17:07:49 +00004594 WeakTrackingVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004595 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004596
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004597 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004598
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004599 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004600 // If the iterator instruction was recursively deleted, start over at the
4601 // start of the block.
4602 CurInstIterator = BB->begin();
4603 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004604 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004605 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004606 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004607 return true;
4608}
4609
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004610/// If there are any memory operands, use OptimizeMemoryInst to sink their
4611/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004612bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004613 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004614
Eric Christopher11e4df72015-02-26 22:38:43 +00004615 const TargetRegisterInfo *TRI =
Sanjay Patel4137d512017-06-07 14:29:52 +00004616 TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004617 TargetLowering::AsmOperandInfoVector TargetConstraints =
4618 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004619 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004620 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4621 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004622
Evan Cheng1da25002008-02-26 02:42:37 +00004623 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004624 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004625
Eli Friedman666bbe32008-02-26 18:37:49 +00004626 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4627 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004628 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004629 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004630 } else if (OpInfo.Type == InlineAsm::isInput)
4631 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004632 }
4633
4634 return MadeChange;
4635}
4636
Jun Bum Lim42301012017-03-17 19:05:21 +00004637/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004638/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004639static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4640 assert(!Val->use_empty() && "Input must have at least one use");
4641 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004642 bool IsSExt = isa<SExtInst>(FirstUser);
4643 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004644 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004645 const Instruction *UI = cast<Instruction>(U);
4646 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4647 return false;
4648 Type *CurTy = UI->getType();
4649 // Same input and output types: Same instruction after CSE.
4650 if (CurTy == ExtTy)
4651 continue;
4652
4653 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004654 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004655 // b = sext ty1 a to ty2
4656 // c = sext ty1 a to ty3
4657 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004658 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004659 // b = sext ty1 a to ty2
4660 // c = sext ty2 b to ty3
4661 // However, the last sext is not free.
4662 if (IsSExt)
4663 return false;
4664
4665 // This is a ZExt, maybe this is free to extend from one type to another.
4666 // In that case, we would not account for a different use.
4667 Type *NarrowTy;
4668 Type *LargeTy;
4669 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4670 CurTy->getScalarType()->getIntegerBitWidth()) {
4671 NarrowTy = CurTy;
4672 LargeTy = ExtTy;
4673 } else {
4674 NarrowTy = ExtTy;
4675 LargeTy = CurTy;
4676 }
4677
4678 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4679 return false;
4680 }
4681 // All uses are the same or can be derived from one another for free.
4682 return true;
4683}
4684
Jun Bum Lim42301012017-03-17 19:05:21 +00004685/// \brief Try to speculatively promote extensions in \p Exts and continue
4686/// promoting through newly promoted operands recursively as far as doing so is
4687/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4688/// When some promotion happened, \p TPT contains the proper state to revert
4689/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004690///
Jun Bum Lim42301012017-03-17 19:05:21 +00004691/// \return true if some promotion happened, false otherwise.
Jun Bum Lim42301012017-03-17 19:05:21 +00004692bool CodeGenPrepare::tryToPromoteExts(
4693 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4694 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4695 unsigned CreatedInstsCost) {
4696 bool Promoted = false;
4697
4698 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004699 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004700 // Early check if we directly have ext(load).
4701 if (isa<LoadInst>(I->getOperand(0))) {
4702 ProfitablyMovedExts.push_back(I);
4703 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004704 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004705
4706 // Check whether or not we want to do any promotion. The reason we have
4707 // this check inside the for loop is to catch the case where an extension
4708 // is directly fed by a load because in such case the extension can be moved
4709 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004710 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004711 return false;
4712
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004713 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004714 TypePromotionHelper::Action TPH =
4715 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004716 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004717 if (!TPH) {
4718 // Save the current extension as we cannot move up through its operand.
4719 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004720 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004721 }
4722
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004723 // Save the current state.
4724 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4725 TPT.getRestorationPoint();
4726 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004727 unsigned NewCreatedInstsCost = 0;
4728 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004729 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004730 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4731 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004732 assert(PromotedVal &&
4733 "TypePromotionHelper should have filtered out those cases");
4734
4735 // We would be able to merge only one extension in a load.
4736 // Therefore, if we have more than 1 new extension we heuristically
4737 // cut this search path, because it means we degrade the code quality.
4738 // With exactly 2, the transformation is neutral, because we will merge
4739 // one extension but leave one. However, we optimistically keep going,
4740 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004741 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004742 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004743 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004744 TotalCreatedInstsCost =
4745 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004746 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004747 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004748 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004749 // This promotion is not profitable, rollback to the previous state, and
4750 // save the current extension in ProfitablyMovedExts as the latest
4751 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004752 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004753 ProfitablyMovedExts.push_back(I);
4754 continue;
4755 }
4756 // Continue promoting NewExts as far as doing so is profitable.
4757 SmallVector<Instruction *, 2> NewlyMovedExts;
4758 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4759 bool NewPromoted = false;
4760 for (auto ExtInst : NewlyMovedExts) {
4761 Instruction *MovedExt = cast<Instruction>(ExtInst);
4762 Value *ExtOperand = MovedExt->getOperand(0);
4763 // If we have reached to a load, we need this extra profitability check
4764 // as it could potentially be merged into an ext(load).
4765 if (isa<LoadInst>(ExtOperand) &&
4766 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4767 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4768 continue;
4769
4770 ProfitablyMovedExts.push_back(MovedExt);
4771 NewPromoted = true;
4772 }
4773
4774 // If none of speculative promotions for NewExts is profitable, rollback
4775 // and save the current extension (I) as the last profitable extension.
4776 if (!NewPromoted) {
4777 TPT.rollback(LastKnownGood);
4778 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004779 continue;
4780 }
4781 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004782 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004783 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004784 return Promoted;
4785}
4786
Jun Bum Limdee55652017-04-03 19:20:07 +00004787/// Merging redundant sexts when one is dominating the other.
4788bool CodeGenPrepare::mergeSExts(Function &F) {
4789 DominatorTree DT(F);
4790 bool Changed = false;
4791 for (auto &Entry : ValToSExtendedUses) {
4792 SExts &Insts = Entry.second;
4793 SExts CurPts;
4794 for (Instruction *Inst : Insts) {
4795 if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
4796 Inst->getOperand(0) != Entry.first)
4797 continue;
4798 bool inserted = false;
4799 for (auto &Pt : CurPts) {
4800 if (DT.dominates(Inst, Pt)) {
4801 Pt->replaceAllUsesWith(Inst);
4802 RemovedInsts.insert(Pt);
4803 Pt->removeFromParent();
4804 Pt = Inst;
4805 inserted = true;
4806 Changed = true;
4807 break;
4808 }
4809 if (!DT.dominates(Pt, Inst))
4810 // Give up if we need to merge in a common dominator as the
4811 // expermients show it is not profitable.
4812 continue;
4813 Inst->replaceAllUsesWith(Pt);
4814 RemovedInsts.insert(Inst);
4815 Inst->removeFromParent();
4816 inserted = true;
4817 Changed = true;
4818 break;
4819 }
4820 if (!inserted)
4821 CurPts.push_back(Inst);
4822 }
4823 }
4824 return Changed;
4825}
4826
Jun Bum Lim42301012017-03-17 19:05:21 +00004827/// Return true, if an ext(load) can be formed from an extension in
4828/// \p MovedExts.
4829bool CodeGenPrepare::canFormExtLd(
4830 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4831 Instruction *&Inst, bool HasPromoted) {
4832 for (auto *MovedExtInst : MovedExts) {
4833 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4834 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4835 Inst = MovedExtInst;
4836 break;
4837 }
4838 }
4839 if (!LI)
4840 return false;
4841
4842 // If they're already in the same block, there's nothing to do.
4843 // Make the cheap checks first if we did not promote.
4844 // If we promoted, we need to check if it is indeed profitable.
4845 if (!HasPromoted && LI->getParent() == Inst->getParent())
4846 return false;
4847
Haicheng Wuabdef9e2017-07-15 02:12:16 +00004848 return TLI->isExtLoad(LI, Inst, *DL);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004849}
4850
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004851/// Move a zext or sext fed by a load into the same basic block as the load,
4852/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4853/// extend into the load.
Dan Gohman99429a02009-10-16 20:59:35 +00004854///
Jun Bum Limdee55652017-04-03 19:20:07 +00004855/// E.g.,
4856/// \code
4857/// %ld = load i32* %addr
4858/// %add = add nuw i32 %ld, 4
4859/// %zext = zext i32 %add to i64
4860// \endcode
4861/// =>
4862/// \code
4863/// %ld = load i32* %addr
4864/// %zext = zext i32 %ld to i64
4865/// %add = add nuw i64 %zext, 4
4866/// \encode
4867/// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
4868/// allow us to match zext(load i32*) to i64.
4869///
4870/// Also, try to promote the computations used to obtain a sign extended
4871/// value used into memory accesses.
4872/// E.g.,
4873/// \code
4874/// a = add nsw i32 b, 3
4875/// d = sext i32 a to i64
4876/// e = getelementptr ..., i64 d
4877/// \endcode
4878/// =>
4879/// \code
4880/// f = sext i32 b to i64
4881/// a = add nsw i64 f, 3
4882/// e = getelementptr ..., i64 a
4883/// \endcode
4884///
4885/// \p Inst[in/out] the extension may be modified during the process if some
4886/// promotions apply.
4887bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
4888 // ExtLoad formation and address type promotion infrastructure requires TLI to
4889 // be effective.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004890 if (!TLI)
4891 return false;
4892
Jun Bum Limdee55652017-04-03 19:20:07 +00004893 bool AllowPromotionWithoutCommonHeader = false;
4894 /// See if it is an interesting sext operations for the address type
4895 /// promotion before trying to promote it, e.g., the ones with the right
4896 /// type and used in memory accesses.
4897 bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
4898 *Inst, AllowPromotionWithoutCommonHeader);
4899 TypePromotionTransaction TPT(RemovedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004900 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00004901 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004902 SmallVector<Instruction *, 1> Exts;
Jun Bum Limdee55652017-04-03 19:20:07 +00004903 SmallVector<Instruction *, 2> SpeculativelyMovedExts;
4904 Exts.push_back(Inst);
Jun Bum Lim42301012017-03-17 19:05:21 +00004905
Jun Bum Limdee55652017-04-03 19:20:07 +00004906 bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
Jun Bum Lim42301012017-03-17 19:05:21 +00004907
Dan Gohman99429a02009-10-16 20:59:35 +00004908 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004909 LoadInst *LI = nullptr;
Jun Bum Limdee55652017-04-03 19:20:07 +00004910 Instruction *ExtFedByLoad;
4911
4912 // Try to promote a chain of computation if it allows to form an extended
4913 // load.
4914 if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
4915 assert(LI && ExtFedByLoad && "Expect a valid load and extension");
4916 TPT.commit();
4917 // Move the extend into the same block as the load
Sanjay Patel674d2c22017-08-29 14:07:48 +00004918 ExtFedByLoad->moveAfter(LI);
Jun Bum Limdee55652017-04-03 19:20:07 +00004919 // CGP does not check if the zext would be speculatively executed when moved
4920 // to the same basic block as the load. Preserving its original location
4921 // would pessimize the debugging experience, as well as negatively impact
4922 // the quality of sample pgo. We don't want to use "line 0" as that has a
4923 // size cost in the line-table section and logically the zext can be seen as
4924 // part of the load. Therefore we conservatively reuse the same debug
4925 // location for the load and the zext.
4926 ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
4927 ++NumExtsMoved;
4928 Inst = ExtFedByLoad;
4929 return true;
4930 }
4931
4932 // Continue promoting SExts if known as considerable depending on targets.
4933 if (ATPConsiderable &&
4934 performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
4935 HasPromoted, TPT, SpeculativelyMovedExts))
4936 return true;
4937
4938 TPT.rollback(LastKnownGood);
4939 return false;
4940}
4941
4942// Perform address type promotion if doing so is profitable.
4943// If AllowPromotionWithoutCommonHeader == false, we should find other sext
4944// instructions that sign extended the same initial value. However, if
4945// AllowPromotionWithoutCommonHeader == true, we expect promoting the
4946// extension is just profitable.
4947bool CodeGenPrepare::performAddressTypePromotion(
4948 Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
4949 bool HasPromoted, TypePromotionTransaction &TPT,
4950 SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
4951 bool Promoted = false;
4952 SmallPtrSet<Instruction *, 1> UnhandledExts;
4953 bool AllSeenFirst = true;
4954 for (auto I : SpeculativelyMovedExts) {
4955 Value *HeadOfChain = I->getOperand(0);
4956 DenseMap<Value *, Instruction *>::iterator AlreadySeen =
4957 SeenChainsForSExt.find(HeadOfChain);
4958 // If there is an unhandled SExt which has the same header, try to promote
4959 // it as well.
4960 if (AlreadySeen != SeenChainsForSExt.end()) {
4961 if (AlreadySeen->second != nullptr)
4962 UnhandledExts.insert(AlreadySeen->second);
4963 AllSeenFirst = false;
4964 }
4965 }
4966
4967 if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
4968 SpeculativelyMovedExts.size() == 1)) {
4969 TPT.commit();
4970 if (HasPromoted)
4971 Promoted = true;
4972 for (auto I : SpeculativelyMovedExts) {
4973 Value *HeadOfChain = I->getOperand(0);
4974 SeenChainsForSExt[HeadOfChain] = nullptr;
4975 ValToSExtendedUses[HeadOfChain].push_back(I);
4976 }
4977 // Update Inst as promotion happen.
4978 Inst = SpeculativelyMovedExts.pop_back_val();
4979 } else {
4980 // This is the first chain visited from the header, keep the current chain
4981 // as unhandled. Defer to promote this until we encounter another SExt
4982 // chain derived from the same header.
4983 for (auto I : SpeculativelyMovedExts) {
4984 Value *HeadOfChain = I->getOperand(0);
4985 SeenChainsForSExt[HeadOfChain] = Inst;
4986 }
Dan Gohman99429a02009-10-16 20:59:35 +00004987 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004988 }
Dan Gohman99429a02009-10-16 20:59:35 +00004989
Jun Bum Limdee55652017-04-03 19:20:07 +00004990 if (!AllSeenFirst && !UnhandledExts.empty())
4991 for (auto VisitedSExt : UnhandledExts) {
4992 if (RemovedInsts.count(VisitedSExt))
4993 continue;
4994 TypePromotionTransaction TPT(RemovedInsts);
4995 SmallVector<Instruction *, 1> Exts;
4996 SmallVector<Instruction *, 2> Chains;
4997 Exts.push_back(VisitedSExt);
4998 bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
4999 TPT.commit();
5000 if (HasPromoted)
5001 Promoted = true;
5002 for (auto I : Chains) {
5003 Value *HeadOfChain = I->getOperand(0);
5004 // Mark this as handled.
5005 SeenChainsForSExt[HeadOfChain] = nullptr;
5006 ValToSExtendedUses[HeadOfChain].push_back(I);
5007 }
5008 }
5009 return Promoted;
Dan Gohman99429a02009-10-16 20:59:35 +00005010}
5011
Sanjay Patelfc580a62015-09-21 23:03:16 +00005012bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00005013 BasicBlock *DefBB = I->getParent();
5014
Bob Wilsonff714f92010-09-21 21:44:14 +00005015 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00005016 // other uses of the source with result of extension.
5017 Value *Src = I->getOperand(0);
5018 if (Src->hasOneUse())
5019 return false;
5020
Evan Cheng2011df42007-12-13 07:50:36 +00005021 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00005022 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00005023 return false;
5024
Evan Cheng7bc89422007-12-12 00:51:06 +00005025 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00005026 // this block.
5027 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00005028 return false;
5029
Evan Chengd3d80172007-12-05 23:58:20 +00005030 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005031 for (User *U : I->users()) {
5032 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00005033
5034 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005035 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00005036 if (UserBB == DefBB) continue;
5037 DefIsLiveOut = true;
5038 break;
5039 }
5040 if (!DefIsLiveOut)
5041 return false;
5042
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00005043 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005044 for (User *U : Src->users()) {
5045 Instruction *UI = cast<Instruction>(U);
5046 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00005047 if (UserBB == DefBB) continue;
5048 // Be conservative. We don't want this xform to end up introducing
5049 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005050 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00005051 return false;
5052 }
5053
Evan Chengd3d80172007-12-05 23:58:20 +00005054 // InsertedTruncs - Only insert one trunc in each block once.
5055 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
5056
5057 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005058 for (Use &U : Src->uses()) {
5059 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00005060
5061 // Figure out which BB this ext is used in.
5062 BasicBlock *UserBB = User->getParent();
5063 if (UserBB == DefBB) continue;
5064
5065 // Both src and def are live in this block. Rewrite the use.
5066 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
5067
5068 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00005069 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005070 assert(InsertPt != UserBB->end());
5071 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005072 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00005073 }
5074
5075 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005076 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00005077 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00005078 MadeChange = true;
5079 }
5080
5081 return MadeChange;
5082}
5083
Geoff Berry5256fca2015-11-20 22:34:39 +00005084// Find loads whose uses only use some of the loaded value's bits. Add an "and"
5085// just after the load if the target can fold this into one extload instruction,
5086// with the hope of eliminating some of the other later "and" instructions using
5087// the loaded value. "and"s that are made trivially redundant by the insertion
5088// of the new "and" are removed by this function, while others (e.g. those whose
5089// path from the load goes through a phi) are left for isel to potentially
5090// remove.
5091//
5092// For example:
5093//
5094// b0:
5095// x = load i32
5096// ...
5097// b1:
5098// y = and x, 0xff
5099// z = use y
5100//
5101// becomes:
5102//
5103// b0:
5104// x = load i32
5105// x' = and x, 0xff
5106// ...
5107// b1:
5108// z = use x'
5109//
5110// whereas:
5111//
5112// b0:
5113// x1 = load i32
5114// ...
5115// b1:
5116// x2 = load i32
5117// ...
5118// b2:
5119// x = phi x1, x2
5120// y = and x, 0xff
5121//
5122// becomes (after a call to optimizeLoadExt for each load):
5123//
5124// b0:
5125// x1 = load i32
5126// x1' = and x1, 0xff
5127// ...
5128// b1:
5129// x2 = load i32
5130// x2' = and x2, 0xff
5131// ...
5132// b2:
5133// x = phi x1', x2'
5134// y = and x, 0xff
Geoff Berry5256fca2015-11-20 22:34:39 +00005135bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005136 if (!Load->isSimple() ||
5137 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
5138 return false;
5139
Geoff Berry5d534b62017-02-21 18:53:14 +00005140 // Skip loads we've already transformed.
5141 if (Load->hasOneUse() &&
5142 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
5143 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00005144
5145 // Look at all uses of Load, looking through phis, to determine how many bits
5146 // of the loaded value are needed.
5147 SmallVector<Instruction *, 8> WorkList;
5148 SmallPtrSet<Instruction *, 16> Visited;
5149 SmallVector<Instruction *, 8> AndsToMaybeRemove;
5150 for (auto *U : Load->users())
5151 WorkList.push_back(cast<Instruction>(U));
5152
5153 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
5154 unsigned BitWidth = LoadResultVT.getSizeInBits();
5155 APInt DemandBits(BitWidth, 0);
5156 APInt WidestAndBits(BitWidth, 0);
5157
5158 while (!WorkList.empty()) {
5159 Instruction *I = WorkList.back();
5160 WorkList.pop_back();
5161
5162 // Break use-def graph loops.
5163 if (!Visited.insert(I).second)
5164 continue;
5165
5166 // For a PHI node, push all of its users.
5167 if (auto *Phi = dyn_cast<PHINode>(I)) {
5168 for (auto *U : Phi->users())
5169 WorkList.push_back(cast<Instruction>(U));
5170 continue;
5171 }
5172
5173 switch (I->getOpcode()) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005174 case Instruction::And: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005175 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
5176 if (!AndC)
5177 return false;
5178 APInt AndBits = AndC->getValue();
5179 DemandBits |= AndBits;
5180 // Keep track of the widest and mask we see.
5181 if (AndBits.ugt(WidestAndBits))
5182 WidestAndBits = AndBits;
5183 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
5184 AndsToMaybeRemove.push_back(I);
5185 break;
5186 }
5187
Eugene Zelenko900b6332017-08-29 22:32:07 +00005188 case Instruction::Shl: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005189 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
5190 if (!ShlC)
5191 return false;
5192 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
Craig Topperfc947bc2017-04-18 17:14:21 +00005193 DemandBits.setLowBits(BitWidth - ShiftAmt);
Geoff Berry5256fca2015-11-20 22:34:39 +00005194 break;
5195 }
5196
Eugene Zelenko900b6332017-08-29 22:32:07 +00005197 case Instruction::Trunc: {
Geoff Berry5256fca2015-11-20 22:34:39 +00005198 EVT TruncVT = TLI->getValueType(*DL, I->getType());
5199 unsigned TruncBitWidth = TruncVT.getSizeInBits();
Craig Topperfc947bc2017-04-18 17:14:21 +00005200 DemandBits.setLowBits(TruncBitWidth);
Geoff Berry5256fca2015-11-20 22:34:39 +00005201 break;
5202 }
5203
5204 default:
5205 return false;
5206 }
5207 }
5208
5209 uint32_t ActiveBits = DemandBits.getActiveBits();
5210 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
5211 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
5212 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
5213 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
5214 // followed by an AND.
5215 // TODO: Look into removing this restriction by fixing backends to either
5216 // return false for isLoadExtLegal for i1 or have them select this pattern to
5217 // a single instruction.
5218 //
5219 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
5220 // mask, since these are the only ands that will be removed by isel.
Craig Topperd33ee1b2017-04-03 16:34:59 +00005221 if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
Geoff Berry5256fca2015-11-20 22:34:39 +00005222 WidestAndBits != DemandBits)
5223 return false;
5224
5225 LLVMContext &Ctx = Load->getType()->getContext();
5226 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
5227 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
5228
5229 // Reject cases that won't be matched as extloads.
5230 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
5231 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
5232 return false;
5233
5234 IRBuilder<> Builder(Load->getNextNode());
5235 auto *NewAnd = dyn_cast<Instruction>(
5236 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00005237 // Mark this instruction as "inserted by CGP", so that other
5238 // optimizations don't touch it.
5239 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00005240
5241 // Replace all uses of load with new and (except for the use of load in the
5242 // new and itself).
5243 Load->replaceAllUsesWith(NewAnd);
5244 NewAnd->setOperand(0, Load);
5245
5246 // Remove any and instructions that are now redundant.
5247 for (auto *And : AndsToMaybeRemove)
5248 // Check that the and mask is the same as the one we decided to put on the
5249 // new and.
5250 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
5251 And->replaceAllUsesWith(NewAnd);
5252 if (&*CurInstIterator == And)
5253 CurInstIterator = std::next(And->getIterator());
5254 And->eraseFromParent();
5255 ++NumAndUses;
5256 }
5257
5258 ++NumAndsAdded;
5259 return true;
5260}
5261
Sanjay Patel69a50a12015-10-19 21:59:12 +00005262/// Check if V (an operand of a select instruction) is an expensive instruction
5263/// that is only used once.
5264static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
5265 auto *I = dyn_cast<Instruction>(V);
5266 // If it's safe to speculatively execute, then it should not have side
5267 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00005268 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
5269 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005270}
5271
Sanjay Patel4ac6b112015-09-21 22:47:23 +00005272/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005273static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00005274 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00005275 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00005276 // If even a predictable select is cheap, then a branch can't be cheaper.
5277 if (!TLI->isPredictableSelectExpensive())
5278 return false;
5279
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005280 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00005281 // whether a select is better represented as a branch.
5282
5283 // If metadata tells us that the select condition is obviously predictable,
5284 // then we want to replace the select with a branch.
5285 uint64_t TrueWeight, FalseWeight;
5286 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
5287 uint64_t Max = std::max(TrueWeight, FalseWeight);
5288 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00005289 if (Sum != 0) {
5290 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
5291 if (Probability > TLI->getPredictableBranchThreshold())
5292 return true;
5293 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00005294 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005295
5296 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
5297
Sanjay Patel4e652762015-09-28 22:14:51 +00005298 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
5299 // comparison condition. If the compare has more than one use, there's
5300 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00005301 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005302 return false;
5303
Sanjay Patel69a50a12015-10-19 21:59:12 +00005304 // If either operand of the select is expensive and only needed on one side
5305 // of the select, we should form a branch.
5306 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
5307 sinkSelectOperand(TTI, SI->getFalseValue()))
5308 return true;
5309
5310 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005311}
5312
Dehao Chen9bbb9412016-09-12 20:23:28 +00005313/// If \p isTrue is true, return the true value of \p SI, otherwise return
5314/// false value of \p SI. If the true/false value of \p SI is defined by any
5315/// select instructions in \p Selects, look through the defining select
5316/// instruction until the true/false value is not defined in \p Selects.
5317static Value *getTrueOrFalseValue(
5318 SelectInst *SI, bool isTrue,
5319 const SmallPtrSet<const Instruction *, 2> &Selects) {
5320 Value *V;
5321
5322 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5323 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005324 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005325 "The condition of DefSI does not match with SI");
5326 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5327 }
5328 return V;
5329}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005330
Nadav Rotem9d832022012-09-02 12:10:19 +00005331/// If we have a SelectInst that will likely profit from branch prediction,
5332/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005333bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005334 // Find all consecutive select instructions that share the same condition.
5335 SmallVector<SelectInst *, 2> ASI;
5336 ASI.push_back(SI);
5337 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5338 It != SI->getParent()->end(); ++It) {
5339 SelectInst *I = dyn_cast<SelectInst>(&*It);
5340 if (I && SI->getCondition() == I->getCondition()) {
5341 ASI.push_back(I);
5342 } else {
5343 break;
5344 }
5345 }
5346
5347 SelectInst *LastSI = ASI.back();
5348 // Increment the current iterator to skip all the rest of select instructions
5349 // because they will be either "not lowered" or "all lowered" to branch.
5350 CurInstIterator = std::next(LastSI->getIterator());
5351
Nadav Rotem9d832022012-09-02 12:10:19 +00005352 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5353
5354 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005355 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5356 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005357 return false;
5358
Nadav Rotem9d832022012-09-02 12:10:19 +00005359 TargetLowering::SelectSupportKind SelectKind;
5360 if (VectorCond)
5361 SelectKind = TargetLowering::VectorMaskSelect;
5362 else if (SI->getType()->isVectorTy())
5363 SelectKind = TargetLowering::ScalarCondVectorVal;
5364 else
5365 SelectKind = TargetLowering::ScalarValSelect;
5366
Sanjay Pateld66607b2016-04-26 17:11:17 +00005367 if (TLI->isSelectSupported(SelectKind) &&
5368 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5369 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005370
5371 ModifiedDT = true;
5372
Sanjay Patel69a50a12015-10-19 21:59:12 +00005373 // Transform a sequence like this:
5374 // start:
5375 // %cmp = cmp uge i32 %a, %b
5376 // %sel = select i1 %cmp, i32 %c, i32 %d
5377 //
5378 // Into:
5379 // start:
5380 // %cmp = cmp uge i32 %a, %b
5381 // br i1 %cmp, label %select.true, label %select.false
5382 // select.true:
5383 // br label %select.end
5384 // select.false:
5385 // br label %select.end
5386 // select.end:
5387 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5388 //
5389 // In addition, we may sink instructions that produce %c or %d from
5390 // the entry block into the destination(s) of the new branch.
5391 // If the true or false blocks do not contain a sunken instruction, that
5392 // block and its branch may be optimized away. In that case, one side of the
5393 // first branch will point directly to select.end, and the corresponding PHI
5394 // predecessor block will be the start block.
5395
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005396 // First, we split the block containing the select into 2 blocks.
5397 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005398 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005399 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005400
Sanjay Patel69a50a12015-10-19 21:59:12 +00005401 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005402 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005403
5404 // These are the new basic blocks for the conditional branch.
5405 // At least one will become an actual new basic block.
5406 BasicBlock *TrueBlock = nullptr;
5407 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005408 BranchInst *TrueBranch = nullptr;
5409 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005410
5411 // Sink expensive instructions into the conditional blocks to avoid executing
5412 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005413 for (SelectInst *SI : ASI) {
5414 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5415 if (TrueBlock == nullptr) {
5416 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5417 EndBlock->getParent(), EndBlock);
5418 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5419 }
5420 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5421 TrueInst->moveBefore(TrueBranch);
5422 }
5423 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5424 if (FalseBlock == nullptr) {
5425 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5426 EndBlock->getParent(), EndBlock);
5427 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5428 }
5429 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5430 FalseInst->moveBefore(FalseBranch);
5431 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005432 }
5433
5434 // If there was nothing to sink, then arbitrarily choose the 'false' side
5435 // for a new input value to the PHI.
5436 if (TrueBlock == FalseBlock) {
5437 assert(TrueBlock == nullptr &&
5438 "Unexpected basic block transform while optimizing select");
5439
5440 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5441 EndBlock->getParent(), EndBlock);
5442 BranchInst::Create(EndBlock, FalseBlock);
5443 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005444
5445 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005446 // If we did not create a new block for one of the 'true' or 'false' paths
5447 // of the condition, it means that side of the branch goes to the end block
5448 // directly and the path originates from the start block from the point of
5449 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005450 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005451 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005452 TT = EndBlock;
5453 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005454 TrueBlock = StartBlock;
5455 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005456 TT = TrueBlock;
5457 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005458 FalseBlock = StartBlock;
5459 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005460 TT = TrueBlock;
5461 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005462 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005463 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005464
Dehao Chen9bbb9412016-09-12 20:23:28 +00005465 SmallPtrSet<const Instruction *, 2> INS;
5466 INS.insert(ASI.begin(), ASI.end());
5467 // Use reverse iterator because later select may use the value of the
5468 // earlier select, and we need to propagate value through earlier select
5469 // to get the PHI operand.
5470 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5471 SelectInst *SI = *It;
5472 // The select itself is replaced with a PHI Node.
5473 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5474 PN->takeName(SI);
5475 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5476 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005477
Dehao Chen9bbb9412016-09-12 20:23:28 +00005478 SI->replaceAllUsesWith(PN);
5479 SI->eraseFromParent();
5480 INS.erase(SI);
5481 ++NumSelectsExpanded;
5482 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005483
5484 // Instruct OptimizeBlock to skip to the next block.
5485 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005486 return true;
5487}
5488
Benjamin Kramer573ff362014-03-01 17:24:40 +00005489static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005490 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5491 int SplatElem = -1;
5492 for (unsigned i = 0; i < Mask.size(); ++i) {
5493 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5494 return false;
5495 SplatElem = Mask[i];
5496 }
5497
5498 return true;
5499}
5500
5501/// Some targets have expensive vector shifts if the lanes aren't all the same
5502/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5503/// it's often worth sinking a shufflevector splat down to its use so that
5504/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005505bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005506 BasicBlock *DefBB = SVI->getParent();
5507
5508 // Only do this xform if variable vector shifts are particularly expensive.
5509 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5510 return false;
5511
5512 // We only expect better codegen by sinking a shuffle if we can recognise a
5513 // constant splat.
5514 if (!isBroadcastShuffle(SVI))
5515 return false;
5516
5517 // InsertedShuffles - Only insert a shuffle in each block once.
5518 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5519
5520 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005521 for (User *U : SVI->users()) {
5522 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005523
5524 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005525 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005526 if (UserBB == DefBB) continue;
5527
5528 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005529 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005530
5531 // Everything checks out, sink the shuffle if the user's block doesn't
5532 // already have a copy.
5533 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5534
5535 if (!InsertedShuffle) {
5536 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005537 assert(InsertPt != UserBB->end());
5538 InsertedShuffle =
5539 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5540 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005541 }
5542
Chandler Carruthcdf47882014-03-09 03:16:01 +00005543 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005544 MadeChange = true;
5545 }
5546
5547 // If we removed all uses, nuke the shuffle.
5548 if (SVI->use_empty()) {
5549 SVI->eraseFromParent();
5550 MadeChange = true;
5551 }
5552
5553 return MadeChange;
5554}
5555
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005556bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5557 if (!TLI || !DL)
5558 return false;
5559
5560 Value *Cond = SI->getCondition();
5561 Type *OldType = Cond->getType();
5562 LLVMContext &Context = Cond->getContext();
5563 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5564 unsigned RegWidth = RegType.getSizeInBits();
5565
5566 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5567 return false;
5568
5569 // If the register width is greater than the type width, expand the condition
5570 // of the switch instruction and each case constant to the width of the
5571 // register. By widening the type of the switch condition, subsequent
5572 // comparisons (for case comparisons) will not need to be extended to the
5573 // preferred register width, so we will potentially eliminate N-1 extends,
5574 // where N is the number of cases in the switch.
5575 auto *NewType = Type::getIntNTy(Context, RegWidth);
5576
5577 // Zero-extend the switch condition and case constants unless the switch
5578 // condition is a function argument that is already being sign-extended.
5579 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5580 // everything instead.
5581 Instruction::CastOps ExtType = Instruction::ZExt;
5582 if (auto *Arg = dyn_cast<Argument>(Cond))
5583 if (Arg->hasSExtAttr())
5584 ExtType = Instruction::SExt;
5585
5586 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5587 ExtInst->insertBefore(SI);
5588 SI->setCondition(ExtInst);
Chandler Carruth927d8e62017-04-12 07:27:28 +00005589 for (auto Case : SI->cases()) {
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005590 APInt NarrowConst = Case.getCaseValue()->getValue();
5591 APInt WideConst = (ExtType == Instruction::ZExt) ?
5592 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5593 Case.setValue(ConstantInt::get(Context, WideConst));
5594 }
5595
5596 return true;
5597}
5598
Zaara Syeda3a7578c2017-05-31 17:12:38 +00005599
Quentin Colombetc32615d2014-10-31 17:52:53 +00005600namespace {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005601
Quentin Colombetc32615d2014-10-31 17:52:53 +00005602/// \brief Helper class to promote a scalar operation to a vector one.
5603/// This class is used to move downward extractelement transition.
5604/// E.g.,
5605/// a = vector_op <2 x i32>
5606/// b = extractelement <2 x i32> a, i32 0
5607/// c = scalar_op b
5608/// store c
5609///
5610/// =>
5611/// a = vector_op <2 x i32>
5612/// c = vector_op a (equivalent to scalar_op on the related lane)
5613/// * d = extractelement <2 x i32> c, i32 0
5614/// * store d
5615/// Assuming both extractelement and store can be combine, we get rid of the
5616/// transition.
5617class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005618 /// DataLayout associated with the current module.
5619 const DataLayout &DL;
5620
Quentin Colombetc32615d2014-10-31 17:52:53 +00005621 /// Used to perform some checks on the legality of vector operations.
5622 const TargetLowering &TLI;
5623
5624 /// Used to estimated the cost of the promoted chain.
5625 const TargetTransformInfo &TTI;
5626
5627 /// The transition being moved downwards.
5628 Instruction *Transition;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005629
Quentin Colombetc32615d2014-10-31 17:52:53 +00005630 /// The sequence of instructions to be promoted.
5631 SmallVector<Instruction *, 4> InstsToBePromoted;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005632
Quentin Colombetc32615d2014-10-31 17:52:53 +00005633 /// Cost of combining a store and an extract.
5634 unsigned StoreExtractCombineCost;
Eugene Zelenko900b6332017-08-29 22:32:07 +00005635
Quentin Colombetc32615d2014-10-31 17:52:53 +00005636 /// Instruction that will be combined with the transition.
Eugene Zelenko900b6332017-08-29 22:32:07 +00005637 Instruction *CombineInst = nullptr;
Quentin Colombetc32615d2014-10-31 17:52:53 +00005638
5639 /// \brief The instruction that represents the current end of the transition.
5640 /// Since we are faking the promotion until we reach the end of the chain
5641 /// of computation, we need a way to get the current end of the transition.
5642 Instruction *getEndOfTransition() const {
5643 if (InstsToBePromoted.empty())
5644 return Transition;
5645 return InstsToBePromoted.back();
5646 }
5647
5648 /// \brief Return the index of the original value in the transition.
5649 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5650 /// c, is at index 0.
5651 unsigned getTransitionOriginalValueIdx() const {
5652 assert(isa<ExtractElementInst>(Transition) &&
5653 "Other kind of transitions are not supported yet");
5654 return 0;
5655 }
5656
5657 /// \brief Return the index of the index in the transition.
5658 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5659 /// is at index 1.
5660 unsigned getTransitionIdx() const {
5661 assert(isa<ExtractElementInst>(Transition) &&
5662 "Other kind of transitions are not supported yet");
5663 return 1;
5664 }
5665
5666 /// \brief Get the type of the transition.
5667 /// This is the type of the original value.
5668 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5669 /// transition is <2 x i32>.
5670 Type *getTransitionType() const {
5671 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5672 }
5673
5674 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5675 /// I.e., we have the following sequence:
5676 /// Def = Transition <ty1> a to <ty2>
5677 /// b = ToBePromoted <ty2> Def, ...
5678 /// =>
5679 /// b = ToBePromoted <ty1> a, ...
5680 /// Def = Transition <ty1> ToBePromoted to <ty2>
5681 void promoteImpl(Instruction *ToBePromoted);
5682
5683 /// \brief Check whether or not it is profitable to promote all the
5684 /// instructions enqueued to be promoted.
5685 bool isProfitableToPromote() {
5686 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5687 unsigned Index = isa<ConstantInt>(ValIdx)
5688 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5689 : -1;
5690 Type *PromotedType = getTransitionType();
5691
5692 StoreInst *ST = cast<StoreInst>(CombineInst);
5693 unsigned AS = ST->getPointerAddressSpace();
5694 unsigned Align = ST->getAlignment();
5695 // Check if this store is supported.
5696 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005697 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5698 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005699 // If this is not supported, there is no way we can combine
5700 // the extract with the store.
5701 return false;
5702 }
5703
5704 // The scalar chain of computation has to pay for the transition
5705 // scalar to vector.
5706 // The vector chain has to account for the combining cost.
5707 uint64_t ScalarCost =
5708 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5709 uint64_t VectorCost = StoreExtractCombineCost;
5710 for (const auto &Inst : InstsToBePromoted) {
5711 // Compute the cost.
5712 // By construction, all instructions being promoted are arithmetic ones.
5713 // Moreover, one argument is a constant that can be viewed as a splat
5714 // constant.
5715 Value *Arg0 = Inst->getOperand(0);
5716 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5717 isa<ConstantFP>(Arg0);
5718 TargetTransformInfo::OperandValueKind Arg0OVK =
5719 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5720 : TargetTransformInfo::OK_AnyValue;
5721 TargetTransformInfo::OperandValueKind Arg1OVK =
5722 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5723 : TargetTransformInfo::OK_AnyValue;
5724 ScalarCost += TTI.getArithmeticInstrCost(
5725 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5726 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5727 Arg0OVK, Arg1OVK);
5728 }
5729 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5730 << ScalarCost << "\nVector: " << VectorCost << '\n');
5731 return ScalarCost > VectorCost;
5732 }
5733
5734 /// \brief Generate a constant vector with \p Val with the same
5735 /// number of elements as the transition.
5736 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005737 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005738 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5739 /// otherwise we generate a vector with as many undef as possible:
5740 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5741 /// used at the index of the extract.
5742 Value *getConstantVector(Constant *Val, bool UseSplat) const {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005743 unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005744 if (!UseSplat) {
5745 // If we cannot determine where the constant must be, we have to
5746 // use a splat constant.
5747 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5748 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5749 ExtractIdx = CstVal->getSExtValue();
5750 else
5751 UseSplat = true;
5752 }
5753
5754 unsigned End = getTransitionType()->getVectorNumElements();
5755 if (UseSplat)
5756 return ConstantVector::getSplat(End, Val);
5757
5758 SmallVector<Constant *, 4> ConstVec;
5759 UndefValue *UndefVal = UndefValue::get(Val->getType());
5760 for (unsigned Idx = 0; Idx != End; ++Idx) {
5761 if (Idx == ExtractIdx)
5762 ConstVec.push_back(Val);
5763 else
5764 ConstVec.push_back(UndefVal);
5765 }
5766 return ConstantVector::get(ConstVec);
5767 }
5768
5769 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5770 /// in \p Use can trigger undefined behavior.
5771 static bool canCauseUndefinedBehavior(const Instruction *Use,
5772 unsigned OperandIdx) {
5773 // This is not safe to introduce undef when the operand is on
5774 // the right hand side of a division-like instruction.
5775 if (OperandIdx != 1)
5776 return false;
5777 switch (Use->getOpcode()) {
5778 default:
5779 return false;
5780 case Instruction::SDiv:
5781 case Instruction::UDiv:
5782 case Instruction::SRem:
5783 case Instruction::URem:
5784 return true;
5785 case Instruction::FDiv:
5786 case Instruction::FRem:
5787 return !Use->hasNoNaNs();
5788 }
5789 llvm_unreachable(nullptr);
5790 }
5791
5792public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005793 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5794 const TargetTransformInfo &TTI, Instruction *Transition,
5795 unsigned CombineCost)
5796 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Eugene Zelenko900b6332017-08-29 22:32:07 +00005797 StoreExtractCombineCost(CombineCost) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005798 assert(Transition && "Do not know how to promote null");
5799 }
5800
5801 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5802 bool canPromote(const Instruction *ToBePromoted) const {
5803 // We could support CastInst too.
5804 return isa<BinaryOperator>(ToBePromoted);
5805 }
5806
5807 /// \brief Check if it is profitable to promote \p ToBePromoted
5808 /// by moving downward the transition through.
5809 bool shouldPromote(const Instruction *ToBePromoted) const {
5810 // Promote only if all the operands can be statically expanded.
5811 // Indeed, we do not want to introduce any new kind of transitions.
5812 for (const Use &U : ToBePromoted->operands()) {
5813 const Value *Val = U.get();
5814 if (Val == getEndOfTransition()) {
5815 // If the use is a division and the transition is on the rhs,
5816 // we cannot promote the operation, otherwise we may create a
5817 // division by zero.
5818 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5819 return false;
5820 continue;
5821 }
5822 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5823 !isa<ConstantFP>(Val))
5824 return false;
5825 }
5826 // Check that the resulting operation is legal.
5827 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5828 if (!ISDOpcode)
5829 return false;
5830 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005831 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005832 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005833 }
5834
5835 /// \brief Check whether or not \p Use can be combined
5836 /// with the transition.
5837 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5838 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5839
5840 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5841 void enqueueForPromotion(Instruction *ToBePromoted) {
5842 InstsToBePromoted.push_back(ToBePromoted);
5843 }
5844
5845 /// \brief Set the instruction that will be combined with the transition.
5846 void recordCombineInstruction(Instruction *ToBeCombined) {
5847 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5848 CombineInst = ToBeCombined;
5849 }
5850
5851 /// \brief Promote all the instructions enqueued for promotion if it is
5852 /// is profitable.
5853 /// \return True if the promotion happened, false otherwise.
5854 bool promote() {
5855 // Check if there is something to promote.
5856 // Right now, if we do not have anything to combine with,
5857 // we assume the promotion is not profitable.
5858 if (InstsToBePromoted.empty() || !CombineInst)
5859 return false;
5860
5861 // Check cost.
5862 if (!StressStoreExtract && !isProfitableToPromote())
5863 return false;
5864
5865 // Promote.
5866 for (auto &ToBePromoted : InstsToBePromoted)
5867 promoteImpl(ToBePromoted);
5868 InstsToBePromoted.clear();
5869 return true;
5870 }
5871};
Eugene Zelenko900b6332017-08-29 22:32:07 +00005872
5873} // end anonymous namespace
Quentin Colombetc32615d2014-10-31 17:52:53 +00005874
5875void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5876 // At this point, we know that all the operands of ToBePromoted but Def
5877 // can be statically promoted.
5878 // For Def, we need to use its parameter in ToBePromoted:
5879 // b = ToBePromoted ty1 a
5880 // Def = Transition ty1 b to ty2
5881 // Move the transition down.
5882 // 1. Replace all uses of the promoted operation by the transition.
5883 // = ... b => = ... Def.
5884 assert(ToBePromoted->getType() == Transition->getType() &&
5885 "The type of the result of the transition does not match "
5886 "the final type");
5887 ToBePromoted->replaceAllUsesWith(Transition);
5888 // 2. Update the type of the uses.
5889 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5890 Type *TransitionTy = getTransitionType();
5891 ToBePromoted->mutateType(TransitionTy);
5892 // 3. Update all the operands of the promoted operation with promoted
5893 // operands.
5894 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5895 for (Use &U : ToBePromoted->operands()) {
5896 Value *Val = U.get();
5897 Value *NewVal = nullptr;
5898 if (Val == Transition)
5899 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5900 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5901 isa<ConstantFP>(Val)) {
5902 // Use a splat constant if it is not safe to use undef.
5903 NewVal = getConstantVector(
5904 cast<Constant>(Val),
5905 isa<UndefValue>(Val) ||
5906 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5907 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005908 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5909 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005910 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5911 }
Sanjay Patel674d2c22017-08-29 14:07:48 +00005912 Transition->moveAfter(ToBePromoted);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005913 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5914}
5915
5916/// Some targets can do store(extractelement) with one instruction.
5917/// Try to push the extractelement towards the stores when the target
5918/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005919bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Eugene Zelenko900b6332017-08-29 22:32:07 +00005920 unsigned CombineCost = std::numeric_limits<unsigned>::max();
Quentin Colombetc32615d2014-10-31 17:52:53 +00005921 if (DisableStoreExtract || !TLI ||
5922 (!StressStoreExtract &&
5923 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5924 Inst->getOperand(1), CombineCost)))
5925 return false;
5926
5927 // At this point we know that Inst is a vector to scalar transition.
5928 // Try to move it down the def-use chain, until:
5929 // - We can combine the transition with its single use
5930 // => we got rid of the transition.
5931 // - We escape the current basic block
5932 // => we would need to check that we are moving it at a cheaper place and
5933 // we do not do that for now.
5934 BasicBlock *Parent = Inst->getParent();
5935 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005936 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005937 // If the transition has more than one use, assume this is not going to be
5938 // beneficial.
5939 while (Inst->hasOneUse()) {
5940 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5941 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5942
5943 if (ToBePromoted->getParent() != Parent) {
5944 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5945 << ToBePromoted->getParent()->getName()
5946 << ") than the transition (" << Parent->getName() << ").\n");
5947 return false;
5948 }
5949
5950 if (VPH.canCombine(ToBePromoted)) {
5951 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5952 << "will be combined with: " << *ToBePromoted << '\n');
5953 VPH.recordCombineInstruction(ToBePromoted);
5954 bool Changed = VPH.promote();
5955 NumStoreExtractExposed += Changed;
5956 return Changed;
5957 }
5958
5959 DEBUG(dbgs() << "Try promoting.\n");
5960 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5961 return false;
5962
5963 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5964
5965 VPH.enqueueForPromotion(ToBePromoted);
5966 Inst = ToBePromoted;
5967 }
5968 return false;
5969}
5970
Wei Mia2f0b592016-12-22 19:44:45 +00005971/// For the instruction sequence of store below, F and I values
5972/// are bundled together as an i64 value before being stored into memory.
5973/// Sometimes it is more efficent to generate separate stores for F and I,
5974/// which can remove the bitwise instructions or sink them to colder places.
5975///
5976/// (store (or (zext (bitcast F to i32) to i64),
5977/// (shl (zext I to i64), 32)), addr) -->
5978/// (store F, addr) and (store I, addr+4)
5979///
5980/// Similarly, splitting for other merged store can also be beneficial, like:
5981/// For pair of {i32, i32}, i64 store --> two i32 stores.
5982/// For pair of {i32, i16}, i64 store --> two i32 stores.
5983/// For pair of {i16, i16}, i32 store --> two i16 stores.
5984/// For pair of {i16, i8}, i32 store --> two i16 stores.
5985/// For pair of {i8, i8}, i16 store --> two i8 stores.
5986///
5987/// We allow each target to determine specifically which kind of splitting is
5988/// supported.
5989///
5990/// The store patterns are commonly seen from the simple code snippet below
5991/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5992/// void goo(const std::pair<int, float> &);
5993/// hoo() {
5994/// ...
5995/// goo(std::make_pair(tmp, ftmp));
5996/// ...
5997/// }
5998///
5999/// Although we already have similar splitting in DAG Combine, we duplicate
6000/// it in CodeGenPrepare to catch the case in which pattern is across
6001/// multiple BBs. The logic in DAG Combine is kept to catch case generated
6002/// during code expansion.
6003static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
6004 const TargetLowering &TLI) {
6005 // Handle simple but common cases only.
6006 Type *StoreType = SI.getValueOperand()->getType();
6007 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
6008 DL.getTypeSizeInBits(StoreType) == 0)
6009 return false;
6010
6011 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
6012 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
6013 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
6014 DL.getTypeSizeInBits(SplitStoreType))
6015 return false;
6016
6017 // Match the following patterns:
6018 // (store (or (zext LValue to i64),
6019 // (shl (zext HValue to i64), 32)), HalfValBitSize)
6020 // or
6021 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
6022 // (zext LValue to i64),
6023 // Expect both operands of OR and the first operand of SHL have only
6024 // one use.
6025 Value *LValue, *HValue;
6026 if (!match(SI.getValueOperand(),
6027 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
6028 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
6029 m_SpecificInt(HalfValBitSize))))))
6030 return false;
6031
6032 // Check LValue and HValue are int with size less or equal than 32.
6033 if (!LValue->getType()->isIntegerTy() ||
6034 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
6035 !HValue->getType()->isIntegerTy() ||
6036 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
6037 return false;
6038
6039 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
6040 // as the input of target query.
6041 auto *LBC = dyn_cast<BitCastInst>(LValue);
6042 auto *HBC = dyn_cast<BitCastInst>(HValue);
6043 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
6044 : EVT::getEVT(LValue->getType());
6045 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
6046 : EVT::getEVT(HValue->getType());
6047 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
6048 return false;
6049
6050 // Start to split store.
6051 IRBuilder<> Builder(SI.getContext());
6052 Builder.SetInsertPoint(&SI);
6053
6054 // If LValue/HValue is a bitcast in another BB, create a new one in current
6055 // BB so it may be merged with the splitted stores by dag combiner.
6056 if (LBC && LBC->getParent() != SI.getParent())
6057 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
6058 if (HBC && HBC->getParent() != SI.getParent())
6059 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
6060
6061 auto CreateSplitStore = [&](Value *V, bool Upper) {
6062 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
6063 Value *Addr = Builder.CreateBitCast(
6064 SI.getOperand(1),
6065 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
6066 if (Upper)
6067 Addr = Builder.CreateGEP(
6068 SplitStoreType, Addr,
6069 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
6070 Builder.CreateAlignedStore(
6071 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
6072 };
6073
6074 CreateSplitStore(LValue, false);
6075 CreateSplitStore(HValue, true);
6076
6077 // Delete the old store.
6078 SI.eraseFromParent();
6079 return true;
6080}
6081
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006082// Return true if the GEP has two operands, the first operand is of a sequential
6083// type, and the second operand is a constant.
6084static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
6085 gep_type_iterator I = gep_type_begin(*GEP);
6086 return GEP->getNumOperands() == 2 &&
6087 I.isSequential() &&
6088 isa<ConstantInt>(GEP->getOperand(1));
6089}
6090
6091// Try unmerging GEPs to reduce liveness interference (register pressure) across
6092// IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
6093// reducing liveness interference across those edges benefits global register
6094// allocation. Currently handles only certain cases.
6095//
6096// For example, unmerge %GEPI and %UGEPI as below.
6097//
6098// ---------- BEFORE ----------
6099// SrcBlock:
6100// ...
6101// %GEPIOp = ...
6102// ...
6103// %GEPI = gep %GEPIOp, Idx
6104// ...
6105// indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
6106// (* %GEPI is alive on the indirectbr edges due to other uses ahead)
6107// (* %GEPIOp is alive on the indirectbr edges only because of it's used by
6108// %UGEPI)
6109//
6110// DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
6111// DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
6112// ...
6113//
6114// DstBi:
6115// ...
6116// %UGEPI = gep %GEPIOp, UIdx
6117// ...
6118// ---------------------------
6119//
6120// ---------- AFTER ----------
6121// SrcBlock:
6122// ... (same as above)
6123// (* %GEPI is still alive on the indirectbr edges)
6124// (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
6125// unmerging)
6126// ...
6127//
6128// DstBi:
6129// ...
6130// %UGEPI = gep %GEPI, (UIdx-Idx)
6131// ...
6132// ---------------------------
6133//
6134// The register pressure on the IndirectBr edges is reduced because %GEPIOp is
6135// no longer alive on them.
6136//
6137// We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
6138// of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
6139// not to disable further simplications and optimizations as a result of GEP
6140// merging.
6141//
6142// Note this unmerging may increase the length of the data flow critical path
6143// (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
6144// between the register pressure and the length of data-flow critical
6145// path. Restricting this to the uncommon IndirectBr case would minimize the
6146// impact of potentially longer critical path, if any, and the impact on compile
6147// time.
6148static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
6149 const TargetTransformInfo *TTI) {
6150 BasicBlock *SrcBlock = GEPI->getParent();
6151 // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
6152 // (non-IndirectBr) cases exit early here.
6153 if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
6154 return false;
6155 // Check that GEPI is a simple gep with a single constant index.
6156 if (!GEPSequentialConstIndexed(GEPI))
6157 return false;
6158 ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
6159 // Check that GEPI is a cheap one.
6160 if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
6161 > TargetTransformInfo::TCC_Basic)
6162 return false;
6163 Value *GEPIOp = GEPI->getOperand(0);
6164 // Check that GEPIOp is an instruction that's also defined in SrcBlock.
6165 if (!isa<Instruction>(GEPIOp))
6166 return false;
6167 auto *GEPIOpI = cast<Instruction>(GEPIOp);
6168 if (GEPIOpI->getParent() != SrcBlock)
6169 return false;
6170 // Check that GEP is used outside the block, meaning it's alive on the
6171 // IndirectBr edge(s).
6172 if (find_if(GEPI->users(), [&](User *Usr) {
6173 if (auto *I = dyn_cast<Instruction>(Usr)) {
6174 if (I->getParent() != SrcBlock) {
6175 return true;
6176 }
6177 }
6178 return false;
6179 }) == GEPI->users().end())
6180 return false;
6181 // The second elements of the GEP chains to be unmerged.
6182 std::vector<GetElementPtrInst *> UGEPIs;
6183 // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
6184 // on IndirectBr edges.
6185 for (User *Usr : GEPIOp->users()) {
6186 if (Usr == GEPI) continue;
6187 // Check if Usr is an Instruction. If not, give up.
6188 if (!isa<Instruction>(Usr))
6189 return false;
6190 auto *UI = cast<Instruction>(Usr);
6191 // Check if Usr in the same block as GEPIOp, which is fine, skip.
6192 if (UI->getParent() == SrcBlock)
6193 continue;
6194 // Check if Usr is a GEP. If not, give up.
6195 if (!isa<GetElementPtrInst>(Usr))
6196 return false;
6197 auto *UGEPI = cast<GetElementPtrInst>(Usr);
6198 // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
6199 // the pointer operand to it. If so, record it in the vector. If not, give
6200 // up.
6201 if (!GEPSequentialConstIndexed(UGEPI))
6202 return false;
6203 if (UGEPI->getOperand(0) != GEPIOp)
6204 return false;
6205 if (GEPIIdx->getType() !=
6206 cast<ConstantInt>(UGEPI->getOperand(1))->getType())
6207 return false;
6208 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6209 if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
6210 > TargetTransformInfo::TCC_Basic)
6211 return false;
6212 UGEPIs.push_back(UGEPI);
6213 }
6214 if (UGEPIs.size() == 0)
6215 return false;
6216 // Check the materializing cost of (Uidx-Idx).
6217 for (GetElementPtrInst *UGEPI : UGEPIs) {
6218 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6219 APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
6220 unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
6221 if (ImmCost > TargetTransformInfo::TCC_Basic)
6222 return false;
6223 }
6224 // Now unmerge between GEPI and UGEPIs.
6225 for (GetElementPtrInst *UGEPI : UGEPIs) {
6226 UGEPI->setOperand(0, GEPI);
6227 ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
6228 Constant *NewUGEPIIdx =
6229 ConstantInt::get(GEPIIdx->getType(),
6230 UGEPIIdx->getValue() - GEPIIdx->getValue());
6231 UGEPI->setOperand(1, NewUGEPIIdx);
6232 // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
6233 // inbounds to avoid UB.
6234 if (!GEPI->isInBounds()) {
6235 UGEPI->setIsInBounds(false);
6236 }
6237 }
6238 // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
6239 // alive on IndirectBr edges).
6240 assert(find_if(GEPIOp->users(), [&](User *Usr) {
6241 return cast<Instruction>(Usr)->getParent() != SrcBlock;
6242 }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
6243 return true;
6244}
6245
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006246bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00006247 // Bail out if we inserted the instruction to prevent optimizations from
6248 // stepping on each other's toes.
6249 if (InsertedInsts.count(I))
6250 return false;
6251
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006252 if (PHINode *P = dyn_cast<PHINode>(I)) {
6253 // It is possible for very late stage optimizations (such as SimplifyCFG)
6254 // to introduce PHI nodes too late to be cleaned up. If we detect such a
6255 // trivial PHI, go ahead and zap it here.
Daniel Berlin4d0fe642017-04-28 19:55:38 +00006256 if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006257 P->replaceAllUsesWith(V);
6258 P->eraseFromParent();
6259 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00006260 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006261 }
Chris Lattneree588de2011-01-15 07:29:01 +00006262 return false;
6263 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006264
Chris Lattneree588de2011-01-15 07:29:01 +00006265 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006266 // If the source of the cast is a constant, then this should have
6267 // already been constant folded. The only reason NOT to constant fold
6268 // it is if something (e.g. LSR) was careful to place the constant
6269 // evaluation in a block other than then one that uses it (e.g. to hoist
6270 // the address of globals out of a loop). If this is the case, we don't
6271 // want to forward-subst the cast.
6272 if (isa<Constant>(CI->getOperand(0)))
6273 return false;
6274
Mehdi Amini44ede332015-07-09 02:09:04 +00006275 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00006276 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006277
Chris Lattneree588de2011-01-15 07:29:01 +00006278 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006279 /// Sink a zext or sext into its user blocks if the target type doesn't
6280 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00006281 if (TLI &&
6282 TLI->getTypeAction(CI->getContext(),
6283 TLI->getValueType(*DL, CI->getType())) ==
6284 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006285 return SinkCast(CI);
6286 } else {
Jun Bum Limdee55652017-04-03 19:20:07 +00006287 bool MadeChange = optimizeExt(I);
Sanjay Patelfc580a62015-09-21 23:03:16 +00006288 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00006289 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006290 }
Chris Lattneree588de2011-01-15 07:29:01 +00006291 return false;
6292 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006293
Chris Lattneree588de2011-01-15 07:29:01 +00006294 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00006295 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00006296 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00006297
Chris Lattneree588de2011-01-15 07:29:01 +00006298 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00006299 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006300 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00006301 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006302 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00006303 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
6304 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006305 }
Hans Wennborgf3254832012-10-30 11:23:25 +00006306 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00006307 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006308
Chris Lattneree588de2011-01-15 07:29:01 +00006309 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00006310 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
6311 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00006312 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006313 if (TLI) {
6314 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00006315 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00006316 SI->getOperand(0)->getType(), AS);
6317 }
Chris Lattneree588de2011-01-15 07:29:01 +00006318 return false;
6319 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006320
Matt Arsenault02d915b2017-03-15 22:35:20 +00006321 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
6322 unsigned AS = RMW->getPointerAddressSpace();
6323 return optimizeMemoryInst(I, RMW->getPointerOperand(),
6324 RMW->getType(), AS);
6325 }
6326
6327 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
6328 unsigned AS = CmpX->getPointerAddressSpace();
6329 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
6330 CmpX->getCompareOperand()->getType(), AS);
6331 }
6332
Yi Jiangd069f632014-04-21 19:34:27 +00006333 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
6334
Geoff Berry5d534b62017-02-21 18:53:14 +00006335 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
6336 EnableAndCmpSinking && TLI)
6337 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
6338
Yi Jiangd069f632014-04-21 19:34:27 +00006339 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
6340 BinOp->getOpcode() == Instruction::LShr)) {
6341 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
6342 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00006343 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00006344
6345 return false;
6346 }
6347
Chris Lattneree588de2011-01-15 07:29:01 +00006348 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006349 if (GEPI->hasAllZeroIndices()) {
6350 /// The GEP operand must be a pointer, so must its result -> BitCast
6351 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
6352 GEPI->getName(), GEPI);
6353 GEPI->replaceAllUsesWith(NC);
6354 GEPI->eraseFromParent();
6355 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00006356 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00006357 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00006358 }
Hiroshi Yamauchi93644322017-09-11 17:52:08 +00006359 if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
6360 return true;
6361 }
Chris Lattneree588de2011-01-15 07:29:01 +00006362 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006363 }
Nadav Rotem465834c2012-07-24 10:51:42 +00006364
Chris Lattneree588de2011-01-15 07:29:01 +00006365 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006366 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006367
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006368 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006369 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00006370
Tim Northoveraeb8e062014-02-19 10:02:43 +00006371 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006372 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00006373
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00006374 if (auto *Switch = dyn_cast<SwitchInst>(I))
6375 return optimizeSwitchInst(Switch);
6376
Quentin Colombetc32615d2014-10-31 17:52:53 +00006377 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00006378 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00006379
Chris Lattneree588de2011-01-15 07:29:01 +00006380 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00006381}
6382
James Molloyf01488e2016-01-15 09:20:19 +00006383/// Given an OR instruction, check to see if this is a bitreverse
6384/// idiom. If so, insert the new intrinsic and return true.
6385static bool makeBitReverse(Instruction &I, const DataLayout &DL,
6386 const TargetLowering &TLI) {
6387 if (!I.getType()->isIntegerTy() ||
6388 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
6389 TLI.getValueType(DL, I.getType(), true)))
6390 return false;
6391
6392 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00006393 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00006394 return false;
6395 Instruction *LastInst = Insts.back();
6396 I.replaceAllUsesWith(LastInst);
6397 RecursivelyDeleteTriviallyDeadInstructions(&I);
6398 return true;
6399}
6400
Chris Lattnerf2836d12007-03-31 04:06:36 +00006401// In this pass we look for GEP and cast instructions that are used
6402// across basic blocks and rewrite them to improve basic-block-at-a-time
6403// selection.
Sanjay Patel3b8974b2017-06-08 20:00:09 +00006404bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00006405 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00006406 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00006407
Chris Lattner7a277142011-01-15 07:14:54 +00006408 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006409 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006410 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00006411 if (ModifiedDT)
6412 return true;
6413 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00006414
James Molloyf01488e2016-01-15 09:20:19 +00006415 bool MadeBitReverse = true;
6416 while (TLI && MadeBitReverse) {
6417 MadeBitReverse = false;
6418 for (auto &I : reverse(BB)) {
6419 if (makeBitReverse(I, *DL, *TLI)) {
6420 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00006421 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00006422 break;
6423 }
6424 }
6425 }
James Molloy3ef84c42016-01-15 10:36:01 +00006426 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00006427
Chris Lattnerf2836d12007-03-31 04:06:36 +00006428 return MadeChange;
6429}
Devang Patel53771ba2011-08-18 00:50:51 +00006430
6431// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00006432// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00006433// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00006434bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00006435 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006436 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00006437 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00006438 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00006439 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00006440 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00006441 // Leave dbg.values that refer to an alloca alone. These
Craig Topper87e715f2017-11-07 20:56:17 +00006442 // intrinsics describe the address of a variable (= the alloca)
Adrian Prantl32da8892014-04-25 20:49:25 +00006443 // being taken. They should not be moved next to the alloca
6444 // (and to the beginning of the scope), but rather stay close to
6445 // where said address is used.
6446 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00006447 PrevNonDbgInst = Insn;
6448 continue;
6449 }
6450
6451 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
6452 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00006453 // If VI is a phi in a block with an EHPad terminator, we can't insert
6454 // after it.
6455 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
6456 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00006457 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
6458 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00006459 if (isa<PHINode>(VI))
6460 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
6461 else
6462 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00006463 MadeChange = true;
6464 ++NumDbgValueMoved;
6465 }
6466 }
6467 }
6468 return MadeChange;
6469}
Tim Northovercea0abb2014-03-29 08:22:29 +00006470
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006471/// \brief Scale down both weights to fit into uint32_t.
6472static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
6473 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
Eugene Zelenko900b6332017-08-29 22:32:07 +00006474 uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006475 NewTrue = NewTrue / Scale;
6476 NewFalse = NewFalse / Scale;
6477}
6478
6479/// \brief Some targets prefer to split a conditional branch like:
6480/// \code
6481/// %0 = icmp ne i32 %a, 0
6482/// %1 = icmp ne i32 %b, 0
6483/// %or.cond = or i1 %0, %1
6484/// br i1 %or.cond, label %TrueBB, label %FalseBB
6485/// \endcode
6486/// into multiple branch instructions like:
6487/// \code
6488/// bb1:
6489/// %0 = icmp ne i32 %a, 0
6490/// br i1 %0, label %TrueBB, label %bb2
6491/// bb2:
6492/// %1 = icmp ne i32 %b, 0
6493/// br i1 %1, label %TrueBB, label %FalseBB
6494/// \endcode
6495/// This usually allows instruction selection to do even further optimizations
6496/// and combine the compare with the branch instruction. Currently this is
6497/// applied for targets which have "cheap" jump instructions.
6498///
6499/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6500///
6501bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006502 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006503 return false;
6504
6505 bool MadeChange = false;
6506 for (auto &BB : F) {
6507 // Does this BB end with the following?
6508 // %cond1 = icmp|fcmp|binary instruction ...
6509 // %cond2 = icmp|fcmp|binary instruction ...
6510 // %cond.or = or|and i1 %cond1, cond2
6511 // br i1 %cond.or label %dest1, label %dest2"
6512 BinaryOperator *LogicOp;
6513 BasicBlock *TBB, *FBB;
6514 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6515 continue;
6516
Sanjay Patel42574202015-09-02 19:23:23 +00006517 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6518 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6519 continue;
6520
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006521 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006522 Value *Cond1, *Cond2;
6523 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6524 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006525 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006526 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6527 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006528 Opc = Instruction::Or;
6529 else
6530 continue;
6531
6532 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6533 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6534 continue;
6535
6536 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6537
6538 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006539 auto TmpBB =
6540 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6541 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006542
6543 // Update original basic block by using the first condition directly by the
6544 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006545 Br1->setCondition(Cond1);
6546 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006547
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006548 // Depending on the conditon we have to either replace the true or the false
6549 // successor of the original branch instruction.
6550 if (Opc == Instruction::And)
6551 Br1->setSuccessor(0, TmpBB);
6552 else
6553 Br1->setSuccessor(1, TmpBB);
6554
6555 // Fill in the new basic block.
6556 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006557 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6558 I->removeFromParent();
6559 I->insertBefore(Br2);
6560 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006561
6562 // Update PHI nodes in both successors. The original BB needs to be
Hiroshi Inoue6a391bb2017-06-27 10:35:37 +00006563 // replaced in one successor's PHI nodes, because the branch comes now from
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006564 // the newly generated BB (NewBB). In the other successor we need to add one
6565 // incoming edge to the PHI nodes, because both branch instructions target
6566 // now the same successor. Depending on the original branch condition
6567 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006568 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006569 // This doesn't change the successor order of the just created branch
6570 // instruction (or any other instruction).
6571 if (Opc == Instruction::Or)
6572 std::swap(TBB, FBB);
6573
6574 // Replace the old BB with the new BB.
6575 for (auto &I : *TBB) {
6576 PHINode *PN = dyn_cast<PHINode>(&I);
6577 if (!PN)
6578 break;
6579 int i;
6580 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6581 PN->setIncomingBlock(i, TmpBB);
6582 }
6583
6584 // Add another incoming edge form the new BB.
6585 for (auto &I : *FBB) {
6586 PHINode *PN = dyn_cast<PHINode>(&I);
6587 if (!PN)
6588 break;
6589 auto *Val = PN->getIncomingValueForBlock(&BB);
6590 PN->addIncoming(Val, TmpBB);
6591 }
6592
6593 // Update the branch weights (from SelectionDAGBuilder::
6594 // FindMergedConditions).
6595 if (Opc == Instruction::Or) {
6596 // Codegen X | Y as:
6597 // BB1:
6598 // jmp_if_X TBB
6599 // jmp TmpBB
6600 // TmpBB:
6601 // jmp_if_Y TBB
6602 // jmp FBB
6603 //
6604
6605 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6606 // The requirement is that
6607 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6608 // = TrueProb for orignal BB.
6609 // Assuming the orignal weights are A and B, one choice is to set BB1's
6610 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6611 // assumes that
6612 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6613 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6614 // TmpBB, but the math is more complicated.
6615 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006616 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006617 uint64_t NewTrueWeight = TrueWeight;
6618 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6619 scaleWeights(NewTrueWeight, NewFalseWeight);
6620 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6621 .createBranchWeights(TrueWeight, FalseWeight));
6622
6623 NewTrueWeight = TrueWeight;
6624 NewFalseWeight = 2 * FalseWeight;
6625 scaleWeights(NewTrueWeight, NewFalseWeight);
6626 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6627 .createBranchWeights(TrueWeight, FalseWeight));
6628 }
6629 } else {
6630 // Codegen X & Y as:
6631 // BB1:
6632 // jmp_if_X TmpBB
6633 // jmp FBB
6634 // TmpBB:
6635 // jmp_if_Y TBB
6636 // jmp FBB
6637 //
6638 // This requires creation of TmpBB after CurBB.
6639
6640 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6641 // The requirement is that
6642 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6643 // = FalseProb for orignal BB.
6644 // Assuming the orignal weights are A and B, one choice is to set BB1's
6645 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6646 // assumes that
6647 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6648 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006649 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006650 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6651 uint64_t NewFalseWeight = FalseWeight;
6652 scaleWeights(NewTrueWeight, NewFalseWeight);
6653 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6654 .createBranchWeights(TrueWeight, FalseWeight));
6655
6656 NewTrueWeight = 2 * TrueWeight;
6657 NewFalseWeight = FalseWeight;
6658 scaleWeights(NewTrueWeight, NewFalseWeight);
6659 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6660 .createBranchWeights(TrueWeight, FalseWeight));
6661 }
6662 }
6663
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006664 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006665 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006666 ModifiedDT = true;
6667
6668 MadeChange = true;
6669
6670 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6671 TmpBB->dump());
6672 }
6673 return MadeChange;
6674}