blob: bd111325beec64ed218c03911edc3f62c8842ce0 [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
Quentin Colombeta3490842014-02-22 00:07:45 +000016#include "llvm/CodeGen/Passes.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/DenseMap.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000018#include "llvm/ADT/SetVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/SmallSet.h"
20#include "llvm/ADT/Statistic.h"
Jun Bum Lim90b6b502016-12-16 20:38:39 +000021#include "llvm/Analysis/BlockFrequencyInfo.h"
22#include "llvm/Analysis/BranchProbabilityInfo.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000023#include "llvm/Analysis/CFG.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000025#include "llvm/Analysis/LoopInfo.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000026#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000028#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000029#include "llvm/Analysis/ValueTracking.h"
Petar Jovanovic644b8c12016-04-13 12:25:25 +000030#include "llvm/Analysis/MemoryBuiltins.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000031#include "llvm/CodeGen/Analysis.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000032#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000036#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000038#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/InlineAsm.h"
41#include "llvm/IR/Instructions.h"
42#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000043#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000044#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000045#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000046#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000047#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000048#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000049#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000050#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000051#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000052#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000053#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000054#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000055#include "llvm/Transforms/Utils/BasicBlockUtils.h"
56#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000057#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000058#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000059#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000060#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Michael Kuperstein13bf8a22017-02-28 00:11:34 +000061#include "llvm/Transforms/Utils/ValueMapper.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000062using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000063using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000064
Chandler Carruth1b9dde02014-04-22 02:02:50 +000065#define DEBUG_TYPE "codegenprepare"
66
Cameron Zwarichced753f2011-01-05 17:27:27 +000067STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000068STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
69STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000070STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
71 "sunken Cmps");
72STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
73 "of sunken Casts");
74STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
75 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000076STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
77STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000078STATISTIC(NumAndsAdded,
79 "Number of and mask instructions added to form ext loads");
80STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000081STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000082STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000083STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000084STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000085
Cameron Zwarich338d3622011-03-11 21:52:04 +000086static cl::opt<bool> DisableBranchOpts(
87 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
88 cl::desc("Disable branch optimizations in CodeGenPrepare"));
89
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000090static cl::opt<bool>
91 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
92 cl::desc("Disable GC optimizations in CodeGenPrepare"));
93
Benjamin Kramer3d38c172012-05-06 14:25:16 +000094static cl::opt<bool> DisableSelectToBranch(
95 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
96 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000097
Hal Finkelc3998302014-04-12 00:59:48 +000098static cl::opt<bool> AddrSinkUsingGEPs(
99 "addr-sink-using-gep", cl::Hidden, cl::init(false),
100 cl::desc("Address sinking in CGP using GEPs."));
101
Tim Northovercea0abb2014-03-29 08:22:29 +0000102static cl::opt<bool> EnableAndCmpSinking(
103 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
104 cl::desc("Enable sinkinig and/cmp into branches."));
105
Quentin Colombetc32615d2014-10-31 17:52:53 +0000106static cl::opt<bool> DisableStoreExtract(
107 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
108 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
109
110static cl::opt<bool> StressStoreExtract(
111 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
112 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
113
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000114static cl::opt<bool> DisableExtLdPromotion(
115 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
116 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
117 "CodeGenPrepare"));
118
119static cl::opt<bool> StressExtLdPromotion(
120 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
121 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
122 "optimization in CodeGenPrepare"));
123
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000124static cl::opt<bool> DisablePreheaderProtect(
125 "disable-preheader-prot", cl::Hidden, cl::init(false),
126 cl::desc("Disable protection against removing loop preheaders"));
127
Dehao Chen302b69c2016-10-18 20:42:47 +0000128static cl::opt<bool> ProfileGuidedSectionPrefix(
129 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
130 cl::desc("Use profile info to add section prefix for hot/cold functions"));
131
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000132static cl::opt<unsigned> FreqRatioToSkipMerge(
133 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
134 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
135 "(frequency of destination block) is greater than this ratio"));
136
Wei Mia2f0b592016-12-22 19:44:45 +0000137static cl::opt<bool> ForceSplitStore(
138 "force-split-store", cl::Hidden, cl::init(false),
139 cl::desc("Force store splitting no matter what the target query says."));
140
Eric Christopherc1ea1492008-09-24 05:32:41 +0000141namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000142typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000143typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000144typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000145class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000146
Chris Lattner2dd09db2009-09-02 06:11:42 +0000147 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000148 const TargetMachine *TM;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000149 const TargetSubtargetInfo *SubtargetInfo;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000150 const TargetLowering *TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000151 const TargetRegisterInfo *TRI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000152 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000153 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000154 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000155 std::unique_ptr<BlockFrequencyInfo> BFI;
156 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000157
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000158 /// As we scan instructions optimizing them, this is the next instruction
159 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000160 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000161
Evan Cheng0663f232011-03-21 01:19:09 +0000162 /// Keeps track of non-local addresses that have been sunk into a block.
163 /// This allows us to avoid inserting duplicate code for blocks with
164 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000165 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000166
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000167 /// Keeps track of all instructions inserted for the current function.
168 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000169 /// Keeps track of the type of the related instruction before their
170 /// promotion for the current function.
171 InstrToOrigTy PromotedInsts;
172
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000173 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000174 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000175
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000176 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000177 bool OptSize;
178
Mehdi Amini4fe37982015-07-07 18:45:17 +0000179 /// DataLayout for the Function being processed.
180 const DataLayout *DL;
181
Chris Lattnerf2836d12007-03-31 04:06:36 +0000182 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000183 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000184 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000185 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000186 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
187 }
Craig Topper4584cd52014-03-07 09:26:03 +0000188 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000189
Mehdi Amini117296c2016-10-01 02:56:57 +0000190 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000191
Craig Topper4584cd52014-03-07 09:26:03 +0000192 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000193 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000194 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000195 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000196 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000197 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000198 }
199
Chris Lattnerf2836d12007-03-31 04:06:36 +0000200 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000201 bool eliminateFallThrough(Function &F);
202 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000203 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000204 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
205 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000206 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
207 bool isPreheader);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000208 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
209 bool optimizeInst(Instruction *I, bool& ModifiedDT);
210 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000211 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000212 bool optimizeInlineAsmInst(CallInst *CS);
213 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
214 bool moveExtToFormExtLoad(Instruction *&I);
215 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000216 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000217 bool optimizeSelectInst(SelectInst *SI);
218 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000219 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000220 bool optimizeExtractElementInst(Instruction *Inst);
221 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
222 bool placeDbgValues(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000223 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000224 Instruction *&Inst,
225 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000226 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000227 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000228 bool simplifyOffsetableRelocate(Instruction &I);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000229 bool splitIndirectCriticalEdges(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000230 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000231}
Devang Patel09f162c2007-05-01 21:15:47 +0000232
Devang Patel8c78a0b2007-05-03 01:11:54 +0000233char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000234INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
235 "Optimize for code generation", false, false)
236INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
237INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
238 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000239
Bill Wendling7a639ea2013-06-19 21:07:11 +0000240FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
241 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000242}
243
Chris Lattnerf2836d12007-03-31 04:06:36 +0000244bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000245 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000246 return false;
247
Mehdi Amini4fe37982015-07-07 18:45:17 +0000248 DL = &F.getParent()->getDataLayout();
249
Chris Lattnerf2836d12007-03-31 04:06:36 +0000250 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000251 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000252 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000253 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000254 BFI.reset();
255 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000256
Devang Patel8f606d72011-03-24 15:35:25 +0000257 ModifiedDT = false;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000258 if (TM) {
259 SubtargetInfo = TM->getSubtargetImpl(F);
260 TLI = SubtargetInfo->getTargetLowering();
261 TRI = SubtargetInfo->getRegisterInfo();
262 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000263 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000264 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000265 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000266 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000267
Dehao Chen302b69c2016-10-18 20:42:47 +0000268 if (ProfileGuidedSectionPrefix) {
269 ProfileSummaryInfo *PSI =
270 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
271 if (PSI->isFunctionEntryHot(&F))
272 F.setSectionPrefix(".hot");
273 else if (PSI->isFunctionEntryCold(&F))
274 F.setSectionPrefix(".cold");
275 }
276
Preston Gurdcdf540d2012-09-04 18:22:17 +0000277 /// This optimization identifies DIV instructions that can be
278 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000279 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000280 const DenseMap<unsigned int, unsigned int> &BypassWidths =
281 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000282 BasicBlock* BB = &*F.begin();
283 while (BB != nullptr) {
284 // bypassSlowDivision may create new BBs, but we don't want to reapply the
285 // optimization to those blocks.
286 BasicBlock* Next = BB->getNextNode();
287 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
288 BB = Next;
289 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000290 }
291
292 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000293 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000294 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000295
Devang Patel53771ba2011-08-18 00:50:51 +0000296 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000297 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000298 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000299 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000300
Geoff Berry5d534b62017-02-21 18:53:14 +0000301 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000302 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000303
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000304 // Split some critical edges where one of the sources is an indirect branch,
305 // to help generate sane code for PHIs involving such edges.
306 EverMadeChange |= splitIndirectCriticalEdges(F);
307
Chris Lattnerc3748562007-04-02 01:35:34 +0000308 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000309 while (MadeChange) {
310 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000311 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000312 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000313 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000314 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000315
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000316 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000317 if (ModifiedDTOnIteration)
318 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000319 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000320 EverMadeChange |= MadeChange;
321 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000322
323 SunkAddrs.clear();
324
Cameron Zwarich338d3622011-03-11 21:52:04 +0000325 if (!DisableBranchOpts) {
326 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000327 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000328 for (BasicBlock &BB : F) {
329 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
330 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000331 if (!MadeChange) continue;
332
333 for (SmallVectorImpl<BasicBlock*>::iterator
334 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
335 if (pred_begin(*II) == pred_end(*II))
336 WorkList.insert(*II);
337 }
338
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000339 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000340 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000341 while (!WorkList.empty()) {
342 BasicBlock *BB = *WorkList.begin();
343 WorkList.erase(BB);
344 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
345
346 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000347
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000348 for (SmallVectorImpl<BasicBlock*>::iterator
349 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
350 if (pred_begin(*II) == pred_end(*II))
351 WorkList.insert(*II);
352 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000353
Nadav Rotem70409992012-08-14 05:19:07 +0000354 // Merge pairs of basic blocks with unconditional branches, connected by
355 // a single edge.
356 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000357 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000358
Cameron Zwarich338d3622011-03-11 21:52:04 +0000359 EverMadeChange |= MadeChange;
360 }
361
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000362 if (!DisableGCOpts) {
363 SmallVector<Instruction *, 2> Statepoints;
364 for (BasicBlock &BB : F)
365 for (Instruction &I : BB)
366 if (isStatepoint(I))
367 Statepoints.push_back(&I);
368 for (auto &I : Statepoints)
369 EverMadeChange |= simplifyOffsetableRelocate(*I);
370 }
371
Chris Lattnerf2836d12007-03-31 04:06:36 +0000372 return EverMadeChange;
373}
374
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000375/// Merge basic blocks which are connected by a single edge, where one of the
376/// basic blocks has a single successor pointing to the other basic block,
377/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000378bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000379 bool Changed = false;
380 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000381 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000382 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000383 // If the destination block has a single pred, then this is a trivial
384 // edge, just collapse it.
385 BasicBlock *SinglePred = BB->getSinglePredecessor();
386
Evan Cheng64a223a2012-09-28 23:58:57 +0000387 // Don't merge if BB's address is taken.
388 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000389
390 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
391 if (Term && !Term->isConditional()) {
392 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000393 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000394 // Remember if SinglePred was the entry block of the function.
395 // If so, we will need to move BB back to the entry position.
396 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000397 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000398
399 if (isEntry && BB != &BB->getParent()->getEntryBlock())
400 BB->moveBefore(&BB->getParent()->getEntryBlock());
401
402 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000403 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000404 }
405 }
406 return Changed;
407}
408
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000409/// Find a destination block from BB if BB is mergeable empty block.
410BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
411 // If this block doesn't end with an uncond branch, ignore it.
412 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
413 if (!BI || !BI->isUnconditional())
414 return nullptr;
415
416 // If the instruction before the branch (skipping debug info) isn't a phi
417 // node, then other stuff is happening here.
418 BasicBlock::iterator BBI = BI->getIterator();
419 if (BBI != BB->begin()) {
420 --BBI;
421 while (isa<DbgInfoIntrinsic>(BBI)) {
422 if (BBI == BB->begin())
423 break;
424 --BBI;
425 }
426 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
427 return nullptr;
428 }
429
430 // Do not break infinite loops.
431 BasicBlock *DestBB = BI->getSuccessor(0);
432 if (DestBB == BB)
433 return nullptr;
434
435 if (!canMergeBlocks(BB, DestBB))
436 DestBB = nullptr;
437
438 return DestBB;
439}
440
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000441// Return the unique indirectbr predecessor of a block. This may return null
442// even if such a predecessor exists, if it's not useful for splitting.
443// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
444// predecessors of BB.
445static BasicBlock *
446findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
447 // If the block doesn't have any PHIs, we don't care about it, since there's
448 // no point in splitting it.
449 PHINode *PN = dyn_cast<PHINode>(BB->begin());
450 if (!PN)
451 return nullptr;
452
453 // Verify we have exactly one IBR predecessor.
454 // Conservatively bail out if one of the other predecessors is not a "regular"
455 // terminator (that is, not a switch or a br).
456 BasicBlock *IBB = nullptr;
457 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
458 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
459 TerminatorInst *PredTerm = PredBB->getTerminator();
460 switch (PredTerm->getOpcode()) {
461 case Instruction::IndirectBr:
462 if (IBB)
463 return nullptr;
464 IBB = PredBB;
465 break;
466 case Instruction::Br:
467 case Instruction::Switch:
468 OtherPreds.push_back(PredBB);
469 continue;
470 default:
471 return nullptr;
472 }
473 }
474
475 return IBB;
476}
477
478// Split critical edges where the source of the edge is an indirectbr
479// instruction. This isn't always possible, but we can handle some easy cases.
480// This is useful because MI is unable to split such critical edges,
481// which means it will not be able to sink instructions along those edges.
482// This is especially painful for indirect branches with many successors, where
483// we end up having to prepare all outgoing values in the origin block.
484//
485// Our normal algorithm for splitting critical edges requires us to update
486// the outgoing edges of the edge origin block, but for an indirectbr this
487// is hard, since it would require finding and updating the block addresses
488// the indirect branch uses. But if a block only has a single indirectbr
489// predecessor, with the others being regular branches, we can do it in a
490// different way.
491// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
492// We can split D into D0 and D1, where D0 contains only the PHIs from D,
493// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
494// create the following structure:
495// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
496bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
497 // Check whether the function has any indirectbrs, and collect which blocks
498 // they may jump to. Since most functions don't have indirect branches,
499 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
500 SmallSetVector<BasicBlock *, 16> Targets;
501 for (auto &BB : F) {
502 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
503 if (!IBI)
504 continue;
505
506 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
507 Targets.insert(IBI->getSuccessor(Succ));
508 }
509
510 if (Targets.empty())
511 return false;
512
513 bool Changed = false;
514 for (BasicBlock *Target : Targets) {
515 SmallVector<BasicBlock *, 16> OtherPreds;
516 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
517 // If we did not found an indirectbr, or the indirectbr is the only
518 // incoming edge, this isn't the kind of edge we're looking for.
519 if (!IBRPred || OtherPreds.empty())
520 continue;
521
522 // Don't even think about ehpads/landingpads.
523 Instruction *FirstNonPHI = Target->getFirstNonPHI();
524 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
525 continue;
526
527 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
528 // It's possible Target was its own successor through an indirectbr.
529 // In this case, the indirectbr now comes from BodyBlock.
530 if (IBRPred == Target)
531 IBRPred = BodyBlock;
532
533 // At this point Target only has PHIs, and BodyBlock has the rest of the
534 // block's body. Create a copy of Target that will be used by the "direct"
535 // preds.
536 ValueToValueMapTy VMap;
537 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
538
539 for (BasicBlock *Pred : OtherPreds)
540 Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
541
542 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
543 // they are clones, so the number of PHIs are the same.
544 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
545 // (b) Leave that as the only edge in the "Indirect" PHI.
546 // (c) Merge the two in the body block.
547 BasicBlock::iterator Indirect = Target->begin(),
548 End = Target->getFirstNonPHI()->getIterator();
549 BasicBlock::iterator Direct = DirectSucc->begin();
550 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
551
552 assert(&*End == Target->getTerminator() &&
553 "Block was expected to only contain PHIs");
554
555 while (Indirect != End) {
556 PHINode *DirPHI = cast<PHINode>(Direct);
557 PHINode *IndPHI = cast<PHINode>(Indirect);
558
559 // Now, clean up - the direct block shouldn't get the indirect value,
560 // and vice versa.
561 DirPHI->removeIncomingValue(IBRPred);
562 Direct++;
563
564 // Advance the pointer here, to avoid invalidation issues when the old
565 // PHI is erased.
566 Indirect++;
567
568 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
569 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
570 IBRPred);
571
572 // Create a PHI in the body block, to merge the direct and indirect
573 // predecessors.
574 PHINode *MergePHI =
575 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
576 MergePHI->addIncoming(NewIndPHI, Target);
577 MergePHI->addIncoming(DirPHI, DirectSucc);
578
579 IndPHI->replaceAllUsesWith(MergePHI);
580 IndPHI->eraseFromParent();
581 }
582
583 Changed = true;
584 }
585
586 return Changed;
587}
588
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000589/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
590/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
591/// edges in ways that are non-optimal for isel. Start by eliminating these
592/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000593bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000594 SmallPtrSet<BasicBlock *, 16> Preheaders;
595 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
596 while (!LoopList.empty()) {
597 Loop *L = LoopList.pop_back_val();
598 LoopList.insert(LoopList.end(), L->begin(), L->end());
599 if (BasicBlock *Preheader = L->getLoopPreheader())
600 Preheaders.insert(Preheader);
601 }
602
Chris Lattnerc3748562007-04-02 01:35:34 +0000603 bool MadeChange = false;
604 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000605 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000606 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000607 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
608 if (!DestBB ||
609 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000610 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000611
Sanjay Patelfc580a62015-09-21 23:03:16 +0000612 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000613 MadeChange = true;
614 }
615 return MadeChange;
616}
617
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000618bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
619 BasicBlock *DestBB,
620 bool isPreheader) {
621 // Do not delete loop preheaders if doing so would create a critical edge.
622 // Loop preheaders can be good locations to spill registers. If the
623 // preheader is deleted and we create a critical edge, registers may be
624 // spilled in the loop body instead.
625 if (!DisablePreheaderProtect && isPreheader &&
626 !(BB->getSinglePredecessor() &&
627 BB->getSinglePredecessor()->getSingleSuccessor()))
628 return false;
629
630 // Try to skip merging if the unique predecessor of BB is terminated by a
631 // switch or indirect branch instruction, and BB is used as an incoming block
632 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
633 // add COPY instructions in the predecessor of BB instead of BB (if it is not
634 // merged). Note that the critical edge created by merging such blocks wont be
635 // split in MachineSink because the jump table is not analyzable. By keeping
636 // such empty block (BB), ISel will place COPY instructions in BB, not in the
637 // predecessor of BB.
638 BasicBlock *Pred = BB->getUniquePredecessor();
639 if (!Pred ||
640 !(isa<SwitchInst>(Pred->getTerminator()) ||
641 isa<IndirectBrInst>(Pred->getTerminator())))
642 return true;
643
644 if (BB->getTerminator() != BB->getFirstNonPHI())
645 return true;
646
647 // We use a simple cost heuristic which determine skipping merging is
648 // profitable if the cost of skipping merging is less than the cost of
649 // merging : Cost(skipping merging) < Cost(merging BB), where the
650 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
651 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
652 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
653 // Freq(Pred) / Freq(BB) > 2.
654 // Note that if there are multiple empty blocks sharing the same incoming
655 // value for the PHIs in the DestBB, we consider them together. In such
656 // case, Cost(merging BB) will be the sum of their frequencies.
657
658 if (!isa<PHINode>(DestBB->begin()))
659 return true;
660
661 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
662
663 // Find all other incoming blocks from which incoming values of all PHIs in
664 // DestBB are the same as the ones from BB.
665 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
666 ++PI) {
667 BasicBlock *DestBBPred = *PI;
668 if (DestBBPred == BB)
669 continue;
670
671 bool HasAllSameValue = true;
672 BasicBlock::const_iterator DestBBI = DestBB->begin();
673 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
674 if (DestPN->getIncomingValueForBlock(BB) !=
675 DestPN->getIncomingValueForBlock(DestBBPred)) {
676 HasAllSameValue = false;
677 break;
678 }
679 }
680 if (HasAllSameValue)
681 SameIncomingValueBBs.insert(DestBBPred);
682 }
683
684 // See if all BB's incoming values are same as the value from Pred. In this
685 // case, no reason to skip merging because COPYs are expected to be place in
686 // Pred already.
687 if (SameIncomingValueBBs.count(Pred))
688 return true;
689
690 if (!BFI) {
691 Function &F = *BB->getParent();
692 LoopInfo LI{DominatorTree(F)};
693 BPI.reset(new BranchProbabilityInfo(F, LI));
694 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
695 }
696
697 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
698 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
699
700 for (auto SameValueBB : SameIncomingValueBBs)
701 if (SameValueBB->getUniquePredecessor() == Pred &&
702 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
703 BBFreq += BFI->getBlockFreq(SameValueBB);
704
705 return PredFreq.getFrequency() <=
706 BBFreq.getFrequency() * FreqRatioToSkipMerge;
707}
708
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000709/// Return true if we can merge BB into DestBB if there is a single
710/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000711/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000712bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000713 const BasicBlock *DestBB) const {
714 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
715 // the successor. If there are more complex condition (e.g. preheaders),
716 // don't mess around with them.
717 BasicBlock::const_iterator BBI = BB->begin();
718 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000719 for (const User *U : PN->users()) {
720 const Instruction *UI = cast<Instruction>(U);
721 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000722 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000723 // If User is inside DestBB block and it is a PHINode then check
724 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000725 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000726 if (UI->getParent() == DestBB) {
727 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000728 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
729 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
730 if (Insn && Insn->getParent() == BB &&
731 Insn->getParent() != UPN->getIncomingBlock(I))
732 return false;
733 }
734 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000735 }
736 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000737
Chris Lattnerc3748562007-04-02 01:35:34 +0000738 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
739 // and DestBB may have conflicting incoming values for the block. If so, we
740 // can't merge the block.
741 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
742 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000743
Chris Lattnerc3748562007-04-02 01:35:34 +0000744 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000745 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000746 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
747 // It is faster to get preds from a PHI than with pred_iterator.
748 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
749 BBPreds.insert(BBPN->getIncomingBlock(i));
750 } else {
751 BBPreds.insert(pred_begin(BB), pred_end(BB));
752 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000753
Chris Lattnerc3748562007-04-02 01:35:34 +0000754 // Walk the preds of DestBB.
755 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
756 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
757 if (BBPreds.count(Pred)) { // Common predecessor?
758 BBI = DestBB->begin();
759 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
760 const Value *V1 = PN->getIncomingValueForBlock(Pred);
761 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000762
Chris Lattnerc3748562007-04-02 01:35:34 +0000763 // If V2 is a phi node in BB, look up what the mapped value will be.
764 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
765 if (V2PN->getParent() == BB)
766 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000767
Chris Lattnerc3748562007-04-02 01:35:34 +0000768 // If there is a conflict, bail out.
769 if (V1 != V2) return false;
770 }
771 }
772 }
773
774 return true;
775}
776
777
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000778/// Eliminate a basic block that has only phi's and an unconditional branch in
779/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000780void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000781 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
782 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000783
David Greene74e2d492010-01-05 01:27:11 +0000784 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000785
Chris Lattnerc3748562007-04-02 01:35:34 +0000786 // If the destination block has a single pred, then this is a trivial edge,
787 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000788 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000789 if (SinglePred != DestBB) {
790 // Remember if SinglePred was the entry block of the function. If so, we
791 // will need to move BB back to the entry position.
792 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000793 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000794
Chris Lattner8a172da2008-11-28 19:54:49 +0000795 if (isEntry && BB != &BB->getParent()->getEntryBlock())
796 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000797
David Greene74e2d492010-01-05 01:27:11 +0000798 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000799 return;
800 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000801 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000802
Chris Lattnerc3748562007-04-02 01:35:34 +0000803 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
804 // to handle the new incoming edges it is about to have.
805 PHINode *PN;
806 for (BasicBlock::iterator BBI = DestBB->begin();
807 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
808 // Remove the incoming value for BB, and remember it.
809 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000810
Chris Lattnerc3748562007-04-02 01:35:34 +0000811 // Two options: either the InVal is a phi node defined in BB or it is some
812 // value that dominates BB.
813 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
814 if (InValPhi && InValPhi->getParent() == BB) {
815 // Add all of the input values of the input PHI as inputs of this phi.
816 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
817 PN->addIncoming(InValPhi->getIncomingValue(i),
818 InValPhi->getIncomingBlock(i));
819 } else {
820 // Otherwise, add one instance of the dominating value for each edge that
821 // we will be adding.
822 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
823 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
824 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
825 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000826 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
827 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000828 }
829 }
830 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000831
Chris Lattnerc3748562007-04-02 01:35:34 +0000832 // The PHIs are now updated, change everything that refers to BB to use
833 // DestBB and remove BB.
834 BB->replaceAllUsesWith(DestBB);
835 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000836 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000837
David Greene74e2d492010-01-05 01:27:11 +0000838 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000839}
840
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000841// Computes a map of base pointer relocation instructions to corresponding
842// derived pointer relocation instructions given a vector of all relocate calls
843static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000844 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
845 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
846 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000847 // Collect information in two maps: one primarily for locating the base object
848 // while filling the second map; the second map is the final structure holding
849 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000850 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
851 for (auto *ThisRelocate : AllRelocateCalls) {
852 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
853 ThisRelocate->getDerivedPtrIndex());
854 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000855 }
856 for (auto &Item : RelocateIdxMap) {
857 std::pair<unsigned, unsigned> Key = Item.first;
858 if (Key.first == Key.second)
859 // Base relocation: nothing to insert
860 continue;
861
Manuel Jacob83eefa62016-01-05 04:03:00 +0000862 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000863 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000864
865 // We're iterating over RelocateIdxMap so we cannot modify it.
866 auto MaybeBase = RelocateIdxMap.find(BaseKey);
867 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000868 // TODO: We might want to insert a new base object relocate and gep off
869 // that, if there are enough derived object relocates.
870 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000871
872 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000873 }
874}
875
876// Accepts a GEP and extracts the operands into a vector provided they're all
877// small integer constants
878static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
879 SmallVectorImpl<Value *> &OffsetV) {
880 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
881 // Only accept small constant integer operands
882 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
883 if (!Op || Op->getZExtValue() > 20)
884 return false;
885 }
886
887 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
888 OffsetV.push_back(GEP->getOperand(i));
889 return true;
890}
891
892// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
893// replace, computes a replacement, and affects it.
894static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000895simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
896 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000897 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000898 for (GCRelocateInst *ToReplace : Targets) {
899 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000900 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000901 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000902 // A duplicate relocate call. TODO: coalesce duplicates.
903 continue;
904 }
905
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000906 if (RelocatedBase->getParent() != ToReplace->getParent()) {
907 // Base and derived relocates are in different basic blocks.
908 // In this case transform is only valid when base dominates derived
909 // relocate. However it would be too expensive to check dominance
910 // for each such relocate, so we skip the whole transformation.
911 continue;
912 }
913
Manuel Jacob83eefa62016-01-05 04:03:00 +0000914 Value *Base = ToReplace->getBasePtr();
915 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000916 if (!Derived || Derived->getPointerOperand() != Base)
917 continue;
918
919 SmallVector<Value *, 2> OffsetV;
920 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
921 continue;
922
923 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000924 assert(RelocatedBase->getNextNode() &&
925 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000926
927 // Insert after RelocatedBase
928 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000929 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000930
931 // If gc_relocate does not match the actual type, cast it to the right type.
932 // In theory, there must be a bitcast after gc_relocate if the type does not
933 // match, and we should reuse it to get the derived pointer. But it could be
934 // cases like this:
935 // bb1:
936 // ...
937 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
938 // br label %merge
939 //
940 // bb2:
941 // ...
942 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
943 // br label %merge
944 //
945 // merge:
946 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
947 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
948 //
949 // In this case, we can not find the bitcast any more. So we insert a new bitcast
950 // no matter there is already one or not. In this way, we can handle all cases, and
951 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000952 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000953 if (RelocatedBase->getType() != Base->getType()) {
954 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000955 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000956 }
David Blaikie68d535c2015-03-24 22:38:16 +0000957 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000958 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000959 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000960 // If the newly generated derived pointer's type does not match the original derived
961 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000962 Value *ActualReplacement = Replacement;
963 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000964 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000965 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000966 }
967 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000968 ToReplace->eraseFromParent();
969
970 MadeChange = true;
971 }
972 return MadeChange;
973}
974
975// Turns this:
976//
977// %base = ...
978// %ptr = gep %base + 15
979// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
980// %base' = relocate(%tok, i32 4, i32 4)
981// %ptr' = relocate(%tok, i32 4, i32 5)
982// %val = load %ptr'
983//
984// into this:
985//
986// %base = ...
987// %ptr = gep %base + 15
988// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
989// %base' = gc.relocate(%tok, i32 4, i32 4)
990// %ptr' = gep %base' + 15
991// %val = load %ptr'
992bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
993 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000994 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000995
996 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000997 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000998 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000999 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001000
1001 // We need atleast one base pointer relocation + one derived pointer
1002 // relocation to mangle
1003 if (AllRelocateCalls.size() < 2)
1004 return false;
1005
1006 // RelocateInstMap is a mapping from the base relocate instruction to the
1007 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001008 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001009 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1010 if (RelocateInstMap.empty())
1011 return false;
1012
1013 for (auto &Item : RelocateInstMap)
1014 // Item.first is the RelocatedBase to offset against
1015 // Item.second is the vector of Targets to replace
1016 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1017 return MadeChange;
1018}
1019
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001020/// SinkCast - Sink the specified cast instruction into its user blocks
1021static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001022 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001023
Chris Lattnerf2836d12007-03-31 04:06:36 +00001024 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001025 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001026
Chris Lattnerf2836d12007-03-31 04:06:36 +00001027 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001028 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001029 UI != E; ) {
1030 Use &TheUse = UI.getUse();
1031 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001032
Chris Lattnerf2836d12007-03-31 04:06:36 +00001033 // Figure out which BB this cast is used in. For PHI's this is the
1034 // appropriate predecessor block.
1035 BasicBlock *UserBB = User->getParent();
1036 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001037 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001038 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001039
Chris Lattnerf2836d12007-03-31 04:06:36 +00001040 // Preincrement use iterator so we don't invalidate it.
1041 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001042
David Majnemer0c80e2e2016-04-27 19:36:38 +00001043 // The first insertion point of a block containing an EH pad is after the
1044 // pad. If the pad is the user, we cannot sink the cast past the pad.
1045 if (User->isEHPad())
1046 continue;
1047
Andrew Kaylord0430e82015-11-23 19:16:15 +00001048 // If the block selected to receive the cast is an EH pad that does not
1049 // allow non-PHI instructions before the terminator, we can't sink the
1050 // cast.
1051 if (UserBB->getTerminator()->isEHPad())
1052 continue;
1053
Chris Lattnerf2836d12007-03-31 04:06:36 +00001054 // If this user is in the same block as the cast, don't change the cast.
1055 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001056
Chris Lattnerf2836d12007-03-31 04:06:36 +00001057 // If we have already inserted a cast into this block, use it.
1058 CastInst *&InsertedCast = InsertedCasts[UserBB];
1059
1060 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001061 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001062 assert(InsertPt != UserBB->end());
1063 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1064 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001065 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001066
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001067 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001068 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001069 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001070 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001071 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001072
Chris Lattnerf2836d12007-03-31 04:06:36 +00001073 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001074 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001075 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001076 MadeChange = true;
1077 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001078
Chris Lattnerf2836d12007-03-31 04:06:36 +00001079 return MadeChange;
1080}
1081
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001082/// If the specified cast instruction is a noop copy (e.g. it's casting from
1083/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1084/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001085///
1086/// Return true if any changes are made.
1087///
Mehdi Amini44ede332015-07-09 02:09:04 +00001088static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1089 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001090 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1091 // than sinking only nop casts, but is helpful on some platforms.
1092 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1093 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1094 ASC->getDestAddressSpace()))
1095 return false;
1096 }
1097
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001098 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001099 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1100 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001101
1102 // This is an fp<->int conversion?
1103 if (SrcVT.isInteger() != DstVT.isInteger())
1104 return false;
1105
1106 // If this is an extension, it will be a zero or sign extension, which
1107 // isn't a noop.
1108 if (SrcVT.bitsLT(DstVT)) return false;
1109
1110 // If these values will be promoted, find out what they will be promoted
1111 // to. This helps us consider truncates on PPC as noop copies when they
1112 // are.
1113 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1114 TargetLowering::TypePromoteInteger)
1115 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1116 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1117 TargetLowering::TypePromoteInteger)
1118 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1119
1120 // If, after promotion, these are the same types, this is a noop copy.
1121 if (SrcVT != DstVT)
1122 return false;
1123
1124 return SinkCast(CI);
1125}
1126
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001127/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1128/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001129///
1130/// Return true if any changes were made.
1131static bool CombineUAddWithOverflow(CmpInst *CI) {
1132 Value *A, *B;
1133 Instruction *AddI;
1134 if (!match(CI,
1135 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1136 return false;
1137
1138 Type *Ty = AddI->getType();
1139 if (!isa<IntegerType>(Ty))
1140 return false;
1141
1142 // We don't want to move around uses of condition values this late, so we we
1143 // check if it is legal to create the call to the intrinsic in the basic
1144 // block containing the icmp:
1145
1146 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1147 return false;
1148
1149#ifndef NDEBUG
1150 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1151 // for now:
1152 if (AddI->hasOneUse())
1153 assert(*AddI->user_begin() == CI && "expected!");
1154#endif
1155
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001156 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001157 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1158
1159 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1160
1161 auto *UAddWithOverflow =
1162 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1163 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1164 auto *Overflow =
1165 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1166
1167 CI->replaceAllUsesWith(Overflow);
1168 AddI->replaceAllUsesWith(UAdd);
1169 CI->eraseFromParent();
1170 AddI->eraseFromParent();
1171 return true;
1172}
1173
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001174/// Sink the given CmpInst into user blocks to reduce the number of virtual
1175/// registers that must be created and coalesced. This is a clear win except on
1176/// targets with multiple condition code registers (PowerPC), where it might
1177/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001178///
1179/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001180static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001181 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001182
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001183 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001184 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001185 return false;
1186
1187 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001188 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001189
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001190 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001191 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001192 UI != E; ) {
1193 Use &TheUse = UI.getUse();
1194 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001195
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001196 // Preincrement use iterator so we don't invalidate it.
1197 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001198
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001199 // Don't bother for PHI nodes.
1200 if (isa<PHINode>(User))
1201 continue;
1202
1203 // Figure out which BB this cmp is used in.
1204 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001205
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001206 // If this user is in the same block as the cmp, don't change the cmp.
1207 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001208
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001209 // If we have already inserted a cmp into this block, use it.
1210 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1211
1212 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001213 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001214 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001215 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001216 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1217 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001218 // Propagate the debug info.
1219 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001220 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001221
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001222 // Replace a use of the cmp with a use of the new cmp.
1223 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001224 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001225 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001226 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001227
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001228 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001229 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001230 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001231 MadeChange = true;
1232 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001233
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001234 return MadeChange;
1235}
1236
Peter Zotovf87e5502016-04-03 17:11:53 +00001237static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001238 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001239 return true;
1240
1241 if (CombineUAddWithOverflow(CI))
1242 return true;
1243
1244 return false;
1245}
1246
Geoff Berry5d534b62017-02-21 18:53:14 +00001247/// Duplicate and sink the given 'and' instruction into user blocks where it is
1248/// used in a compare to allow isel to generate better code for targets where
1249/// this operation can be combined.
1250///
1251/// Return true if any changes are made.
1252static bool sinkAndCmp0Expression(Instruction *AndI,
1253 const TargetLowering &TLI,
1254 SetOfInstrs &InsertedInsts) {
1255 // Double-check that we're not trying to optimize an instruction that was
1256 // already optimized by some other part of this pass.
1257 assert(!InsertedInsts.count(AndI) &&
1258 "Attempting to optimize already optimized and instruction");
1259 (void) InsertedInsts;
1260
1261 // Nothing to do for single use in same basic block.
1262 if (AndI->hasOneUse() &&
1263 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1264 return false;
1265
1266 // Try to avoid cases where sinking/duplicating is likely to increase register
1267 // pressure.
1268 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1269 !isa<ConstantInt>(AndI->getOperand(1)) &&
1270 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1271 return false;
1272
1273 for (auto *U : AndI->users()) {
1274 Instruction *User = cast<Instruction>(U);
1275
1276 // Only sink for and mask feeding icmp with 0.
1277 if (!isa<ICmpInst>(User))
1278 return false;
1279
1280 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1281 if (!CmpC || !CmpC->isZero())
1282 return false;
1283 }
1284
1285 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1286 return false;
1287
1288 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1289 DEBUG(AndI->getParent()->dump());
1290
1291 // Push the 'and' into the same block as the icmp 0. There should only be
1292 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1293 // others, so we don't need to keep track of which BBs we insert into.
1294 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1295 UI != E; ) {
1296 Use &TheUse = UI.getUse();
1297 Instruction *User = cast<Instruction>(*UI);
1298
1299 // Preincrement use iterator so we don't invalidate it.
1300 ++UI;
1301
1302 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1303
1304 // Keep the 'and' in the same place if the use is already in the same block.
1305 Instruction *InsertPt =
1306 User->getParent() == AndI->getParent() ? AndI : User;
1307 Instruction *InsertedAnd =
1308 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1309 AndI->getOperand(1), "", InsertPt);
1310 // Propagate the debug info.
1311 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1312
1313 // Replace a use of the 'and' with a use of the new 'and'.
1314 TheUse = InsertedAnd;
1315 ++NumAndUses;
1316 DEBUG(User->getParent()->dump());
1317 }
1318
1319 // We removed all uses, nuke the and.
1320 AndI->eraseFromParent();
1321 return true;
1322}
1323
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001324/// Check if the candidates could be combined with a shift instruction, which
1325/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001326/// 1. Truncate instruction
1327/// 2. And instruction and the imm is a mask of the low bits:
1328/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001329static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001330 if (!isa<TruncInst>(User)) {
1331 if (User->getOpcode() != Instruction::And ||
1332 !isa<ConstantInt>(User->getOperand(1)))
1333 return false;
1334
Quentin Colombetd4f44692014-04-22 01:20:34 +00001335 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001336
Quentin Colombetd4f44692014-04-22 01:20:34 +00001337 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001338 return false;
1339 }
1340 return true;
1341}
1342
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001343/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001344static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001345SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1346 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001347 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001348 BasicBlock *UserBB = User->getParent();
1349 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1350 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1351 bool MadeChange = false;
1352
1353 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1354 TruncE = TruncI->user_end();
1355 TruncUI != TruncE;) {
1356
1357 Use &TruncTheUse = TruncUI.getUse();
1358 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1359 // Preincrement use iterator so we don't invalidate it.
1360
1361 ++TruncUI;
1362
1363 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1364 if (!ISDOpcode)
1365 continue;
1366
Tim Northovere2239ff2014-07-29 10:20:22 +00001367 // If the use is actually a legal node, there will not be an
1368 // implicit truncate.
1369 // FIXME: always querying the result type is just an
1370 // approximation; some nodes' legality is determined by the
1371 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001372 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001373 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001374 continue;
1375
1376 // Don't bother for PHI nodes.
1377 if (isa<PHINode>(TruncUser))
1378 continue;
1379
1380 BasicBlock *TruncUserBB = TruncUser->getParent();
1381
1382 if (UserBB == TruncUserBB)
1383 continue;
1384
1385 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1386 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1387
1388 if (!InsertedShift && !InsertedTrunc) {
1389 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001390 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001391 // Sink the shift
1392 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001393 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1394 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001395 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001396 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1397 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001398
1399 // Sink the trunc
1400 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1401 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001402 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001403
1404 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001405 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001406
1407 MadeChange = true;
1408
1409 TruncTheUse = InsertedTrunc;
1410 }
1411 }
1412 return MadeChange;
1413}
1414
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001415/// Sink the shift *right* instruction into user blocks if the uses could
1416/// potentially be combined with this shift instruction and generate BitExtract
1417/// instruction. It will only be applied if the architecture supports BitExtract
1418/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001419/// BB1:
1420/// %x.extract.shift = lshr i64 %arg1, 32
1421/// BB2:
1422/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1423/// ==>
1424///
1425/// BB2:
1426/// %x.extract.shift.1 = lshr i64 %arg1, 32
1427/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1428///
1429/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1430/// instruction.
1431/// Return true if any changes are made.
1432static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001433 const TargetLowering &TLI,
1434 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001435 BasicBlock *DefBB = ShiftI->getParent();
1436
1437 /// Only insert instructions in each block once.
1438 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1439
Mehdi Amini44ede332015-07-09 02:09:04 +00001440 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001441
1442 bool MadeChange = false;
1443 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1444 UI != E;) {
1445 Use &TheUse = UI.getUse();
1446 Instruction *User = cast<Instruction>(*UI);
1447 // Preincrement use iterator so we don't invalidate it.
1448 ++UI;
1449
1450 // Don't bother for PHI nodes.
1451 if (isa<PHINode>(User))
1452 continue;
1453
1454 if (!isExtractBitsCandidateUse(User))
1455 continue;
1456
1457 BasicBlock *UserBB = User->getParent();
1458
1459 if (UserBB == DefBB) {
1460 // If the shift and truncate instruction are in the same BB. The use of
1461 // the truncate(TruncUse) may still introduce another truncate if not
1462 // legal. In this case, we would like to sink both shift and truncate
1463 // instruction to the BB of TruncUse.
1464 // for example:
1465 // BB1:
1466 // i64 shift.result = lshr i64 opnd, imm
1467 // trunc.result = trunc shift.result to i16
1468 //
1469 // BB2:
1470 // ----> We will have an implicit truncate here if the architecture does
1471 // not have i16 compare.
1472 // cmp i16 trunc.result, opnd2
1473 //
1474 if (isa<TruncInst>(User) && shiftIsLegal
1475 // If the type of the truncate is legal, no trucate will be
1476 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001477 &&
1478 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001479 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001480 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001481
1482 continue;
1483 }
1484 // If we have already inserted a shift into this block, use it.
1485 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1486
1487 if (!InsertedShift) {
1488 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001489 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001490
1491 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001492 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1493 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001494 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001495 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1496 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001497
1498 MadeChange = true;
1499 }
1500
1501 // Replace a use of the shift with a use of the new shift.
1502 TheUse = InsertedShift;
1503 }
1504
1505 // If we removed all uses, nuke the shift.
1506 if (ShiftI->use_empty())
1507 ShiftI->eraseFromParent();
1508
1509 return MadeChange;
1510}
1511
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001512// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001513// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1514// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001515// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001516// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001517//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001518// %1 = bitcast i8* %addr to i32*
1519// %2 = extractelement <16 x i1> %mask, i32 0
1520// %3 = icmp eq i1 %2, true
1521// br i1 %3, label %cond.load, label %else
1522//
1523//cond.load: ; preds = %0
1524// %4 = getelementptr i32* %1, i32 0
1525// %5 = load i32* %4
1526// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1527// br label %else
1528//
1529//else: ; preds = %0, %cond.load
1530// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1531// %7 = extractelement <16 x i1> %mask, i32 1
1532// %8 = icmp eq i1 %7, true
1533// br i1 %8, label %cond.load1, label %else2
1534//
1535//cond.load1: ; preds = %else
1536// %9 = getelementptr i32* %1, i32 1
1537// %10 = load i32* %9
1538// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1539// br label %else2
1540//
1541//else2: ; preds = %else, %cond.load1
1542// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1543// %12 = extractelement <16 x i1> %mask, i32 2
1544// %13 = icmp eq i1 %12, true
1545// br i1 %13, label %cond.load4, label %else5
1546//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001547static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001548 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001549 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001550 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001551 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001552
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001553 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1554 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001555 assert(VecType && "Unexpected return type of masked load intrinsic");
1556
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001557 Type *EltTy = CI->getType()->getVectorElementType();
1558
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001559 IRBuilder<> Builder(CI->getContext());
1560 Instruction *InsertPt = CI;
1561 BasicBlock *IfBlock = CI->getParent();
1562 BasicBlock *CondBlock = nullptr;
1563 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001564
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001565 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001566 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1567
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001568 // Short-cut if the mask is all-true.
1569 bool IsAllOnesMask = isa<Constant>(Mask) &&
1570 cast<Constant>(Mask)->isAllOnesValue();
1571
1572 if (IsAllOnesMask) {
1573 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1574 CI->replaceAllUsesWith(NewI);
1575 CI->eraseFromParent();
1576 return;
1577 }
1578
1579 // Adjust alignment for the scalar instruction.
1580 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001581 // Bitcast %addr fron i8* to EltTy*
1582 Type *NewPtrType =
1583 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1584 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001585 unsigned VectorWidth = VecType->getNumElements();
1586
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001587 Value *UndefVal = UndefValue::get(VecType);
1588
1589 // The result vector
1590 Value *VResult = UndefVal;
1591
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001592 if (isa<ConstantVector>(Mask)) {
1593 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1594 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1595 continue;
1596 Value *Gep =
1597 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1598 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1599 VResult = Builder.CreateInsertElement(VResult, Load,
1600 Builder.getInt32(Idx));
1601 }
1602 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1603 CI->replaceAllUsesWith(NewI);
1604 CI->eraseFromParent();
1605 return;
1606 }
1607
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001608 PHINode *Phi = nullptr;
1609 Value *PrevPhi = UndefVal;
1610
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001611 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1612
1613 // Fill the "else" block, created in the previous iteration
1614 //
1615 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1616 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1617 // %to_load = icmp eq i1 %mask_1, true
1618 // br i1 %to_load, label %cond.load, label %else
1619 //
1620 if (Idx > 0) {
1621 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1622 Phi->addIncoming(VResult, CondBlock);
1623 Phi->addIncoming(PrevPhi, PrevIfBlock);
1624 PrevPhi = Phi;
1625 VResult = Phi;
1626 }
1627
1628 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1629 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1630 ConstantInt::get(Predicate->getType(), 1));
1631
1632 // Create "cond" block
1633 //
1634 // %EltAddr = getelementptr i32* %1, i32 0
1635 // %Elt = load i32* %EltAddr
1636 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1637 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001638 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001639 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001640
1641 Value *Gep =
1642 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001643 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001644 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1645
1646 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001647 BasicBlock *NewIfBlock =
1648 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001649 Builder.SetInsertPoint(InsertPt);
1650 Instruction *OldBr = IfBlock->getTerminator();
1651 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1652 OldBr->eraseFromParent();
1653 PrevIfBlock = IfBlock;
1654 IfBlock = NewIfBlock;
1655 }
1656
1657 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1658 Phi->addIncoming(VResult, CondBlock);
1659 Phi->addIncoming(PrevPhi, PrevIfBlock);
1660 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1661 CI->replaceAllUsesWith(NewI);
1662 CI->eraseFromParent();
1663}
1664
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001665// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001666// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1667// <16 x i1> %mask)
1668// to a chain of basic blocks, that stores element one-by-one if
1669// the appropriate mask bit is set
1670//
1671// %1 = bitcast i8* %addr to i32*
1672// %2 = extractelement <16 x i1> %mask, i32 0
1673// %3 = icmp eq i1 %2, true
1674// br i1 %3, label %cond.store, label %else
1675//
1676// cond.store: ; preds = %0
1677// %4 = extractelement <16 x i32> %val, i32 0
1678// %5 = getelementptr i32* %1, i32 0
1679// store i32 %4, i32* %5
1680// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001681//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001682// else: ; preds = %0, %cond.store
1683// %6 = extractelement <16 x i1> %mask, i32 1
1684// %7 = icmp eq i1 %6, true
1685// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001686//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001687// cond.store1: ; preds = %else
1688// %8 = extractelement <16 x i32> %val, i32 1
1689// %9 = getelementptr i32* %1, i32 1
1690// store i32 %8, i32* %9
1691// br label %else2
1692// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001693static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001694 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001695 Value *Ptr = CI->getArgOperand(1);
1696 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001697 Value *Mask = CI->getArgOperand(3);
1698
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001699 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001700 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001701 assert(VecType && "Unexpected data type in masked store intrinsic");
1702
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001703 Type *EltTy = VecType->getElementType();
1704
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001705 IRBuilder<> Builder(CI->getContext());
1706 Instruction *InsertPt = CI;
1707 BasicBlock *IfBlock = CI->getParent();
1708 Builder.SetInsertPoint(InsertPt);
1709 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1710
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001711 // Short-cut if the mask is all-true.
1712 bool IsAllOnesMask = isa<Constant>(Mask) &&
1713 cast<Constant>(Mask)->isAllOnesValue();
1714
1715 if (IsAllOnesMask) {
1716 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1717 CI->eraseFromParent();
1718 return;
1719 }
1720
1721 // Adjust alignment for the scalar instruction.
1722 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001723 // Bitcast %addr fron i8* to EltTy*
1724 Type *NewPtrType =
1725 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1726 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001727 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001728
1729 if (isa<ConstantVector>(Mask)) {
1730 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1731 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1732 continue;
1733 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1734 Value *Gep =
1735 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1736 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1737 }
1738 CI->eraseFromParent();
1739 return;
1740 }
1741
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001742 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1743
1744 // Fill the "else" block, created in the previous iteration
1745 //
1746 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1747 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001748 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001749 //
1750 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1751 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1752 ConstantInt::get(Predicate->getType(), 1));
1753
1754 // Create "cond" block
1755 //
1756 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1757 // %EltAddr = getelementptr i32* %1, i32 0
1758 // %store i32 %OneElt, i32* %EltAddr
1759 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001760 BasicBlock *CondBlock =
1761 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001762 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001763
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001764 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001765 Value *Gep =
1766 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001767 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001768
1769 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001770 BasicBlock *NewIfBlock =
1771 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001772 Builder.SetInsertPoint(InsertPt);
1773 Instruction *OldBr = IfBlock->getTerminator();
1774 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1775 OldBr->eraseFromParent();
1776 IfBlock = NewIfBlock;
1777 }
1778 CI->eraseFromParent();
1779}
1780
Elena Demikhovsky09285852015-10-25 15:37:55 +00001781// Translate a masked gather intrinsic like
1782// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1783// <16 x i1> %Mask, <16 x i32> %Src)
1784// to a chain of basic blocks, with loading element one-by-one if
1785// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001786//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001787// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1788// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1789// % ToLoad0 = icmp eq i1 % Mask0, true
1790// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001791//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001792// cond.load:
1793// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1794// % Load0 = load i32, i32* % Ptr0, align 4
1795// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1796// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001797//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001798// else:
1799// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1800// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1801// % ToLoad1 = icmp eq i1 % Mask1, true
1802// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001803//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001804// cond.load1:
1805// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1806// % Load1 = load i32, i32* % Ptr1, align 4
1807// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1808// br label %else2
1809// . . .
1810// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1811// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001812static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001813 Value *Ptrs = CI->getArgOperand(0);
1814 Value *Alignment = CI->getArgOperand(1);
1815 Value *Mask = CI->getArgOperand(2);
1816 Value *Src0 = CI->getArgOperand(3);
1817
1818 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1819
1820 assert(VecType && "Unexpected return type of masked load intrinsic");
1821
1822 IRBuilder<> Builder(CI->getContext());
1823 Instruction *InsertPt = CI;
1824 BasicBlock *IfBlock = CI->getParent();
1825 BasicBlock *CondBlock = nullptr;
1826 BasicBlock *PrevIfBlock = CI->getParent();
1827 Builder.SetInsertPoint(InsertPt);
1828 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1829
1830 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1831
1832 Value *UndefVal = UndefValue::get(VecType);
1833
1834 // The result vector
1835 Value *VResult = UndefVal;
1836 unsigned VectorWidth = VecType->getNumElements();
1837
1838 // Shorten the way if the mask is a vector of constants.
1839 bool IsConstMask = isa<ConstantVector>(Mask);
1840
1841 if (IsConstMask) {
1842 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1843 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1844 continue;
1845 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1846 "Ptr" + Twine(Idx));
1847 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1848 "Load" + Twine(Idx));
1849 VResult = Builder.CreateInsertElement(VResult, Load,
1850 Builder.getInt32(Idx),
1851 "Res" + Twine(Idx));
1852 }
1853 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1854 CI->replaceAllUsesWith(NewI);
1855 CI->eraseFromParent();
1856 return;
1857 }
1858
1859 PHINode *Phi = nullptr;
1860 Value *PrevPhi = UndefVal;
1861
1862 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1863
1864 // Fill the "else" block, created in the previous iteration
1865 //
1866 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1867 // %ToLoad1 = icmp eq i1 %Mask1, true
1868 // br i1 %ToLoad1, label %cond.load, label %else
1869 //
1870 if (Idx > 0) {
1871 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1872 Phi->addIncoming(VResult, CondBlock);
1873 Phi->addIncoming(PrevPhi, PrevIfBlock);
1874 PrevPhi = Phi;
1875 VResult = Phi;
1876 }
1877
1878 Value *Predicate = Builder.CreateExtractElement(Mask,
1879 Builder.getInt32(Idx),
1880 "Mask" + Twine(Idx));
1881 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1882 ConstantInt::get(Predicate->getType(), 1),
1883 "ToLoad" + Twine(Idx));
1884
1885 // Create "cond" block
1886 //
1887 // %EltAddr = getelementptr i32* %1, i32 0
1888 // %Elt = load i32* %EltAddr
1889 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1890 //
1891 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1892 Builder.SetInsertPoint(InsertPt);
1893
1894 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1895 "Ptr" + Twine(Idx));
1896 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1897 "Load" + Twine(Idx));
1898 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1899 "Res" + Twine(Idx));
1900
1901 // Create "else" block, fill it in the next iteration
1902 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1903 Builder.SetInsertPoint(InsertPt);
1904 Instruction *OldBr = IfBlock->getTerminator();
1905 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1906 OldBr->eraseFromParent();
1907 PrevIfBlock = IfBlock;
1908 IfBlock = NewIfBlock;
1909 }
1910
1911 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1912 Phi->addIncoming(VResult, CondBlock);
1913 Phi->addIncoming(PrevPhi, PrevIfBlock);
1914 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1915 CI->replaceAllUsesWith(NewI);
1916 CI->eraseFromParent();
1917}
1918
1919// Translate a masked scatter intrinsic, like
1920// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1921// <16 x i1> %Mask)
1922// to a chain of basic blocks, that stores element one-by-one if
1923// the appropriate mask bit is set.
1924//
1925// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1926// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1927// % ToStore0 = icmp eq i1 % Mask0, true
1928// br i1 %ToStore0, label %cond.store, label %else
1929//
1930// cond.store:
1931// % Elt0 = extractelement <16 x i32> %Src, i32 0
1932// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1933// store i32 %Elt0, i32* % Ptr0, align 4
1934// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001935//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001936// else:
1937// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1938// % ToStore1 = icmp eq i1 % Mask1, true
1939// br i1 % ToStore1, label %cond.store1, label %else2
1940//
1941// cond.store1:
1942// % Elt1 = extractelement <16 x i32> %Src, i32 1
1943// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1944// store i32 % Elt1, i32* % Ptr1, align 4
1945// br label %else2
1946// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001947static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001948 Value *Src = CI->getArgOperand(0);
1949 Value *Ptrs = CI->getArgOperand(1);
1950 Value *Alignment = CI->getArgOperand(2);
1951 Value *Mask = CI->getArgOperand(3);
1952
1953 assert(isa<VectorType>(Src->getType()) &&
1954 "Unexpected data type in masked scatter intrinsic");
1955 assert(isa<VectorType>(Ptrs->getType()) &&
1956 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1957 "Vector of pointers is expected in masked scatter intrinsic");
1958
1959 IRBuilder<> Builder(CI->getContext());
1960 Instruction *InsertPt = CI;
1961 BasicBlock *IfBlock = CI->getParent();
1962 Builder.SetInsertPoint(InsertPt);
1963 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1964
1965 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1966 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1967
1968 // Shorten the way if the mask is a vector of constants.
1969 bool IsConstMask = isa<ConstantVector>(Mask);
1970
1971 if (IsConstMask) {
1972 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1973 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1974 continue;
1975 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1976 "Elt" + Twine(Idx));
1977 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1978 "Ptr" + Twine(Idx));
1979 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1980 }
1981 CI->eraseFromParent();
1982 return;
1983 }
1984 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1985 // Fill the "else" block, created in the previous iteration
1986 //
1987 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1988 // % ToStore = icmp eq i1 % Mask1, true
1989 // br i1 % ToStore, label %cond.store, label %else
1990 //
1991 Value *Predicate = Builder.CreateExtractElement(Mask,
1992 Builder.getInt32(Idx),
1993 "Mask" + Twine(Idx));
1994 Value *Cmp =
1995 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1996 ConstantInt::get(Predicate->getType(), 1),
1997 "ToStore" + Twine(Idx));
1998
1999 // Create "cond" block
2000 //
2001 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2002 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2003 // %store i32 % Elt1, i32* % Ptr1
2004 //
2005 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2006 Builder.SetInsertPoint(InsertPt);
2007
2008 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2009 "Elt" + Twine(Idx));
2010 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2011 "Ptr" + Twine(Idx));
2012 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2013
2014 // Create "else" block, fill it in the next iteration
2015 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2016 Builder.SetInsertPoint(InsertPt);
2017 Instruction *OldBr = IfBlock->getTerminator();
2018 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2019 OldBr->eraseFromParent();
2020 IfBlock = NewIfBlock;
2021 }
2022 CI->eraseFromParent();
2023}
2024
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002025/// If counting leading or trailing zeros is an expensive operation and a zero
2026/// input is defined, add a check for zero to avoid calling the intrinsic.
2027///
2028/// We want to transform:
2029/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2030///
2031/// into:
2032/// entry:
2033/// %cmpz = icmp eq i64 %A, 0
2034/// br i1 %cmpz, label %cond.end, label %cond.false
2035/// cond.false:
2036/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2037/// br label %cond.end
2038/// cond.end:
2039/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2040///
2041/// If the transform is performed, return true and set ModifiedDT to true.
2042static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2043 const TargetLowering *TLI,
2044 const DataLayout *DL,
2045 bool &ModifiedDT) {
2046 if (!TLI || !DL)
2047 return false;
2048
2049 // If a zero input is undefined, it doesn't make sense to despeculate that.
2050 if (match(CountZeros->getOperand(1), m_One()))
2051 return false;
2052
2053 // If it's cheap to speculate, there's nothing to do.
2054 auto IntrinsicID = CountZeros->getIntrinsicID();
2055 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2056 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2057 return false;
2058
2059 // Only handle legal scalar cases. Anything else requires too much work.
2060 Type *Ty = CountZeros->getType();
2061 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00002062 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002063 return false;
2064
2065 // The intrinsic will be sunk behind a compare against zero and branch.
2066 BasicBlock *StartBlock = CountZeros->getParent();
2067 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2068
2069 // Create another block after the count zero intrinsic. A PHI will be added
2070 // in this block to select the result of the intrinsic or the bit-width
2071 // constant if the input to the intrinsic is zero.
2072 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2073 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2074
2075 // Set up a builder to create a compare, conditional branch, and PHI.
2076 IRBuilder<> Builder(CountZeros->getContext());
2077 Builder.SetInsertPoint(StartBlock->getTerminator());
2078 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2079
2080 // Replace the unconditional branch that was created by the first split with
2081 // a compare against zero and a conditional branch.
2082 Value *Zero = Constant::getNullValue(Ty);
2083 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2084 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2085 StartBlock->getTerminator()->eraseFromParent();
2086
2087 // Create a PHI in the end block to select either the output of the intrinsic
2088 // or the bit width of the operand.
2089 Builder.SetInsertPoint(&EndBlock->front());
2090 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2091 CountZeros->replaceAllUsesWith(PN);
2092 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2093 PN->addIncoming(BitWidth, StartBlock);
2094 PN->addIncoming(CountZeros, CallBlock);
2095
2096 // We are explicitly handling the zero case, so we can set the intrinsic's
2097 // undefined zero argument to 'true'. This will also prevent reprocessing the
2098 // intrinsic; we only despeculate when a zero input is defined.
2099 CountZeros->setArgOperand(1, Builder.getTrue());
2100 ModifiedDT = true;
2101 return true;
2102}
2103
Sanjay Patelfc580a62015-09-21 23:03:16 +00002104bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00002105 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002106
Chris Lattner7a277142011-01-15 07:14:54 +00002107 // Lower inline assembly if we can.
2108 // If we found an inline asm expession, and if the target knows how to
2109 // lower it to normal LLVM code, do so now.
2110 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2111 if (TLI->ExpandInlineAsm(CI)) {
2112 // Avoid invalidating the iterator.
2113 CurInstIterator = BB->begin();
2114 // Avoid processing instructions out of order, which could cause
2115 // reuse before a value is defined.
2116 SunkAddrs.clear();
2117 return true;
2118 }
2119 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002120 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00002121 return true;
2122 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002123
John Brawn0dbcd652015-03-18 12:01:59 +00002124 // Align the pointer arguments to this call if the target thinks it's a good
2125 // idea
2126 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002127 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00002128 for (auto &Arg : CI->arg_operands()) {
2129 // We want to align both objects whose address is used directly and
2130 // objects whose address is used in casts and GEPs, though it only makes
2131 // sense for GEPs if the offset is a multiple of the desired alignment and
2132 // if size - offset meets the size threshold.
2133 if (!Arg->getType()->isPointerTy())
2134 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002135 APInt Offset(DL->getPointerSizeInBits(
2136 cast<PointerType>(Arg->getType())->getAddressSpace()),
2137 0);
2138 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00002139 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00002140 if ((Offset2 & (PrefAlign-1)) != 0)
2141 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00002142 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002143 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2144 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00002145 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00002146 // Global variables can only be aligned if they are defined in this
2147 // object (i.e. they are uniquely initialized in this object), and
2148 // over-aligning global variables that have an explicit section is
2149 // forbidden.
2150 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00002151 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00002152 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002153 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00002154 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00002155 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00002156 }
2157 // If this is a memcpy (or similar) then we may be able to improve the
2158 // alignment
2159 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002160 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00002161 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00002162 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002163 if (Align > MI->getAlignment())
2164 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00002165 }
2166 }
2167
Philip Reamesac115ed2016-03-09 23:13:12 +00002168 // If we have a cold call site, try to sink addressing computation into the
2169 // cold block. This interacts with our handling for loads and stores to
2170 // ensure that we can fold all uses of a potential addressing computation
2171 // into their uses. TODO: generalize this to work over profiling data
2172 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
2173 for (auto &Arg : CI->arg_operands()) {
2174 if (!Arg->getType()->isPointerTy())
2175 continue;
2176 unsigned AS = Arg->getType()->getPointerAddressSpace();
2177 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2178 }
Junmo Park6098cbb2016-03-11 07:05:32 +00002179
Eric Christopher4b7948e2010-03-11 02:41:03 +00002180 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002181 if (II) {
2182 switch (II->getIntrinsicID()) {
2183 default: break;
2184 case Intrinsic::objectsize: {
2185 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00002186 ConstantInt *RetVal =
2187 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002188 // Substituting this can cause recursive simplifications, which can
2189 // invalidate our iterator. Use a WeakVH to hold onto it in case this
2190 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002191 Value *CurValue = &*CurInstIterator;
2192 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00002193
Sanjay Patel545a4562016-01-20 18:59:16 +00002194 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00002195
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002196 // If the iterator instruction was recursively deleted, start over at the
2197 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002198 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002199 CurInstIterator = BB->begin();
2200 SunkAddrs.clear();
2201 }
2202 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00002203 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002204 case Intrinsic::masked_load: {
2205 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00002206 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002207 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002208 ModifiedDT = true;
2209 return true;
2210 }
2211 return false;
2212 }
2213 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00002214 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002215 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002216 ModifiedDT = true;
2217 return true;
2218 }
2219 return false;
2220 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00002221 case Intrinsic::masked_gather: {
2222 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002223 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002224 ModifiedDT = true;
2225 return true;
2226 }
2227 return false;
2228 }
2229 case Intrinsic::masked_scatter: {
2230 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002231 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002232 ModifiedDT = true;
2233 return true;
2234 }
2235 return false;
2236 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002237 case Intrinsic::aarch64_stlxr:
2238 case Intrinsic::aarch64_stxr: {
2239 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2240 if (!ExtVal || !ExtVal->hasOneUse() ||
2241 ExtVal->getParent() == CI->getParent())
2242 return false;
2243 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2244 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002245 // Mark this instruction as "inserted by CGP", so that other
2246 // optimizations don't touch it.
2247 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002248 return true;
2249 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002250 case Intrinsic::invariant_group_barrier:
2251 II->replaceAllUsesWith(II->getArgOperand(0));
2252 II->eraseFromParent();
2253 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002254
2255 case Intrinsic::cttz:
2256 case Intrinsic::ctlz:
2257 // If counting zeros is expensive, try to avoid it.
2258 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002259 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002260
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002261 if (TLI) {
2262 SmallVector<Value*, 2> PtrOps;
2263 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002264 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2265 while (!PtrOps.empty()) {
2266 Value *PtrVal = PtrOps.pop_back_val();
2267 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2268 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002269 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002270 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002271 }
Pete Cooper615fd892012-03-13 20:59:56 +00002272 }
2273
Eric Christopher4b7948e2010-03-11 02:41:03 +00002274 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002275 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002276
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002277 // Lower all default uses of _chk calls. This is very similar
2278 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002279 // to fortified library functions (e.g. __memcpy_chk) that have the default
2280 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002281 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002282 if (Value *V = Simplifier.optimizeCall(CI)) {
2283 CI->replaceAllUsesWith(V);
2284 CI->eraseFromParent();
2285 return true;
2286 }
2287 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002288}
Chris Lattner1b93be52011-01-15 07:25:29 +00002289
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002290/// Look for opportunities to duplicate return instructions to the predecessor
2291/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002292/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002293/// bb0:
2294/// %tmp0 = tail call i32 @f0()
2295/// br label %return
2296/// bb1:
2297/// %tmp1 = tail call i32 @f1()
2298/// br label %return
2299/// bb2:
2300/// %tmp2 = tail call i32 @f2()
2301/// br label %return
2302/// return:
2303/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2304/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002305/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002306///
2307/// =>
2308///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002309/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002310/// bb0:
2311/// %tmp0 = tail call i32 @f0()
2312/// ret i32 %tmp0
2313/// bb1:
2314/// %tmp1 = tail call i32 @f1()
2315/// ret i32 %tmp1
2316/// bb2:
2317/// %tmp2 = tail call i32 @f2()
2318/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002319/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002320bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002321 if (!TLI)
2322 return false;
2323
Michael Kuperstein71321562016-09-07 20:29:49 +00002324 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2325 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002326 return false;
2327
Craig Topperc0196b12014-04-14 00:51:57 +00002328 PHINode *PN = nullptr;
2329 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002330 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002331 if (V) {
2332 BCI = dyn_cast<BitCastInst>(V);
2333 if (BCI)
2334 V = BCI->getOperand(0);
2335
2336 PN = dyn_cast<PHINode>(V);
2337 if (!PN)
2338 return false;
2339 }
Evan Cheng0663f232011-03-21 01:19:09 +00002340
Cameron Zwarich4649f172011-03-24 04:52:10 +00002341 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002342 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002343
Cameron Zwarich4649f172011-03-24 04:52:10 +00002344 // Make sure there are no instructions between the PHI and return, or that the
2345 // return is the first instruction in the block.
2346 if (PN) {
2347 BasicBlock::iterator BI = BB->begin();
2348 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002349 if (&*BI == BCI)
2350 // Also skip over the bitcast.
2351 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002352 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002353 return false;
2354 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002355 BasicBlock::iterator BI = BB->begin();
2356 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002357 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002358 return false;
2359 }
Evan Cheng0663f232011-03-21 01:19:09 +00002360
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002361 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2362 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002363 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002364 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002365 if (PN) {
2366 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2367 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2368 // Make sure the phi value is indeed produced by the tail call.
2369 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002370 TLI->mayBeEmittedAsTailCall(CI) &&
2371 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002372 TailCalls.push_back(CI);
2373 }
2374 } else {
2375 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002376 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002377 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002378 continue;
2379
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002380 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002381 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2382 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002383 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2384 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002385 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002386
Cameron Zwarich4649f172011-03-24 04:52:10 +00002387 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002388 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2389 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002390 TailCalls.push_back(CI);
2391 }
Evan Cheng0663f232011-03-21 01:19:09 +00002392 }
2393
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002394 bool Changed = false;
2395 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2396 CallInst *CI = TailCalls[i];
2397 CallSite CS(CI);
2398
2399 // Conservatively require the attributes of the call to match those of the
2400 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002401 AttributeSet CalleeAttrs = CS.getAttributes();
2402 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002403 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002404 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002405 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002406 continue;
2407
2408 // Make sure the call instruction is followed by an unconditional branch to
2409 // the return block.
2410 BasicBlock *CallBB = CI->getParent();
2411 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2412 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2413 continue;
2414
2415 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002416 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002417 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002418 ++NumRetsDup;
2419 }
2420
2421 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002422 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002423 BB->eraseFromParent();
2424
2425 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002426}
2427
Chris Lattner728f9022008-11-25 07:09:13 +00002428//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002429// Memory Optimization
2430//===----------------------------------------------------------------------===//
2431
Chandler Carruthc8925912013-01-05 02:09:22 +00002432namespace {
2433
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002434/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002435/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002436struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002437 Value *BaseReg;
2438 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002439 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002440 void print(raw_ostream &OS) const;
2441 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002442
Chandler Carruthc8925912013-01-05 02:09:22 +00002443 bool operator==(const ExtAddrMode& O) const {
2444 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2445 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2446 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2447 }
2448};
2449
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002450#ifndef NDEBUG
2451static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2452 AM.print(OS);
2453 return OS;
2454}
2455#endif
2456
Chandler Carruthc8925912013-01-05 02:09:22 +00002457void ExtAddrMode::print(raw_ostream &OS) const {
2458 bool NeedPlus = false;
2459 OS << "[";
2460 if (BaseGV) {
2461 OS << (NeedPlus ? " + " : "")
2462 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002463 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002464 NeedPlus = true;
2465 }
2466
Richard Trieuc0f91212014-05-30 03:15:17 +00002467 if (BaseOffs) {
2468 OS << (NeedPlus ? " + " : "")
2469 << BaseOffs;
2470 NeedPlus = true;
2471 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002472
2473 if (BaseReg) {
2474 OS << (NeedPlus ? " + " : "")
2475 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002476 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002477 NeedPlus = true;
2478 }
2479 if (Scale) {
2480 OS << (NeedPlus ? " + " : "")
2481 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002482 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002483 }
2484
2485 OS << ']';
2486}
2487
2488#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002489LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002490 print(dbgs());
2491 dbgs() << '\n';
2492}
2493#endif
2494
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002495/// \brief This class provides transaction based operation on the IR.
2496/// Every change made through this class is recorded in the internal state and
2497/// can be undone (rollback) until commit is called.
2498class TypePromotionTransaction {
2499
2500 /// \brief This represents the common interface of the individual transaction.
2501 /// Each class implements the logic for doing one specific modification on
2502 /// the IR via the TypePromotionTransaction.
2503 class TypePromotionAction {
2504 protected:
2505 /// The Instruction modified.
2506 Instruction *Inst;
2507
2508 public:
2509 /// \brief Constructor of the action.
2510 /// The constructor performs the related action on the IR.
2511 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2512
2513 virtual ~TypePromotionAction() {}
2514
2515 /// \brief Undo the modification done by this action.
2516 /// When this method is called, the IR must be in the same state as it was
2517 /// before this action was applied.
2518 /// \pre Undoing the action works if and only if the IR is in the exact same
2519 /// state as it was directly after this action was applied.
2520 virtual void undo() = 0;
2521
2522 /// \brief Advocate every change made by this action.
2523 /// When the results on the IR of the action are to be kept, it is important
2524 /// to call this function, otherwise hidden information may be kept forever.
2525 virtual void commit() {
2526 // Nothing to be done, this action is not doing anything.
2527 }
2528 };
2529
2530 /// \brief Utility to remember the position of an instruction.
2531 class InsertionHandler {
2532 /// Position of an instruction.
2533 /// Either an instruction:
2534 /// - Is the first in a basic block: BB is used.
2535 /// - Has a previous instructon: PrevInst is used.
2536 union {
2537 Instruction *PrevInst;
2538 BasicBlock *BB;
2539 } Point;
2540 /// Remember whether or not the instruction had a previous instruction.
2541 bool HasPrevInstruction;
2542
2543 public:
2544 /// \brief Record the position of \p Inst.
2545 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002546 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002547 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2548 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002549 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002550 else
2551 Point.BB = Inst->getParent();
2552 }
2553
2554 /// \brief Insert \p Inst at the recorded position.
2555 void insert(Instruction *Inst) {
2556 if (HasPrevInstruction) {
2557 if (Inst->getParent())
2558 Inst->removeFromParent();
2559 Inst->insertAfter(Point.PrevInst);
2560 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002561 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002562 if (Inst->getParent())
2563 Inst->moveBefore(Position);
2564 else
2565 Inst->insertBefore(Position);
2566 }
2567 }
2568 };
2569
2570 /// \brief Move an instruction before another.
2571 class InstructionMoveBefore : public TypePromotionAction {
2572 /// Original position of the instruction.
2573 InsertionHandler Position;
2574
2575 public:
2576 /// \brief Move \p Inst before \p Before.
2577 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2578 : TypePromotionAction(Inst), Position(Inst) {
2579 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2580 Inst->moveBefore(Before);
2581 }
2582
2583 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002584 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002585 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2586 Position.insert(Inst);
2587 }
2588 };
2589
2590 /// \brief Set the operand of an instruction with a new value.
2591 class OperandSetter : public TypePromotionAction {
2592 /// Original operand of the instruction.
2593 Value *Origin;
2594 /// Index of the modified instruction.
2595 unsigned Idx;
2596
2597 public:
2598 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2599 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2600 : TypePromotionAction(Inst), Idx(Idx) {
2601 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2602 << "for:" << *Inst << "\n"
2603 << "with:" << *NewVal << "\n");
2604 Origin = Inst->getOperand(Idx);
2605 Inst->setOperand(Idx, NewVal);
2606 }
2607
2608 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002609 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002610 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2611 << "for: " << *Inst << "\n"
2612 << "with: " << *Origin << "\n");
2613 Inst->setOperand(Idx, Origin);
2614 }
2615 };
2616
2617 /// \brief Hide the operands of an instruction.
2618 /// Do as if this instruction was not using any of its operands.
2619 class OperandsHider : public TypePromotionAction {
2620 /// The list of original operands.
2621 SmallVector<Value *, 4> OriginalValues;
2622
2623 public:
2624 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2625 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2626 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2627 unsigned NumOpnds = Inst->getNumOperands();
2628 OriginalValues.reserve(NumOpnds);
2629 for (unsigned It = 0; It < NumOpnds; ++It) {
2630 // Save the current operand.
2631 Value *Val = Inst->getOperand(It);
2632 OriginalValues.push_back(Val);
2633 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002634 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002635 // that we are not willing to pay.
2636 Inst->setOperand(It, UndefValue::get(Val->getType()));
2637 }
2638 }
2639
2640 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002641 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002642 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2643 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2644 Inst->setOperand(It, OriginalValues[It]);
2645 }
2646 };
2647
2648 /// \brief Build a truncate instruction.
2649 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002650 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002651 public:
2652 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2653 /// result.
2654 /// trunc Opnd to Ty.
2655 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2656 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002657 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2658 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002659 }
2660
Quentin Colombetac55b152014-09-16 22:36:07 +00002661 /// \brief Get the built value.
2662 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002663
2664 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002665 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002666 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2667 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2668 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002669 }
2670 };
2671
2672 /// \brief Build a sign extension instruction.
2673 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002674 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002675 public:
2676 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2677 /// result.
2678 /// sext Opnd to Ty.
2679 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002680 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002681 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002682 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2683 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002684 }
2685
Quentin Colombetac55b152014-09-16 22:36:07 +00002686 /// \brief Get the built value.
2687 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002688
2689 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002690 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002691 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2692 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2693 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002694 }
2695 };
2696
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002697 /// \brief Build a zero extension instruction.
2698 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002699 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002700 public:
2701 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2702 /// result.
2703 /// zext Opnd to Ty.
2704 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002705 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002706 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002707 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2708 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002709 }
2710
Quentin Colombetac55b152014-09-16 22:36:07 +00002711 /// \brief Get the built value.
2712 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002713
2714 /// \brief Remove the built instruction.
2715 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002716 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2717 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2718 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002719 }
2720 };
2721
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002722 /// \brief Mutate an instruction to another type.
2723 class TypeMutator : public TypePromotionAction {
2724 /// Record the original type.
2725 Type *OrigTy;
2726
2727 public:
2728 /// \brief Mutate the type of \p Inst into \p NewTy.
2729 TypeMutator(Instruction *Inst, Type *NewTy)
2730 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2731 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2732 << "\n");
2733 Inst->mutateType(NewTy);
2734 }
2735
2736 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002737 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002738 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2739 << "\n");
2740 Inst->mutateType(OrigTy);
2741 }
2742 };
2743
2744 /// \brief Replace the uses of an instruction by another instruction.
2745 class UsesReplacer : public TypePromotionAction {
2746 /// Helper structure to keep track of the replaced uses.
2747 struct InstructionAndIdx {
2748 /// The instruction using the instruction.
2749 Instruction *Inst;
2750 /// The index where this instruction is used for Inst.
2751 unsigned Idx;
2752 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2753 : Inst(Inst), Idx(Idx) {}
2754 };
2755
2756 /// Keep track of the original uses (pair Instruction, Index).
2757 SmallVector<InstructionAndIdx, 4> OriginalUses;
2758 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2759
2760 public:
2761 /// \brief Replace all the use of \p Inst by \p New.
2762 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2763 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2764 << "\n");
2765 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002766 for (Use &U : Inst->uses()) {
2767 Instruction *UserI = cast<Instruction>(U.getUser());
2768 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002769 }
2770 // Now, we can replace the uses.
2771 Inst->replaceAllUsesWith(New);
2772 }
2773
2774 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002775 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002776 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2777 for (use_iterator UseIt = OriginalUses.begin(),
2778 EndIt = OriginalUses.end();
2779 UseIt != EndIt; ++UseIt) {
2780 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2781 }
2782 }
2783 };
2784
2785 /// \brief Remove an instruction from the IR.
2786 class InstructionRemover : public TypePromotionAction {
2787 /// Original position of the instruction.
2788 InsertionHandler Inserter;
2789 /// Helper structure to hide all the link to the instruction. In other
2790 /// words, this helps to do as if the instruction was removed.
2791 OperandsHider Hider;
2792 /// Keep track of the uses replaced, if any.
2793 UsesReplacer *Replacer;
2794
2795 public:
2796 /// \brief Remove all reference of \p Inst and optinally replace all its
2797 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002798 /// \pre If !Inst->use_empty(), then New != nullptr
2799 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002800 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002801 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002802 if (New)
2803 Replacer = new UsesReplacer(Inst, New);
2804 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2805 Inst->removeFromParent();
2806 }
2807
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002808 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002809
2810 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002811 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002812
2813 /// \brief Resurrect the instruction and reassign it to the proper uses if
2814 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002815 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002816 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2817 Inserter.insert(Inst);
2818 if (Replacer)
2819 Replacer->undo();
2820 Hider.undo();
2821 }
2822 };
2823
2824public:
2825 /// Restoration point.
2826 /// The restoration point is a pointer to an action instead of an iterator
2827 /// because the iterator may be invalidated but not the pointer.
2828 typedef const TypePromotionAction *ConstRestorationPt;
2829 /// Advocate every changes made in that transaction.
2830 void commit();
2831 /// Undo all the changes made after the given point.
2832 void rollback(ConstRestorationPt Point);
2833 /// Get the current restoration point.
2834 ConstRestorationPt getRestorationPoint() const;
2835
2836 /// \name API for IR modification with state keeping to support rollback.
2837 /// @{
2838 /// Same as Instruction::setOperand.
2839 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2840 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002841 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002842 /// Same as Value::replaceAllUsesWith.
2843 void replaceAllUsesWith(Instruction *Inst, Value *New);
2844 /// Same as Value::mutateType.
2845 void mutateType(Instruction *Inst, Type *NewTy);
2846 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002847 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002848 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002849 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002850 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002851 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002852 /// Same as Instruction::moveBefore.
2853 void moveBefore(Instruction *Inst, Instruction *Before);
2854 /// @}
2855
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002856private:
2857 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002858 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2859 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002860};
2861
2862void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2863 Value *NewVal) {
2864 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002865 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002866}
2867
2868void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2869 Value *NewVal) {
2870 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002871 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002872}
2873
2874void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2875 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002876 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002877}
2878
2879void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002880 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002881}
2882
Quentin Colombetac55b152014-09-16 22:36:07 +00002883Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2884 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002885 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002886 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002887 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002888 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002889}
2890
Quentin Colombetac55b152014-09-16 22:36:07 +00002891Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2892 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002893 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002894 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002895 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002896 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002897}
2898
Quentin Colombetac55b152014-09-16 22:36:07 +00002899Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2900 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002901 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002902 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002903 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002904 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002905}
2906
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002907void TypePromotionTransaction::moveBefore(Instruction *Inst,
2908 Instruction *Before) {
2909 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002910 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002911}
2912
2913TypePromotionTransaction::ConstRestorationPt
2914TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002915 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002916}
2917
2918void TypePromotionTransaction::commit() {
2919 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002920 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002921 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002922 Actions.clear();
2923}
2924
2925void TypePromotionTransaction::rollback(
2926 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002927 while (!Actions.empty() && Point != Actions.back().get()) {
2928 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002929 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002930 }
2931}
2932
Chandler Carruthc8925912013-01-05 02:09:22 +00002933/// \brief A helper class for matching addressing modes.
2934///
2935/// This encapsulates the logic for matching the target-legal addressing modes.
2936class AddressingModeMatcher {
2937 SmallVectorImpl<Instruction*> &AddrModeInsts;
2938 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002939 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002940 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002941
2942 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2943 /// the memory instruction that we're computing this address for.
2944 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002945 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002946 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002947
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002948 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002949 /// part of the return value of this addressing mode matching stuff.
2950 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002951
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002952 /// The instructions inserted by other CodeGenPrepare optimizations.
2953 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002954 /// A map from the instructions to their type before promotion.
2955 InstrToOrigTy &PromotedInsts;
2956 /// The ongoing transaction where every action should be registered.
2957 TypePromotionTransaction &TPT;
2958
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002959 /// This is set to true when we should not do profitability checks.
2960 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002961 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002962
Eric Christopherd75c00c2015-02-26 22:38:34 +00002963 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002964 const TargetLowering &TLI,
2965 const TargetRegisterInfo &TRI,
2966 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002967 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002968 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002969 InstrToOrigTy &PromotedInsts,
2970 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002971 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002972 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2973 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2974 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002975 IgnoreProfitability = false;
2976 }
2977public:
Stephen Lin837bba12013-07-15 17:55:02 +00002978
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002979 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002980 /// give an access type of AccessTy. This returns a list of involved
2981 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002982 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002983 /// optimizations.
2984 /// \p PromotedInsts maps the instructions to their type before promotion.
2985 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002986 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002987 Instruction *MemoryInst,
2988 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002989 const TargetLowering &TLI,
2990 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002991 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002992 InstrToOrigTy &PromotedInsts,
2993 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002994 ExtAddrMode Result;
2995
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002996 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2997 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002998 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002999 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003000 (void)Success; assert(Success && "Couldn't select *anything*?");
3001 return Result;
3002 }
3003private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00003004 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3005 bool matchAddr(Value *V, unsigned Depth);
3006 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00003007 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003008 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00003009 ExtAddrMode &AMBefore,
3010 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003011 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3012 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00003013 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00003014};
3015
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003016/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003017/// Return true and update AddrMode if this addr mode is legal for the target,
3018/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003019bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003020 unsigned Depth) {
3021 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3022 // mode. Just process that directly.
3023 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003024 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003025
Chandler Carruthc8925912013-01-05 02:09:22 +00003026 // If the scale is 0, it takes nothing to add this.
3027 if (Scale == 0)
3028 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003029
Chandler Carruthc8925912013-01-05 02:09:22 +00003030 // If we already have a scale of this value, we can add to it, otherwise, we
3031 // need an available scale field.
3032 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3033 return false;
3034
3035 ExtAddrMode TestAddrMode = AddrMode;
3036
3037 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3038 // [A+B + A*7] -> [B+A*8].
3039 TestAddrMode.Scale += Scale;
3040 TestAddrMode.ScaledReg = ScaleReg;
3041
3042 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003043 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003044 return false;
3045
3046 // It was legal, so commit it.
3047 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003048
Chandler Carruthc8925912013-01-05 02:09:22 +00003049 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3050 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3051 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003052 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003053 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3054 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3055 TestAddrMode.ScaledReg = AddLHS;
3056 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003057
Chandler Carruthc8925912013-01-05 02:09:22 +00003058 // If this addressing mode is legal, commit it and remember that we folded
3059 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003060 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003061 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3062 AddrMode = TestAddrMode;
3063 return true;
3064 }
3065 }
3066
3067 // Otherwise, not (x+c)*scale, just return what we have.
3068 return true;
3069}
3070
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003071/// This is a little filter, which returns true if an addressing computation
3072/// involving I might be folded into a load/store accessing it.
3073/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003074/// the set of instructions that MatchOperationAddr can.
3075static bool MightBeFoldableInst(Instruction *I) {
3076 switch (I->getOpcode()) {
3077 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003078 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003079 // Don't touch identity bitcasts.
3080 if (I->getType() == I->getOperand(0)->getType())
3081 return false;
3082 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3083 case Instruction::PtrToInt:
3084 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3085 return true;
3086 case Instruction::IntToPtr:
3087 // We know the input is intptr_t, so this is foldable.
3088 return true;
3089 case Instruction::Add:
3090 return true;
3091 case Instruction::Mul:
3092 case Instruction::Shl:
3093 // Can only handle X*C and X << C.
3094 return isa<ConstantInt>(I->getOperand(1));
3095 case Instruction::GetElementPtr:
3096 return true;
3097 default:
3098 return false;
3099 }
3100}
3101
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003102/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3103/// \note \p Val is assumed to be the product of some type promotion.
3104/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3105/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003106static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3107 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003108 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3109 if (!PromotedInst)
3110 return false;
3111 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3112 // If the ISDOpcode is undefined, it was undefined before the promotion.
3113 if (!ISDOpcode)
3114 return true;
3115 // Otherwise, check if the promoted instruction is legal or not.
3116 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003117 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003118}
3119
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003120/// \brief Hepler class to perform type promotion.
3121class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003122 /// \brief Utility function to check whether or not a sign or zero extension
3123 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3124 /// either using the operands of \p Inst or promoting \p Inst.
3125 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003126 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003127 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003128 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003129 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003130 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003131 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003132 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003133 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3134 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003135
3136 /// \brief Utility function to determine if \p OpIdx should be promoted when
3137 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003138 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003139 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003140 }
3141
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003142 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003143 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003144 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003145 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003146 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003147 /// Newly added extensions are inserted in \p Exts.
3148 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003149 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003150 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003151 static Value *promoteOperandForTruncAndAnyExt(
3152 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003153 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003154 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003155 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003156
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003157 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003158 /// operand is promotable and is not a supported trunc or sext.
3159 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003160 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003161 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003162 /// Newly added extensions are inserted in \p Exts.
3163 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003164 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003165 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003166 static Value *promoteOperandForOther(Instruction *Ext,
3167 TypePromotionTransaction &TPT,
3168 InstrToOrigTy &PromotedInsts,
3169 unsigned &CreatedInstsCost,
3170 SmallVectorImpl<Instruction *> *Exts,
3171 SmallVectorImpl<Instruction *> *Truncs,
3172 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003173
3174 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003175 static Value *signExtendOperandForOther(
3176 Instruction *Ext, TypePromotionTransaction &TPT,
3177 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3178 SmallVectorImpl<Instruction *> *Exts,
3179 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3180 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3181 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003182 }
3183
3184 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003185 static Value *zeroExtendOperandForOther(
3186 Instruction *Ext, TypePromotionTransaction &TPT,
3187 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3188 SmallVectorImpl<Instruction *> *Exts,
3189 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3190 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3191 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003192 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003193
3194public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003195 /// Type for the utility function that promotes the operand of Ext.
3196 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003197 InstrToOrigTy &PromotedInsts,
3198 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003199 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003200 SmallVectorImpl<Instruction *> *Truncs,
3201 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003202 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3203 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003204 /// \return NULL if no promotable action is possible with the current
3205 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003206 /// \p InsertedInsts keeps track of all the instructions inserted by the
3207 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003208 /// because we do not want to promote these instructions as CodeGenPrepare
3209 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3210 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003211 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003212 const TargetLowering &TLI,
3213 const InstrToOrigTy &PromotedInsts);
3214};
3215
3216bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003217 Type *ConsideredExtType,
3218 const InstrToOrigTy &PromotedInsts,
3219 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003220 // The promotion helper does not know how to deal with vector types yet.
3221 // To be able to fix that, we would need to fix the places where we
3222 // statically extend, e.g., constants and such.
3223 if (Inst->getType()->isVectorTy())
3224 return false;
3225
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003226 // We can always get through zext.
3227 if (isa<ZExtInst>(Inst))
3228 return true;
3229
3230 // sext(sext) is ok too.
3231 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003232 return true;
3233
3234 // We can get through binary operator, if it is legal. In other words, the
3235 // binary operator must have a nuw or nsw flag.
3236 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3237 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003238 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3239 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003240 return true;
3241
3242 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003243 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003244 if (!isa<TruncInst>(Inst))
3245 return false;
3246
3247 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003248 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003249 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003250 if (!OpndVal->getType()->isIntegerTy() ||
3251 OpndVal->getType()->getIntegerBitWidth() >
3252 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003253 return false;
3254
3255 // If the operand of the truncate is not an instruction, we will not have
3256 // any information on the dropped bits.
3257 // (Actually we could for constant but it is not worth the extra logic).
3258 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3259 if (!Opnd)
3260 return false;
3261
3262 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003263 // I.e., check that trunc just drops extended bits of the same kind of
3264 // the extension.
3265 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003266 const Type *OpndType;
3267 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003268 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3269 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003270 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3271 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003272 else
3273 return false;
3274
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003275 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003276 return Inst->getType()->getIntegerBitWidth() >=
3277 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003278}
3279
3280TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003281 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003282 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003283 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3284 "Unexpected instruction type");
3285 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3286 Type *ExtTy = Ext->getType();
3287 bool IsSExt = isa<SExtInst>(Ext);
3288 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003289 // get through.
3290 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003291 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003292 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003293
3294 // Do not promote if the operand has been added by codegenprepare.
3295 // Otherwise, it means we are undoing an optimization that is likely to be
3296 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003297 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003298 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003299
3300 // SExt or Trunc instructions.
3301 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003302 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3303 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003304 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003305
3306 // Regular instruction.
3307 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003308 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003309 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003310 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003311}
3312
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003313Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003314 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003315 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003316 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003317 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003318 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3319 // get through it and this method should not be called.
3320 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003321 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003322 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003323 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003324 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003325 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003326 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003327 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003328 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3329 TPT.replaceAllUsesWith(SExt, ZExt);
3330 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003331 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003332 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003333 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3334 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003335 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3336 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003337 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003338
3339 // Remove dead code.
3340 if (SExtOpnd->use_empty())
3341 TPT.eraseInstruction(SExtOpnd);
3342
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003343 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003344 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003345 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003346 if (ExtInst) {
3347 if (Exts)
3348 Exts->push_back(ExtInst);
3349 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3350 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003351 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003352 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003353
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003354 // At this point we have: ext ty opnd to ty.
3355 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3356 Value *NextVal = ExtInst->getOperand(0);
3357 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003358 return NextVal;
3359}
3360
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003361Value *TypePromotionHelper::promoteOperandForOther(
3362 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003363 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003364 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003365 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3366 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003367 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003368 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003369 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003370 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003371 if (!ExtOpnd->hasOneUse()) {
3372 // ExtOpnd will be promoted.
3373 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003374 // promoted version.
3375 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003376 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003377 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3378 ITrunc->removeFromParent();
3379 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003380 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003381 if (Truncs)
3382 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003383 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003384
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003385 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003386 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003387 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003388 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003389 }
3390
3391 // Get through the Instruction:
3392 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003393 // 2. Replace the uses of Ext by Inst.
3394 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003395
3396 // Remember the original type of the instruction before promotion.
3397 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003398 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3399 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003400 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003401 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003402 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003403 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003404 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003405 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003406
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003407 DEBUG(dbgs() << "Propagate Ext to operands\n");
3408 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003409 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003410 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3411 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3412 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003413 DEBUG(dbgs() << "No need to propagate\n");
3414 continue;
3415 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003416 // Check if we can statically extend the operand.
3417 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003418 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003419 DEBUG(dbgs() << "Statically extend\n");
3420 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3421 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3422 : Cst->getValue().zext(BitWidth);
3423 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003424 continue;
3425 }
3426 // UndefValue are typed, so we have to statically sign extend them.
3427 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003428 DEBUG(dbgs() << "Statically extend\n");
3429 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003430 continue;
3431 }
3432
3433 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003434 // Check if Ext was reused to extend an operand.
3435 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003436 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003437 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003438 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3439 : TPT.createZExt(Ext, Opnd, Ext->getType());
3440 if (!isa<Instruction>(ValForExtOpnd)) {
3441 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3442 continue;
3443 }
3444 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003445 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003446 if (Exts)
3447 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003448 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003449
3450 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003451 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3452 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003453 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003454 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003455 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003456 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003457 if (ExtForOpnd == Ext) {
3458 DEBUG(dbgs() << "Extension is useless now\n");
3459 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003460 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003461 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003462}
3463
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003464/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003465/// \p NewCost gives the cost of extension instructions created by the
3466/// promotion.
3467/// \p OldCost gives the cost of extension instructions before the promotion
3468/// plus the number of instructions that have been
3469/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003470/// \p PromotedOperand is the value that has been promoted.
3471/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003472bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003473 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3474 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3475 // The cost of the new extensions is greater than the cost of the
3476 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003477 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003478 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003479 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003480 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003481 return true;
3482 // The promotion is neutral but it may help folding the sign extension in
3483 // loads for instance.
3484 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003485 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003486}
3487
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003488/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003489/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003490/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003491/// If \p MovedAway is not NULL, it contains the information of whether or
3492/// not AddrInst has to be folded into the addressing mode on success.
3493/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3494/// because it has been moved away.
3495/// Thus AddrInst must not be added in the matched instructions.
3496/// This state can happen when AddrInst is a sext, since it may be moved away.
3497/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3498/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003499bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003500 unsigned Depth,
3501 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003502 // Avoid exponential behavior on extremely deep expression trees.
3503 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003504
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003505 // By default, all matched instructions stay in place.
3506 if (MovedAway)
3507 *MovedAway = false;
3508
Chandler Carruthc8925912013-01-05 02:09:22 +00003509 switch (Opcode) {
3510 case Instruction::PtrToInt:
3511 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003512 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003513 case Instruction::IntToPtr: {
3514 auto AS = AddrInst->getType()->getPointerAddressSpace();
3515 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003516 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003517 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003518 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003519 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003520 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003521 case Instruction::BitCast:
3522 // BitCast is always a noop, and we can handle it as long as it is
3523 // int->int or pointer->pointer (we don't want int<->fp or something).
3524 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3525 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3526 // Don't touch identity bitcasts. These were probably put here by LSR,
3527 // and we don't want to mess around with them. Assume it knows what it
3528 // is doing.
3529 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003530 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003531 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003532 case Instruction::AddrSpaceCast: {
3533 unsigned SrcAS
3534 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3535 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3536 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003537 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003538 return false;
3539 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003540 case Instruction::Add: {
3541 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3542 ExtAddrMode BackupAddrMode = AddrMode;
3543 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003544 // Start a transaction at this point.
3545 // The LHS may match but not the RHS.
3546 // Therefore, we need a higher level restoration point to undo partially
3547 // matched operation.
3548 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3549 TPT.getRestorationPoint();
3550
Sanjay Patelfc580a62015-09-21 23:03:16 +00003551 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3552 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003553 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003554
Chandler Carruthc8925912013-01-05 02:09:22 +00003555 // Restore the old addr mode info.
3556 AddrMode = BackupAddrMode;
3557 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003558 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003559
Chandler Carruthc8925912013-01-05 02:09:22 +00003560 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003561 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3562 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003563 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003564
Chandler Carruthc8925912013-01-05 02:09:22 +00003565 // Otherwise we definitely can't merge the ADD in.
3566 AddrMode = BackupAddrMode;
3567 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003568 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003569 break;
3570 }
3571 //case Instruction::Or:
3572 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3573 //break;
3574 case Instruction::Mul:
3575 case Instruction::Shl: {
3576 // Can only handle X*C and X << C.
3577 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003578 if (!RHS)
3579 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003580 int64_t Scale = RHS->getSExtValue();
3581 if (Opcode == Instruction::Shl)
3582 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003583
Sanjay Patelfc580a62015-09-21 23:03:16 +00003584 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003585 }
3586 case Instruction::GetElementPtr: {
3587 // Scan the GEP. We check it if it contains constant offsets and at most
3588 // one variable offset.
3589 int VariableOperand = -1;
3590 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003591
Chandler Carruthc8925912013-01-05 02:09:22 +00003592 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003593 gep_type_iterator GTI = gep_type_begin(AddrInst);
3594 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003595 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003596 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003597 unsigned Idx =
3598 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3599 ConstantOffset += SL->getElementOffset(Idx);
3600 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003601 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003602 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3603 ConstantOffset += CI->getSExtValue()*TypeSize;
3604 } else if (TypeSize) { // Scales of zero don't do anything.
3605 // We only allow one variable index at the moment.
3606 if (VariableOperand != -1)
3607 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003608
Chandler Carruthc8925912013-01-05 02:09:22 +00003609 // Remember the variable index.
3610 VariableOperand = i;
3611 VariableScale = TypeSize;
3612 }
3613 }
3614 }
Stephen Lin837bba12013-07-15 17:55:02 +00003615
Chandler Carruthc8925912013-01-05 02:09:22 +00003616 // A common case is for the GEP to only do a constant offset. In this case,
3617 // just add it to the disp field and check validity.
3618 if (VariableOperand == -1) {
3619 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003620 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003621 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003622 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003623 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003624 return true;
3625 }
3626 AddrMode.BaseOffs -= ConstantOffset;
3627 return false;
3628 }
3629
3630 // Save the valid addressing mode in case we can't match.
3631 ExtAddrMode BackupAddrMode = AddrMode;
3632 unsigned OldSize = AddrModeInsts.size();
3633
3634 // See if the scale and offset amount is valid for this target.
3635 AddrMode.BaseOffs += ConstantOffset;
3636
3637 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003638 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003639 // If it couldn't be matched, just stuff the value in a register.
3640 if (AddrMode.HasBaseReg) {
3641 AddrMode = BackupAddrMode;
3642 AddrModeInsts.resize(OldSize);
3643 return false;
3644 }
3645 AddrMode.HasBaseReg = true;
3646 AddrMode.BaseReg = AddrInst->getOperand(0);
3647 }
3648
3649 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003650 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003651 Depth)) {
3652 // If it couldn't be matched, try stuffing the base into a register
3653 // instead of matching it, and retrying the match of the scale.
3654 AddrMode = BackupAddrMode;
3655 AddrModeInsts.resize(OldSize);
3656 if (AddrMode.HasBaseReg)
3657 return false;
3658 AddrMode.HasBaseReg = true;
3659 AddrMode.BaseReg = AddrInst->getOperand(0);
3660 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003661 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003662 VariableScale, Depth)) {
3663 // If even that didn't work, bail.
3664 AddrMode = BackupAddrMode;
3665 AddrModeInsts.resize(OldSize);
3666 return false;
3667 }
3668 }
3669
3670 return true;
3671 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003672 case Instruction::SExt:
3673 case Instruction::ZExt: {
3674 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3675 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003676 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003677
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003678 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003679 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003680 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003681 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003682 if (!TPH)
3683 return false;
3684
3685 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3686 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003687 unsigned CreatedInstsCost = 0;
3688 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003689 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003690 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003691 // SExt has been moved away.
3692 // Thus either it will be rematched later in the recursive calls or it is
3693 // gone. Anyway, we must not fold it into the addressing mode at this point.
3694 // E.g.,
3695 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003696 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003697 // addr = gep base, idx
3698 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003699 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003700 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3701 // addr = gep base, op <- match
3702 if (MovedAway)
3703 *MovedAway = true;
3704
3705 assert(PromotedOperand &&
3706 "TypePromotionHelper should have filtered out those cases");
3707
3708 ExtAddrMode BackupAddrMode = AddrMode;
3709 unsigned OldSize = AddrModeInsts.size();
3710
Sanjay Patelfc580a62015-09-21 23:03:16 +00003711 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003712 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003713 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003714 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003715 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003716 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003717 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003718 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003719 AddrMode = BackupAddrMode;
3720 AddrModeInsts.resize(OldSize);
3721 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3722 TPT.rollback(LastKnownGood);
3723 return false;
3724 }
3725 return true;
3726 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003727 }
3728 return false;
3729}
3730
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003731/// If we can, try to add the value of 'Addr' into the current addressing mode.
3732/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3733/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3734/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003735///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003736bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003737 // Start a transaction at this point that we will rollback if the matching
3738 // fails.
3739 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3740 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003741 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3742 // Fold in immediates if legal for the target.
3743 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003744 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003745 return true;
3746 AddrMode.BaseOffs -= CI->getSExtValue();
3747 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3748 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003749 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003750 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003751 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003752 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003753 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003754 }
3755 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3756 ExtAddrMode BackupAddrMode = AddrMode;
3757 unsigned OldSize = AddrModeInsts.size();
3758
3759 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003760 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003761 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003762 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003763 // to check here.
3764 if (MovedAway)
3765 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003766 // Okay, it's possible to fold this. Check to see if it is actually
3767 // *profitable* to do so. We use a simple cost model to avoid increasing
3768 // register pressure too much.
3769 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003770 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003771 AddrModeInsts.push_back(I);
3772 return true;
3773 }
Stephen Lin837bba12013-07-15 17:55:02 +00003774
Chandler Carruthc8925912013-01-05 02:09:22 +00003775 // It isn't profitable to do this, roll back.
3776 //cerr << "NOT FOLDING: " << *I;
3777 AddrMode = BackupAddrMode;
3778 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003779 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003780 }
3781 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003782 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003783 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003784 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003785 } else if (isa<ConstantPointerNull>(Addr)) {
3786 // Null pointer gets folded without affecting the addressing mode.
3787 return true;
3788 }
3789
3790 // Worse case, the target should support [reg] addressing modes. :)
3791 if (!AddrMode.HasBaseReg) {
3792 AddrMode.HasBaseReg = true;
3793 AddrMode.BaseReg = Addr;
3794 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003795 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003796 return true;
3797 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003798 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003799 }
3800
3801 // If the base register is already taken, see if we can do [r+r].
3802 if (AddrMode.Scale == 0) {
3803 AddrMode.Scale = 1;
3804 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003805 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003806 return true;
3807 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003808 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003809 }
3810 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003811 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003812 return false;
3813}
3814
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003815/// Check to see if all uses of OpVal by the specified inline asm call are due
3816/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003817static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003818 const TargetLowering &TLI,
3819 const TargetRegisterInfo &TRI) {
Eric Christopher11e4df72015-02-26 22:38:43 +00003820 const Function *F = CI->getParent()->getParent();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003821 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003822 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003823 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003824
Chandler Carruthc8925912013-01-05 02:09:22 +00003825 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3826 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003827
Chandler Carruthc8925912013-01-05 02:09:22 +00003828 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003829 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003830
3831 // If this asm operand is our Value*, and if it isn't an indirect memory
3832 // operand, we can't fold it!
3833 if (OpInfo.CallOperandVal == OpVal &&
3834 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3835 !OpInfo.isIndirect))
3836 return false;
3837 }
3838
3839 return true;
3840}
3841
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003842/// Recursively walk all the uses of I until we find a memory use.
3843/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003844/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003845static bool FindAllMemoryUses(
3846 Instruction *I,
3847 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003848 SmallPtrSetImpl<Instruction *> &ConsideredInsts,
3849 const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003850 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003851 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003852 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003853
Chandler Carruthc8925912013-01-05 02:09:22 +00003854 // If this is an obviously unfoldable instruction, bail out.
3855 if (!MightBeFoldableInst(I))
3856 return true;
3857
Philip Reamesac115ed2016-03-09 23:13:12 +00003858 const bool OptSize = I->getFunction()->optForSize();
3859
Chandler Carruthc8925912013-01-05 02:09:22 +00003860 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003861 for (Use &U : I->uses()) {
3862 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003863
Chandler Carruthcdf47882014-03-09 03:16:01 +00003864 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3865 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003866 continue;
3867 }
Stephen Lin837bba12013-07-15 17:55:02 +00003868
Chandler Carruthcdf47882014-03-09 03:16:01 +00003869 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3870 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003871 if (opNo == 0) return true; // Storing addr, not into addr.
3872 MemoryUses.push_back(std::make_pair(SI, opNo));
3873 continue;
3874 }
Stephen Lin837bba12013-07-15 17:55:02 +00003875
Chandler Carruthcdf47882014-03-09 03:16:01 +00003876 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003877 // If this is a cold call, we can sink the addressing calculation into
3878 // the cold path. See optimizeCallInst
3879 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3880 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003881
Chandler Carruthc8925912013-01-05 02:09:22 +00003882 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3883 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003884
Chandler Carruthc8925912013-01-05 02:09:22 +00003885 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003886 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003887 return true;
3888 continue;
3889 }
Stephen Lin837bba12013-07-15 17:55:02 +00003890
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003891 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003892 return true;
3893 }
3894
3895 return false;
3896}
3897
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003898/// Return true if Val is already known to be live at the use site that we're
3899/// folding it into. If so, there is no cost to include it in the addressing
3900/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3901/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003902bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003903 Value *KnownLive2) {
3904 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003905 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003906 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003907
Chandler Carruthc8925912013-01-05 02:09:22 +00003908 // All values other than instructions and arguments (e.g. constants) are live.
3909 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003910
Chandler Carruthc8925912013-01-05 02:09:22 +00003911 // If Val is a constant sized alloca in the entry block, it is live, this is
3912 // true because it is just a reference to the stack/frame pointer, which is
3913 // live for the whole function.
3914 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3915 if (AI->isStaticAlloca())
3916 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003917
Chandler Carruthc8925912013-01-05 02:09:22 +00003918 // Check to see if this value is already used in the memory instruction's
3919 // block. If so, it's already live into the block at the very least, so we
3920 // can reasonably fold it.
3921 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3922}
3923
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003924/// It is possible for the addressing mode of the machine to fold the specified
3925/// instruction into a load or store that ultimately uses it.
3926/// However, the specified instruction has multiple uses.
3927/// Given this, it may actually increase register pressure to fold it
3928/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003929///
3930/// X = ...
3931/// Y = X+1
3932/// use(Y) -> nonload/store
3933/// Z = Y+1
3934/// load Z
3935///
3936/// In this case, Y has multiple uses, and can be folded into the load of Z
3937/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3938/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3939/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3940/// number of computations either.
3941///
3942/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3943/// X was live across 'load Z' for other reasons, we actually *would* want to
3944/// fold the addressing mode in the Z case. This would make Y die earlier.
3945bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003946isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003947 ExtAddrMode &AMAfter) {
3948 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003949
Chandler Carruthc8925912013-01-05 02:09:22 +00003950 // AMBefore is the addressing mode before this instruction was folded into it,
3951 // and AMAfter is the addressing mode after the instruction was folded. Get
3952 // the set of registers referenced by AMAfter and subtract out those
3953 // referenced by AMBefore: this is the set of values which folding in this
3954 // address extends the lifetime of.
3955 //
3956 // Note that there are only two potential values being referenced here,
3957 // BaseReg and ScaleReg (global addresses are always available, as are any
3958 // folded immediates).
3959 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003960
Chandler Carruthc8925912013-01-05 02:09:22 +00003961 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3962 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003963 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003964 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003965 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003966 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003967
3968 // If folding this instruction (and it's subexprs) didn't extend any live
3969 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003970 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003971 return true;
3972
Philip Reamesac115ed2016-03-09 23:13:12 +00003973 // If all uses of this instruction can have the address mode sunk into them,
3974 // we can remove the addressing mode and effectively trade one live register
3975 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003976 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003977 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3978 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003979 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003980 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003981
Chandler Carruthc8925912013-01-05 02:09:22 +00003982 // Now that we know that all uses of this instruction are part of a chain of
3983 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003984 // into a memory use, loop over each of these memory operation uses and see
3985 // if they could *actually* fold the instruction. The assumption is that
3986 // addressing modes are cheap and that duplicating the computation involved
3987 // many times is worthwhile, even on a fastpath. For sinking candidates
3988 // (i.e. cold call sites), this serves as a way to prevent excessive code
3989 // growth since most architectures have some reasonable small and fast way to
3990 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003991 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3992 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3993 Instruction *User = MemoryUses[i].first;
3994 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003995
Chandler Carruthc8925912013-01-05 02:09:22 +00003996 // Get the access type of this use. If the use isn't a pointer, we don't
3997 // know what it accesses.
3998 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003999 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4000 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004001 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004002 Type *AddressAccessTy = AddrTy->getElementType();
4003 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004004
Chandler Carruthc8925912013-01-05 02:09:22 +00004005 // Do a match against the root of this address, ignoring profitability. This
4006 // will tell us if the addressing mode for the memory operation will
4007 // *actually* cover the shared instruction.
4008 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004009 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4010 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004011 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4012 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004013 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004014 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004015 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004016 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004017 (void)Success; assert(Success && "Couldn't select *anything*?");
4018
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004019 // The match was to check the profitability, the changes made are not
4020 // part of the original matcher. Therefore, they should be dropped
4021 // otherwise the original matcher will not present the right state.
4022 TPT.rollback(LastKnownGood);
4023
Chandler Carruthc8925912013-01-05 02:09:22 +00004024 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004025 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004026 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004027
Chandler Carruthc8925912013-01-05 02:09:22 +00004028 MatchedAddrModeInsts.clear();
4029 }
Stephen Lin837bba12013-07-15 17:55:02 +00004030
Chandler Carruthc8925912013-01-05 02:09:22 +00004031 return true;
4032}
4033
4034} // end anonymous namespace
4035
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004036/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004037/// different basic block than BB.
4038static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4039 if (Instruction *I = dyn_cast<Instruction>(V))
4040 return I->getParent() != BB;
4041 return false;
4042}
4043
Philip Reamesac115ed2016-03-09 23:13:12 +00004044/// Sink addressing mode computation immediate before MemoryInst if doing so
4045/// can be done without increasing register pressure. The need for the
4046/// register pressure constraint means this can end up being an all or nothing
4047/// decision for all uses of the same addressing computation.
4048///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004049/// Load and Store Instructions often have addressing modes that can do
4050/// significant amounts of computation. As such, instruction selection will try
4051/// to get the load or store to do as much computation as possible for the
4052/// program. The problem is that isel can only see within a single block. As
4053/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004054///
4055/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004056/// operands. It's also used to sink addressing computations feeding into cold
4057/// call sites into their (cold) basic block.
4058///
4059/// The motivation for handling sinking into cold blocks is that doing so can
4060/// both enable other address mode sinking (by satisfying the register pressure
4061/// constraint above), and reduce register pressure globally (by removing the
4062/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004063bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004064 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004065 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004066
4067 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004068 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004069 SmallVector<Value*, 8> worklist;
4070 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004071 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004072
Owen Anderson8ba5f392010-11-27 08:15:55 +00004073 // Use a worklist to iteratively look through PHI nodes, and ensure that
4074 // the addressing mode obtained from the non-PHI roots of the graph
4075 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00004076 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004077 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004078 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004079 SmallVector<Instruction*, 16> AddrModeInsts;
4080 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004081 TypePromotionTransaction TPT;
4082 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4083 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004084 while (!worklist.empty()) {
4085 Value *V = worklist.back();
4086 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004087
Owen Anderson8ba5f392010-11-27 08:15:55 +00004088 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00004089 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00004090 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004091 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004092 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004093
Owen Anderson8ba5f392010-11-27 08:15:55 +00004094 // For a PHI node, push all of its incoming values.
4095 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004096 for (Value *IncValue : P->incoming_values())
4097 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00004098 continue;
4099 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004100
Philip Reamesac115ed2016-03-09 23:13:12 +00004101 // For non-PHIs, determine the addressing mode being computed. Note that
4102 // the result may differ depending on what other uses our candidate
4103 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00004104 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004105 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004106 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004107 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004108
4109 // This check is broken into two cases with very similar code to avoid using
4110 // getNumUses() as much as possible. Some values have a lot of uses, so
4111 // calling getNumUses() unconditionally caused a significant compile-time
4112 // regression.
4113 if (!Consensus) {
4114 Consensus = V;
4115 AddrMode = NewAddrMode;
4116 AddrModeInsts = NewAddrModeInsts;
4117 continue;
4118 } else if (NewAddrMode == AddrMode) {
4119 if (!IsNumUsesConsensusValid) {
4120 NumUsesConsensus = Consensus->getNumUses();
4121 IsNumUsesConsensusValid = true;
4122 }
4123
4124 // Ensure that the obtained addressing mode is equivalent to that obtained
4125 // for all other roots of the PHI traversal. Also, when choosing one
4126 // such root as representative, select the one with the most uses in order
4127 // to keep the cost modeling heuristics in AddressingModeMatcher
4128 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004129 unsigned NumUses = V->getNumUses();
4130 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004131 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004132 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004133 AddrModeInsts = NewAddrModeInsts;
4134 }
4135 continue;
4136 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004137
Craig Topperc0196b12014-04-14 00:51:57 +00004138 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004139 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004140 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004141
Owen Anderson8ba5f392010-11-27 08:15:55 +00004142 // If the addressing mode couldn't be determined, or if multiple different
4143 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004144 if (!Consensus) {
4145 TPT.rollback(LastKnownGood);
4146 return false;
4147 }
4148 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004149
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004150 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00004151 if (none_of(AddrModeInsts, [&](Value *V) {
4152 return IsNonLocalValue(V, MemoryInst->getParent());
4153 })) {
David Greene74e2d492010-01-05 01:27:11 +00004154 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004155 return false;
4156 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004157
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004158 // Insert this computation right after this user. Since our caller is
4159 // scanning from the top of the BB to the bottom, reuse of the expr are
4160 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004161 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004162
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004163 // Now that we determined the addressing expression we want to use and know
4164 // that we have to sink it into this block. Check to see if we have already
4165 // done this for some other load/store instr in this block. If so, reuse the
4166 // computation.
4167 Value *&SunkAddr = SunkAddrs[Addr];
4168 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004169 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004170 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004171 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004172 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004173 } else if (AddrSinkUsingGEPs ||
4174 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004175 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004176 // By default, we use the GEP-based method when AA is used later. This
4177 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4178 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004179 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004180 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004181 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004182
4183 // First, find the pointer.
4184 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4185 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004186 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004187 }
4188
4189 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4190 // We can't add more than one pointer together, nor can we scale a
4191 // pointer (both of which seem meaningless).
4192 if (ResultPtr || AddrMode.Scale != 1)
4193 return false;
4194
4195 ResultPtr = AddrMode.ScaledReg;
4196 AddrMode.Scale = 0;
4197 }
4198
4199 if (AddrMode.BaseGV) {
4200 if (ResultPtr)
4201 return false;
4202
4203 ResultPtr = AddrMode.BaseGV;
4204 }
4205
4206 // If the real base value actually came from an inttoptr, then the matcher
4207 // will look through it and provide only the integer value. In that case,
4208 // use it here.
4209 if (!ResultPtr && AddrMode.BaseReg) {
4210 ResultPtr =
4211 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00004212 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004213 } else if (!ResultPtr && AddrMode.Scale == 1) {
4214 ResultPtr =
4215 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4216 AddrMode.Scale = 0;
4217 }
4218
4219 if (!ResultPtr &&
4220 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4221 SunkAddr = Constant::getNullValue(Addr->getType());
4222 } else if (!ResultPtr) {
4223 return false;
4224 } else {
4225 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004226 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4227 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004228
4229 // Start with the base register. Do this first so that subsequent address
4230 // matching finds it last, which will prevent it from trying to match it
4231 // as the scaled value in case it happens to be a mul. That would be
4232 // problematic if we've sunk a different mul for the scale, because then
4233 // we'd end up sinking both muls.
4234 if (AddrMode.BaseReg) {
4235 Value *V = AddrMode.BaseReg;
4236 if (V->getType() != IntPtrTy)
4237 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4238
4239 ResultIndex = V;
4240 }
4241
4242 // Add the scale value.
4243 if (AddrMode.Scale) {
4244 Value *V = AddrMode.ScaledReg;
4245 if (V->getType() == IntPtrTy) {
4246 // done.
4247 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4248 cast<IntegerType>(V->getType())->getBitWidth()) {
4249 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4250 } else {
4251 // It is only safe to sign extend the BaseReg if we know that the math
4252 // required to create it did not overflow before we extend it. Since
4253 // the original IR value was tossed in favor of a constant back when
4254 // the AddrMode was created we need to bail out gracefully if widths
4255 // do not match instead of extending it.
4256 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4257 if (I && (ResultIndex != AddrMode.BaseReg))
4258 I->eraseFromParent();
4259 return false;
4260 }
4261
4262 if (AddrMode.Scale != 1)
4263 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4264 "sunkaddr");
4265 if (ResultIndex)
4266 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4267 else
4268 ResultIndex = V;
4269 }
4270
4271 // Add in the Base Offset if present.
4272 if (AddrMode.BaseOffs) {
4273 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4274 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004275 // We need to add this separately from the scale above to help with
4276 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004277 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004278 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004279 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004280 }
4281
4282 ResultIndex = V;
4283 }
4284
4285 if (!ResultIndex) {
4286 SunkAddr = ResultPtr;
4287 } else {
4288 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004289 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004290 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004291 }
4292
4293 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004294 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004295 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004296 } else {
David Greene74e2d492010-01-05 01:27:11 +00004297 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004298 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004299 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004300 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004301
4302 // Start with the base register. Do this first so that subsequent address
4303 // matching finds it last, which will prevent it from trying to match it
4304 // as the scaled value in case it happens to be a mul. That would be
4305 // problematic if we've sunk a different mul for the scale, because then
4306 // we'd end up sinking both muls.
4307 if (AddrMode.BaseReg) {
4308 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004309 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004310 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004311 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004312 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004313 Result = V;
4314 }
4315
4316 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004317 if (AddrMode.Scale) {
4318 Value *V = AddrMode.ScaledReg;
4319 if (V->getType() == IntPtrTy) {
4320 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004321 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004322 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004323 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4324 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004325 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004326 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004327 // It is only safe to sign extend the BaseReg if we know that the math
4328 // required to create it did not overflow before we extend it. Since
4329 // the original IR value was tossed in favor of a constant back when
4330 // the AddrMode was created we need to bail out gracefully if widths
4331 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004332 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004333 if (I && (Result != AddrMode.BaseReg))
4334 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004335 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004336 }
4337 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004338 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4339 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004340 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004341 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004342 else
4343 Result = V;
4344 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004345
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004346 // Add in the BaseGV if present.
4347 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004348 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004349 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004350 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004351 else
4352 Result = V;
4353 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004354
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004355 // Add in the Base Offset if present.
4356 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004357 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004358 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004359 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004360 else
4361 Result = V;
4362 }
4363
Craig Topperc0196b12014-04-14 00:51:57 +00004364 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004365 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004366 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004367 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004368 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004369
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004370 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004371
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004372 // If we have no uses, recursively delete the value and all dead instructions
4373 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004374 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004375 // This can cause recursive deletion, which can invalidate our iterator.
4376 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004377 Value *CurValue = &*CurInstIterator;
4378 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004379 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004380
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004381 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004382
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004383 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004384 // If the iterator instruction was recursively deleted, start over at the
4385 // start of the block.
4386 CurInstIterator = BB->begin();
4387 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004388 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004389 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004390 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004391 return true;
4392}
4393
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004394/// If there are any memory operands, use OptimizeMemoryInst to sink their
4395/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004396bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004397 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004398
Eric Christopher11e4df72015-02-26 22:38:43 +00004399 const TargetRegisterInfo *TRI =
4400 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004401 TargetLowering::AsmOperandInfoVector TargetConstraints =
4402 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004403 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004404 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4405 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004406
Evan Cheng1da25002008-02-26 02:42:37 +00004407 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004408 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004409
Eli Friedman666bbe32008-02-26 18:37:49 +00004410 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4411 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004412 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004413 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004414 } else if (OpInfo.Type == InlineAsm::isInput)
4415 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004416 }
4417
4418 return MadeChange;
4419}
4420
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004421/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4422/// sign extensions.
4423static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4424 assert(!Inst->use_empty() && "Input must have at least one use");
4425 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4426 bool IsSExt = isa<SExtInst>(FirstUser);
4427 Type *ExtTy = FirstUser->getType();
4428 for (const User *U : Inst->users()) {
4429 const Instruction *UI = cast<Instruction>(U);
4430 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4431 return false;
4432 Type *CurTy = UI->getType();
4433 // Same input and output types: Same instruction after CSE.
4434 if (CurTy == ExtTy)
4435 continue;
4436
4437 // If IsSExt is true, we are in this situation:
4438 // a = Inst
4439 // b = sext ty1 a to ty2
4440 // c = sext ty1 a to ty3
4441 // Assuming ty2 is shorter than ty3, this could be turned into:
4442 // a = Inst
4443 // b = sext ty1 a to ty2
4444 // c = sext ty2 b to ty3
4445 // However, the last sext is not free.
4446 if (IsSExt)
4447 return false;
4448
4449 // This is a ZExt, maybe this is free to extend from one type to another.
4450 // In that case, we would not account for a different use.
4451 Type *NarrowTy;
4452 Type *LargeTy;
4453 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4454 CurTy->getScalarType()->getIntegerBitWidth()) {
4455 NarrowTy = CurTy;
4456 LargeTy = ExtTy;
4457 } else {
4458 NarrowTy = ExtTy;
4459 LargeTy = CurTy;
4460 }
4461
4462 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4463 return false;
4464 }
4465 // All uses are the same or can be derived from one another for free.
4466 return true;
4467}
4468
4469/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4470/// load instruction.
4471/// If an ext(load) can be formed, it is returned via \p LI for the load
4472/// and \p Inst for the extension.
4473/// Otherwise LI == nullptr and Inst == nullptr.
4474/// When some promotion happened, \p TPT contains the proper state to
4475/// revert them.
4476///
4477/// \return true when promoting was necessary to expose the ext(load)
4478/// opportunity, false otherwise.
4479///
4480/// Example:
4481/// \code
4482/// %ld = load i32* %addr
4483/// %add = add nuw i32 %ld, 4
4484/// %zext = zext i32 %add to i64
4485/// \endcode
4486/// =>
4487/// \code
4488/// %ld = load i32* %addr
4489/// %zext = zext i32 %ld to i64
4490/// %add = add nuw i64 %zext, 4
Haicheng Wu8ce2d142017-01-18 21:12:10 +00004491/// \endcode
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004492/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004493bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004494 LoadInst *&LI, Instruction *&Inst,
4495 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004496 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004497 // Iterate over all the extensions to see if one form an ext(load).
4498 for (auto I : Exts) {
4499 // Check if we directly have ext(load).
4500 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4501 Inst = I;
4502 // No promotion happened here.
4503 return false;
4504 }
4505 // Check whether or not we want to do any promotion.
4506 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4507 continue;
4508 // Get the action to perform the promotion.
4509 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004510 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004511 // Check if we can promote.
4512 if (!TPH)
4513 continue;
4514 // Save the current state.
4515 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4516 TPT.getRestorationPoint();
4517 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004518 unsigned NewCreatedInstsCost = 0;
4519 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004520 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004521 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4522 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004523 assert(PromotedVal &&
4524 "TypePromotionHelper should have filtered out those cases");
4525
4526 // We would be able to merge only one extension in a load.
4527 // Therefore, if we have more than 1 new extension we heuristically
4528 // cut this search path, because it means we degrade the code quality.
4529 // With exactly 2, the transformation is neutral, because we will merge
4530 // one extension but leave one. However, we optimistically keep going,
4531 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004532 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004533 // FIXME: It would be possible to propagate a negative value instead of
4534 // conservatively ceiling it to 0.
4535 TotalCreatedInstsCost =
4536 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004537 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004538 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004539 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004540 // The promotion is not profitable, rollback to the previous state.
4541 TPT.rollback(LastKnownGood);
4542 continue;
4543 }
4544 // The promotion is profitable.
4545 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004546 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004547 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004548 // If we have created a new extension, i.e., now we have two
4549 // extensions. We must make sure one of them is merged with
4550 // the load, otherwise we may degrade the code quality.
4551 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4552 // Promotion happened.
4553 return true;
4554 // If this does not help to expose an ext(load) then, rollback.
4555 TPT.rollback(LastKnownGood);
4556 }
4557 // None of the extension can form an ext(load).
4558 LI = nullptr;
4559 Inst = nullptr;
4560 return false;
4561}
4562
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004563/// Move a zext or sext fed by a load into the same basic block as the load,
4564/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4565/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004566/// \p I[in/out] the extension may be modified during the process if some
4567/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004568///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004569bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004570 // ExtLoad formation infrastructure requires TLI to be effective.
4571 if (!TLI)
4572 return false;
4573
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004574 // Try to promote a chain of computation if it allows to form
4575 // an extended load.
4576 TypePromotionTransaction TPT;
4577 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4578 TPT.getRestorationPoint();
4579 SmallVector<Instruction *, 1> Exts;
4580 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004581 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004582 LoadInst *LI = nullptr;
4583 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004584 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004585 if (!LI || !I) {
4586 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4587 "the code must remain the same");
4588 I = OldExt;
4589 return false;
4590 }
Dan Gohman99429a02009-10-16 20:59:35 +00004591
4592 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004593 // Make the cheap checks first if we did not promote.
4594 // If we promoted, we need to check if it is indeed profitable.
4595 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004596 return false;
4597
Mehdi Amini44ede332015-07-09 02:09:04 +00004598 EVT VT = TLI->getValueType(*DL, I->getType());
4599 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004600
Dan Gohman99429a02009-10-16 20:59:35 +00004601 // If the load has other users and the truncate is not free, this probably
4602 // isn't worthwhile.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004603 if (!LI->hasOneUse() &&
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004604 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004605 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4606 I = OldExt;
4607 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004608 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004609 }
Dan Gohman99429a02009-10-16 20:59:35 +00004610
4611 // Check whether the target supports casts folded into loads.
4612 unsigned LType;
4613 if (isa<ZExtInst>(I))
4614 LType = ISD::ZEXTLOAD;
4615 else {
4616 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4617 LType = ISD::SEXTLOAD;
4618 }
Chandler Carruth0f139b42016-11-04 06:54:00 +00004619 if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004620 I = OldExt;
4621 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004622 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004623 }
Dan Gohman99429a02009-10-16 20:59:35 +00004624
4625 // Move the extend into the same block as the load, so that SelectionDAG
4626 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004627 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004628 I->removeFromParent();
4629 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004630 // CGP does not check if the zext would be speculatively executed when moved
4631 // to the same basic block as the load. Preserving its original location would
4632 // pessimize the debugging experience, as well as negatively impact the
4633 // quality of sample pgo. We don't want to use "line 0" as that has a
4634 // size cost in the line-table section and logically the zext can be seen as
4635 // part of the load. Therefore we conservatively reuse the same debug location
4636 // for the load and the zext.
4637 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004638 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004639 return true;
4640}
4641
Sanjay Patelfc580a62015-09-21 23:03:16 +00004642bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004643 BasicBlock *DefBB = I->getParent();
4644
Bob Wilsonff714f92010-09-21 21:44:14 +00004645 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004646 // other uses of the source with result of extension.
4647 Value *Src = I->getOperand(0);
4648 if (Src->hasOneUse())
4649 return false;
4650
Evan Cheng2011df42007-12-13 07:50:36 +00004651 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004652 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004653 return false;
4654
Evan Cheng7bc89422007-12-12 00:51:06 +00004655 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004656 // this block.
4657 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004658 return false;
4659
Evan Chengd3d80172007-12-05 23:58:20 +00004660 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004661 for (User *U : I->users()) {
4662 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004663
4664 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004665 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004666 if (UserBB == DefBB) continue;
4667 DefIsLiveOut = true;
4668 break;
4669 }
4670 if (!DefIsLiveOut)
4671 return false;
4672
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004673 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004674 for (User *U : Src->users()) {
4675 Instruction *UI = cast<Instruction>(U);
4676 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004677 if (UserBB == DefBB) continue;
4678 // Be conservative. We don't want this xform to end up introducing
4679 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004680 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004681 return false;
4682 }
4683
Evan Chengd3d80172007-12-05 23:58:20 +00004684 // InsertedTruncs - Only insert one trunc in each block once.
4685 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4686
4687 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004688 for (Use &U : Src->uses()) {
4689 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004690
4691 // Figure out which BB this ext is used in.
4692 BasicBlock *UserBB = User->getParent();
4693 if (UserBB == DefBB) continue;
4694
4695 // Both src and def are live in this block. Rewrite the use.
4696 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4697
4698 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004699 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004700 assert(InsertPt != UserBB->end());
4701 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004702 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004703 }
4704
4705 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004706 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004707 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004708 MadeChange = true;
4709 }
4710
4711 return MadeChange;
4712}
4713
Geoff Berry5256fca2015-11-20 22:34:39 +00004714// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4715// just after the load if the target can fold this into one extload instruction,
4716// with the hope of eliminating some of the other later "and" instructions using
4717// the loaded value. "and"s that are made trivially redundant by the insertion
4718// of the new "and" are removed by this function, while others (e.g. those whose
4719// path from the load goes through a phi) are left for isel to potentially
4720// remove.
4721//
4722// For example:
4723//
4724// b0:
4725// x = load i32
4726// ...
4727// b1:
4728// y = and x, 0xff
4729// z = use y
4730//
4731// becomes:
4732//
4733// b0:
4734// x = load i32
4735// x' = and x, 0xff
4736// ...
4737// b1:
4738// z = use x'
4739//
4740// whereas:
4741//
4742// b0:
4743// x1 = load i32
4744// ...
4745// b1:
4746// x2 = load i32
4747// ...
4748// b2:
4749// x = phi x1, x2
4750// y = and x, 0xff
4751//
4752// becomes (after a call to optimizeLoadExt for each load):
4753//
4754// b0:
4755// x1 = load i32
4756// x1' = and x1, 0xff
4757// ...
4758// b1:
4759// x2 = load i32
4760// x2' = and x2, 0xff
4761// ...
4762// b2:
4763// x = phi x1', x2'
4764// y = and x, 0xff
4765//
4766
4767bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4768
4769 if (!Load->isSimple() ||
4770 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4771 return false;
4772
Geoff Berry5d534b62017-02-21 18:53:14 +00004773 // Skip loads we've already transformed.
4774 if (Load->hasOneUse() &&
4775 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
4776 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00004777
4778 // Look at all uses of Load, looking through phis, to determine how many bits
4779 // of the loaded value are needed.
4780 SmallVector<Instruction *, 8> WorkList;
4781 SmallPtrSet<Instruction *, 16> Visited;
4782 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4783 for (auto *U : Load->users())
4784 WorkList.push_back(cast<Instruction>(U));
4785
4786 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4787 unsigned BitWidth = LoadResultVT.getSizeInBits();
4788 APInt DemandBits(BitWidth, 0);
4789 APInt WidestAndBits(BitWidth, 0);
4790
4791 while (!WorkList.empty()) {
4792 Instruction *I = WorkList.back();
4793 WorkList.pop_back();
4794
4795 // Break use-def graph loops.
4796 if (!Visited.insert(I).second)
4797 continue;
4798
4799 // For a PHI node, push all of its users.
4800 if (auto *Phi = dyn_cast<PHINode>(I)) {
4801 for (auto *U : Phi->users())
4802 WorkList.push_back(cast<Instruction>(U));
4803 continue;
4804 }
4805
4806 switch (I->getOpcode()) {
4807 case llvm::Instruction::And: {
4808 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4809 if (!AndC)
4810 return false;
4811 APInt AndBits = AndC->getValue();
4812 DemandBits |= AndBits;
4813 // Keep track of the widest and mask we see.
4814 if (AndBits.ugt(WidestAndBits))
4815 WidestAndBits = AndBits;
4816 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4817 AndsToMaybeRemove.push_back(I);
4818 break;
4819 }
4820
4821 case llvm::Instruction::Shl: {
4822 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4823 if (!ShlC)
4824 return false;
4825 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4826 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4827 DemandBits |= ShlDemandBits;
4828 break;
4829 }
4830
4831 case llvm::Instruction::Trunc: {
4832 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4833 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4834 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4835 DemandBits |= TruncBits;
4836 break;
4837 }
4838
4839 default:
4840 return false;
4841 }
4842 }
4843
4844 uint32_t ActiveBits = DemandBits.getActiveBits();
4845 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4846 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4847 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4848 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4849 // followed by an AND.
4850 // TODO: Look into removing this restriction by fixing backends to either
4851 // return false for isLoadExtLegal for i1 or have them select this pattern to
4852 // a single instruction.
4853 //
4854 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4855 // mask, since these are the only ands that will be removed by isel.
4856 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4857 WidestAndBits != DemandBits)
4858 return false;
4859
4860 LLVMContext &Ctx = Load->getType()->getContext();
4861 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4862 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4863
4864 // Reject cases that won't be matched as extloads.
4865 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4866 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4867 return false;
4868
4869 IRBuilder<> Builder(Load->getNextNode());
4870 auto *NewAnd = dyn_cast<Instruction>(
4871 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00004872 // Mark this instruction as "inserted by CGP", so that other
4873 // optimizations don't touch it.
4874 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00004875
4876 // Replace all uses of load with new and (except for the use of load in the
4877 // new and itself).
4878 Load->replaceAllUsesWith(NewAnd);
4879 NewAnd->setOperand(0, Load);
4880
4881 // Remove any and instructions that are now redundant.
4882 for (auto *And : AndsToMaybeRemove)
4883 // Check that the and mask is the same as the one we decided to put on the
4884 // new and.
4885 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4886 And->replaceAllUsesWith(NewAnd);
4887 if (&*CurInstIterator == And)
4888 CurInstIterator = std::next(And->getIterator());
4889 And->eraseFromParent();
4890 ++NumAndUses;
4891 }
4892
4893 ++NumAndsAdded;
4894 return true;
4895}
4896
Sanjay Patel69a50a12015-10-19 21:59:12 +00004897/// Check if V (an operand of a select instruction) is an expensive instruction
4898/// that is only used once.
4899static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4900 auto *I = dyn_cast<Instruction>(V);
4901 // If it's safe to speculatively execute, then it should not have side
4902 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004903 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4904 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004905}
4906
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004907/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004908static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004909 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004910 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004911 // If even a predictable select is cheap, then a branch can't be cheaper.
4912 if (!TLI->isPredictableSelectExpensive())
4913 return false;
4914
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004915 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004916 // whether a select is better represented as a branch.
4917
4918 // If metadata tells us that the select condition is obviously predictable,
4919 // then we want to replace the select with a branch.
4920 uint64_t TrueWeight, FalseWeight;
4921 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4922 uint64_t Max = std::max(TrueWeight, FalseWeight);
4923 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004924 if (Sum != 0) {
4925 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4926 if (Probability > TLI->getPredictableBranchThreshold())
4927 return true;
4928 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004929 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004930
4931 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4932
Sanjay Patel4e652762015-09-28 22:14:51 +00004933 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4934 // comparison condition. If the compare has more than one use, there's
4935 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004936 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004937 return false;
4938
Sanjay Patel69a50a12015-10-19 21:59:12 +00004939 // If either operand of the select is expensive and only needed on one side
4940 // of the select, we should form a branch.
4941 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4942 sinkSelectOperand(TTI, SI->getFalseValue()))
4943 return true;
4944
4945 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004946}
4947
Dehao Chen9bbb9412016-09-12 20:23:28 +00004948/// If \p isTrue is true, return the true value of \p SI, otherwise return
4949/// false value of \p SI. If the true/false value of \p SI is defined by any
4950/// select instructions in \p Selects, look through the defining select
4951/// instruction until the true/false value is not defined in \p Selects.
4952static Value *getTrueOrFalseValue(
4953 SelectInst *SI, bool isTrue,
4954 const SmallPtrSet<const Instruction *, 2> &Selects) {
4955 Value *V;
4956
4957 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4958 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004959 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004960 "The condition of DefSI does not match with SI");
4961 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4962 }
4963 return V;
4964}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004965
Nadav Rotem9d832022012-09-02 12:10:19 +00004966/// If we have a SelectInst that will likely profit from branch prediction,
4967/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004968bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004969 // Find all consecutive select instructions that share the same condition.
4970 SmallVector<SelectInst *, 2> ASI;
4971 ASI.push_back(SI);
4972 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4973 It != SI->getParent()->end(); ++It) {
4974 SelectInst *I = dyn_cast<SelectInst>(&*It);
4975 if (I && SI->getCondition() == I->getCondition()) {
4976 ASI.push_back(I);
4977 } else {
4978 break;
4979 }
4980 }
4981
4982 SelectInst *LastSI = ASI.back();
4983 // Increment the current iterator to skip all the rest of select instructions
4984 // because they will be either "not lowered" or "all lowered" to branch.
4985 CurInstIterator = std::next(LastSI->getIterator());
4986
Nadav Rotem9d832022012-09-02 12:10:19 +00004987 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4988
4989 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004990 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4991 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004992 return false;
4993
Nadav Rotem9d832022012-09-02 12:10:19 +00004994 TargetLowering::SelectSupportKind SelectKind;
4995 if (VectorCond)
4996 SelectKind = TargetLowering::VectorMaskSelect;
4997 else if (SI->getType()->isVectorTy())
4998 SelectKind = TargetLowering::ScalarCondVectorVal;
4999 else
5000 SelectKind = TargetLowering::ScalarValSelect;
5001
Sanjay Pateld66607b2016-04-26 17:11:17 +00005002 if (TLI->isSelectSupported(SelectKind) &&
5003 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5004 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005005
5006 ModifiedDT = true;
5007
Sanjay Patel69a50a12015-10-19 21:59:12 +00005008 // Transform a sequence like this:
5009 // start:
5010 // %cmp = cmp uge i32 %a, %b
5011 // %sel = select i1 %cmp, i32 %c, i32 %d
5012 //
5013 // Into:
5014 // start:
5015 // %cmp = cmp uge i32 %a, %b
5016 // br i1 %cmp, label %select.true, label %select.false
5017 // select.true:
5018 // br label %select.end
5019 // select.false:
5020 // br label %select.end
5021 // select.end:
5022 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5023 //
5024 // In addition, we may sink instructions that produce %c or %d from
5025 // the entry block into the destination(s) of the new branch.
5026 // If the true or false blocks do not contain a sunken instruction, that
5027 // block and its branch may be optimized away. In that case, one side of the
5028 // first branch will point directly to select.end, and the corresponding PHI
5029 // predecessor block will be the start block.
5030
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005031 // First, we split the block containing the select into 2 blocks.
5032 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005033 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005034 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005035
Sanjay Patel69a50a12015-10-19 21:59:12 +00005036 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005037 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005038
5039 // These are the new basic blocks for the conditional branch.
5040 // At least one will become an actual new basic block.
5041 BasicBlock *TrueBlock = nullptr;
5042 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005043 BranchInst *TrueBranch = nullptr;
5044 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005045
5046 // Sink expensive instructions into the conditional blocks to avoid executing
5047 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005048 for (SelectInst *SI : ASI) {
5049 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5050 if (TrueBlock == nullptr) {
5051 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5052 EndBlock->getParent(), EndBlock);
5053 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5054 }
5055 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5056 TrueInst->moveBefore(TrueBranch);
5057 }
5058 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5059 if (FalseBlock == nullptr) {
5060 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5061 EndBlock->getParent(), EndBlock);
5062 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5063 }
5064 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5065 FalseInst->moveBefore(FalseBranch);
5066 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005067 }
5068
5069 // If there was nothing to sink, then arbitrarily choose the 'false' side
5070 // for a new input value to the PHI.
5071 if (TrueBlock == FalseBlock) {
5072 assert(TrueBlock == nullptr &&
5073 "Unexpected basic block transform while optimizing select");
5074
5075 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5076 EndBlock->getParent(), EndBlock);
5077 BranchInst::Create(EndBlock, FalseBlock);
5078 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005079
5080 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005081 // If we did not create a new block for one of the 'true' or 'false' paths
5082 // of the condition, it means that side of the branch goes to the end block
5083 // directly and the path originates from the start block from the point of
5084 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005085 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005086 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005087 TT = EndBlock;
5088 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005089 TrueBlock = StartBlock;
5090 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005091 TT = TrueBlock;
5092 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005093 FalseBlock = StartBlock;
5094 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005095 TT = TrueBlock;
5096 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005097 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005098 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005099
Dehao Chen9bbb9412016-09-12 20:23:28 +00005100 SmallPtrSet<const Instruction *, 2> INS;
5101 INS.insert(ASI.begin(), ASI.end());
5102 // Use reverse iterator because later select may use the value of the
5103 // earlier select, and we need to propagate value through earlier select
5104 // to get the PHI operand.
5105 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5106 SelectInst *SI = *It;
5107 // The select itself is replaced with a PHI Node.
5108 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5109 PN->takeName(SI);
5110 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5111 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005112
Dehao Chen9bbb9412016-09-12 20:23:28 +00005113 SI->replaceAllUsesWith(PN);
5114 SI->eraseFromParent();
5115 INS.erase(SI);
5116 ++NumSelectsExpanded;
5117 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005118
5119 // Instruct OptimizeBlock to skip to the next block.
5120 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005121 return true;
5122}
5123
Benjamin Kramer573ff362014-03-01 17:24:40 +00005124static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005125 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5126 int SplatElem = -1;
5127 for (unsigned i = 0; i < Mask.size(); ++i) {
5128 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5129 return false;
5130 SplatElem = Mask[i];
5131 }
5132
5133 return true;
5134}
5135
5136/// Some targets have expensive vector shifts if the lanes aren't all the same
5137/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5138/// it's often worth sinking a shufflevector splat down to its use so that
5139/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005140bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005141 BasicBlock *DefBB = SVI->getParent();
5142
5143 // Only do this xform if variable vector shifts are particularly expensive.
5144 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5145 return false;
5146
5147 // We only expect better codegen by sinking a shuffle if we can recognise a
5148 // constant splat.
5149 if (!isBroadcastShuffle(SVI))
5150 return false;
5151
5152 // InsertedShuffles - Only insert a shuffle in each block once.
5153 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5154
5155 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005156 for (User *U : SVI->users()) {
5157 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005158
5159 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005160 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005161 if (UserBB == DefBB) continue;
5162
5163 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005164 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005165
5166 // Everything checks out, sink the shuffle if the user's block doesn't
5167 // already have a copy.
5168 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5169
5170 if (!InsertedShuffle) {
5171 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005172 assert(InsertPt != UserBB->end());
5173 InsertedShuffle =
5174 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5175 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005176 }
5177
Chandler Carruthcdf47882014-03-09 03:16:01 +00005178 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005179 MadeChange = true;
5180 }
5181
5182 // If we removed all uses, nuke the shuffle.
5183 if (SVI->use_empty()) {
5184 SVI->eraseFromParent();
5185 MadeChange = true;
5186 }
5187
5188 return MadeChange;
5189}
5190
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005191bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5192 if (!TLI || !DL)
5193 return false;
5194
5195 Value *Cond = SI->getCondition();
5196 Type *OldType = Cond->getType();
5197 LLVMContext &Context = Cond->getContext();
5198 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5199 unsigned RegWidth = RegType.getSizeInBits();
5200
5201 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5202 return false;
5203
5204 // If the register width is greater than the type width, expand the condition
5205 // of the switch instruction and each case constant to the width of the
5206 // register. By widening the type of the switch condition, subsequent
5207 // comparisons (for case comparisons) will not need to be extended to the
5208 // preferred register width, so we will potentially eliminate N-1 extends,
5209 // where N is the number of cases in the switch.
5210 auto *NewType = Type::getIntNTy(Context, RegWidth);
5211
5212 // Zero-extend the switch condition and case constants unless the switch
5213 // condition is a function argument that is already being sign-extended.
5214 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5215 // everything instead.
5216 Instruction::CastOps ExtType = Instruction::ZExt;
5217 if (auto *Arg = dyn_cast<Argument>(Cond))
5218 if (Arg->hasSExtAttr())
5219 ExtType = Instruction::SExt;
5220
5221 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5222 ExtInst->insertBefore(SI);
5223 SI->setCondition(ExtInst);
5224 for (SwitchInst::CaseIt Case : SI->cases()) {
5225 APInt NarrowConst = Case.getCaseValue()->getValue();
5226 APInt WideConst = (ExtType == Instruction::ZExt) ?
5227 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5228 Case.setValue(ConstantInt::get(Context, WideConst));
5229 }
5230
5231 return true;
5232}
5233
Quentin Colombetc32615d2014-10-31 17:52:53 +00005234namespace {
5235/// \brief Helper class to promote a scalar operation to a vector one.
5236/// This class is used to move downward extractelement transition.
5237/// E.g.,
5238/// a = vector_op <2 x i32>
5239/// b = extractelement <2 x i32> a, i32 0
5240/// c = scalar_op b
5241/// store c
5242///
5243/// =>
5244/// a = vector_op <2 x i32>
5245/// c = vector_op a (equivalent to scalar_op on the related lane)
5246/// * d = extractelement <2 x i32> c, i32 0
5247/// * store d
5248/// Assuming both extractelement and store can be combine, we get rid of the
5249/// transition.
5250class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005251 /// DataLayout associated with the current module.
5252 const DataLayout &DL;
5253
Quentin Colombetc32615d2014-10-31 17:52:53 +00005254 /// Used to perform some checks on the legality of vector operations.
5255 const TargetLowering &TLI;
5256
5257 /// Used to estimated the cost of the promoted chain.
5258 const TargetTransformInfo &TTI;
5259
5260 /// The transition being moved downwards.
5261 Instruction *Transition;
5262 /// The sequence of instructions to be promoted.
5263 SmallVector<Instruction *, 4> InstsToBePromoted;
5264 /// Cost of combining a store and an extract.
5265 unsigned StoreExtractCombineCost;
5266 /// Instruction that will be combined with the transition.
5267 Instruction *CombineInst;
5268
5269 /// \brief The instruction that represents the current end of the transition.
5270 /// Since we are faking the promotion until we reach the end of the chain
5271 /// of computation, we need a way to get the current end of the transition.
5272 Instruction *getEndOfTransition() const {
5273 if (InstsToBePromoted.empty())
5274 return Transition;
5275 return InstsToBePromoted.back();
5276 }
5277
5278 /// \brief Return the index of the original value in the transition.
5279 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5280 /// c, is at index 0.
5281 unsigned getTransitionOriginalValueIdx() const {
5282 assert(isa<ExtractElementInst>(Transition) &&
5283 "Other kind of transitions are not supported yet");
5284 return 0;
5285 }
5286
5287 /// \brief Return the index of the index in the transition.
5288 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5289 /// is at index 1.
5290 unsigned getTransitionIdx() const {
5291 assert(isa<ExtractElementInst>(Transition) &&
5292 "Other kind of transitions are not supported yet");
5293 return 1;
5294 }
5295
5296 /// \brief Get the type of the transition.
5297 /// This is the type of the original value.
5298 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5299 /// transition is <2 x i32>.
5300 Type *getTransitionType() const {
5301 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5302 }
5303
5304 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5305 /// I.e., we have the following sequence:
5306 /// Def = Transition <ty1> a to <ty2>
5307 /// b = ToBePromoted <ty2> Def, ...
5308 /// =>
5309 /// b = ToBePromoted <ty1> a, ...
5310 /// Def = Transition <ty1> ToBePromoted to <ty2>
5311 void promoteImpl(Instruction *ToBePromoted);
5312
5313 /// \brief Check whether or not it is profitable to promote all the
5314 /// instructions enqueued to be promoted.
5315 bool isProfitableToPromote() {
5316 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5317 unsigned Index = isa<ConstantInt>(ValIdx)
5318 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5319 : -1;
5320 Type *PromotedType = getTransitionType();
5321
5322 StoreInst *ST = cast<StoreInst>(CombineInst);
5323 unsigned AS = ST->getPointerAddressSpace();
5324 unsigned Align = ST->getAlignment();
5325 // Check if this store is supported.
5326 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005327 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5328 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005329 // If this is not supported, there is no way we can combine
5330 // the extract with the store.
5331 return false;
5332 }
5333
5334 // The scalar chain of computation has to pay for the transition
5335 // scalar to vector.
5336 // The vector chain has to account for the combining cost.
5337 uint64_t ScalarCost =
5338 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5339 uint64_t VectorCost = StoreExtractCombineCost;
5340 for (const auto &Inst : InstsToBePromoted) {
5341 // Compute the cost.
5342 // By construction, all instructions being promoted are arithmetic ones.
5343 // Moreover, one argument is a constant that can be viewed as a splat
5344 // constant.
5345 Value *Arg0 = Inst->getOperand(0);
5346 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5347 isa<ConstantFP>(Arg0);
5348 TargetTransformInfo::OperandValueKind Arg0OVK =
5349 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5350 : TargetTransformInfo::OK_AnyValue;
5351 TargetTransformInfo::OperandValueKind Arg1OVK =
5352 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5353 : TargetTransformInfo::OK_AnyValue;
5354 ScalarCost += TTI.getArithmeticInstrCost(
5355 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5356 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5357 Arg0OVK, Arg1OVK);
5358 }
5359 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5360 << ScalarCost << "\nVector: " << VectorCost << '\n');
5361 return ScalarCost > VectorCost;
5362 }
5363
5364 /// \brief Generate a constant vector with \p Val with the same
5365 /// number of elements as the transition.
5366 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005367 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005368 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5369 /// otherwise we generate a vector with as many undef as possible:
5370 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5371 /// used at the index of the extract.
5372 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5373 unsigned ExtractIdx = UINT_MAX;
5374 if (!UseSplat) {
5375 // If we cannot determine where the constant must be, we have to
5376 // use a splat constant.
5377 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5378 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5379 ExtractIdx = CstVal->getSExtValue();
5380 else
5381 UseSplat = true;
5382 }
5383
5384 unsigned End = getTransitionType()->getVectorNumElements();
5385 if (UseSplat)
5386 return ConstantVector::getSplat(End, Val);
5387
5388 SmallVector<Constant *, 4> ConstVec;
5389 UndefValue *UndefVal = UndefValue::get(Val->getType());
5390 for (unsigned Idx = 0; Idx != End; ++Idx) {
5391 if (Idx == ExtractIdx)
5392 ConstVec.push_back(Val);
5393 else
5394 ConstVec.push_back(UndefVal);
5395 }
5396 return ConstantVector::get(ConstVec);
5397 }
5398
5399 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5400 /// in \p Use can trigger undefined behavior.
5401 static bool canCauseUndefinedBehavior(const Instruction *Use,
5402 unsigned OperandIdx) {
5403 // This is not safe to introduce undef when the operand is on
5404 // the right hand side of a division-like instruction.
5405 if (OperandIdx != 1)
5406 return false;
5407 switch (Use->getOpcode()) {
5408 default:
5409 return false;
5410 case Instruction::SDiv:
5411 case Instruction::UDiv:
5412 case Instruction::SRem:
5413 case Instruction::URem:
5414 return true;
5415 case Instruction::FDiv:
5416 case Instruction::FRem:
5417 return !Use->hasNoNaNs();
5418 }
5419 llvm_unreachable(nullptr);
5420 }
5421
5422public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005423 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5424 const TargetTransformInfo &TTI, Instruction *Transition,
5425 unsigned CombineCost)
5426 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005427 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5428 assert(Transition && "Do not know how to promote null");
5429 }
5430
5431 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5432 bool canPromote(const Instruction *ToBePromoted) const {
5433 // We could support CastInst too.
5434 return isa<BinaryOperator>(ToBePromoted);
5435 }
5436
5437 /// \brief Check if it is profitable to promote \p ToBePromoted
5438 /// by moving downward the transition through.
5439 bool shouldPromote(const Instruction *ToBePromoted) const {
5440 // Promote only if all the operands can be statically expanded.
5441 // Indeed, we do not want to introduce any new kind of transitions.
5442 for (const Use &U : ToBePromoted->operands()) {
5443 const Value *Val = U.get();
5444 if (Val == getEndOfTransition()) {
5445 // If the use is a division and the transition is on the rhs,
5446 // we cannot promote the operation, otherwise we may create a
5447 // division by zero.
5448 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5449 return false;
5450 continue;
5451 }
5452 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5453 !isa<ConstantFP>(Val))
5454 return false;
5455 }
5456 // Check that the resulting operation is legal.
5457 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5458 if (!ISDOpcode)
5459 return false;
5460 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005461 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005462 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005463 }
5464
5465 /// \brief Check whether or not \p Use can be combined
5466 /// with the transition.
5467 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5468 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5469
5470 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5471 void enqueueForPromotion(Instruction *ToBePromoted) {
5472 InstsToBePromoted.push_back(ToBePromoted);
5473 }
5474
5475 /// \brief Set the instruction that will be combined with the transition.
5476 void recordCombineInstruction(Instruction *ToBeCombined) {
5477 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5478 CombineInst = ToBeCombined;
5479 }
5480
5481 /// \brief Promote all the instructions enqueued for promotion if it is
5482 /// is profitable.
5483 /// \return True if the promotion happened, false otherwise.
5484 bool promote() {
5485 // Check if there is something to promote.
5486 // Right now, if we do not have anything to combine with,
5487 // we assume the promotion is not profitable.
5488 if (InstsToBePromoted.empty() || !CombineInst)
5489 return false;
5490
5491 // Check cost.
5492 if (!StressStoreExtract && !isProfitableToPromote())
5493 return false;
5494
5495 // Promote.
5496 for (auto &ToBePromoted : InstsToBePromoted)
5497 promoteImpl(ToBePromoted);
5498 InstsToBePromoted.clear();
5499 return true;
5500 }
5501};
5502} // End of anonymous namespace.
5503
5504void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5505 // At this point, we know that all the operands of ToBePromoted but Def
5506 // can be statically promoted.
5507 // For Def, we need to use its parameter in ToBePromoted:
5508 // b = ToBePromoted ty1 a
5509 // Def = Transition ty1 b to ty2
5510 // Move the transition down.
5511 // 1. Replace all uses of the promoted operation by the transition.
5512 // = ... b => = ... Def.
5513 assert(ToBePromoted->getType() == Transition->getType() &&
5514 "The type of the result of the transition does not match "
5515 "the final type");
5516 ToBePromoted->replaceAllUsesWith(Transition);
5517 // 2. Update the type of the uses.
5518 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5519 Type *TransitionTy = getTransitionType();
5520 ToBePromoted->mutateType(TransitionTy);
5521 // 3. Update all the operands of the promoted operation with promoted
5522 // operands.
5523 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5524 for (Use &U : ToBePromoted->operands()) {
5525 Value *Val = U.get();
5526 Value *NewVal = nullptr;
5527 if (Val == Transition)
5528 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5529 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5530 isa<ConstantFP>(Val)) {
5531 // Use a splat constant if it is not safe to use undef.
5532 NewVal = getConstantVector(
5533 cast<Constant>(Val),
5534 isa<UndefValue>(Val) ||
5535 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5536 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005537 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5538 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005539 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5540 }
5541 Transition->removeFromParent();
5542 Transition->insertAfter(ToBePromoted);
5543 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5544}
5545
5546/// Some targets can do store(extractelement) with one instruction.
5547/// Try to push the extractelement towards the stores when the target
5548/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005549bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005550 unsigned CombineCost = UINT_MAX;
5551 if (DisableStoreExtract || !TLI ||
5552 (!StressStoreExtract &&
5553 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5554 Inst->getOperand(1), CombineCost)))
5555 return false;
5556
5557 // At this point we know that Inst is a vector to scalar transition.
5558 // Try to move it down the def-use chain, until:
5559 // - We can combine the transition with its single use
5560 // => we got rid of the transition.
5561 // - We escape the current basic block
5562 // => we would need to check that we are moving it at a cheaper place and
5563 // we do not do that for now.
5564 BasicBlock *Parent = Inst->getParent();
5565 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005566 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005567 // If the transition has more than one use, assume this is not going to be
5568 // beneficial.
5569 while (Inst->hasOneUse()) {
5570 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5571 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5572
5573 if (ToBePromoted->getParent() != Parent) {
5574 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5575 << ToBePromoted->getParent()->getName()
5576 << ") than the transition (" << Parent->getName() << ").\n");
5577 return false;
5578 }
5579
5580 if (VPH.canCombine(ToBePromoted)) {
5581 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5582 << "will be combined with: " << *ToBePromoted << '\n');
5583 VPH.recordCombineInstruction(ToBePromoted);
5584 bool Changed = VPH.promote();
5585 NumStoreExtractExposed += Changed;
5586 return Changed;
5587 }
5588
5589 DEBUG(dbgs() << "Try promoting.\n");
5590 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5591 return false;
5592
5593 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5594
5595 VPH.enqueueForPromotion(ToBePromoted);
5596 Inst = ToBePromoted;
5597 }
5598 return false;
5599}
5600
Wei Mia2f0b592016-12-22 19:44:45 +00005601/// For the instruction sequence of store below, F and I values
5602/// are bundled together as an i64 value before being stored into memory.
5603/// Sometimes it is more efficent to generate separate stores for F and I,
5604/// which can remove the bitwise instructions or sink them to colder places.
5605///
5606/// (store (or (zext (bitcast F to i32) to i64),
5607/// (shl (zext I to i64), 32)), addr) -->
5608/// (store F, addr) and (store I, addr+4)
5609///
5610/// Similarly, splitting for other merged store can also be beneficial, like:
5611/// For pair of {i32, i32}, i64 store --> two i32 stores.
5612/// For pair of {i32, i16}, i64 store --> two i32 stores.
5613/// For pair of {i16, i16}, i32 store --> two i16 stores.
5614/// For pair of {i16, i8}, i32 store --> two i16 stores.
5615/// For pair of {i8, i8}, i16 store --> two i8 stores.
5616///
5617/// We allow each target to determine specifically which kind of splitting is
5618/// supported.
5619///
5620/// The store patterns are commonly seen from the simple code snippet below
5621/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5622/// void goo(const std::pair<int, float> &);
5623/// hoo() {
5624/// ...
5625/// goo(std::make_pair(tmp, ftmp));
5626/// ...
5627/// }
5628///
5629/// Although we already have similar splitting in DAG Combine, we duplicate
5630/// it in CodeGenPrepare to catch the case in which pattern is across
5631/// multiple BBs. The logic in DAG Combine is kept to catch case generated
5632/// during code expansion.
5633static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5634 const TargetLowering &TLI) {
5635 // Handle simple but common cases only.
5636 Type *StoreType = SI.getValueOperand()->getType();
5637 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5638 DL.getTypeSizeInBits(StoreType) == 0)
5639 return false;
5640
5641 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5642 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5643 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5644 DL.getTypeSizeInBits(SplitStoreType))
5645 return false;
5646
5647 // Match the following patterns:
5648 // (store (or (zext LValue to i64),
5649 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5650 // or
5651 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5652 // (zext LValue to i64),
5653 // Expect both operands of OR and the first operand of SHL have only
5654 // one use.
5655 Value *LValue, *HValue;
5656 if (!match(SI.getValueOperand(),
5657 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5658 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5659 m_SpecificInt(HalfValBitSize))))))
5660 return false;
5661
5662 // Check LValue and HValue are int with size less or equal than 32.
5663 if (!LValue->getType()->isIntegerTy() ||
5664 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5665 !HValue->getType()->isIntegerTy() ||
5666 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5667 return false;
5668
5669 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5670 // as the input of target query.
5671 auto *LBC = dyn_cast<BitCastInst>(LValue);
5672 auto *HBC = dyn_cast<BitCastInst>(HValue);
5673 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5674 : EVT::getEVT(LValue->getType());
5675 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5676 : EVT::getEVT(HValue->getType());
5677 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5678 return false;
5679
5680 // Start to split store.
5681 IRBuilder<> Builder(SI.getContext());
5682 Builder.SetInsertPoint(&SI);
5683
5684 // If LValue/HValue is a bitcast in another BB, create a new one in current
5685 // BB so it may be merged with the splitted stores by dag combiner.
5686 if (LBC && LBC->getParent() != SI.getParent())
5687 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5688 if (HBC && HBC->getParent() != SI.getParent())
5689 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
5690
5691 auto CreateSplitStore = [&](Value *V, bool Upper) {
5692 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
5693 Value *Addr = Builder.CreateBitCast(
5694 SI.getOperand(1),
5695 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
5696 if (Upper)
5697 Addr = Builder.CreateGEP(
5698 SplitStoreType, Addr,
5699 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
5700 Builder.CreateAlignedStore(
5701 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
5702 };
5703
5704 CreateSplitStore(LValue, false);
5705 CreateSplitStore(HValue, true);
5706
5707 // Delete the old store.
5708 SI.eraseFromParent();
5709 return true;
5710}
5711
Sanjay Patelfc580a62015-09-21 23:03:16 +00005712bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005713 // Bail out if we inserted the instruction to prevent optimizations from
5714 // stepping on each other's toes.
5715 if (InsertedInsts.count(I))
5716 return false;
5717
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005718 if (PHINode *P = dyn_cast<PHINode>(I)) {
5719 // It is possible for very late stage optimizations (such as SimplifyCFG)
5720 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5721 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005722 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005723 P->replaceAllUsesWith(V);
5724 P->eraseFromParent();
5725 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005726 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005727 }
Chris Lattneree588de2011-01-15 07:29:01 +00005728 return false;
5729 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005730
Chris Lattneree588de2011-01-15 07:29:01 +00005731 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005732 // If the source of the cast is a constant, then this should have
5733 // already been constant folded. The only reason NOT to constant fold
5734 // it is if something (e.g. LSR) was careful to place the constant
5735 // evaluation in a block other than then one that uses it (e.g. to hoist
5736 // the address of globals out of a loop). If this is the case, we don't
5737 // want to forward-subst the cast.
5738 if (isa<Constant>(CI->getOperand(0)))
5739 return false;
5740
Mehdi Amini44ede332015-07-09 02:09:04 +00005741 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005742 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005743
Chris Lattneree588de2011-01-15 07:29:01 +00005744 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005745 /// Sink a zext or sext into its user blocks if the target type doesn't
5746 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005747 if (TLI &&
5748 TLI->getTypeAction(CI->getContext(),
5749 TLI->getValueType(*DL, CI->getType())) ==
5750 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005751 return SinkCast(CI);
5752 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005753 bool MadeChange = moveExtToFormExtLoad(I);
5754 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005755 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005756 }
Chris Lattneree588de2011-01-15 07:29:01 +00005757 return false;
5758 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005759
Chris Lattneree588de2011-01-15 07:29:01 +00005760 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005761 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005762 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005763
Chris Lattneree588de2011-01-15 07:29:01 +00005764 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00005765 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005766 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005767 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005768 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005769 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5770 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005771 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005772 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005773 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005774
Chris Lattneree588de2011-01-15 07:29:01 +00005775 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00005776 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
5777 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00005778 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005779 if (TLI) {
5780 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005781 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005782 SI->getOperand(0)->getType(), AS);
5783 }
Chris Lattneree588de2011-01-15 07:29:01 +00005784 return false;
5785 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005786
Yi Jiangd069f632014-04-21 19:34:27 +00005787 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5788
Geoff Berry5d534b62017-02-21 18:53:14 +00005789 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
5790 EnableAndCmpSinking && TLI)
5791 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
5792
Yi Jiangd069f632014-04-21 19:34:27 +00005793 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5794 BinOp->getOpcode() == Instruction::LShr)) {
5795 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5796 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005797 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005798
5799 return false;
5800 }
5801
Chris Lattneree588de2011-01-15 07:29:01 +00005802 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005803 if (GEPI->hasAllZeroIndices()) {
5804 /// The GEP operand must be a pointer, so must its result -> BitCast
5805 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5806 GEPI->getName(), GEPI);
5807 GEPI->replaceAllUsesWith(NC);
5808 GEPI->eraseFromParent();
5809 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005810 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005811 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005812 }
Chris Lattneree588de2011-01-15 07:29:01 +00005813 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005814 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005815
Chris Lattneree588de2011-01-15 07:29:01 +00005816 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005817 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005818
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005819 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005820 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005821
Tim Northoveraeb8e062014-02-19 10:02:43 +00005822 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005823 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005824
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005825 if (auto *Switch = dyn_cast<SwitchInst>(I))
5826 return optimizeSwitchInst(Switch);
5827
Quentin Colombetc32615d2014-10-31 17:52:53 +00005828 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005829 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005830
Chris Lattneree588de2011-01-15 07:29:01 +00005831 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005832}
5833
James Molloyf01488e2016-01-15 09:20:19 +00005834/// Given an OR instruction, check to see if this is a bitreverse
5835/// idiom. If so, insert the new intrinsic and return true.
5836static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5837 const TargetLowering &TLI) {
5838 if (!I.getType()->isIntegerTy() ||
5839 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5840 TLI.getValueType(DL, I.getType(), true)))
5841 return false;
5842
5843 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005844 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005845 return false;
5846 Instruction *LastInst = Insts.back();
5847 I.replaceAllUsesWith(LastInst);
5848 RecursivelyDeleteTriviallyDeadInstructions(&I);
5849 return true;
5850}
5851
Chris Lattnerf2836d12007-03-31 04:06:36 +00005852// In this pass we look for GEP and cast instructions that are used
5853// across basic blocks and rewrite them to improve basic-block-at-a-time
5854// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005855bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005856 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005857 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005858
Chris Lattner7a277142011-01-15 07:14:54 +00005859 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005860 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005861 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005862 if (ModifiedDT)
5863 return true;
5864 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005865
James Molloyf01488e2016-01-15 09:20:19 +00005866 bool MadeBitReverse = true;
5867 while (TLI && MadeBitReverse) {
5868 MadeBitReverse = false;
5869 for (auto &I : reverse(BB)) {
5870 if (makeBitReverse(I, *DL, *TLI)) {
5871 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005872 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005873 break;
5874 }
5875 }
5876 }
James Molloy3ef84c42016-01-15 10:36:01 +00005877 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005878
Chris Lattnerf2836d12007-03-31 04:06:36 +00005879 return MadeChange;
5880}
Devang Patel53771ba2011-08-18 00:50:51 +00005881
5882// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005883// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005884// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005885bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005886 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005887 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005888 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005889 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005890 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005891 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005892 // Leave dbg.values that refer to an alloca alone. These
5893 // instrinsics describe the address of a variable (= the alloca)
5894 // being taken. They should not be moved next to the alloca
5895 // (and to the beginning of the scope), but rather stay close to
5896 // where said address is used.
5897 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005898 PrevNonDbgInst = Insn;
5899 continue;
5900 }
5901
5902 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5903 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005904 // If VI is a phi in a block with an EHPad terminator, we can't insert
5905 // after it.
5906 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5907 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005908 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5909 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005910 if (isa<PHINode>(VI))
5911 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5912 else
5913 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005914 MadeChange = true;
5915 ++NumDbgValueMoved;
5916 }
5917 }
5918 }
5919 return MadeChange;
5920}
Tim Northovercea0abb2014-03-29 08:22:29 +00005921
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005922/// \brief Scale down both weights to fit into uint32_t.
5923static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5924 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5925 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5926 NewTrue = NewTrue / Scale;
5927 NewFalse = NewFalse / Scale;
5928}
5929
5930/// \brief Some targets prefer to split a conditional branch like:
5931/// \code
5932/// %0 = icmp ne i32 %a, 0
5933/// %1 = icmp ne i32 %b, 0
5934/// %or.cond = or i1 %0, %1
5935/// br i1 %or.cond, label %TrueBB, label %FalseBB
5936/// \endcode
5937/// into multiple branch instructions like:
5938/// \code
5939/// bb1:
5940/// %0 = icmp ne i32 %a, 0
5941/// br i1 %0, label %TrueBB, label %bb2
5942/// bb2:
5943/// %1 = icmp ne i32 %b, 0
5944/// br i1 %1, label %TrueBB, label %FalseBB
5945/// \endcode
5946/// This usually allows instruction selection to do even further optimizations
5947/// and combine the compare with the branch instruction. Currently this is
5948/// applied for targets which have "cheap" jump instructions.
5949///
5950/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5951///
5952bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005953 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005954 return false;
5955
5956 bool MadeChange = false;
5957 for (auto &BB : F) {
5958 // Does this BB end with the following?
5959 // %cond1 = icmp|fcmp|binary instruction ...
5960 // %cond2 = icmp|fcmp|binary instruction ...
5961 // %cond.or = or|and i1 %cond1, cond2
5962 // br i1 %cond.or label %dest1, label %dest2"
5963 BinaryOperator *LogicOp;
5964 BasicBlock *TBB, *FBB;
5965 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5966 continue;
5967
Sanjay Patel42574202015-09-02 19:23:23 +00005968 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5969 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5970 continue;
5971
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005972 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005973 Value *Cond1, *Cond2;
5974 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5975 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005976 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005977 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5978 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005979 Opc = Instruction::Or;
5980 else
5981 continue;
5982
5983 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5984 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5985 continue;
5986
5987 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5988
5989 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005990 auto TmpBB =
5991 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5992 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005993
5994 // Update original basic block by using the first condition directly by the
5995 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005996 Br1->setCondition(Cond1);
5997 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005998
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005999 // Depending on the conditon we have to either replace the true or the false
6000 // successor of the original branch instruction.
6001 if (Opc == Instruction::And)
6002 Br1->setSuccessor(0, TmpBB);
6003 else
6004 Br1->setSuccessor(1, TmpBB);
6005
6006 // Fill in the new basic block.
6007 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006008 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6009 I->removeFromParent();
6010 I->insertBefore(Br2);
6011 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006012
6013 // Update PHI nodes in both successors. The original BB needs to be
6014 // replaced in one succesor's PHI nodes, because the branch comes now from
6015 // the newly generated BB (NewBB). In the other successor we need to add one
6016 // incoming edge to the PHI nodes, because both branch instructions target
6017 // now the same successor. Depending on the original branch condition
6018 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006019 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006020 // This doesn't change the successor order of the just created branch
6021 // instruction (or any other instruction).
6022 if (Opc == Instruction::Or)
6023 std::swap(TBB, FBB);
6024
6025 // Replace the old BB with the new BB.
6026 for (auto &I : *TBB) {
6027 PHINode *PN = dyn_cast<PHINode>(&I);
6028 if (!PN)
6029 break;
6030 int i;
6031 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6032 PN->setIncomingBlock(i, TmpBB);
6033 }
6034
6035 // Add another incoming edge form the new BB.
6036 for (auto &I : *FBB) {
6037 PHINode *PN = dyn_cast<PHINode>(&I);
6038 if (!PN)
6039 break;
6040 auto *Val = PN->getIncomingValueForBlock(&BB);
6041 PN->addIncoming(Val, TmpBB);
6042 }
6043
6044 // Update the branch weights (from SelectionDAGBuilder::
6045 // FindMergedConditions).
6046 if (Opc == Instruction::Or) {
6047 // Codegen X | Y as:
6048 // BB1:
6049 // jmp_if_X TBB
6050 // jmp TmpBB
6051 // TmpBB:
6052 // jmp_if_Y TBB
6053 // jmp FBB
6054 //
6055
6056 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6057 // The requirement is that
6058 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6059 // = TrueProb for orignal BB.
6060 // Assuming the orignal weights are A and B, one choice is to set BB1's
6061 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6062 // assumes that
6063 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6064 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6065 // TmpBB, but the math is more complicated.
6066 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006067 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006068 uint64_t NewTrueWeight = TrueWeight;
6069 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6070 scaleWeights(NewTrueWeight, NewFalseWeight);
6071 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6072 .createBranchWeights(TrueWeight, FalseWeight));
6073
6074 NewTrueWeight = TrueWeight;
6075 NewFalseWeight = 2 * FalseWeight;
6076 scaleWeights(NewTrueWeight, NewFalseWeight);
6077 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6078 .createBranchWeights(TrueWeight, FalseWeight));
6079 }
6080 } else {
6081 // Codegen X & Y as:
6082 // BB1:
6083 // jmp_if_X TmpBB
6084 // jmp FBB
6085 // TmpBB:
6086 // jmp_if_Y TBB
6087 // jmp FBB
6088 //
6089 // This requires creation of TmpBB after CurBB.
6090
6091 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6092 // The requirement is that
6093 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6094 // = FalseProb for orignal BB.
6095 // Assuming the orignal weights are A and B, one choice is to set BB1's
6096 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6097 // assumes that
6098 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6099 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006100 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006101 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6102 uint64_t NewFalseWeight = FalseWeight;
6103 scaleWeights(NewTrueWeight, NewFalseWeight);
6104 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6105 .createBranchWeights(TrueWeight, FalseWeight));
6106
6107 NewTrueWeight = 2 * TrueWeight;
6108 NewFalseWeight = FalseWeight;
6109 scaleWeights(NewTrueWeight, NewFalseWeight);
6110 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6111 .createBranchWeights(TrueWeight, FalseWeight));
6112 }
6113 }
6114
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006115 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006116 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006117 ModifiedDT = true;
6118
6119 MadeChange = true;
6120
6121 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6122 TmpBB->dump());
6123 }
6124 return MadeChange;
6125}