blob: 93d1b7a124319a908252512e798f1cc56cbcfa0f [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);
Jun Bum Lim42301012017-03-17 19:05:21 +0000223 bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
224 LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
225 bool tryToPromoteExts(TypePromotionTransaction &TPT,
226 const SmallVectorImpl<Instruction *> &Exts,
227 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
228 unsigned CreatedInstsCost = 0);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000229 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000230 bool simplifyOffsetableRelocate(Instruction &I);
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000231 bool splitIndirectCriticalEdges(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000232 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000233}
Devang Patel09f162c2007-05-01 21:15:47 +0000234
Devang Patel8c78a0b2007-05-03 01:11:54 +0000235char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000236INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
237 "Optimize for code generation", false, false)
238INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
239INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
240 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000241
Bill Wendling7a639ea2013-06-19 21:07:11 +0000242FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
243 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000244}
245
Chris Lattnerf2836d12007-03-31 04:06:36 +0000246bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000247 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000248 return false;
249
Mehdi Amini4fe37982015-07-07 18:45:17 +0000250 DL = &F.getParent()->getDataLayout();
251
Chris Lattnerf2836d12007-03-31 04:06:36 +0000252 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000253 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000254 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000255 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000256 BFI.reset();
257 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000258
Devang Patel8f606d72011-03-24 15:35:25 +0000259 ModifiedDT = false;
Igor Laevsky3be81ba2017-02-07 13:27:20 +0000260 if (TM) {
261 SubtargetInfo = TM->getSubtargetImpl(F);
262 TLI = SubtargetInfo->getTargetLowering();
263 TRI = SubtargetInfo->getRegisterInfo();
264 }
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000265 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000266 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000267 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000268 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000269
Dehao Chen302b69c2016-10-18 20:42:47 +0000270 if (ProfileGuidedSectionPrefix) {
271 ProfileSummaryInfo *PSI =
272 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
273 if (PSI->isFunctionEntryHot(&F))
274 F.setSectionPrefix(".hot");
275 else if (PSI->isFunctionEntryCold(&F))
276 F.setSectionPrefix(".cold");
277 }
278
Preston Gurdcdf540d2012-09-04 18:22:17 +0000279 /// This optimization identifies DIV instructions that can be
280 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000281 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000282 const DenseMap<unsigned int, unsigned int> &BypassWidths =
283 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000284 BasicBlock* BB = &*F.begin();
285 while (BB != nullptr) {
286 // bypassSlowDivision may create new BBs, but we don't want to reapply the
287 // optimization to those blocks.
288 BasicBlock* Next = BB->getNextNode();
289 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
290 BB = Next;
291 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000292 }
293
294 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000295 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000296 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000297
Devang Patel53771ba2011-08-18 00:50:51 +0000298 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000299 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000300 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000301 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000302
Geoff Berry5d534b62017-02-21 18:53:14 +0000303 if (!DisableBranchOpts)
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000304 EverMadeChange |= splitBranchCondition(F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000305
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000306 // Split some critical edges where one of the sources is an indirect branch,
307 // to help generate sane code for PHIs involving such edges.
308 EverMadeChange |= splitIndirectCriticalEdges(F);
309
Chris Lattnerc3748562007-04-02 01:35:34 +0000310 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000311 while (MadeChange) {
312 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000313 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000314 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000315 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000316 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000317
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000318 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000319 if (ModifiedDTOnIteration)
320 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000321 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000322 EverMadeChange |= MadeChange;
323 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000324
325 SunkAddrs.clear();
326
Cameron Zwarich338d3622011-03-11 21:52:04 +0000327 if (!DisableBranchOpts) {
328 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000329 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000330 for (BasicBlock &BB : F) {
331 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
332 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000333 if (!MadeChange) continue;
334
335 for (SmallVectorImpl<BasicBlock*>::iterator
336 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
337 if (pred_begin(*II) == pred_end(*II))
338 WorkList.insert(*II);
339 }
340
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000341 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000342 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000343 while (!WorkList.empty()) {
344 BasicBlock *BB = *WorkList.begin();
345 WorkList.erase(BB);
346 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
347
348 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000349
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000350 for (SmallVectorImpl<BasicBlock*>::iterator
351 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
352 if (pred_begin(*II) == pred_end(*II))
353 WorkList.insert(*II);
354 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000355
Nadav Rotem70409992012-08-14 05:19:07 +0000356 // Merge pairs of basic blocks with unconditional branches, connected by
357 // a single edge.
358 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000359 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000360
Cameron Zwarich338d3622011-03-11 21:52:04 +0000361 EverMadeChange |= MadeChange;
362 }
363
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000364 if (!DisableGCOpts) {
365 SmallVector<Instruction *, 2> Statepoints;
366 for (BasicBlock &BB : F)
367 for (Instruction &I : BB)
368 if (isStatepoint(I))
369 Statepoints.push_back(&I);
370 for (auto &I : Statepoints)
371 EverMadeChange |= simplifyOffsetableRelocate(*I);
372 }
373
Chris Lattnerf2836d12007-03-31 04:06:36 +0000374 return EverMadeChange;
375}
376
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000377/// Merge basic blocks which are connected by a single edge, where one of the
378/// basic blocks has a single successor pointing to the other basic block,
379/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000380bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000381 bool Changed = false;
382 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000383 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000384 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000385 // If the destination block has a single pred, then this is a trivial
386 // edge, just collapse it.
387 BasicBlock *SinglePred = BB->getSinglePredecessor();
388
Evan Cheng64a223a2012-09-28 23:58:57 +0000389 // Don't merge if BB's address is taken.
390 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000391
392 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
393 if (Term && !Term->isConditional()) {
394 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000395 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000396 // Remember if SinglePred was the entry block of the function.
397 // If so, we will need to move BB back to the entry position.
398 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000399 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000400
401 if (isEntry && BB != &BB->getParent()->getEntryBlock())
402 BB->moveBefore(&BB->getParent()->getEntryBlock());
403
404 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000405 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000406 }
407 }
408 return Changed;
409}
410
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000411/// Find a destination block from BB if BB is mergeable empty block.
412BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
413 // If this block doesn't end with an uncond branch, ignore it.
414 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
415 if (!BI || !BI->isUnconditional())
416 return nullptr;
417
418 // If the instruction before the branch (skipping debug info) isn't a phi
419 // node, then other stuff is happening here.
420 BasicBlock::iterator BBI = BI->getIterator();
421 if (BBI != BB->begin()) {
422 --BBI;
423 while (isa<DbgInfoIntrinsic>(BBI)) {
424 if (BBI == BB->begin())
425 break;
426 --BBI;
427 }
428 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
429 return nullptr;
430 }
431
432 // Do not break infinite loops.
433 BasicBlock *DestBB = BI->getSuccessor(0);
434 if (DestBB == BB)
435 return nullptr;
436
437 if (!canMergeBlocks(BB, DestBB))
438 DestBB = nullptr;
439
440 return DestBB;
441}
442
Michael Kuperstein13bf8a22017-02-28 00:11:34 +0000443// Return the unique indirectbr predecessor of a block. This may return null
444// even if such a predecessor exists, if it's not useful for splitting.
445// If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
446// predecessors of BB.
447static BasicBlock *
448findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
449 // If the block doesn't have any PHIs, we don't care about it, since there's
450 // no point in splitting it.
451 PHINode *PN = dyn_cast<PHINode>(BB->begin());
452 if (!PN)
453 return nullptr;
454
455 // Verify we have exactly one IBR predecessor.
456 // Conservatively bail out if one of the other predecessors is not a "regular"
457 // terminator (that is, not a switch or a br).
458 BasicBlock *IBB = nullptr;
459 for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
460 BasicBlock *PredBB = PN->getIncomingBlock(Pred);
461 TerminatorInst *PredTerm = PredBB->getTerminator();
462 switch (PredTerm->getOpcode()) {
463 case Instruction::IndirectBr:
464 if (IBB)
465 return nullptr;
466 IBB = PredBB;
467 break;
468 case Instruction::Br:
469 case Instruction::Switch:
470 OtherPreds.push_back(PredBB);
471 continue;
472 default:
473 return nullptr;
474 }
475 }
476
477 return IBB;
478}
479
480// Split critical edges where the source of the edge is an indirectbr
481// instruction. This isn't always possible, but we can handle some easy cases.
482// This is useful because MI is unable to split such critical edges,
483// which means it will not be able to sink instructions along those edges.
484// This is especially painful for indirect branches with many successors, where
485// we end up having to prepare all outgoing values in the origin block.
486//
487// Our normal algorithm for splitting critical edges requires us to update
488// the outgoing edges of the edge origin block, but for an indirectbr this
489// is hard, since it would require finding and updating the block addresses
490// the indirect branch uses. But if a block only has a single indirectbr
491// predecessor, with the others being regular branches, we can do it in a
492// different way.
493// Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
494// We can split D into D0 and D1, where D0 contains only the PHIs from D,
495// and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
496// create the following structure:
497// A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
498bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
499 // Check whether the function has any indirectbrs, and collect which blocks
500 // they may jump to. Since most functions don't have indirect branches,
501 // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
502 SmallSetVector<BasicBlock *, 16> Targets;
503 for (auto &BB : F) {
504 auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
505 if (!IBI)
506 continue;
507
508 for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
509 Targets.insert(IBI->getSuccessor(Succ));
510 }
511
512 if (Targets.empty())
513 return false;
514
515 bool Changed = false;
516 for (BasicBlock *Target : Targets) {
517 SmallVector<BasicBlock *, 16> OtherPreds;
518 BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
519 // If we did not found an indirectbr, or the indirectbr is the only
520 // incoming edge, this isn't the kind of edge we're looking for.
521 if (!IBRPred || OtherPreds.empty())
522 continue;
523
524 // Don't even think about ehpads/landingpads.
525 Instruction *FirstNonPHI = Target->getFirstNonPHI();
526 if (FirstNonPHI->isEHPad() || Target->isLandingPad())
527 continue;
528
529 BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
530 // It's possible Target was its own successor through an indirectbr.
531 // In this case, the indirectbr now comes from BodyBlock.
532 if (IBRPred == Target)
533 IBRPred = BodyBlock;
534
535 // At this point Target only has PHIs, and BodyBlock has the rest of the
536 // block's body. Create a copy of Target that will be used by the "direct"
537 // preds.
538 ValueToValueMapTy VMap;
539 BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
540
541 for (BasicBlock *Pred : OtherPreds)
542 Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
543
544 // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
545 // they are clones, so the number of PHIs are the same.
546 // (a) Remove the edge coming from IBRPred from the "Direct" PHI
547 // (b) Leave that as the only edge in the "Indirect" PHI.
548 // (c) Merge the two in the body block.
549 BasicBlock::iterator Indirect = Target->begin(),
550 End = Target->getFirstNonPHI()->getIterator();
551 BasicBlock::iterator Direct = DirectSucc->begin();
552 BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
553
554 assert(&*End == Target->getTerminator() &&
555 "Block was expected to only contain PHIs");
556
557 while (Indirect != End) {
558 PHINode *DirPHI = cast<PHINode>(Direct);
559 PHINode *IndPHI = cast<PHINode>(Indirect);
560
561 // Now, clean up - the direct block shouldn't get the indirect value,
562 // and vice versa.
563 DirPHI->removeIncomingValue(IBRPred);
564 Direct++;
565
566 // Advance the pointer here, to avoid invalidation issues when the old
567 // PHI is erased.
568 Indirect++;
569
570 PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
571 NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
572 IBRPred);
573
574 // Create a PHI in the body block, to merge the direct and indirect
575 // predecessors.
576 PHINode *MergePHI =
577 PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
578 MergePHI->addIncoming(NewIndPHI, Target);
579 MergePHI->addIncoming(DirPHI, DirectSucc);
580
581 IndPHI->replaceAllUsesWith(MergePHI);
582 IndPHI->eraseFromParent();
583 }
584
585 Changed = true;
586 }
587
588 return Changed;
589}
590
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000591/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
592/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
593/// edges in ways that are non-optimal for isel. Start by eliminating these
594/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000595bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000596 SmallPtrSet<BasicBlock *, 16> Preheaders;
597 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
598 while (!LoopList.empty()) {
599 Loop *L = LoopList.pop_back_val();
600 LoopList.insert(LoopList.end(), L->begin(), L->end());
601 if (BasicBlock *Preheader = L->getLoopPreheader())
602 Preheaders.insert(Preheader);
603 }
604
Chris Lattnerc3748562007-04-02 01:35:34 +0000605 bool MadeChange = false;
606 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000607 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000608 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000609 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
610 if (!DestBB ||
611 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000612 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000613
Sanjay Patelfc580a62015-09-21 23:03:16 +0000614 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000615 MadeChange = true;
616 }
617 return MadeChange;
618}
619
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000620bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
621 BasicBlock *DestBB,
622 bool isPreheader) {
623 // Do not delete loop preheaders if doing so would create a critical edge.
624 // Loop preheaders can be good locations to spill registers. If the
625 // preheader is deleted and we create a critical edge, registers may be
626 // spilled in the loop body instead.
627 if (!DisablePreheaderProtect && isPreheader &&
628 !(BB->getSinglePredecessor() &&
629 BB->getSinglePredecessor()->getSingleSuccessor()))
630 return false;
631
632 // Try to skip merging if the unique predecessor of BB is terminated by a
633 // switch or indirect branch instruction, and BB is used as an incoming block
634 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
635 // add COPY instructions in the predecessor of BB instead of BB (if it is not
636 // merged). Note that the critical edge created by merging such blocks wont be
637 // split in MachineSink because the jump table is not analyzable. By keeping
638 // such empty block (BB), ISel will place COPY instructions in BB, not in the
639 // predecessor of BB.
640 BasicBlock *Pred = BB->getUniquePredecessor();
641 if (!Pred ||
642 !(isa<SwitchInst>(Pred->getTerminator()) ||
643 isa<IndirectBrInst>(Pred->getTerminator())))
644 return true;
645
646 if (BB->getTerminator() != BB->getFirstNonPHI())
647 return true;
648
649 // We use a simple cost heuristic which determine skipping merging is
650 // profitable if the cost of skipping merging is less than the cost of
651 // merging : Cost(skipping merging) < Cost(merging BB), where the
652 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
653 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
654 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
655 // Freq(Pred) / Freq(BB) > 2.
656 // Note that if there are multiple empty blocks sharing the same incoming
657 // value for the PHIs in the DestBB, we consider them together. In such
658 // case, Cost(merging BB) will be the sum of their frequencies.
659
660 if (!isa<PHINode>(DestBB->begin()))
661 return true;
662
663 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
664
665 // Find all other incoming blocks from which incoming values of all PHIs in
666 // DestBB are the same as the ones from BB.
667 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
668 ++PI) {
669 BasicBlock *DestBBPred = *PI;
670 if (DestBBPred == BB)
671 continue;
672
673 bool HasAllSameValue = true;
674 BasicBlock::const_iterator DestBBI = DestBB->begin();
675 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
676 if (DestPN->getIncomingValueForBlock(BB) !=
677 DestPN->getIncomingValueForBlock(DestBBPred)) {
678 HasAllSameValue = false;
679 break;
680 }
681 }
682 if (HasAllSameValue)
683 SameIncomingValueBBs.insert(DestBBPred);
684 }
685
686 // See if all BB's incoming values are same as the value from Pred. In this
687 // case, no reason to skip merging because COPYs are expected to be place in
688 // Pred already.
689 if (SameIncomingValueBBs.count(Pred))
690 return true;
691
692 if (!BFI) {
693 Function &F = *BB->getParent();
694 LoopInfo LI{DominatorTree(F)};
695 BPI.reset(new BranchProbabilityInfo(F, LI));
696 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
697 }
698
699 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
700 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
701
702 for (auto SameValueBB : SameIncomingValueBBs)
703 if (SameValueBB->getUniquePredecessor() == Pred &&
704 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
705 BBFreq += BFI->getBlockFreq(SameValueBB);
706
707 return PredFreq.getFrequency() <=
708 BBFreq.getFrequency() * FreqRatioToSkipMerge;
709}
710
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000711/// Return true if we can merge BB into DestBB if there is a single
712/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000713/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000714bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000715 const BasicBlock *DestBB) const {
716 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
717 // the successor. If there are more complex condition (e.g. preheaders),
718 // don't mess around with them.
719 BasicBlock::const_iterator BBI = BB->begin();
720 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000721 for (const User *U : PN->users()) {
722 const Instruction *UI = cast<Instruction>(U);
723 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000724 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000725 // If User is inside DestBB block and it is a PHINode then check
726 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000727 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000728 if (UI->getParent() == DestBB) {
729 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000730 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
731 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
732 if (Insn && Insn->getParent() == BB &&
733 Insn->getParent() != UPN->getIncomingBlock(I))
734 return false;
735 }
736 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000737 }
738 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000739
Chris Lattnerc3748562007-04-02 01:35:34 +0000740 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
741 // and DestBB may have conflicting incoming values for the block. If so, we
742 // can't merge the block.
743 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
744 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000745
Chris Lattnerc3748562007-04-02 01:35:34 +0000746 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000747 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000748 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
749 // It is faster to get preds from a PHI than with pred_iterator.
750 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
751 BBPreds.insert(BBPN->getIncomingBlock(i));
752 } else {
753 BBPreds.insert(pred_begin(BB), pred_end(BB));
754 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000755
Chris Lattnerc3748562007-04-02 01:35:34 +0000756 // Walk the preds of DestBB.
757 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
758 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
759 if (BBPreds.count(Pred)) { // Common predecessor?
760 BBI = DestBB->begin();
761 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
762 const Value *V1 = PN->getIncomingValueForBlock(Pred);
763 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000764
Chris Lattnerc3748562007-04-02 01:35:34 +0000765 // If V2 is a phi node in BB, look up what the mapped value will be.
766 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
767 if (V2PN->getParent() == BB)
768 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000769
Chris Lattnerc3748562007-04-02 01:35:34 +0000770 // If there is a conflict, bail out.
771 if (V1 != V2) return false;
772 }
773 }
774 }
775
776 return true;
777}
778
779
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000780/// Eliminate a basic block that has only phi's and an unconditional branch in
781/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000782void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000783 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
784 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000785
David Greene74e2d492010-01-05 01:27:11 +0000786 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000787
Chris Lattnerc3748562007-04-02 01:35:34 +0000788 // If the destination block has a single pred, then this is a trivial edge,
789 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000790 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000791 if (SinglePred != DestBB) {
792 // Remember if SinglePred was the entry block of the function. If so, we
793 // will need to move BB back to the entry position.
794 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000795 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000796
Chris Lattner8a172da2008-11-28 19:54:49 +0000797 if (isEntry && BB != &BB->getParent()->getEntryBlock())
798 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000799
David Greene74e2d492010-01-05 01:27:11 +0000800 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000801 return;
802 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000803 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000804
Chris Lattnerc3748562007-04-02 01:35:34 +0000805 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
806 // to handle the new incoming edges it is about to have.
807 PHINode *PN;
808 for (BasicBlock::iterator BBI = DestBB->begin();
809 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
810 // Remove the incoming value for BB, and remember it.
811 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000812
Chris Lattnerc3748562007-04-02 01:35:34 +0000813 // Two options: either the InVal is a phi node defined in BB or it is some
814 // value that dominates BB.
815 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
816 if (InValPhi && InValPhi->getParent() == BB) {
817 // Add all of the input values of the input PHI as inputs of this phi.
818 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
819 PN->addIncoming(InValPhi->getIncomingValue(i),
820 InValPhi->getIncomingBlock(i));
821 } else {
822 // Otherwise, add one instance of the dominating value for each edge that
823 // we will be adding.
824 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
825 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
826 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
827 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000828 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
829 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000830 }
831 }
832 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000833
Chris Lattnerc3748562007-04-02 01:35:34 +0000834 // The PHIs are now updated, change everything that refers to BB to use
835 // DestBB and remove BB.
836 BB->replaceAllUsesWith(DestBB);
837 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000838 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000839
David Greene74e2d492010-01-05 01:27:11 +0000840 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000841}
842
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000843// Computes a map of base pointer relocation instructions to corresponding
844// derived pointer relocation instructions given a vector of all relocate calls
845static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000846 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
847 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
848 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000849 // Collect information in two maps: one primarily for locating the base object
850 // while filling the second map; the second map is the final structure holding
851 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000852 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
853 for (auto *ThisRelocate : AllRelocateCalls) {
854 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
855 ThisRelocate->getDerivedPtrIndex());
856 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000857 }
858 for (auto &Item : RelocateIdxMap) {
859 std::pair<unsigned, unsigned> Key = Item.first;
860 if (Key.first == Key.second)
861 // Base relocation: nothing to insert
862 continue;
863
Manuel Jacob83eefa62016-01-05 04:03:00 +0000864 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000865 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000866
867 // We're iterating over RelocateIdxMap so we cannot modify it.
868 auto MaybeBase = RelocateIdxMap.find(BaseKey);
869 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000870 // TODO: We might want to insert a new base object relocate and gep off
871 // that, if there are enough derived object relocates.
872 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000873
874 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000875 }
876}
877
878// Accepts a GEP and extracts the operands into a vector provided they're all
879// small integer constants
880static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
881 SmallVectorImpl<Value *> &OffsetV) {
882 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
883 // Only accept small constant integer operands
884 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
885 if (!Op || Op->getZExtValue() > 20)
886 return false;
887 }
888
889 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
890 OffsetV.push_back(GEP->getOperand(i));
891 return true;
892}
893
894// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
895// replace, computes a replacement, and affects it.
896static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000897simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
898 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000899 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000900 for (GCRelocateInst *ToReplace : Targets) {
901 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000902 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000903 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000904 // A duplicate relocate call. TODO: coalesce duplicates.
905 continue;
906 }
907
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000908 if (RelocatedBase->getParent() != ToReplace->getParent()) {
909 // Base and derived relocates are in different basic blocks.
910 // In this case transform is only valid when base dominates derived
911 // relocate. However it would be too expensive to check dominance
912 // for each such relocate, so we skip the whole transformation.
913 continue;
914 }
915
Manuel Jacob83eefa62016-01-05 04:03:00 +0000916 Value *Base = ToReplace->getBasePtr();
917 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000918 if (!Derived || Derived->getPointerOperand() != Base)
919 continue;
920
921 SmallVector<Value *, 2> OffsetV;
922 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
923 continue;
924
925 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000926 assert(RelocatedBase->getNextNode() &&
927 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000928
929 // Insert after RelocatedBase
930 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000931 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000932
933 // If gc_relocate does not match the actual type, cast it to the right type.
934 // In theory, there must be a bitcast after gc_relocate if the type does not
935 // match, and we should reuse it to get the derived pointer. But it could be
936 // cases like this:
937 // bb1:
938 // ...
939 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
940 // br label %merge
941 //
942 // bb2:
943 // ...
944 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
945 // br label %merge
946 //
947 // merge:
948 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
949 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
950 //
951 // In this case, we can not find the bitcast any more. So we insert a new bitcast
952 // no matter there is already one or not. In this way, we can handle all cases, and
953 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000954 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000955 if (RelocatedBase->getType() != Base->getType()) {
956 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000957 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000958 }
David Blaikie68d535c2015-03-24 22:38:16 +0000959 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000960 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000961 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000962 // If the newly generated derived pointer's type does not match the original derived
963 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000964 Value *ActualReplacement = Replacement;
965 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000966 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000967 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000968 }
969 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000970 ToReplace->eraseFromParent();
971
972 MadeChange = true;
973 }
974 return MadeChange;
975}
976
977// Turns this:
978//
979// %base = ...
980// %ptr = gep %base + 15
981// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
982// %base' = relocate(%tok, i32 4, i32 4)
983// %ptr' = relocate(%tok, i32 4, i32 5)
984// %val = load %ptr'
985//
986// into this:
987//
988// %base = ...
989// %ptr = gep %base + 15
990// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
991// %base' = gc.relocate(%tok, i32 4, i32 4)
992// %ptr' = gep %base' + 15
993// %val = load %ptr'
994bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
995 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000996 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000997
998 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000999 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001000 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +00001001 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001002
1003 // We need atleast one base pointer relocation + one derived pointer
1004 // relocation to mangle
1005 if (AllRelocateCalls.size() < 2)
1006 return false;
1007
1008 // RelocateInstMap is a mapping from the base relocate instruction to the
1009 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +00001010 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +00001011 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
1012 if (RelocateInstMap.empty())
1013 return false;
1014
1015 for (auto &Item : RelocateInstMap)
1016 // Item.first is the RelocatedBase to offset against
1017 // Item.second is the vector of Targets to replace
1018 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
1019 return MadeChange;
1020}
1021
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001022/// SinkCast - Sink the specified cast instruction into its user blocks
1023static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001024 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001025
Chris Lattnerf2836d12007-03-31 04:06:36 +00001026 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001027 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001028
Chris Lattnerf2836d12007-03-31 04:06:36 +00001029 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001030 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +00001031 UI != E; ) {
1032 Use &TheUse = UI.getUse();
1033 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001034
Chris Lattnerf2836d12007-03-31 04:06:36 +00001035 // Figure out which BB this cast is used in. For PHI's this is the
1036 // appropriate predecessor block.
1037 BasicBlock *UserBB = User->getParent();
1038 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001039 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001040 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001041
Chris Lattnerf2836d12007-03-31 04:06:36 +00001042 // Preincrement use iterator so we don't invalidate it.
1043 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001044
David Majnemer0c80e2e2016-04-27 19:36:38 +00001045 // The first insertion point of a block containing an EH pad is after the
1046 // pad. If the pad is the user, we cannot sink the cast past the pad.
1047 if (User->isEHPad())
1048 continue;
1049
Andrew Kaylord0430e82015-11-23 19:16:15 +00001050 // If the block selected to receive the cast is an EH pad that does not
1051 // allow non-PHI instructions before the terminator, we can't sink the
1052 // cast.
1053 if (UserBB->getTerminator()->isEHPad())
1054 continue;
1055
Chris Lattnerf2836d12007-03-31 04:06:36 +00001056 // If this user is in the same block as the cast, don't change the cast.
1057 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001058
Chris Lattnerf2836d12007-03-31 04:06:36 +00001059 // If we have already inserted a cast into this block, use it.
1060 CastInst *&InsertedCast = InsertedCasts[UserBB];
1061
1062 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001063 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001064 assert(InsertPt != UserBB->end());
1065 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
1066 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +00001067 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001068
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001069 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +00001070 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001071 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001072 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +00001073 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001074
Chris Lattnerf2836d12007-03-31 04:06:36 +00001075 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +00001076 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +00001077 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +00001078 MadeChange = true;
1079 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001080
Chris Lattnerf2836d12007-03-31 04:06:36 +00001081 return MadeChange;
1082}
1083
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001084/// If the specified cast instruction is a noop copy (e.g. it's casting from
1085/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
1086/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001087///
1088/// Return true if any changes are made.
1089///
Mehdi Amini44ede332015-07-09 02:09:04 +00001090static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
1091 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +00001092 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
1093 // than sinking only nop casts, but is helpful on some platforms.
1094 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
1095 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
1096 ASC->getDestAddressSpace()))
1097 return false;
1098 }
1099
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001100 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +00001101 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
1102 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +00001103
1104 // This is an fp<->int conversion?
1105 if (SrcVT.isInteger() != DstVT.isInteger())
1106 return false;
1107
1108 // If this is an extension, it will be a zero or sign extension, which
1109 // isn't a noop.
1110 if (SrcVT.bitsLT(DstVT)) return false;
1111
1112 // If these values will be promoted, find out what they will be promoted
1113 // to. This helps us consider truncates on PPC as noop copies when they
1114 // are.
1115 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
1116 TargetLowering::TypePromoteInteger)
1117 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
1118 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
1119 TargetLowering::TypePromoteInteger)
1120 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
1121
1122 // If, after promotion, these are the same types, this is a noop copy.
1123 if (SrcVT != DstVT)
1124 return false;
1125
1126 return SinkCast(CI);
1127}
1128
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001129/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
1130/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001131///
1132/// Return true if any changes were made.
1133static bool CombineUAddWithOverflow(CmpInst *CI) {
1134 Value *A, *B;
1135 Instruction *AddI;
1136 if (!match(CI,
1137 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
1138 return false;
1139
1140 Type *Ty = AddI->getType();
1141 if (!isa<IntegerType>(Ty))
1142 return false;
1143
1144 // We don't want to move around uses of condition values this late, so we we
1145 // check if it is legal to create the call to the intrinsic in the basic
1146 // block containing the icmp:
1147
1148 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
1149 return false;
1150
1151#ifndef NDEBUG
1152 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
1153 // for now:
1154 if (AddI->hasOneUse())
1155 assert(*AddI->user_begin() == CI && "expected!");
1156#endif
1157
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001158 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001159 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1160
1161 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1162
1163 auto *UAddWithOverflow =
1164 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1165 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1166 auto *Overflow =
1167 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1168
1169 CI->replaceAllUsesWith(Overflow);
1170 AddI->replaceAllUsesWith(UAdd);
1171 CI->eraseFromParent();
1172 AddI->eraseFromParent();
1173 return true;
1174}
1175
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001176/// Sink the given CmpInst into user blocks to reduce the number of virtual
1177/// registers that must be created and coalesced. This is a clear win except on
1178/// targets with multiple condition code registers (PowerPC), where it might
1179/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001180///
1181/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001182static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001183 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001184
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001185 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001186 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001187 return false;
1188
1189 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001190 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001191
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001192 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001193 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001194 UI != E; ) {
1195 Use &TheUse = UI.getUse();
1196 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001197
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001198 // Preincrement use iterator so we don't invalidate it.
1199 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001200
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001201 // Don't bother for PHI nodes.
1202 if (isa<PHINode>(User))
1203 continue;
1204
1205 // Figure out which BB this cmp is used in.
1206 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001207
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001208 // If this user is in the same block as the cmp, don't change the cmp.
1209 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001210
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001211 // If we have already inserted a cmp into this block, use it.
1212 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1213
1214 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001215 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001216 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001217 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001218 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1219 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001220 // Propagate the debug info.
1221 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001222 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001223
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001224 // Replace a use of the cmp with a use of the new cmp.
1225 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001226 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001227 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001228 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001229
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001230 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001231 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001232 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001233 MadeChange = true;
1234 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001235
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001236 return MadeChange;
1237}
1238
Peter Zotovf87e5502016-04-03 17:11:53 +00001239static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001240 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001241 return true;
1242
1243 if (CombineUAddWithOverflow(CI))
1244 return true;
1245
1246 return false;
1247}
1248
Geoff Berry5d534b62017-02-21 18:53:14 +00001249/// Duplicate and sink the given 'and' instruction into user blocks where it is
1250/// used in a compare to allow isel to generate better code for targets where
1251/// this operation can be combined.
1252///
1253/// Return true if any changes are made.
1254static bool sinkAndCmp0Expression(Instruction *AndI,
1255 const TargetLowering &TLI,
1256 SetOfInstrs &InsertedInsts) {
1257 // Double-check that we're not trying to optimize an instruction that was
1258 // already optimized by some other part of this pass.
1259 assert(!InsertedInsts.count(AndI) &&
1260 "Attempting to optimize already optimized and instruction");
1261 (void) InsertedInsts;
1262
1263 // Nothing to do for single use in same basic block.
1264 if (AndI->hasOneUse() &&
1265 AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
1266 return false;
1267
1268 // Try to avoid cases where sinking/duplicating is likely to increase register
1269 // pressure.
1270 if (!isa<ConstantInt>(AndI->getOperand(0)) &&
1271 !isa<ConstantInt>(AndI->getOperand(1)) &&
1272 AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
1273 return false;
1274
1275 for (auto *U : AndI->users()) {
1276 Instruction *User = cast<Instruction>(U);
1277
1278 // Only sink for and mask feeding icmp with 0.
1279 if (!isa<ICmpInst>(User))
1280 return false;
1281
1282 auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
1283 if (!CmpC || !CmpC->isZero())
1284 return false;
1285 }
1286
1287 if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
1288 return false;
1289
1290 DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
1291 DEBUG(AndI->getParent()->dump());
1292
1293 // Push the 'and' into the same block as the icmp 0. There should only be
1294 // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
1295 // others, so we don't need to keep track of which BBs we insert into.
1296 for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
1297 UI != E; ) {
1298 Use &TheUse = UI.getUse();
1299 Instruction *User = cast<Instruction>(*UI);
1300
1301 // Preincrement use iterator so we don't invalidate it.
1302 ++UI;
1303
1304 DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
1305
1306 // Keep the 'and' in the same place if the use is already in the same block.
1307 Instruction *InsertPt =
1308 User->getParent() == AndI->getParent() ? AndI : User;
1309 Instruction *InsertedAnd =
1310 BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
1311 AndI->getOperand(1), "", InsertPt);
1312 // Propagate the debug info.
1313 InsertedAnd->setDebugLoc(AndI->getDebugLoc());
1314
1315 // Replace a use of the 'and' with a use of the new 'and'.
1316 TheUse = InsertedAnd;
1317 ++NumAndUses;
1318 DEBUG(User->getParent()->dump());
1319 }
1320
1321 // We removed all uses, nuke the and.
1322 AndI->eraseFromParent();
1323 return true;
1324}
1325
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001326/// Check if the candidates could be combined with a shift instruction, which
1327/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001328/// 1. Truncate instruction
1329/// 2. And instruction and the imm is a mask of the low bits:
1330/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001331static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001332 if (!isa<TruncInst>(User)) {
1333 if (User->getOpcode() != Instruction::And ||
1334 !isa<ConstantInt>(User->getOperand(1)))
1335 return false;
1336
Quentin Colombetd4f44692014-04-22 01:20:34 +00001337 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001338
Quentin Colombetd4f44692014-04-22 01:20:34 +00001339 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001340 return false;
1341 }
1342 return true;
1343}
1344
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001345/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001346static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001347SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1348 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001349 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001350 BasicBlock *UserBB = User->getParent();
1351 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1352 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1353 bool MadeChange = false;
1354
1355 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1356 TruncE = TruncI->user_end();
1357 TruncUI != TruncE;) {
1358
1359 Use &TruncTheUse = TruncUI.getUse();
1360 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1361 // Preincrement use iterator so we don't invalidate it.
1362
1363 ++TruncUI;
1364
1365 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1366 if (!ISDOpcode)
1367 continue;
1368
Tim Northovere2239ff2014-07-29 10:20:22 +00001369 // If the use is actually a legal node, there will not be an
1370 // implicit truncate.
1371 // FIXME: always querying the result type is just an
1372 // approximation; some nodes' legality is determined by the
1373 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001374 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001375 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001376 continue;
1377
1378 // Don't bother for PHI nodes.
1379 if (isa<PHINode>(TruncUser))
1380 continue;
1381
1382 BasicBlock *TruncUserBB = TruncUser->getParent();
1383
1384 if (UserBB == TruncUserBB)
1385 continue;
1386
1387 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1388 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1389
1390 if (!InsertedShift && !InsertedTrunc) {
1391 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001392 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001393 // Sink the shift
1394 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001395 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1396 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001397 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001398 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1399 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001400
1401 // Sink the trunc
1402 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1403 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001404 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001405
1406 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001407 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001408
1409 MadeChange = true;
1410
1411 TruncTheUse = InsertedTrunc;
1412 }
1413 }
1414 return MadeChange;
1415}
1416
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001417/// Sink the shift *right* instruction into user blocks if the uses could
1418/// potentially be combined with this shift instruction and generate BitExtract
1419/// instruction. It will only be applied if the architecture supports BitExtract
1420/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001421/// BB1:
1422/// %x.extract.shift = lshr i64 %arg1, 32
1423/// BB2:
1424/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1425/// ==>
1426///
1427/// BB2:
1428/// %x.extract.shift.1 = lshr i64 %arg1, 32
1429/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1430///
1431/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1432/// instruction.
1433/// Return true if any changes are made.
1434static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001435 const TargetLowering &TLI,
1436 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001437 BasicBlock *DefBB = ShiftI->getParent();
1438
1439 /// Only insert instructions in each block once.
1440 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1441
Mehdi Amini44ede332015-07-09 02:09:04 +00001442 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001443
1444 bool MadeChange = false;
1445 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1446 UI != E;) {
1447 Use &TheUse = UI.getUse();
1448 Instruction *User = cast<Instruction>(*UI);
1449 // Preincrement use iterator so we don't invalidate it.
1450 ++UI;
1451
1452 // Don't bother for PHI nodes.
1453 if (isa<PHINode>(User))
1454 continue;
1455
1456 if (!isExtractBitsCandidateUse(User))
1457 continue;
1458
1459 BasicBlock *UserBB = User->getParent();
1460
1461 if (UserBB == DefBB) {
1462 // If the shift and truncate instruction are in the same BB. The use of
1463 // the truncate(TruncUse) may still introduce another truncate if not
1464 // legal. In this case, we would like to sink both shift and truncate
1465 // instruction to the BB of TruncUse.
1466 // for example:
1467 // BB1:
1468 // i64 shift.result = lshr i64 opnd, imm
1469 // trunc.result = trunc shift.result to i16
1470 //
1471 // BB2:
1472 // ----> We will have an implicit truncate here if the architecture does
1473 // not have i16 compare.
1474 // cmp i16 trunc.result, opnd2
1475 //
1476 if (isa<TruncInst>(User) && shiftIsLegal
1477 // If the type of the truncate is legal, no trucate will be
1478 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001479 &&
1480 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001481 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001482 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001483
1484 continue;
1485 }
1486 // If we have already inserted a shift into this block, use it.
1487 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1488
1489 if (!InsertedShift) {
1490 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001491 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001492
1493 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001494 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1495 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001496 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001497 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1498 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001499
1500 MadeChange = true;
1501 }
1502
1503 // Replace a use of the shift with a use of the new shift.
1504 TheUse = InsertedShift;
1505 }
1506
1507 // If we removed all uses, nuke the shift.
1508 if (ShiftI->use_empty())
1509 ShiftI->eraseFromParent();
1510
1511 return MadeChange;
1512}
1513
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001514// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001515// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1516// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001517// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001518// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001519//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001520// %1 = bitcast i8* %addr to i32*
1521// %2 = extractelement <16 x i1> %mask, i32 0
1522// %3 = icmp eq i1 %2, true
1523// br i1 %3, label %cond.load, label %else
1524//
1525//cond.load: ; preds = %0
1526// %4 = getelementptr i32* %1, i32 0
1527// %5 = load i32* %4
1528// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1529// br label %else
1530//
1531//else: ; preds = %0, %cond.load
1532// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1533// %7 = extractelement <16 x i1> %mask, i32 1
1534// %8 = icmp eq i1 %7, true
1535// br i1 %8, label %cond.load1, label %else2
1536//
1537//cond.load1: ; preds = %else
1538// %9 = getelementptr i32* %1, i32 1
1539// %10 = load i32* %9
1540// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1541// br label %else2
1542//
1543//else2: ; preds = %else, %cond.load1
1544// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1545// %12 = extractelement <16 x i1> %mask, i32 2
1546// %13 = icmp eq i1 %12, true
1547// br i1 %13, label %cond.load4, label %else5
1548//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001549static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001550 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001551 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001552 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001553 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001554
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001555 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1556 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001557 assert(VecType && "Unexpected return type of masked load intrinsic");
1558
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001559 Type *EltTy = CI->getType()->getVectorElementType();
1560
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001561 IRBuilder<> Builder(CI->getContext());
1562 Instruction *InsertPt = CI;
1563 BasicBlock *IfBlock = CI->getParent();
1564 BasicBlock *CondBlock = nullptr;
1565 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001566
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001567 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001568 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1569
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001570 // Short-cut if the mask is all-true.
1571 bool IsAllOnesMask = isa<Constant>(Mask) &&
1572 cast<Constant>(Mask)->isAllOnesValue();
1573
1574 if (IsAllOnesMask) {
1575 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1576 CI->replaceAllUsesWith(NewI);
1577 CI->eraseFromParent();
1578 return;
1579 }
1580
1581 // Adjust alignment for the scalar instruction.
1582 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001583 // Bitcast %addr fron i8* to EltTy*
1584 Type *NewPtrType =
1585 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1586 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001587 unsigned VectorWidth = VecType->getNumElements();
1588
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001589 Value *UndefVal = UndefValue::get(VecType);
1590
1591 // The result vector
1592 Value *VResult = UndefVal;
1593
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001594 if (isa<ConstantVector>(Mask)) {
1595 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1596 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1597 continue;
1598 Value *Gep =
1599 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1600 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1601 VResult = Builder.CreateInsertElement(VResult, Load,
1602 Builder.getInt32(Idx));
1603 }
1604 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1605 CI->replaceAllUsesWith(NewI);
1606 CI->eraseFromParent();
1607 return;
1608 }
1609
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001610 PHINode *Phi = nullptr;
1611 Value *PrevPhi = UndefVal;
1612
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001613 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1614
1615 // Fill the "else" block, created in the previous iteration
1616 //
1617 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1618 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1619 // %to_load = icmp eq i1 %mask_1, true
1620 // br i1 %to_load, label %cond.load, label %else
1621 //
1622 if (Idx > 0) {
1623 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1624 Phi->addIncoming(VResult, CondBlock);
1625 Phi->addIncoming(PrevPhi, PrevIfBlock);
1626 PrevPhi = Phi;
1627 VResult = Phi;
1628 }
1629
1630 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1631 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1632 ConstantInt::get(Predicate->getType(), 1));
1633
1634 // Create "cond" block
1635 //
1636 // %EltAddr = getelementptr i32* %1, i32 0
1637 // %Elt = load i32* %EltAddr
1638 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1639 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001640 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001641 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001642
1643 Value *Gep =
1644 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001645 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001646 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1647
1648 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001649 BasicBlock *NewIfBlock =
1650 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001651 Builder.SetInsertPoint(InsertPt);
1652 Instruction *OldBr = IfBlock->getTerminator();
1653 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1654 OldBr->eraseFromParent();
1655 PrevIfBlock = IfBlock;
1656 IfBlock = NewIfBlock;
1657 }
1658
1659 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1660 Phi->addIncoming(VResult, CondBlock);
1661 Phi->addIncoming(PrevPhi, PrevIfBlock);
1662 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1663 CI->replaceAllUsesWith(NewI);
1664 CI->eraseFromParent();
1665}
1666
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001667// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001668// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1669// <16 x i1> %mask)
1670// to a chain of basic blocks, that stores element one-by-one if
1671// the appropriate mask bit is set
1672//
1673// %1 = bitcast i8* %addr to i32*
1674// %2 = extractelement <16 x i1> %mask, i32 0
1675// %3 = icmp eq i1 %2, true
1676// br i1 %3, label %cond.store, label %else
1677//
1678// cond.store: ; preds = %0
1679// %4 = extractelement <16 x i32> %val, i32 0
1680// %5 = getelementptr i32* %1, i32 0
1681// store i32 %4, i32* %5
1682// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001683//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001684// else: ; preds = %0, %cond.store
1685// %6 = extractelement <16 x i1> %mask, i32 1
1686// %7 = icmp eq i1 %6, true
1687// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001688//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001689// cond.store1: ; preds = %else
1690// %8 = extractelement <16 x i32> %val, i32 1
1691// %9 = getelementptr i32* %1, i32 1
1692// store i32 %8, i32* %9
1693// br label %else2
1694// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001695static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001696 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001697 Value *Ptr = CI->getArgOperand(1);
1698 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001699 Value *Mask = CI->getArgOperand(3);
1700
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001701 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001702 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001703 assert(VecType && "Unexpected data type in masked store intrinsic");
1704
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001705 Type *EltTy = VecType->getElementType();
1706
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001707 IRBuilder<> Builder(CI->getContext());
1708 Instruction *InsertPt = CI;
1709 BasicBlock *IfBlock = CI->getParent();
1710 Builder.SetInsertPoint(InsertPt);
1711 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1712
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001713 // Short-cut if the mask is all-true.
1714 bool IsAllOnesMask = isa<Constant>(Mask) &&
1715 cast<Constant>(Mask)->isAllOnesValue();
1716
1717 if (IsAllOnesMask) {
1718 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1719 CI->eraseFromParent();
1720 return;
1721 }
1722
1723 // Adjust alignment for the scalar instruction.
1724 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001725 // Bitcast %addr fron i8* to EltTy*
1726 Type *NewPtrType =
1727 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1728 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001729 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001730
1731 if (isa<ConstantVector>(Mask)) {
1732 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1733 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1734 continue;
1735 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1736 Value *Gep =
1737 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1738 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1739 }
1740 CI->eraseFromParent();
1741 return;
1742 }
1743
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001744 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1745
1746 // Fill the "else" block, created in the previous iteration
1747 //
1748 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1749 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001750 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001751 //
1752 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1753 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1754 ConstantInt::get(Predicate->getType(), 1));
1755
1756 // Create "cond" block
1757 //
1758 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1759 // %EltAddr = getelementptr i32* %1, i32 0
1760 // %store i32 %OneElt, i32* %EltAddr
1761 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001762 BasicBlock *CondBlock =
1763 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001764 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001765
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001766 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001767 Value *Gep =
1768 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001769 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001770
1771 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001772 BasicBlock *NewIfBlock =
1773 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001774 Builder.SetInsertPoint(InsertPt);
1775 Instruction *OldBr = IfBlock->getTerminator();
1776 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1777 OldBr->eraseFromParent();
1778 IfBlock = NewIfBlock;
1779 }
1780 CI->eraseFromParent();
1781}
1782
Elena Demikhovsky09285852015-10-25 15:37:55 +00001783// Translate a masked gather intrinsic like
1784// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1785// <16 x i1> %Mask, <16 x i32> %Src)
1786// to a chain of basic blocks, with loading element one-by-one if
1787// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001788//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001789// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1790// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1791// % ToLoad0 = icmp eq i1 % Mask0, true
1792// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001793//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001794// cond.load:
1795// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1796// % Load0 = load i32, i32* % Ptr0, align 4
1797// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1798// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001799//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001800// else:
1801// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1802// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1803// % ToLoad1 = icmp eq i1 % Mask1, true
1804// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001805//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001806// cond.load1:
1807// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1808// % Load1 = load i32, i32* % Ptr1, align 4
1809// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1810// br label %else2
1811// . . .
1812// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1813// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001814static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001815 Value *Ptrs = CI->getArgOperand(0);
1816 Value *Alignment = CI->getArgOperand(1);
1817 Value *Mask = CI->getArgOperand(2);
1818 Value *Src0 = CI->getArgOperand(3);
1819
1820 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1821
1822 assert(VecType && "Unexpected return type of masked load intrinsic");
1823
1824 IRBuilder<> Builder(CI->getContext());
1825 Instruction *InsertPt = CI;
1826 BasicBlock *IfBlock = CI->getParent();
1827 BasicBlock *CondBlock = nullptr;
1828 BasicBlock *PrevIfBlock = CI->getParent();
1829 Builder.SetInsertPoint(InsertPt);
1830 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1831
1832 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1833
1834 Value *UndefVal = UndefValue::get(VecType);
1835
1836 // The result vector
1837 Value *VResult = UndefVal;
1838 unsigned VectorWidth = VecType->getNumElements();
1839
1840 // Shorten the way if the mask is a vector of constants.
1841 bool IsConstMask = isa<ConstantVector>(Mask);
1842
1843 if (IsConstMask) {
1844 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1845 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1846 continue;
1847 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1848 "Ptr" + Twine(Idx));
1849 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1850 "Load" + Twine(Idx));
1851 VResult = Builder.CreateInsertElement(VResult, Load,
1852 Builder.getInt32(Idx),
1853 "Res" + Twine(Idx));
1854 }
1855 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1856 CI->replaceAllUsesWith(NewI);
1857 CI->eraseFromParent();
1858 return;
1859 }
1860
1861 PHINode *Phi = nullptr;
1862 Value *PrevPhi = UndefVal;
1863
1864 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1865
1866 // Fill the "else" block, created in the previous iteration
1867 //
1868 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1869 // %ToLoad1 = icmp eq i1 %Mask1, true
1870 // br i1 %ToLoad1, label %cond.load, label %else
1871 //
1872 if (Idx > 0) {
1873 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1874 Phi->addIncoming(VResult, CondBlock);
1875 Phi->addIncoming(PrevPhi, PrevIfBlock);
1876 PrevPhi = Phi;
1877 VResult = Phi;
1878 }
1879
1880 Value *Predicate = Builder.CreateExtractElement(Mask,
1881 Builder.getInt32(Idx),
1882 "Mask" + Twine(Idx));
1883 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1884 ConstantInt::get(Predicate->getType(), 1),
1885 "ToLoad" + Twine(Idx));
1886
1887 // Create "cond" block
1888 //
1889 // %EltAddr = getelementptr i32* %1, i32 0
1890 // %Elt = load i32* %EltAddr
1891 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1892 //
1893 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1894 Builder.SetInsertPoint(InsertPt);
1895
1896 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1897 "Ptr" + Twine(Idx));
1898 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1899 "Load" + Twine(Idx));
1900 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1901 "Res" + Twine(Idx));
1902
1903 // Create "else" block, fill it in the next iteration
1904 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1905 Builder.SetInsertPoint(InsertPt);
1906 Instruction *OldBr = IfBlock->getTerminator();
1907 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1908 OldBr->eraseFromParent();
1909 PrevIfBlock = IfBlock;
1910 IfBlock = NewIfBlock;
1911 }
1912
1913 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1914 Phi->addIncoming(VResult, CondBlock);
1915 Phi->addIncoming(PrevPhi, PrevIfBlock);
1916 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1917 CI->replaceAllUsesWith(NewI);
1918 CI->eraseFromParent();
1919}
1920
1921// Translate a masked scatter intrinsic, like
1922// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1923// <16 x i1> %Mask)
1924// to a chain of basic blocks, that stores element one-by-one if
1925// the appropriate mask bit is set.
1926//
1927// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1928// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1929// % ToStore0 = icmp eq i1 % Mask0, true
1930// br i1 %ToStore0, label %cond.store, label %else
1931//
1932// cond.store:
1933// % Elt0 = extractelement <16 x i32> %Src, i32 0
1934// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1935// store i32 %Elt0, i32* % Ptr0, align 4
1936// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001937//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001938// else:
1939// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1940// % ToStore1 = icmp eq i1 % Mask1, true
1941// br i1 % ToStore1, label %cond.store1, label %else2
1942//
1943// cond.store1:
1944// % Elt1 = extractelement <16 x i32> %Src, i32 1
1945// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1946// store i32 % Elt1, i32* % Ptr1, align 4
1947// br label %else2
1948// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001949static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001950 Value *Src = CI->getArgOperand(0);
1951 Value *Ptrs = CI->getArgOperand(1);
1952 Value *Alignment = CI->getArgOperand(2);
1953 Value *Mask = CI->getArgOperand(3);
1954
1955 assert(isa<VectorType>(Src->getType()) &&
1956 "Unexpected data type in masked scatter intrinsic");
1957 assert(isa<VectorType>(Ptrs->getType()) &&
1958 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1959 "Vector of pointers is expected in masked scatter intrinsic");
1960
1961 IRBuilder<> Builder(CI->getContext());
1962 Instruction *InsertPt = CI;
1963 BasicBlock *IfBlock = CI->getParent();
1964 Builder.SetInsertPoint(InsertPt);
1965 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1966
1967 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1968 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1969
1970 // Shorten the way if the mask is a vector of constants.
1971 bool IsConstMask = isa<ConstantVector>(Mask);
1972
1973 if (IsConstMask) {
1974 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1975 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1976 continue;
1977 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1978 "Elt" + Twine(Idx));
1979 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1980 "Ptr" + Twine(Idx));
1981 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1982 }
1983 CI->eraseFromParent();
1984 return;
1985 }
1986 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1987 // Fill the "else" block, created in the previous iteration
1988 //
1989 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1990 // % ToStore = icmp eq i1 % Mask1, true
1991 // br i1 % ToStore, label %cond.store, label %else
1992 //
1993 Value *Predicate = Builder.CreateExtractElement(Mask,
1994 Builder.getInt32(Idx),
1995 "Mask" + Twine(Idx));
1996 Value *Cmp =
1997 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1998 ConstantInt::get(Predicate->getType(), 1),
1999 "ToStore" + Twine(Idx));
2000
2001 // Create "cond" block
2002 //
2003 // % Elt1 = extractelement <16 x i32> %Src, i32 1
2004 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
2005 // %store i32 % Elt1, i32* % Ptr1
2006 //
2007 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
2008 Builder.SetInsertPoint(InsertPt);
2009
2010 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
2011 "Elt" + Twine(Idx));
2012 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
2013 "Ptr" + Twine(Idx));
2014 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
2015
2016 // Create "else" block, fill it in the next iteration
2017 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
2018 Builder.SetInsertPoint(InsertPt);
2019 Instruction *OldBr = IfBlock->getTerminator();
2020 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
2021 OldBr->eraseFromParent();
2022 IfBlock = NewIfBlock;
2023 }
2024 CI->eraseFromParent();
2025}
2026
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002027/// If counting leading or trailing zeros is an expensive operation and a zero
2028/// input is defined, add a check for zero to avoid calling the intrinsic.
2029///
2030/// We want to transform:
2031/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
2032///
2033/// into:
2034/// entry:
2035/// %cmpz = icmp eq i64 %A, 0
2036/// br i1 %cmpz, label %cond.end, label %cond.false
2037/// cond.false:
2038/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
2039/// br label %cond.end
2040/// cond.end:
2041/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
2042///
2043/// If the transform is performed, return true and set ModifiedDT to true.
2044static bool despeculateCountZeros(IntrinsicInst *CountZeros,
2045 const TargetLowering *TLI,
2046 const DataLayout *DL,
2047 bool &ModifiedDT) {
2048 if (!TLI || !DL)
2049 return false;
2050
2051 // If a zero input is undefined, it doesn't make sense to despeculate that.
2052 if (match(CountZeros->getOperand(1), m_One()))
2053 return false;
2054
2055 // If it's cheap to speculate, there's nothing to do.
2056 auto IntrinsicID = CountZeros->getIntrinsicID();
2057 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
2058 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
2059 return false;
2060
2061 // Only handle legal scalar cases. Anything else requires too much work.
2062 Type *Ty = CountZeros->getType();
2063 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00002064 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002065 return false;
2066
2067 // The intrinsic will be sunk behind a compare against zero and branch.
2068 BasicBlock *StartBlock = CountZeros->getParent();
2069 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
2070
2071 // Create another block after the count zero intrinsic. A PHI will be added
2072 // in this block to select the result of the intrinsic or the bit-width
2073 // constant if the input to the intrinsic is zero.
2074 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
2075 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
2076
2077 // Set up a builder to create a compare, conditional branch, and PHI.
2078 IRBuilder<> Builder(CountZeros->getContext());
2079 Builder.SetInsertPoint(StartBlock->getTerminator());
2080 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
2081
2082 // Replace the unconditional branch that was created by the first split with
2083 // a compare against zero and a conditional branch.
2084 Value *Zero = Constant::getNullValue(Ty);
2085 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
2086 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
2087 StartBlock->getTerminator()->eraseFromParent();
2088
2089 // Create a PHI in the end block to select either the output of the intrinsic
2090 // or the bit width of the operand.
2091 Builder.SetInsertPoint(&EndBlock->front());
2092 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
2093 CountZeros->replaceAllUsesWith(PN);
2094 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
2095 PN->addIncoming(BitWidth, StartBlock);
2096 PN->addIncoming(CountZeros, CallBlock);
2097
2098 // We are explicitly handling the zero case, so we can set the intrinsic's
2099 // undefined zero argument to 'true'. This will also prevent reprocessing the
2100 // intrinsic; we only despeculate when a zero input is defined.
2101 CountZeros->setArgOperand(1, Builder.getTrue());
2102 ModifiedDT = true;
2103 return true;
2104}
2105
Sanjay Patelfc580a62015-09-21 23:03:16 +00002106bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00002107 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002108
Chris Lattner7a277142011-01-15 07:14:54 +00002109 // Lower inline assembly if we can.
2110 // If we found an inline asm expession, and if the target knows how to
2111 // lower it to normal LLVM code, do so now.
2112 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
2113 if (TLI->ExpandInlineAsm(CI)) {
2114 // Avoid invalidating the iterator.
2115 CurInstIterator = BB->begin();
2116 // Avoid processing instructions out of order, which could cause
2117 // reuse before a value is defined.
2118 SunkAddrs.clear();
2119 return true;
2120 }
2121 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002122 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00002123 return true;
2124 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002125
John Brawn0dbcd652015-03-18 12:01:59 +00002126 // Align the pointer arguments to this call if the target thinks it's a good
2127 // idea
2128 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002129 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00002130 for (auto &Arg : CI->arg_operands()) {
2131 // We want to align both objects whose address is used directly and
2132 // objects whose address is used in casts and GEPs, though it only makes
2133 // sense for GEPs if the offset is a multiple of the desired alignment and
2134 // if size - offset meets the size threshold.
2135 if (!Arg->getType()->isPointerTy())
2136 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002137 APInt Offset(DL->getPointerSizeInBits(
2138 cast<PointerType>(Arg->getType())->getAddressSpace()),
2139 0);
2140 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00002141 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00002142 if ((Offset2 & (PrefAlign-1)) != 0)
2143 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00002144 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002145 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
2146 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00002147 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00002148 // Global variables can only be aligned if they are defined in this
2149 // object (i.e. they are uniquely initialized in this object), and
2150 // over-aligning global variables that have an explicit section is
2151 // forbidden.
2152 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00002153 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00002154 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002155 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00002156 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00002157 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00002158 }
2159 // If this is a memcpy (or similar) then we may be able to improve the
2160 // alignment
2161 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002162 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00002163 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00002164 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00002165 if (Align > MI->getAlignment())
2166 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00002167 }
2168 }
2169
Philip Reamesac115ed2016-03-09 23:13:12 +00002170 // If we have a cold call site, try to sink addressing computation into the
2171 // cold block. This interacts with our handling for loads and stores to
2172 // ensure that we can fold all uses of a potential addressing computation
2173 // into their uses. TODO: generalize this to work over profiling data
2174 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
2175 for (auto &Arg : CI->arg_operands()) {
2176 if (!Arg->getType()->isPointerTy())
2177 continue;
2178 unsigned AS = Arg->getType()->getPointerAddressSpace();
2179 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
2180 }
Junmo Park6098cbb2016-03-11 07:05:32 +00002181
Eric Christopher4b7948e2010-03-11 02:41:03 +00002182 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002183 if (II) {
2184 switch (II->getIntrinsicID()) {
2185 default: break;
2186 case Intrinsic::objectsize: {
2187 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00002188 ConstantInt *RetVal =
2189 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002190 // Substituting this can cause recursive simplifications, which can
2191 // invalidate our iterator. Use a WeakVH to hold onto it in case this
2192 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002193 Value *CurValue = &*CurInstIterator;
2194 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00002195
Sanjay Patel545a4562016-01-20 18:59:16 +00002196 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00002197
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002198 // If the iterator instruction was recursively deleted, start over at the
2199 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00002200 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002201 CurInstIterator = BB->begin();
2202 SunkAddrs.clear();
2203 }
2204 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00002205 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002206 case Intrinsic::masked_load: {
2207 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00002208 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002209 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002210 ModifiedDT = true;
2211 return true;
2212 }
2213 return false;
2214 }
2215 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00002216 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002217 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002218 ModifiedDT = true;
2219 return true;
2220 }
2221 return false;
2222 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00002223 case Intrinsic::masked_gather: {
2224 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002225 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002226 ModifiedDT = true;
2227 return true;
2228 }
2229 return false;
2230 }
2231 case Intrinsic::masked_scatter: {
2232 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002233 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002234 ModifiedDT = true;
2235 return true;
2236 }
2237 return false;
2238 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002239 case Intrinsic::aarch64_stlxr:
2240 case Intrinsic::aarch64_stxr: {
2241 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2242 if (!ExtVal || !ExtVal->hasOneUse() ||
2243 ExtVal->getParent() == CI->getParent())
2244 return false;
2245 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2246 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002247 // Mark this instruction as "inserted by CGP", so that other
2248 // optimizations don't touch it.
2249 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002250 return true;
2251 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002252 case Intrinsic::invariant_group_barrier:
2253 II->replaceAllUsesWith(II->getArgOperand(0));
2254 II->eraseFromParent();
2255 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002256
2257 case Intrinsic::cttz:
2258 case Intrinsic::ctlz:
2259 // If counting zeros is expensive, try to avoid it.
2260 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002261 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002262
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002263 if (TLI) {
2264 SmallVector<Value*, 2> PtrOps;
2265 Type *AccessTy;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002266 if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
2267 while (!PtrOps.empty()) {
2268 Value *PtrVal = PtrOps.pop_back_val();
2269 unsigned AS = PtrVal->getType()->getPointerAddressSpace();
2270 if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002271 return true;
Matt Arsenault1672b1b2017-02-08 07:09:03 +00002272 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002273 }
Pete Cooper615fd892012-03-13 20:59:56 +00002274 }
2275
Eric Christopher4b7948e2010-03-11 02:41:03 +00002276 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002277 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002278
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002279 // Lower all default uses of _chk calls. This is very similar
2280 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002281 // to fortified library functions (e.g. __memcpy_chk) that have the default
2282 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002283 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002284 if (Value *V = Simplifier.optimizeCall(CI)) {
2285 CI->replaceAllUsesWith(V);
2286 CI->eraseFromParent();
2287 return true;
2288 }
2289 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002290}
Chris Lattner1b93be52011-01-15 07:25:29 +00002291
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002292/// Look for opportunities to duplicate return instructions to the predecessor
2293/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002294/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002295/// bb0:
2296/// %tmp0 = tail call i32 @f0()
2297/// br label %return
2298/// bb1:
2299/// %tmp1 = tail call i32 @f1()
2300/// br label %return
2301/// bb2:
2302/// %tmp2 = tail call i32 @f2()
2303/// br label %return
2304/// return:
2305/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2306/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002307/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002308///
2309/// =>
2310///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002311/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002312/// bb0:
2313/// %tmp0 = tail call i32 @f0()
2314/// ret i32 %tmp0
2315/// bb1:
2316/// %tmp1 = tail call i32 @f1()
2317/// ret i32 %tmp1
2318/// bb2:
2319/// %tmp2 = tail call i32 @f2()
2320/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002321/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002322bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002323 if (!TLI)
2324 return false;
2325
Michael Kuperstein71321562016-09-07 20:29:49 +00002326 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2327 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002328 return false;
2329
Craig Topperc0196b12014-04-14 00:51:57 +00002330 PHINode *PN = nullptr;
2331 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002332 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002333 if (V) {
2334 BCI = dyn_cast<BitCastInst>(V);
2335 if (BCI)
2336 V = BCI->getOperand(0);
2337
2338 PN = dyn_cast<PHINode>(V);
2339 if (!PN)
2340 return false;
2341 }
Evan Cheng0663f232011-03-21 01:19:09 +00002342
Cameron Zwarich4649f172011-03-24 04:52:10 +00002343 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002344 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002345
Cameron Zwarich4649f172011-03-24 04:52:10 +00002346 // Make sure there are no instructions between the PHI and return, or that the
2347 // return is the first instruction in the block.
2348 if (PN) {
2349 BasicBlock::iterator BI = BB->begin();
2350 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002351 if (&*BI == BCI)
2352 // Also skip over the bitcast.
2353 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002354 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002355 return false;
2356 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002357 BasicBlock::iterator BI = BB->begin();
2358 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002359 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002360 return false;
2361 }
Evan Cheng0663f232011-03-21 01:19:09 +00002362
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002363 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2364 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002365 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002366 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002367 if (PN) {
2368 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2369 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2370 // Make sure the phi value is indeed produced by the tail call.
2371 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002372 TLI->mayBeEmittedAsTailCall(CI) &&
2373 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002374 TailCalls.push_back(CI);
2375 }
2376 } else {
2377 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002378 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002379 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002380 continue;
2381
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002382 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002383 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2384 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002385 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2386 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002387 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002388
Cameron Zwarich4649f172011-03-24 04:52:10 +00002389 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002390 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2391 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002392 TailCalls.push_back(CI);
2393 }
Evan Cheng0663f232011-03-21 01:19:09 +00002394 }
2395
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002396 bool Changed = false;
2397 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2398 CallInst *CI = TailCalls[i];
2399 CallSite CS(CI);
2400
2401 // Conservatively require the attributes of the call to match those of the
2402 // return. Ignore noalias because it doesn't affect the call sequence.
Reid Klecknerb5180542017-03-21 16:57:19 +00002403 AttributeList CalleeAttrs = CS.getAttributes();
2404 if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2405 .removeAttribute(Attribute::NoAlias) !=
2406 AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
2407 .removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002408 continue;
2409
2410 // Make sure the call instruction is followed by an unconditional branch to
2411 // the return block.
2412 BasicBlock *CallBB = CI->getParent();
2413 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2414 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2415 continue;
2416
2417 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002418 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002419 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002420 ++NumRetsDup;
2421 }
2422
2423 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002424 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002425 BB->eraseFromParent();
2426
2427 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002428}
2429
Chris Lattner728f9022008-11-25 07:09:13 +00002430//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002431// Memory Optimization
2432//===----------------------------------------------------------------------===//
2433
Chandler Carruthc8925912013-01-05 02:09:22 +00002434namespace {
2435
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002436/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002437/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002438struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002439 Value *BaseReg;
2440 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002441 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002442 void print(raw_ostream &OS) const;
2443 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002444
Chandler Carruthc8925912013-01-05 02:09:22 +00002445 bool operator==(const ExtAddrMode& O) const {
2446 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2447 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2448 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2449 }
2450};
2451
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002452#ifndef NDEBUG
2453static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2454 AM.print(OS);
2455 return OS;
2456}
2457#endif
2458
Chandler Carruthc8925912013-01-05 02:09:22 +00002459void ExtAddrMode::print(raw_ostream &OS) const {
2460 bool NeedPlus = false;
2461 OS << "[";
2462 if (BaseGV) {
2463 OS << (NeedPlus ? " + " : "")
2464 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002465 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002466 NeedPlus = true;
2467 }
2468
Richard Trieuc0f91212014-05-30 03:15:17 +00002469 if (BaseOffs) {
2470 OS << (NeedPlus ? " + " : "")
2471 << BaseOffs;
2472 NeedPlus = true;
2473 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002474
2475 if (BaseReg) {
2476 OS << (NeedPlus ? " + " : "")
2477 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002478 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002479 NeedPlus = true;
2480 }
2481 if (Scale) {
2482 OS << (NeedPlus ? " + " : "")
2483 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002484 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002485 }
2486
2487 OS << ']';
2488}
2489
2490#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002491LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002492 print(dbgs());
2493 dbgs() << '\n';
2494}
2495#endif
2496
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497/// \brief This class provides transaction based operation on the IR.
2498/// Every change made through this class is recorded in the internal state and
2499/// can be undone (rollback) until commit is called.
2500class TypePromotionTransaction {
2501
2502 /// \brief This represents the common interface of the individual transaction.
2503 /// Each class implements the logic for doing one specific modification on
2504 /// the IR via the TypePromotionTransaction.
2505 class TypePromotionAction {
2506 protected:
2507 /// The Instruction modified.
2508 Instruction *Inst;
2509
2510 public:
2511 /// \brief Constructor of the action.
2512 /// The constructor performs the related action on the IR.
2513 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2514
2515 virtual ~TypePromotionAction() {}
2516
2517 /// \brief Undo the modification done by this action.
2518 /// When this method is called, the IR must be in the same state as it was
2519 /// before this action was applied.
2520 /// \pre Undoing the action works if and only if the IR is in the exact same
2521 /// state as it was directly after this action was applied.
2522 virtual void undo() = 0;
2523
2524 /// \brief Advocate every change made by this action.
2525 /// When the results on the IR of the action are to be kept, it is important
2526 /// to call this function, otherwise hidden information may be kept forever.
2527 virtual void commit() {
2528 // Nothing to be done, this action is not doing anything.
2529 }
2530 };
2531
2532 /// \brief Utility to remember the position of an instruction.
2533 class InsertionHandler {
2534 /// Position of an instruction.
2535 /// Either an instruction:
2536 /// - Is the first in a basic block: BB is used.
2537 /// - Has a previous instructon: PrevInst is used.
2538 union {
2539 Instruction *PrevInst;
2540 BasicBlock *BB;
2541 } Point;
2542 /// Remember whether or not the instruction had a previous instruction.
2543 bool HasPrevInstruction;
2544
2545 public:
2546 /// \brief Record the position of \p Inst.
2547 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002548 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002549 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2550 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002551 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002552 else
2553 Point.BB = Inst->getParent();
2554 }
2555
2556 /// \brief Insert \p Inst at the recorded position.
2557 void insert(Instruction *Inst) {
2558 if (HasPrevInstruction) {
2559 if (Inst->getParent())
2560 Inst->removeFromParent();
2561 Inst->insertAfter(Point.PrevInst);
2562 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002563 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002564 if (Inst->getParent())
2565 Inst->moveBefore(Position);
2566 else
2567 Inst->insertBefore(Position);
2568 }
2569 }
2570 };
2571
2572 /// \brief Move an instruction before another.
2573 class InstructionMoveBefore : public TypePromotionAction {
2574 /// Original position of the instruction.
2575 InsertionHandler Position;
2576
2577 public:
2578 /// \brief Move \p Inst before \p Before.
2579 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2580 : TypePromotionAction(Inst), Position(Inst) {
2581 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2582 Inst->moveBefore(Before);
2583 }
2584
2585 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002586 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002587 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2588 Position.insert(Inst);
2589 }
2590 };
2591
2592 /// \brief Set the operand of an instruction with a new value.
2593 class OperandSetter : public TypePromotionAction {
2594 /// Original operand of the instruction.
2595 Value *Origin;
2596 /// Index of the modified instruction.
2597 unsigned Idx;
2598
2599 public:
2600 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2601 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2602 : TypePromotionAction(Inst), Idx(Idx) {
2603 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2604 << "for:" << *Inst << "\n"
2605 << "with:" << *NewVal << "\n");
2606 Origin = Inst->getOperand(Idx);
2607 Inst->setOperand(Idx, NewVal);
2608 }
2609
2610 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002611 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002612 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2613 << "for: " << *Inst << "\n"
2614 << "with: " << *Origin << "\n");
2615 Inst->setOperand(Idx, Origin);
2616 }
2617 };
2618
2619 /// \brief Hide the operands of an instruction.
2620 /// Do as if this instruction was not using any of its operands.
2621 class OperandsHider : public TypePromotionAction {
2622 /// The list of original operands.
2623 SmallVector<Value *, 4> OriginalValues;
2624
2625 public:
2626 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2627 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2628 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2629 unsigned NumOpnds = Inst->getNumOperands();
2630 OriginalValues.reserve(NumOpnds);
2631 for (unsigned It = 0; It < NumOpnds; ++It) {
2632 // Save the current operand.
2633 Value *Val = Inst->getOperand(It);
2634 OriginalValues.push_back(Val);
2635 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002636 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002637 // that we are not willing to pay.
2638 Inst->setOperand(It, UndefValue::get(Val->getType()));
2639 }
2640 }
2641
2642 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002643 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002644 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2645 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2646 Inst->setOperand(It, OriginalValues[It]);
2647 }
2648 };
2649
2650 /// \brief Build a truncate instruction.
2651 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002652 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002653 public:
2654 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2655 /// result.
2656 /// trunc Opnd to Ty.
2657 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2658 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002659 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2660 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002661 }
2662
Quentin Colombetac55b152014-09-16 22:36:07 +00002663 /// \brief Get the built value.
2664 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002665
2666 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002667 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002668 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2669 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2670 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002671 }
2672 };
2673
2674 /// \brief Build a sign extension instruction.
2675 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002676 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002677 public:
2678 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2679 /// result.
2680 /// sext Opnd to Ty.
2681 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002682 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002683 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002684 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2685 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002686 }
2687
Quentin Colombetac55b152014-09-16 22:36:07 +00002688 /// \brief Get the built value.
2689 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002690
2691 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002692 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002693 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2694 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2695 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002696 }
2697 };
2698
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002699 /// \brief Build a zero extension instruction.
2700 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002701 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002702 public:
2703 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2704 /// result.
2705 /// zext Opnd to Ty.
2706 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002707 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002708 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002709 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2710 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002711 }
2712
Quentin Colombetac55b152014-09-16 22:36:07 +00002713 /// \brief Get the built value.
2714 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002715
2716 /// \brief Remove the built instruction.
2717 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002718 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2719 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2720 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002721 }
2722 };
2723
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002724 /// \brief Mutate an instruction to another type.
2725 class TypeMutator : public TypePromotionAction {
2726 /// Record the original type.
2727 Type *OrigTy;
2728
2729 public:
2730 /// \brief Mutate the type of \p Inst into \p NewTy.
2731 TypeMutator(Instruction *Inst, Type *NewTy)
2732 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2733 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2734 << "\n");
2735 Inst->mutateType(NewTy);
2736 }
2737
2738 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002739 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002740 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2741 << "\n");
2742 Inst->mutateType(OrigTy);
2743 }
2744 };
2745
2746 /// \brief Replace the uses of an instruction by another instruction.
2747 class UsesReplacer : public TypePromotionAction {
2748 /// Helper structure to keep track of the replaced uses.
2749 struct InstructionAndIdx {
2750 /// The instruction using the instruction.
2751 Instruction *Inst;
2752 /// The index where this instruction is used for Inst.
2753 unsigned Idx;
2754 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2755 : Inst(Inst), Idx(Idx) {}
2756 };
2757
2758 /// Keep track of the original uses (pair Instruction, Index).
2759 SmallVector<InstructionAndIdx, 4> OriginalUses;
2760 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2761
2762 public:
2763 /// \brief Replace all the use of \p Inst by \p New.
2764 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2765 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2766 << "\n");
2767 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002768 for (Use &U : Inst->uses()) {
2769 Instruction *UserI = cast<Instruction>(U.getUser());
2770 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002771 }
2772 // Now, we can replace the uses.
2773 Inst->replaceAllUsesWith(New);
2774 }
2775
2776 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002777 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002778 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2779 for (use_iterator UseIt = OriginalUses.begin(),
2780 EndIt = OriginalUses.end();
2781 UseIt != EndIt; ++UseIt) {
2782 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2783 }
2784 }
2785 };
2786
2787 /// \brief Remove an instruction from the IR.
2788 class InstructionRemover : public TypePromotionAction {
2789 /// Original position of the instruction.
2790 InsertionHandler Inserter;
2791 /// Helper structure to hide all the link to the instruction. In other
2792 /// words, this helps to do as if the instruction was removed.
2793 OperandsHider Hider;
2794 /// Keep track of the uses replaced, if any.
2795 UsesReplacer *Replacer;
2796
2797 public:
2798 /// \brief Remove all reference of \p Inst and optinally replace all its
2799 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002800 /// \pre If !Inst->use_empty(), then New != nullptr
2801 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002802 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002803 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002804 if (New)
2805 Replacer = new UsesReplacer(Inst, New);
2806 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2807 Inst->removeFromParent();
2808 }
2809
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002810 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002811
2812 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002813 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002814
2815 /// \brief Resurrect the instruction and reassign it to the proper uses if
2816 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002817 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002818 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2819 Inserter.insert(Inst);
2820 if (Replacer)
2821 Replacer->undo();
2822 Hider.undo();
2823 }
2824 };
2825
2826public:
2827 /// Restoration point.
2828 /// The restoration point is a pointer to an action instead of an iterator
2829 /// because the iterator may be invalidated but not the pointer.
2830 typedef const TypePromotionAction *ConstRestorationPt;
2831 /// Advocate every changes made in that transaction.
2832 void commit();
2833 /// Undo all the changes made after the given point.
2834 void rollback(ConstRestorationPt Point);
2835 /// Get the current restoration point.
2836 ConstRestorationPt getRestorationPoint() const;
2837
2838 /// \name API for IR modification with state keeping to support rollback.
2839 /// @{
2840 /// Same as Instruction::setOperand.
2841 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2842 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002843 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002844 /// Same as Value::replaceAllUsesWith.
2845 void replaceAllUsesWith(Instruction *Inst, Value *New);
2846 /// Same as Value::mutateType.
2847 void mutateType(Instruction *Inst, Type *NewTy);
2848 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002849 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002850 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002851 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002852 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002853 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002854 /// Same as Instruction::moveBefore.
2855 void moveBefore(Instruction *Inst, Instruction *Before);
2856 /// @}
2857
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002858private:
2859 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002860 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2861 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002862};
2863
2864void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2865 Value *NewVal) {
2866 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002867 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002868}
2869
2870void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2871 Value *NewVal) {
2872 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002873 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002874}
2875
2876void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2877 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002878 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002879}
2880
2881void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002882 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002883}
2884
Quentin Colombetac55b152014-09-16 22:36:07 +00002885Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2886 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002887 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002888 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002889 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002890 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002891}
2892
Quentin Colombetac55b152014-09-16 22:36:07 +00002893Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2894 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002895 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002896 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002897 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002898 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002899}
2900
Quentin Colombetac55b152014-09-16 22:36:07 +00002901Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2902 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002903 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002904 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002905 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002906 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002907}
2908
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002909void TypePromotionTransaction::moveBefore(Instruction *Inst,
2910 Instruction *Before) {
2911 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002912 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002913}
2914
2915TypePromotionTransaction::ConstRestorationPt
2916TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002917 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002918}
2919
2920void TypePromotionTransaction::commit() {
2921 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002922 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002923 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002924 Actions.clear();
2925}
2926
2927void TypePromotionTransaction::rollback(
2928 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002929 while (!Actions.empty() && Point != Actions.back().get()) {
2930 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002931 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002932 }
2933}
2934
Chandler Carruthc8925912013-01-05 02:09:22 +00002935/// \brief A helper class for matching addressing modes.
2936///
2937/// This encapsulates the logic for matching the target-legal addressing modes.
2938class AddressingModeMatcher {
2939 SmallVectorImpl<Instruction*> &AddrModeInsts;
2940 const TargetLowering &TLI;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002941 const TargetRegisterInfo &TRI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002942 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002943
2944 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2945 /// the memory instruction that we're computing this address for.
2946 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002947 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002948 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002949
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002950 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002951 /// part of the return value of this addressing mode matching stuff.
2952 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002953
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002954 /// The instructions inserted by other CodeGenPrepare optimizations.
2955 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002956 /// A map from the instructions to their type before promotion.
2957 InstrToOrigTy &PromotedInsts;
2958 /// The ongoing transaction where every action should be registered.
2959 TypePromotionTransaction &TPT;
2960
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002961 /// This is set to true when we should not do profitability checks.
2962 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002963 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002964
Eric Christopherd75c00c2015-02-26 22:38:34 +00002965 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002966 const TargetLowering &TLI,
2967 const TargetRegisterInfo &TRI,
2968 Type *AT, unsigned AS,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002969 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002970 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002971 InstrToOrigTy &PromotedInsts,
2972 TypePromotionTransaction &TPT)
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002973 : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002974 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2975 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2976 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002977 IgnoreProfitability = false;
2978 }
2979public:
Stephen Lin837bba12013-07-15 17:55:02 +00002980
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002981 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002982 /// give an access type of AccessTy. This returns a list of involved
2983 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002984 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002985 /// optimizations.
2986 /// \p PromotedInsts maps the instructions to their type before promotion.
2987 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002988 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002989 Instruction *MemoryInst,
2990 SmallVectorImpl<Instruction*> &AddrModeInsts,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002991 const TargetLowering &TLI,
2992 const TargetRegisterInfo &TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002993 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002994 InstrToOrigTy &PromotedInsts,
2995 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002996 ExtAddrMode Result;
2997
Igor Laevsky3be81ba2017-02-07 13:27:20 +00002998 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
2999 AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003000 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00003001 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003002 (void)Success; assert(Success && "Couldn't select *anything*?");
3003 return Result;
3004 }
3005private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00003006 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
3007 bool matchAddr(Value *V, unsigned Depth);
3008 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00003009 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003010 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00003011 ExtAddrMode &AMBefore,
3012 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003013 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
3014 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00003015 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00003016};
3017
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003018/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00003019/// Return true and update AddrMode if this addr mode is legal for the target,
3020/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003021bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003022 unsigned Depth) {
3023 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
3024 // mode. Just process that directly.
3025 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003026 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00003027
Chandler Carruthc8925912013-01-05 02:09:22 +00003028 // If the scale is 0, it takes nothing to add this.
3029 if (Scale == 0)
3030 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003031
Chandler Carruthc8925912013-01-05 02:09:22 +00003032 // If we already have a scale of this value, we can add to it, otherwise, we
3033 // need an available scale field.
3034 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
3035 return false;
3036
3037 ExtAddrMode TestAddrMode = AddrMode;
3038
3039 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
3040 // [A+B + A*7] -> [B+A*8].
3041 TestAddrMode.Scale += Scale;
3042 TestAddrMode.ScaledReg = ScaleReg;
3043
3044 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003045 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003046 return false;
3047
3048 // It was legal, so commit it.
3049 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00003050
Chandler Carruthc8925912013-01-05 02:09:22 +00003051 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
3052 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
3053 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003054 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003055 if (isa<Instruction>(ScaleReg) && // not a constant expr.
3056 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
3057 TestAddrMode.ScaledReg = AddLHS;
3058 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003059
Chandler Carruthc8925912013-01-05 02:09:22 +00003060 // If this addressing mode is legal, commit it and remember that we folded
3061 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003062 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003063 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
3064 AddrMode = TestAddrMode;
3065 return true;
3066 }
3067 }
3068
3069 // Otherwise, not (x+c)*scale, just return what we have.
3070 return true;
3071}
3072
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003073/// This is a little filter, which returns true if an addressing computation
3074/// involving I might be folded into a load/store accessing it.
3075/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00003076/// the set of instructions that MatchOperationAddr can.
3077static bool MightBeFoldableInst(Instruction *I) {
3078 switch (I->getOpcode()) {
3079 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00003080 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00003081 // Don't touch identity bitcasts.
3082 if (I->getType() == I->getOperand(0)->getType())
3083 return false;
3084 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
3085 case Instruction::PtrToInt:
3086 // PtrToInt is always a noop, as we know that the int type is pointer sized.
3087 return true;
3088 case Instruction::IntToPtr:
3089 // We know the input is intptr_t, so this is foldable.
3090 return true;
3091 case Instruction::Add:
3092 return true;
3093 case Instruction::Mul:
3094 case Instruction::Shl:
3095 // Can only handle X*C and X << C.
3096 return isa<ConstantInt>(I->getOperand(1));
3097 case Instruction::GetElementPtr:
3098 return true;
3099 default:
3100 return false;
3101 }
3102}
3103
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003104/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
3105/// \note \p Val is assumed to be the product of some type promotion.
3106/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
3107/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00003108static bool isPromotedInstructionLegal(const TargetLowering &TLI,
3109 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003110 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
3111 if (!PromotedInst)
3112 return false;
3113 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
3114 // If the ISDOpcode is undefined, it was undefined before the promotion.
3115 if (!ISDOpcode)
3116 return true;
3117 // Otherwise, check if the promoted instruction is legal or not.
3118 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00003119 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003120}
3121
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003122/// \brief Hepler class to perform type promotion.
3123class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003124 /// \brief Utility function to check whether or not a sign or zero extension
3125 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
3126 /// either using the operands of \p Inst or promoting \p Inst.
3127 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003128 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003129 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003130 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003131 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003132 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003133 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003134 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003135 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
3136 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003137
3138 /// \brief Utility function to determine if \p OpIdx should be promoted when
3139 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003140 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00003141 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003142 }
3143
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003144 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003145 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003146 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003147 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003148 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003149 /// Newly added extensions are inserted in \p Exts.
3150 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003151 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003152 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003153 static Value *promoteOperandForTruncAndAnyExt(
3154 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003155 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003156 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003157 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003158
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003159 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003160 /// operand is promotable and is not a supported trunc or sext.
3161 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003162 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003163 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003164 /// Newly added extensions are inserted in \p Exts.
3165 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003166 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003167 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003168 static Value *promoteOperandForOther(Instruction *Ext,
3169 TypePromotionTransaction &TPT,
3170 InstrToOrigTy &PromotedInsts,
3171 unsigned &CreatedInstsCost,
3172 SmallVectorImpl<Instruction *> *Exts,
3173 SmallVectorImpl<Instruction *> *Truncs,
3174 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003175
3176 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003177 static Value *signExtendOperandForOther(
3178 Instruction *Ext, TypePromotionTransaction &TPT,
3179 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3180 SmallVectorImpl<Instruction *> *Exts,
3181 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3182 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3183 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003184 }
3185
3186 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003187 static Value *zeroExtendOperandForOther(
3188 Instruction *Ext, TypePromotionTransaction &TPT,
3189 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
3190 SmallVectorImpl<Instruction *> *Exts,
3191 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
3192 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
3193 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003194 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003195
3196public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003197 /// Type for the utility function that promotes the operand of Ext.
3198 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003199 InstrToOrigTy &PromotedInsts,
3200 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003201 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003202 SmallVectorImpl<Instruction *> *Truncs,
3203 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003204 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
3205 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003206 /// \return NULL if no promotable action is possible with the current
3207 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003208 /// \p InsertedInsts keeps track of all the instructions inserted by the
3209 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003210 /// because we do not want to promote these instructions as CodeGenPrepare
3211 /// will reinsert them later. Thus creating an infinite loop: create/remove.
3212 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003213 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003214 const TargetLowering &TLI,
3215 const InstrToOrigTy &PromotedInsts);
3216};
3217
3218bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003219 Type *ConsideredExtType,
3220 const InstrToOrigTy &PromotedInsts,
3221 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003222 // The promotion helper does not know how to deal with vector types yet.
3223 // To be able to fix that, we would need to fix the places where we
3224 // statically extend, e.g., constants and such.
3225 if (Inst->getType()->isVectorTy())
3226 return false;
3227
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003228 // We can always get through zext.
3229 if (isa<ZExtInst>(Inst))
3230 return true;
3231
3232 // sext(sext) is ok too.
3233 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003234 return true;
3235
3236 // We can get through binary operator, if it is legal. In other words, the
3237 // binary operator must have a nuw or nsw flag.
3238 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3239 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003240 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3241 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003242 return true;
3243
3244 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003245 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003246 if (!isa<TruncInst>(Inst))
3247 return false;
3248
3249 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003250 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003251 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003252 if (!OpndVal->getType()->isIntegerTy() ||
3253 OpndVal->getType()->getIntegerBitWidth() >
3254 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003255 return false;
3256
3257 // If the operand of the truncate is not an instruction, we will not have
3258 // any information on the dropped bits.
3259 // (Actually we could for constant but it is not worth the extra logic).
3260 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3261 if (!Opnd)
3262 return false;
3263
3264 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003265 // I.e., check that trunc just drops extended bits of the same kind of
3266 // the extension.
3267 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003268 const Type *OpndType;
3269 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003270 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3271 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003272 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3273 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003274 else
3275 return false;
3276
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003277 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003278 return Inst->getType()->getIntegerBitWidth() >=
3279 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003280}
3281
3282TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003283 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003284 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003285 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3286 "Unexpected instruction type");
3287 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3288 Type *ExtTy = Ext->getType();
3289 bool IsSExt = isa<SExtInst>(Ext);
3290 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003291 // get through.
3292 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003293 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003294 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003295
3296 // Do not promote if the operand has been added by codegenprepare.
3297 // Otherwise, it means we are undoing an optimization that is likely to be
3298 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003299 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003300 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003301
3302 // SExt or Trunc instructions.
3303 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003304 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3305 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003306 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003307
3308 // Regular instruction.
3309 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003310 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003311 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003312 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003313}
3314
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003315Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003316 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003317 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003318 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003319 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003320 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3321 // get through it and this method should not be called.
3322 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003323 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003324 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003325 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003326 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003327 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003328 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003329 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003330 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3331 TPT.replaceAllUsesWith(SExt, ZExt);
3332 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003333 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003334 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003335 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3336 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003337 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3338 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003339 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003340
3341 // Remove dead code.
3342 if (SExtOpnd->use_empty())
3343 TPT.eraseInstruction(SExtOpnd);
3344
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003345 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003346 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003347 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003348 if (ExtInst) {
3349 if (Exts)
3350 Exts->push_back(ExtInst);
3351 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3352 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003353 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003354 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003355
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003356 // At this point we have: ext ty opnd to ty.
3357 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3358 Value *NextVal = ExtInst->getOperand(0);
3359 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003360 return NextVal;
3361}
3362
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003363Value *TypePromotionHelper::promoteOperandForOther(
3364 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003365 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003366 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003367 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3368 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003369 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003370 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003371 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003372 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003373 if (!ExtOpnd->hasOneUse()) {
3374 // ExtOpnd will be promoted.
3375 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003376 // promoted version.
3377 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003378 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003379 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3380 ITrunc->removeFromParent();
3381 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003382 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003383 if (Truncs)
3384 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003385 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003386
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003387 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003388 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003389 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003390 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003391 }
3392
3393 // Get through the Instruction:
3394 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003395 // 2. Replace the uses of Ext by Inst.
3396 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003397
3398 // Remember the original type of the instruction before promotion.
3399 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003400 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3401 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003402 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003403 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003404 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003405 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003406 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003407 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003408
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003409 DEBUG(dbgs() << "Propagate Ext to operands\n");
3410 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003411 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003412 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3413 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3414 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003415 DEBUG(dbgs() << "No need to propagate\n");
3416 continue;
3417 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003418 // Check if we can statically extend the operand.
3419 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003420 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003421 DEBUG(dbgs() << "Statically extend\n");
3422 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3423 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3424 : Cst->getValue().zext(BitWidth);
3425 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003426 continue;
3427 }
3428 // UndefValue are typed, so we have to statically sign extend them.
3429 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003430 DEBUG(dbgs() << "Statically extend\n");
3431 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003432 continue;
3433 }
3434
3435 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003436 // Check if Ext was reused to extend an operand.
3437 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003438 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003439 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003440 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3441 : TPT.createZExt(Ext, Opnd, Ext->getType());
3442 if (!isa<Instruction>(ValForExtOpnd)) {
3443 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3444 continue;
3445 }
3446 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003447 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003448 if (Exts)
3449 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003450 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003451
3452 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003453 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3454 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003455 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003456 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003457 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003458 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003459 if (ExtForOpnd == Ext) {
3460 DEBUG(dbgs() << "Extension is useless now\n");
3461 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003462 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003463 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003464}
3465
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003466/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003467/// \p NewCost gives the cost of extension instructions created by the
3468/// promotion.
3469/// \p OldCost gives the cost of extension instructions before the promotion
3470/// plus the number of instructions that have been
3471/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003472/// \p PromotedOperand is the value that has been promoted.
3473/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003474bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003475 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3476 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3477 // The cost of the new extensions is greater than the cost of the
3478 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003479 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003480 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003481 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003482 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003483 return true;
3484 // The promotion is neutral but it may help folding the sign extension in
3485 // loads for instance.
3486 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003487 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003488}
3489
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003490/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003491/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003492/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003493/// If \p MovedAway is not NULL, it contains the information of whether or
3494/// not AddrInst has to be folded into the addressing mode on success.
3495/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3496/// because it has been moved away.
3497/// Thus AddrInst must not be added in the matched instructions.
3498/// This state can happen when AddrInst is a sext, since it may be moved away.
3499/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3500/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003501bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003502 unsigned Depth,
3503 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003504 // Avoid exponential behavior on extremely deep expression trees.
3505 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003506
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003507 // By default, all matched instructions stay in place.
3508 if (MovedAway)
3509 *MovedAway = false;
3510
Chandler Carruthc8925912013-01-05 02:09:22 +00003511 switch (Opcode) {
3512 case Instruction::PtrToInt:
3513 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003514 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003515 case Instruction::IntToPtr: {
3516 auto AS = AddrInst->getType()->getPointerAddressSpace();
3517 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003518 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003519 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003520 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003521 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003522 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003523 case Instruction::BitCast:
3524 // BitCast is always a noop, and we can handle it as long as it is
3525 // int->int or pointer->pointer (we don't want int<->fp or something).
3526 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3527 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3528 // Don't touch identity bitcasts. These were probably put here by LSR,
3529 // and we don't want to mess around with them. Assume it knows what it
3530 // is doing.
3531 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003532 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003533 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003534 case Instruction::AddrSpaceCast: {
3535 unsigned SrcAS
3536 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3537 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3538 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003539 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003540 return false;
3541 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003542 case Instruction::Add: {
3543 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3544 ExtAddrMode BackupAddrMode = AddrMode;
3545 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003546 // Start a transaction at this point.
3547 // The LHS may match but not the RHS.
3548 // Therefore, we need a higher level restoration point to undo partially
3549 // matched operation.
3550 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3551 TPT.getRestorationPoint();
3552
Sanjay Patelfc580a62015-09-21 23:03:16 +00003553 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3554 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003555 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003556
Chandler Carruthc8925912013-01-05 02:09:22 +00003557 // Restore the old addr mode info.
3558 AddrMode = BackupAddrMode;
3559 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003560 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003561
Chandler Carruthc8925912013-01-05 02:09:22 +00003562 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003563 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3564 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003565 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003566
Chandler Carruthc8925912013-01-05 02:09:22 +00003567 // Otherwise we definitely can't merge the ADD in.
3568 AddrMode = BackupAddrMode;
3569 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003570 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003571 break;
3572 }
3573 //case Instruction::Or:
3574 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3575 //break;
3576 case Instruction::Mul:
3577 case Instruction::Shl: {
3578 // Can only handle X*C and X << C.
3579 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003580 if (!RHS)
3581 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003582 int64_t Scale = RHS->getSExtValue();
3583 if (Opcode == Instruction::Shl)
3584 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003585
Sanjay Patelfc580a62015-09-21 23:03:16 +00003586 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003587 }
3588 case Instruction::GetElementPtr: {
3589 // Scan the GEP. We check it if it contains constant offsets and at most
3590 // one variable offset.
3591 int VariableOperand = -1;
3592 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003593
Chandler Carruthc8925912013-01-05 02:09:22 +00003594 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003595 gep_type_iterator GTI = gep_type_begin(AddrInst);
3596 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003597 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003598 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003599 unsigned Idx =
3600 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3601 ConstantOffset += SL->getElementOffset(Idx);
3602 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003603 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003604 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3605 ConstantOffset += CI->getSExtValue()*TypeSize;
3606 } else if (TypeSize) { // Scales of zero don't do anything.
3607 // We only allow one variable index at the moment.
3608 if (VariableOperand != -1)
3609 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003610
Chandler Carruthc8925912013-01-05 02:09:22 +00003611 // Remember the variable index.
3612 VariableOperand = i;
3613 VariableScale = TypeSize;
3614 }
3615 }
3616 }
Stephen Lin837bba12013-07-15 17:55:02 +00003617
Chandler Carruthc8925912013-01-05 02:09:22 +00003618 // A common case is for the GEP to only do a constant offset. In this case,
3619 // just add it to the disp field and check validity.
3620 if (VariableOperand == -1) {
3621 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003622 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003623 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003624 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003625 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003626 return true;
3627 }
3628 AddrMode.BaseOffs -= ConstantOffset;
3629 return false;
3630 }
3631
3632 // Save the valid addressing mode in case we can't match.
3633 ExtAddrMode BackupAddrMode = AddrMode;
3634 unsigned OldSize = AddrModeInsts.size();
3635
3636 // See if the scale and offset amount is valid for this target.
3637 AddrMode.BaseOffs += ConstantOffset;
3638
3639 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003640 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003641 // If it couldn't be matched, just stuff the value in a register.
3642 if (AddrMode.HasBaseReg) {
3643 AddrMode = BackupAddrMode;
3644 AddrModeInsts.resize(OldSize);
3645 return false;
3646 }
3647 AddrMode.HasBaseReg = true;
3648 AddrMode.BaseReg = AddrInst->getOperand(0);
3649 }
3650
3651 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003652 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003653 Depth)) {
3654 // If it couldn't be matched, try stuffing the base into a register
3655 // instead of matching it, and retrying the match of the scale.
3656 AddrMode = BackupAddrMode;
3657 AddrModeInsts.resize(OldSize);
3658 if (AddrMode.HasBaseReg)
3659 return false;
3660 AddrMode.HasBaseReg = true;
3661 AddrMode.BaseReg = AddrInst->getOperand(0);
3662 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003663 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003664 VariableScale, Depth)) {
3665 // If even that didn't work, bail.
3666 AddrMode = BackupAddrMode;
3667 AddrModeInsts.resize(OldSize);
3668 return false;
3669 }
3670 }
3671
3672 return true;
3673 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003674 case Instruction::SExt:
3675 case Instruction::ZExt: {
3676 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3677 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003678 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003679
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003680 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003681 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003682 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003683 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003684 if (!TPH)
3685 return false;
3686
3687 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3688 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003689 unsigned CreatedInstsCost = 0;
3690 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003691 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003692 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003693 // SExt has been moved away.
3694 // Thus either it will be rematched later in the recursive calls or it is
3695 // gone. Anyway, we must not fold it into the addressing mode at this point.
3696 // E.g.,
3697 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003698 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003699 // addr = gep base, idx
3700 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003701 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003702 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3703 // addr = gep base, op <- match
3704 if (MovedAway)
3705 *MovedAway = true;
3706
3707 assert(PromotedOperand &&
3708 "TypePromotionHelper should have filtered out those cases");
3709
3710 ExtAddrMode BackupAddrMode = AddrMode;
3711 unsigned OldSize = AddrModeInsts.size();
3712
Sanjay Patelfc580a62015-09-21 23:03:16 +00003713 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003714 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003715 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003716 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003717 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003718 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003719 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003720 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003721 AddrMode = BackupAddrMode;
3722 AddrModeInsts.resize(OldSize);
3723 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3724 TPT.rollback(LastKnownGood);
3725 return false;
3726 }
3727 return true;
3728 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003729 }
3730 return false;
3731}
3732
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003733/// If we can, try to add the value of 'Addr' into the current addressing mode.
3734/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3735/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3736/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003737///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003738bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003739 // Start a transaction at this point that we will rollback if the matching
3740 // fails.
3741 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3742 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003743 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3744 // Fold in immediates if legal for the target.
3745 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003746 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003747 return true;
3748 AddrMode.BaseOffs -= CI->getSExtValue();
3749 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3750 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003751 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003752 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003753 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003754 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003755 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003756 }
3757 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3758 ExtAddrMode BackupAddrMode = AddrMode;
3759 unsigned OldSize = AddrModeInsts.size();
3760
3761 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003762 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003763 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003764 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003765 // to check here.
3766 if (MovedAway)
3767 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003768 // Okay, it's possible to fold this. Check to see if it is actually
3769 // *profitable* to do so. We use a simple cost model to avoid increasing
3770 // register pressure too much.
3771 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003772 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003773 AddrModeInsts.push_back(I);
3774 return true;
3775 }
Stephen Lin837bba12013-07-15 17:55:02 +00003776
Chandler Carruthc8925912013-01-05 02:09:22 +00003777 // It isn't profitable to do this, roll back.
3778 //cerr << "NOT FOLDING: " << *I;
3779 AddrMode = BackupAddrMode;
3780 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003781 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003782 }
3783 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003784 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003785 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003786 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003787 } else if (isa<ConstantPointerNull>(Addr)) {
3788 // Null pointer gets folded without affecting the addressing mode.
3789 return true;
3790 }
3791
3792 // Worse case, the target should support [reg] addressing modes. :)
3793 if (!AddrMode.HasBaseReg) {
3794 AddrMode.HasBaseReg = true;
3795 AddrMode.BaseReg = Addr;
3796 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003797 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003798 return true;
3799 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003800 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003801 }
3802
3803 // If the base register is already taken, see if we can do [r+r].
3804 if (AddrMode.Scale == 0) {
3805 AddrMode.Scale = 1;
3806 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003807 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003808 return true;
3809 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003810 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003811 }
3812 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003813 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003814 return false;
3815}
3816
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003817/// Check to see if all uses of OpVal by the specified inline asm call are due
3818/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003819static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003820 const TargetLowering &TLI,
3821 const TargetRegisterInfo &TRI) {
Eric Christopher11e4df72015-02-26 22:38:43 +00003822 const Function *F = CI->getParent()->getParent();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003823 TargetLowering::AsmOperandInfoVector TargetConstraints =
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003824 TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003825 ImmutableCallSite(CI));
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003826
Chandler Carruthc8925912013-01-05 02:09:22 +00003827 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3828 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003829
Chandler Carruthc8925912013-01-05 02:09:22 +00003830 // Compute the constraint code and ConstraintType to use.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003831 TLI.ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003832
3833 // If this asm operand is our Value*, and if it isn't an indirect memory
3834 // operand, we can't fold it!
3835 if (OpInfo.CallOperandVal == OpVal &&
3836 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3837 !OpInfo.isIndirect))
3838 return false;
3839 }
3840
3841 return true;
3842}
3843
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003844/// Recursively walk all the uses of I until we find a memory use.
3845/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003846/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003847static bool FindAllMemoryUses(
3848 Instruction *I,
3849 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003850 SmallPtrSetImpl<Instruction *> &ConsideredInsts,
3851 const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003852 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003853 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003854 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003855
Chandler Carruthc8925912013-01-05 02:09:22 +00003856 // If this is an obviously unfoldable instruction, bail out.
3857 if (!MightBeFoldableInst(I))
3858 return true;
3859
Philip Reamesac115ed2016-03-09 23:13:12 +00003860 const bool OptSize = I->getFunction()->optForSize();
3861
Chandler Carruthc8925912013-01-05 02:09:22 +00003862 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003863 for (Use &U : I->uses()) {
3864 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003865
Chandler Carruthcdf47882014-03-09 03:16:01 +00003866 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3867 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003868 continue;
3869 }
Stephen Lin837bba12013-07-15 17:55:02 +00003870
Chandler Carruthcdf47882014-03-09 03:16:01 +00003871 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3872 unsigned opNo = U.getOperandNo();
Matt Arsenault02d915b2017-03-15 22:35:20 +00003873 if (opNo != StoreInst::getPointerOperandIndex())
3874 return true; // Storing addr, not into addr.
Chandler Carruthc8925912013-01-05 02:09:22 +00003875 MemoryUses.push_back(std::make_pair(SI, opNo));
3876 continue;
3877 }
Stephen Lin837bba12013-07-15 17:55:02 +00003878
Matt Arsenault02d915b2017-03-15 22:35:20 +00003879 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
3880 unsigned opNo = U.getOperandNo();
3881 if (opNo != AtomicRMWInst::getPointerOperandIndex())
3882 return true; // Storing addr, not into addr.
3883 MemoryUses.push_back(std::make_pair(RMW, opNo));
3884 continue;
3885 }
3886
3887 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
3888 unsigned opNo = U.getOperandNo();
3889 if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
3890 return true; // Storing addr, not into addr.
3891 MemoryUses.push_back(std::make_pair(CmpX, opNo));
3892 continue;
3893 }
3894
Chandler Carruthcdf47882014-03-09 03:16:01 +00003895 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003896 // If this is a cold call, we can sink the addressing calculation into
3897 // the cold path. See optimizeCallInst
3898 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3899 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003900
Chandler Carruthc8925912013-01-05 02:09:22 +00003901 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3902 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003903
Chandler Carruthc8925912013-01-05 02:09:22 +00003904 // If this is a memory operand, we're cool, otherwise bail out.
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003905 if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003906 return true;
3907 continue;
3908 }
Stephen Lin837bba12013-07-15 17:55:02 +00003909
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003910 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003911 return true;
3912 }
3913
3914 return false;
3915}
3916
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003917/// Return true if Val is already known to be live at the use site that we're
3918/// folding it into. If so, there is no cost to include it in the addressing
3919/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3920/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003921bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003922 Value *KnownLive2) {
3923 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003924 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003925 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003926
Chandler Carruthc8925912013-01-05 02:09:22 +00003927 // All values other than instructions and arguments (e.g. constants) are live.
3928 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003929
Chandler Carruthc8925912013-01-05 02:09:22 +00003930 // If Val is a constant sized alloca in the entry block, it is live, this is
3931 // true because it is just a reference to the stack/frame pointer, which is
3932 // live for the whole function.
3933 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3934 if (AI->isStaticAlloca())
3935 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003936
Chandler Carruthc8925912013-01-05 02:09:22 +00003937 // Check to see if this value is already used in the memory instruction's
3938 // block. If so, it's already live into the block at the very least, so we
3939 // can reasonably fold it.
3940 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3941}
3942
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003943/// It is possible for the addressing mode of the machine to fold the specified
3944/// instruction into a load or store that ultimately uses it.
3945/// However, the specified instruction has multiple uses.
3946/// Given this, it may actually increase register pressure to fold it
3947/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003948///
3949/// X = ...
3950/// Y = X+1
3951/// use(Y) -> nonload/store
3952/// Z = Y+1
3953/// load Z
3954///
3955/// In this case, Y has multiple uses, and can be folded into the load of Z
3956/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3957/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3958/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3959/// number of computations either.
3960///
3961/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3962/// X was live across 'load Z' for other reasons, we actually *would* want to
3963/// fold the addressing mode in the Z case. This would make Y die earlier.
3964bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003965isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003966 ExtAddrMode &AMAfter) {
3967 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003968
Chandler Carruthc8925912013-01-05 02:09:22 +00003969 // AMBefore is the addressing mode before this instruction was folded into it,
3970 // and AMAfter is the addressing mode after the instruction was folded. Get
3971 // the set of registers referenced by AMAfter and subtract out those
3972 // referenced by AMBefore: this is the set of values which folding in this
3973 // address extends the lifetime of.
3974 //
3975 // Note that there are only two potential values being referenced here,
3976 // BaseReg and ScaleReg (global addresses are always available, as are any
3977 // folded immediates).
3978 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003979
Chandler Carruthc8925912013-01-05 02:09:22 +00003980 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3981 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003982 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003983 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003984 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003985 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003986
3987 // If folding this instruction (and it's subexprs) didn't extend any live
3988 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003989 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003990 return true;
3991
Philip Reamesac115ed2016-03-09 23:13:12 +00003992 // If all uses of this instruction can have the address mode sunk into them,
3993 // we can remove the addressing mode and effectively trade one live register
3994 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003995 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003996 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3997 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Igor Laevsky3be81ba2017-02-07 13:27:20 +00003998 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
Chandler Carruthc8925912013-01-05 02:09:22 +00003999 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00004000
Chandler Carruthc8925912013-01-05 02:09:22 +00004001 // Now that we know that all uses of this instruction are part of a chain of
4002 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00004003 // into a memory use, loop over each of these memory operation uses and see
4004 // if they could *actually* fold the instruction. The assumption is that
4005 // addressing modes are cheap and that duplicating the computation involved
4006 // many times is worthwhile, even on a fastpath. For sinking candidates
4007 // (i.e. cold call sites), this serves as a way to prevent excessive code
4008 // growth since most architectures have some reasonable small and fast way to
4009 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00004010 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
4011 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
4012 Instruction *User = MemoryUses[i].first;
4013 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00004014
Chandler Carruthc8925912013-01-05 02:09:22 +00004015 // Get the access type of this use. If the use isn't a pointer, we don't
4016 // know what it accesses.
4017 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004018 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
4019 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00004020 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004021 Type *AddressAccessTy = AddrTy->getElementType();
4022 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00004023
Chandler Carruthc8925912013-01-05 02:09:22 +00004024 // Do a match against the root of this address, ignoring profitability. This
4025 // will tell us if the addressing mode for the memory operation will
4026 // *actually* cover the shared instruction.
4027 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004028 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4029 TPT.getRestorationPoint();
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004030 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
4031 AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004032 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004033 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00004034 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004035 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00004036 (void)Success; assert(Success && "Couldn't select *anything*?");
4037
Quentin Colombet5a69dda2014-02-11 01:59:02 +00004038 // The match was to check the profitability, the changes made are not
4039 // part of the original matcher. Therefore, they should be dropped
4040 // otherwise the original matcher will not present the right state.
4041 TPT.rollback(LastKnownGood);
4042
Chandler Carruthc8925912013-01-05 02:09:22 +00004043 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00004044 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00004045 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00004046
Chandler Carruthc8925912013-01-05 02:09:22 +00004047 MatchedAddrModeInsts.clear();
4048 }
Stephen Lin837bba12013-07-15 17:55:02 +00004049
Chandler Carruthc8925912013-01-05 02:09:22 +00004050 return true;
4051}
4052
4053} // end anonymous namespace
4054
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004055/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004056/// different basic block than BB.
4057static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
4058 if (Instruction *I = dyn_cast<Instruction>(V))
4059 return I->getParent() != BB;
4060 return false;
4061}
4062
Philip Reamesac115ed2016-03-09 23:13:12 +00004063/// Sink addressing mode computation immediate before MemoryInst if doing so
4064/// can be done without increasing register pressure. The need for the
4065/// register pressure constraint means this can end up being an all or nothing
4066/// decision for all uses of the same addressing computation.
4067///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004068/// Load and Store Instructions often have addressing modes that can do
4069/// significant amounts of computation. As such, instruction selection will try
4070/// to get the load or store to do as much computation as possible for the
4071/// program. The problem is that isel can only see within a single block. As
4072/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00004073///
4074/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00004075/// operands. It's also used to sink addressing computations feeding into cold
4076/// call sites into their (cold) basic block.
4077///
4078/// The motivation for handling sinking into cold blocks is that doing so can
4079/// both enable other address mode sinking (by satisfying the register pressure
4080/// constraint above), and reduce register pressure globally (by removing the
4081/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004082bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004083 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004084 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00004085
4086 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004087 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00004088 SmallVector<Value*, 8> worklist;
4089 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004090 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00004091
Owen Anderson8ba5f392010-11-27 08:15:55 +00004092 // Use a worklist to iteratively look through PHI nodes, and ensure that
4093 // the addressing mode obtained from the non-PHI roots of the graph
4094 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00004095 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004096 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004097 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004098 SmallVector<Instruction*, 16> AddrModeInsts;
4099 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004100 TypePromotionTransaction TPT;
4101 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4102 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00004103 while (!worklist.empty()) {
4104 Value *V = worklist.back();
4105 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00004106
Owen Anderson8ba5f392010-11-27 08:15:55 +00004107 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00004108 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00004109 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004110 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004111 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004112
Owen Anderson8ba5f392010-11-27 08:15:55 +00004113 // For a PHI node, push all of its incoming values.
4114 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00004115 for (Value *IncValue : P->incoming_values())
4116 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00004117 continue;
4118 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004119
Philip Reamesac115ed2016-03-09 23:13:12 +00004120 // For non-PHIs, determine the addressing mode being computed. Note that
4121 // the result may differ depending on what other uses our candidate
4122 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00004123 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004124 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004125 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004126 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00004127
4128 // This check is broken into two cases with very similar code to avoid using
4129 // getNumUses() as much as possible. Some values have a lot of uses, so
4130 // calling getNumUses() unconditionally caused a significant compile-time
4131 // regression.
4132 if (!Consensus) {
4133 Consensus = V;
4134 AddrMode = NewAddrMode;
4135 AddrModeInsts = NewAddrModeInsts;
4136 continue;
4137 } else if (NewAddrMode == AddrMode) {
4138 if (!IsNumUsesConsensusValid) {
4139 NumUsesConsensus = Consensus->getNumUses();
4140 IsNumUsesConsensusValid = true;
4141 }
4142
4143 // Ensure that the obtained addressing mode is equivalent to that obtained
4144 // for all other roots of the PHI traversal. Also, when choosing one
4145 // such root as representative, select the one with the most uses in order
4146 // to keep the cost modeling heuristics in AddressingModeMatcher
4147 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004148 unsigned NumUses = V->getNumUses();
4149 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00004150 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00004151 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004152 AddrModeInsts = NewAddrModeInsts;
4153 }
4154 continue;
4155 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004156
Craig Topperc0196b12014-04-14 00:51:57 +00004157 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00004158 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004159 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004160
Owen Anderson8ba5f392010-11-27 08:15:55 +00004161 // If the addressing mode couldn't be determined, or if multiple different
4162 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00004163 if (!Consensus) {
4164 TPT.rollback(LastKnownGood);
4165 return false;
4166 }
4167 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00004168
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004169 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00004170 if (none_of(AddrModeInsts, [&](Value *V) {
4171 return IsNonLocalValue(V, MemoryInst->getParent());
4172 })) {
David Greene74e2d492010-01-05 01:27:11 +00004173 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004174 return false;
4175 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004176
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004177 // Insert this computation right after this user. Since our caller is
4178 // scanning from the top of the BB to the bottom, reuse of the expr are
4179 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00004180 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004181
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004182 // Now that we determined the addressing expression we want to use and know
4183 // that we have to sink it into this block. Check to see if we have already
4184 // done this for some other load/store instr in this block. If so, reuse the
4185 // computation.
4186 Value *&SunkAddr = SunkAddrs[Addr];
4187 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00004188 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004189 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004190 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004191 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00004192 } else if (AddrSinkUsingGEPs ||
4193 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Igor Laevsky3be81ba2017-02-07 13:27:20 +00004194 SubtargetInfo->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00004195 // By default, we use the GEP-based method when AA is used later. This
4196 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
4197 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004198 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004199 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004200 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004201
4202 // First, find the pointer.
4203 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
4204 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00004205 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004206 }
4207
4208 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
4209 // We can't add more than one pointer together, nor can we scale a
4210 // pointer (both of which seem meaningless).
4211 if (ResultPtr || AddrMode.Scale != 1)
4212 return false;
4213
4214 ResultPtr = AddrMode.ScaledReg;
4215 AddrMode.Scale = 0;
4216 }
4217
4218 if (AddrMode.BaseGV) {
4219 if (ResultPtr)
4220 return false;
4221
4222 ResultPtr = AddrMode.BaseGV;
4223 }
4224
4225 // If the real base value actually came from an inttoptr, then the matcher
4226 // will look through it and provide only the integer value. In that case,
4227 // use it here.
4228 if (!ResultPtr && AddrMode.BaseReg) {
4229 ResultPtr =
4230 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00004231 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00004232 } else if (!ResultPtr && AddrMode.Scale == 1) {
4233 ResultPtr =
4234 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
4235 AddrMode.Scale = 0;
4236 }
4237
4238 if (!ResultPtr &&
4239 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
4240 SunkAddr = Constant::getNullValue(Addr->getType());
4241 } else if (!ResultPtr) {
4242 return false;
4243 } else {
4244 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00004245 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4246 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004247
4248 // Start with the base register. Do this first so that subsequent address
4249 // matching finds it last, which will prevent it from trying to match it
4250 // as the scaled value in case it happens to be a mul. That would be
4251 // problematic if we've sunk a different mul for the scale, because then
4252 // we'd end up sinking both muls.
4253 if (AddrMode.BaseReg) {
4254 Value *V = AddrMode.BaseReg;
4255 if (V->getType() != IntPtrTy)
4256 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4257
4258 ResultIndex = V;
4259 }
4260
4261 // Add the scale value.
4262 if (AddrMode.Scale) {
4263 Value *V = AddrMode.ScaledReg;
4264 if (V->getType() == IntPtrTy) {
4265 // done.
4266 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4267 cast<IntegerType>(V->getType())->getBitWidth()) {
4268 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4269 } else {
4270 // It is only safe to sign extend the BaseReg if we know that the math
4271 // required to create it did not overflow before we extend it. Since
4272 // the original IR value was tossed in favor of a constant back when
4273 // the AddrMode was created we need to bail out gracefully if widths
4274 // do not match instead of extending it.
4275 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4276 if (I && (ResultIndex != AddrMode.BaseReg))
4277 I->eraseFromParent();
4278 return false;
4279 }
4280
4281 if (AddrMode.Scale != 1)
4282 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4283 "sunkaddr");
4284 if (ResultIndex)
4285 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4286 else
4287 ResultIndex = V;
4288 }
4289
4290 // Add in the Base Offset if present.
4291 if (AddrMode.BaseOffs) {
4292 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4293 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004294 // We need to add this separately from the scale above to help with
4295 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004296 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004297 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004298 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004299 }
4300
4301 ResultIndex = V;
4302 }
4303
4304 if (!ResultIndex) {
4305 SunkAddr = ResultPtr;
4306 } else {
4307 if (ResultPtr->getType() != I8PtrTy)
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004308 ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004309 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004310 }
4311
4312 if (SunkAddr->getType() != Addr->getType())
Eli Friedmanc12a5a72017-02-24 20:51:36 +00004313 SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00004314 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004315 } else {
David Greene74e2d492010-01-05 01:27:11 +00004316 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004317 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004318 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004319 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004320
4321 // Start with the base register. Do this first so that subsequent address
4322 // matching finds it last, which will prevent it from trying to match it
4323 // as the scaled value in case it happens to be a mul. That would be
4324 // problematic if we've sunk a different mul for the scale, because then
4325 // we'd end up sinking both muls.
4326 if (AddrMode.BaseReg) {
4327 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004328 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004329 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004330 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004331 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004332 Result = V;
4333 }
4334
4335 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004336 if (AddrMode.Scale) {
4337 Value *V = AddrMode.ScaledReg;
4338 if (V->getType() == IntPtrTy) {
4339 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004340 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004341 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004342 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4343 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004344 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004345 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004346 // It is only safe to sign extend the BaseReg if we know that the math
4347 // required to create it did not overflow before we extend it. Since
4348 // the original IR value was tossed in favor of a constant back when
4349 // the AddrMode was created we need to bail out gracefully if widths
4350 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004351 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004352 if (I && (Result != AddrMode.BaseReg))
4353 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004354 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004355 }
4356 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004357 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4358 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004359 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004360 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004361 else
4362 Result = V;
4363 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004364
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004365 // Add in the BaseGV if present.
4366 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004367 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004368 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004369 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004370 else
4371 Result = V;
4372 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004373
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004374 // Add in the Base Offset if present.
4375 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004376 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004377 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004378 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004379 else
4380 Result = V;
4381 }
4382
Craig Topperc0196b12014-04-14 00:51:57 +00004383 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004384 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004385 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004386 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004387 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004388
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004389 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004390
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004391 // If we have no uses, recursively delete the value and all dead instructions
4392 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004393 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004394 // This can cause recursive deletion, which can invalidate our iterator.
4395 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004396 Value *CurValue = &*CurInstIterator;
4397 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004398 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004399
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004400 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004401
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004402 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004403 // If the iterator instruction was recursively deleted, start over at the
4404 // start of the block.
4405 CurInstIterator = BB->begin();
4406 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004407 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004408 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004409 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004410 return true;
4411}
4412
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004413/// If there are any memory operands, use OptimizeMemoryInst to sink their
4414/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004415bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004416 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004417
Eric Christopher11e4df72015-02-26 22:38:43 +00004418 const TargetRegisterInfo *TRI =
4419 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004420 TargetLowering::AsmOperandInfoVector TargetConstraints =
4421 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004422 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004423 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4424 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004425
Evan Cheng1da25002008-02-26 02:42:37 +00004426 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004427 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004428
Eli Friedman666bbe32008-02-26 18:37:49 +00004429 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4430 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004431 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004432 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004433 } else if (OpInfo.Type == InlineAsm::isInput)
4434 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004435 }
4436
4437 return MadeChange;
4438}
4439
Jun Bum Lim42301012017-03-17 19:05:21 +00004440/// \brief Check if all the uses of \p Val are equivalent (or free) zero or
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004441/// sign extensions.
Jun Bum Lim42301012017-03-17 19:05:21 +00004442static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
4443 assert(!Val->use_empty() && "Input must have at least one use");
4444 const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004445 bool IsSExt = isa<SExtInst>(FirstUser);
4446 Type *ExtTy = FirstUser->getType();
Jun Bum Lim42301012017-03-17 19:05:21 +00004447 for (const User *U : Val->users()) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004448 const Instruction *UI = cast<Instruction>(U);
4449 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4450 return false;
4451 Type *CurTy = UI->getType();
4452 // Same input and output types: Same instruction after CSE.
4453 if (CurTy == ExtTy)
4454 continue;
4455
4456 // If IsSExt is true, we are in this situation:
Jun Bum Lim42301012017-03-17 19:05:21 +00004457 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004458 // b = sext ty1 a to ty2
4459 // c = sext ty1 a to ty3
4460 // Assuming ty2 is shorter than ty3, this could be turned into:
Jun Bum Lim42301012017-03-17 19:05:21 +00004461 // a = Val
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004462 // b = sext ty1 a to ty2
4463 // c = sext ty2 b to ty3
4464 // However, the last sext is not free.
4465 if (IsSExt)
4466 return false;
4467
4468 // This is a ZExt, maybe this is free to extend from one type to another.
4469 // In that case, we would not account for a different use.
4470 Type *NarrowTy;
4471 Type *LargeTy;
4472 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4473 CurTy->getScalarType()->getIntegerBitWidth()) {
4474 NarrowTy = CurTy;
4475 LargeTy = ExtTy;
4476 } else {
4477 NarrowTy = ExtTy;
4478 LargeTy = CurTy;
4479 }
4480
4481 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4482 return false;
4483 }
4484 // All uses are the same or can be derived from one another for free.
4485 return true;
4486}
4487
Jun Bum Lim42301012017-03-17 19:05:21 +00004488/// \brief Try to speculatively promote extensions in \p Exts and continue
4489/// promoting through newly promoted operands recursively as far as doing so is
4490/// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
4491/// When some promotion happened, \p TPT contains the proper state to revert
4492/// them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004493///
Jun Bum Lim42301012017-03-17 19:05:21 +00004494/// \return true if some promotion happened, false otherwise.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004495///
4496/// Example:
4497/// \code
4498/// %ld = load i32* %addr
4499/// %add = add nuw i32 %ld, 4
4500/// %zext = zext i32 %add to i64
4501/// \endcode
4502/// =>
4503/// \code
4504/// %ld = load i32* %addr
4505/// %zext = zext i32 %ld to i64
4506/// %add = add nuw i64 %zext, 4
Haicheng Wu8ce2d142017-01-18 21:12:10 +00004507/// \endcode
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004508/// Thanks to the promotion, we can match zext(load i32*) to i64.
Jun Bum Lim42301012017-03-17 19:05:21 +00004509bool CodeGenPrepare::tryToPromoteExts(
4510 TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
4511 SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
4512 unsigned CreatedInstsCost) {
4513 bool Promoted = false;
4514
4515 // Iterate over all the extensions to try to promote them.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004516 for (auto I : Exts) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004517 // Early check if we directly have ext(load).
4518 if (isa<LoadInst>(I->getOperand(0))) {
4519 ProfitablyMovedExts.push_back(I);
4520 continue;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004521 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004522
4523 // Check whether or not we want to do any promotion. The reason we have
4524 // this check inside the for loop is to catch the case where an extension
4525 // is directly fed by a load because in such case the extension can be moved
4526 // up without any promotion on its operands.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004527 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
Jun Bum Lim42301012017-03-17 19:05:21 +00004528 return false;
4529
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004530 // Get the action to perform the promotion.
Jun Bum Lim42301012017-03-17 19:05:21 +00004531 TypePromotionHelper::Action TPH =
4532 TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004533 // Check if we can promote.
Jun Bum Lim42301012017-03-17 19:05:21 +00004534 if (!TPH) {
4535 // Save the current extension as we cannot move up through its operand.
4536 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004537 continue;
Jun Bum Lim42301012017-03-17 19:05:21 +00004538 }
4539
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004540 // Save the current state.
4541 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4542 TPT.getRestorationPoint();
4543 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004544 unsigned NewCreatedInstsCost = 0;
4545 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004546 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004547 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4548 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004549 assert(PromotedVal &&
4550 "TypePromotionHelper should have filtered out those cases");
4551
4552 // We would be able to merge only one extension in a load.
4553 // Therefore, if we have more than 1 new extension we heuristically
4554 // cut this search path, because it means we degrade the code quality.
4555 // With exactly 2, the transformation is neutral, because we will merge
4556 // one extension but leave one. However, we optimistically keep going,
4557 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004558 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004559 // FIXME: It would be possible to propagate a negative value instead of
Jun Bum Lim42301012017-03-17 19:05:21 +00004560 // conservatively ceiling it to 0.
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004561 TotalCreatedInstsCost =
4562 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004563 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004564 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004565 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Jun Bum Lim42301012017-03-17 19:05:21 +00004566 // This promotion is not profitable, rollback to the previous state, and
4567 // save the current extension in ProfitablyMovedExts as the latest
4568 // speculative promotion turned out to be unprofitable.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004569 TPT.rollback(LastKnownGood);
Jun Bum Lim42301012017-03-17 19:05:21 +00004570 ProfitablyMovedExts.push_back(I);
4571 continue;
4572 }
4573 // Continue promoting NewExts as far as doing so is profitable.
4574 SmallVector<Instruction *, 2> NewlyMovedExts;
4575 (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
4576 bool NewPromoted = false;
4577 for (auto ExtInst : NewlyMovedExts) {
4578 Instruction *MovedExt = cast<Instruction>(ExtInst);
4579 Value *ExtOperand = MovedExt->getOperand(0);
4580 // If we have reached to a load, we need this extra profitability check
4581 // as it could potentially be merged into an ext(load).
4582 if (isa<LoadInst>(ExtOperand) &&
4583 !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
4584 (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
4585 continue;
4586
4587 ProfitablyMovedExts.push_back(MovedExt);
4588 NewPromoted = true;
4589 }
4590
4591 // If none of speculative promotions for NewExts is profitable, rollback
4592 // and save the current extension (I) as the last profitable extension.
4593 if (!NewPromoted) {
4594 TPT.rollback(LastKnownGood);
4595 ProfitablyMovedExts.push_back(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004596 continue;
4597 }
4598 // The promotion is profitable.
Jun Bum Lim42301012017-03-17 19:05:21 +00004599 Promoted = true;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004600 }
Jun Bum Lim42301012017-03-17 19:05:21 +00004601 return Promoted;
4602}
4603
4604/// Return true, if an ext(load) can be formed from an extension in
4605/// \p MovedExts.
4606bool CodeGenPrepare::canFormExtLd(
4607 const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
4608 Instruction *&Inst, bool HasPromoted) {
4609 for (auto *MovedExtInst : MovedExts) {
4610 if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
4611 LI = cast<LoadInst>(MovedExtInst->getOperand(0));
4612 Inst = MovedExtInst;
4613 break;
4614 }
4615 }
4616 if (!LI)
4617 return false;
4618
4619 // If they're already in the same block, there's nothing to do.
4620 // Make the cheap checks first if we did not promote.
4621 // If we promoted, we need to check if it is indeed profitable.
4622 if (!HasPromoted && LI->getParent() == Inst->getParent())
4623 return false;
4624
4625 EVT VT = TLI->getValueType(*DL, Inst->getType());
4626 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
4627
4628 // If the load has other users and the truncate is not free, this probably
4629 // isn't worthwhile.
4630 if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
4631 !TLI->isTruncateFree(Inst->getType(), LI->getType()))
4632 return false;
4633
4634 // Check whether the target supports casts folded into loads.
4635 unsigned LType;
4636 if (isa<ZExtInst>(Inst))
4637 LType = ISD::ZEXTLOAD;
4638 else {
4639 assert(isa<SExtInst>(Inst) && "Unexpected ext type!");
4640 LType = ISD::SEXTLOAD;
4641 }
4642
4643 return TLI->isLoadExtLegal(LType, VT, LoadVT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004644}
4645
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004646/// Move a zext or sext fed by a load into the same basic block as the load,
4647/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4648/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004649/// \p I[in/out] the extension may be modified during the process if some
4650/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004651///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004652bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004653 // ExtLoad formation infrastructure requires TLI to be effective.
4654 if (!TLI)
4655 return false;
4656
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004657 // Try to promote a chain of computation if it allows to form
4658 // an extended load.
4659 TypePromotionTransaction TPT;
4660 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
Jun Bum Lim42301012017-03-17 19:05:21 +00004661 TPT.getRestorationPoint();
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004662 SmallVector<Instruction *, 1> Exts;
Jun Bum Lim42301012017-03-17 19:05:21 +00004663 SmallVector<Instruction *, 2> LastMovedExts;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004664 Exts.push_back(I);
Jun Bum Lim42301012017-03-17 19:05:21 +00004665
4666 bool HasPromoted = tryToPromoteExts(TPT, Exts, LastMovedExts);
4667
Dan Gohman99429a02009-10-16 20:59:35 +00004668 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004669 LoadInst *LI = nullptr;
4670 Instruction *OldExt = I;
Jun Bum Lim42301012017-03-17 19:05:21 +00004671 if (!canFormExtLd(LastMovedExts, LI, I, HasPromoted)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004672 I = OldExt;
4673 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004674 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004675 }
Dan Gohman99429a02009-10-16 20:59:35 +00004676
4677 // Move the extend into the same block as the load, so that SelectionDAG
4678 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004679 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004680 I->removeFromParent();
4681 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004682 // CGP does not check if the zext would be speculatively executed when moved
4683 // to the same basic block as the load. Preserving its original location would
Jun Bum Lim42301012017-03-17 19:05:21 +00004684 // pessimize the debugging experience, as well as negatively impact the
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004685 // quality of sample pgo. We don't want to use "line 0" as that has a
4686 // size cost in the line-table section and logically the zext can be seen as
4687 // part of the load. Therefore we conservatively reuse the same debug location
4688 // for the load and the zext.
4689 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004690 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004691 return true;
4692}
4693
Sanjay Patelfc580a62015-09-21 23:03:16 +00004694bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004695 BasicBlock *DefBB = I->getParent();
4696
Bob Wilsonff714f92010-09-21 21:44:14 +00004697 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004698 // other uses of the source with result of extension.
4699 Value *Src = I->getOperand(0);
4700 if (Src->hasOneUse())
4701 return false;
4702
Evan Cheng2011df42007-12-13 07:50:36 +00004703 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004704 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004705 return false;
4706
Evan Cheng7bc89422007-12-12 00:51:06 +00004707 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004708 // this block.
4709 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004710 return false;
4711
Evan Chengd3d80172007-12-05 23:58:20 +00004712 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004713 for (User *U : I->users()) {
4714 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004715
4716 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004717 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004718 if (UserBB == DefBB) continue;
4719 DefIsLiveOut = true;
4720 break;
4721 }
4722 if (!DefIsLiveOut)
4723 return false;
4724
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004725 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004726 for (User *U : Src->users()) {
4727 Instruction *UI = cast<Instruction>(U);
4728 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004729 if (UserBB == DefBB) continue;
4730 // Be conservative. We don't want this xform to end up introducing
4731 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004732 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004733 return false;
4734 }
4735
Evan Chengd3d80172007-12-05 23:58:20 +00004736 // InsertedTruncs - Only insert one trunc in each block once.
4737 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4738
4739 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004740 for (Use &U : Src->uses()) {
4741 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004742
4743 // Figure out which BB this ext is used in.
4744 BasicBlock *UserBB = User->getParent();
4745 if (UserBB == DefBB) continue;
4746
4747 // Both src and def are live in this block. Rewrite the use.
4748 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4749
4750 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004751 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004752 assert(InsertPt != UserBB->end());
4753 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004754 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004755 }
4756
4757 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004758 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004759 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004760 MadeChange = true;
4761 }
4762
4763 return MadeChange;
4764}
4765
Geoff Berry5256fca2015-11-20 22:34:39 +00004766// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4767// just after the load if the target can fold this into one extload instruction,
4768// with the hope of eliminating some of the other later "and" instructions using
4769// the loaded value. "and"s that are made trivially redundant by the insertion
4770// of the new "and" are removed by this function, while others (e.g. those whose
4771// path from the load goes through a phi) are left for isel to potentially
4772// remove.
4773//
4774// For example:
4775//
4776// b0:
4777// x = load i32
4778// ...
4779// b1:
4780// y = and x, 0xff
4781// z = use y
4782//
4783// becomes:
4784//
4785// b0:
4786// x = load i32
4787// x' = and x, 0xff
4788// ...
4789// b1:
4790// z = use x'
4791//
4792// whereas:
4793//
4794// b0:
4795// x1 = load i32
4796// ...
4797// b1:
4798// x2 = load i32
4799// ...
4800// b2:
4801// x = phi x1, x2
4802// y = and x, 0xff
4803//
4804// becomes (after a call to optimizeLoadExt for each load):
4805//
4806// b0:
4807// x1 = load i32
4808// x1' = and x1, 0xff
4809// ...
4810// b1:
4811// x2 = load i32
4812// x2' = and x2, 0xff
4813// ...
4814// b2:
4815// x = phi x1', x2'
4816// y = and x, 0xff
4817//
4818
4819bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4820
4821 if (!Load->isSimple() ||
4822 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4823 return false;
4824
Geoff Berry5d534b62017-02-21 18:53:14 +00004825 // Skip loads we've already transformed.
4826 if (Load->hasOneUse() &&
4827 InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
4828 return false;
Geoff Berry5256fca2015-11-20 22:34:39 +00004829
4830 // Look at all uses of Load, looking through phis, to determine how many bits
4831 // of the loaded value are needed.
4832 SmallVector<Instruction *, 8> WorkList;
4833 SmallPtrSet<Instruction *, 16> Visited;
4834 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4835 for (auto *U : Load->users())
4836 WorkList.push_back(cast<Instruction>(U));
4837
4838 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4839 unsigned BitWidth = LoadResultVT.getSizeInBits();
4840 APInt DemandBits(BitWidth, 0);
4841 APInt WidestAndBits(BitWidth, 0);
4842
4843 while (!WorkList.empty()) {
4844 Instruction *I = WorkList.back();
4845 WorkList.pop_back();
4846
4847 // Break use-def graph loops.
4848 if (!Visited.insert(I).second)
4849 continue;
4850
4851 // For a PHI node, push all of its users.
4852 if (auto *Phi = dyn_cast<PHINode>(I)) {
4853 for (auto *U : Phi->users())
4854 WorkList.push_back(cast<Instruction>(U));
4855 continue;
4856 }
4857
4858 switch (I->getOpcode()) {
4859 case llvm::Instruction::And: {
4860 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4861 if (!AndC)
4862 return false;
4863 APInt AndBits = AndC->getValue();
4864 DemandBits |= AndBits;
4865 // Keep track of the widest and mask we see.
4866 if (AndBits.ugt(WidestAndBits))
4867 WidestAndBits = AndBits;
4868 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4869 AndsToMaybeRemove.push_back(I);
4870 break;
4871 }
4872
4873 case llvm::Instruction::Shl: {
4874 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4875 if (!ShlC)
4876 return false;
4877 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4878 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4879 DemandBits |= ShlDemandBits;
4880 break;
4881 }
4882
4883 case llvm::Instruction::Trunc: {
4884 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4885 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4886 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4887 DemandBits |= TruncBits;
4888 break;
4889 }
4890
4891 default:
4892 return false;
4893 }
4894 }
4895
4896 uint32_t ActiveBits = DemandBits.getActiveBits();
4897 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4898 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4899 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4900 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4901 // followed by an AND.
4902 // TODO: Look into removing this restriction by fixing backends to either
4903 // return false for isLoadExtLegal for i1 or have them select this pattern to
4904 // a single instruction.
4905 //
4906 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4907 // mask, since these are the only ands that will be removed by isel.
4908 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4909 WidestAndBits != DemandBits)
4910 return false;
4911
4912 LLVMContext &Ctx = Load->getType()->getContext();
4913 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4914 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4915
4916 // Reject cases that won't be matched as extloads.
4917 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4918 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4919 return false;
4920
4921 IRBuilder<> Builder(Load->getNextNode());
4922 auto *NewAnd = dyn_cast<Instruction>(
4923 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
Geoff Berry5d534b62017-02-21 18:53:14 +00004924 // Mark this instruction as "inserted by CGP", so that other
4925 // optimizations don't touch it.
4926 InsertedInsts.insert(NewAnd);
Geoff Berry5256fca2015-11-20 22:34:39 +00004927
4928 // Replace all uses of load with new and (except for the use of load in the
4929 // new and itself).
4930 Load->replaceAllUsesWith(NewAnd);
4931 NewAnd->setOperand(0, Load);
4932
4933 // Remove any and instructions that are now redundant.
4934 for (auto *And : AndsToMaybeRemove)
4935 // Check that the and mask is the same as the one we decided to put on the
4936 // new and.
4937 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4938 And->replaceAllUsesWith(NewAnd);
4939 if (&*CurInstIterator == And)
4940 CurInstIterator = std::next(And->getIterator());
4941 And->eraseFromParent();
4942 ++NumAndUses;
4943 }
4944
4945 ++NumAndsAdded;
4946 return true;
4947}
4948
Sanjay Patel69a50a12015-10-19 21:59:12 +00004949/// Check if V (an operand of a select instruction) is an expensive instruction
4950/// that is only used once.
4951static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4952 auto *I = dyn_cast<Instruction>(V);
4953 // If it's safe to speculatively execute, then it should not have side
4954 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004955 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4956 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004957}
4958
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004959/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004960static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004961 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004962 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004963 // If even a predictable select is cheap, then a branch can't be cheaper.
4964 if (!TLI->isPredictableSelectExpensive())
4965 return false;
4966
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004967 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004968 // whether a select is better represented as a branch.
4969
4970 // If metadata tells us that the select condition is obviously predictable,
4971 // then we want to replace the select with a branch.
4972 uint64_t TrueWeight, FalseWeight;
4973 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4974 uint64_t Max = std::max(TrueWeight, FalseWeight);
4975 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004976 if (Sum != 0) {
4977 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4978 if (Probability > TLI->getPredictableBranchThreshold())
4979 return true;
4980 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004981 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004982
4983 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4984
Sanjay Patel4e652762015-09-28 22:14:51 +00004985 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4986 // comparison condition. If the compare has more than one use, there's
4987 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004988 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004989 return false;
4990
Sanjay Patel69a50a12015-10-19 21:59:12 +00004991 // If either operand of the select is expensive and only needed on one side
4992 // of the select, we should form a branch.
4993 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4994 sinkSelectOperand(TTI, SI->getFalseValue()))
4995 return true;
4996
4997 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004998}
4999
Dehao Chen9bbb9412016-09-12 20:23:28 +00005000/// If \p isTrue is true, return the true value of \p SI, otherwise return
5001/// false value of \p SI. If the true/false value of \p SI is defined by any
5002/// select instructions in \p Selects, look through the defining select
5003/// instruction until the true/false value is not defined in \p Selects.
5004static Value *getTrueOrFalseValue(
5005 SelectInst *SI, bool isTrue,
5006 const SmallPtrSet<const Instruction *, 2> &Selects) {
5007 Value *V;
5008
5009 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
5010 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00005011 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00005012 "The condition of DefSI does not match with SI");
5013 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
5014 }
5015 return V;
5016}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005017
Nadav Rotem9d832022012-09-02 12:10:19 +00005018/// If we have a SelectInst that will likely profit from branch prediction,
5019/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005020bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00005021 // Find all consecutive select instructions that share the same condition.
5022 SmallVector<SelectInst *, 2> ASI;
5023 ASI.push_back(SI);
5024 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
5025 It != SI->getParent()->end(); ++It) {
5026 SelectInst *I = dyn_cast<SelectInst>(&*It);
5027 if (I && SI->getCondition() == I->getCondition()) {
5028 ASI.push_back(I);
5029 } else {
5030 break;
5031 }
5032 }
5033
5034 SelectInst *LastSI = ASI.back();
5035 // Increment the current iterator to skip all the rest of select instructions
5036 // because they will be either "not lowered" or "all lowered" to branch.
5037 CurInstIterator = std::next(LastSI->getIterator());
5038
Nadav Rotem9d832022012-09-02 12:10:19 +00005039 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
5040
5041 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00005042 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
5043 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005044 return false;
5045
Nadav Rotem9d832022012-09-02 12:10:19 +00005046 TargetLowering::SelectSupportKind SelectKind;
5047 if (VectorCond)
5048 SelectKind = TargetLowering::VectorMaskSelect;
5049 else if (SI->getType()->isVectorTy())
5050 SelectKind = TargetLowering::ScalarCondVectorVal;
5051 else
5052 SelectKind = TargetLowering::ScalarValSelect;
5053
Sanjay Pateld66607b2016-04-26 17:11:17 +00005054 if (TLI->isSelectSupported(SelectKind) &&
5055 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
5056 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005057
5058 ModifiedDT = true;
5059
Sanjay Patel69a50a12015-10-19 21:59:12 +00005060 // Transform a sequence like this:
5061 // start:
5062 // %cmp = cmp uge i32 %a, %b
5063 // %sel = select i1 %cmp, i32 %c, i32 %d
5064 //
5065 // Into:
5066 // start:
5067 // %cmp = cmp uge i32 %a, %b
5068 // br i1 %cmp, label %select.true, label %select.false
5069 // select.true:
5070 // br label %select.end
5071 // select.false:
5072 // br label %select.end
5073 // select.end:
5074 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
5075 //
5076 // In addition, we may sink instructions that produce %c or %d from
5077 // the entry block into the destination(s) of the new branch.
5078 // If the true or false blocks do not contain a sunken instruction, that
5079 // block and its branch may be optimized away. In that case, one side of the
5080 // first branch will point directly to select.end, and the corresponding PHI
5081 // predecessor block will be the start block.
5082
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005083 // First, we split the block containing the select into 2 blocks.
5084 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00005085 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00005086 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005087
Sanjay Patel69a50a12015-10-19 21:59:12 +00005088 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005089 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00005090
5091 // These are the new basic blocks for the conditional branch.
5092 // At least one will become an actual new basic block.
5093 BasicBlock *TrueBlock = nullptr;
5094 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00005095 BranchInst *TrueBranch = nullptr;
5096 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005097
5098 // Sink expensive instructions into the conditional blocks to avoid executing
5099 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00005100 for (SelectInst *SI : ASI) {
5101 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
5102 if (TrueBlock == nullptr) {
5103 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
5104 EndBlock->getParent(), EndBlock);
5105 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
5106 }
5107 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
5108 TrueInst->moveBefore(TrueBranch);
5109 }
5110 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
5111 if (FalseBlock == nullptr) {
5112 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
5113 EndBlock->getParent(), EndBlock);
5114 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
5115 }
5116 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
5117 FalseInst->moveBefore(FalseBranch);
5118 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00005119 }
5120
5121 // If there was nothing to sink, then arbitrarily choose the 'false' side
5122 // for a new input value to the PHI.
5123 if (TrueBlock == FalseBlock) {
5124 assert(TrueBlock == nullptr &&
5125 "Unexpected basic block transform while optimizing select");
5126
5127 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
5128 EndBlock->getParent(), EndBlock);
5129 BranchInst::Create(EndBlock, FalseBlock);
5130 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005131
5132 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00005133 // If we did not create a new block for one of the 'true' or 'false' paths
5134 // of the condition, it means that side of the branch goes to the end block
5135 // directly and the path originates from the start block from the point of
5136 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00005137 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005138 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005139 TT = EndBlock;
5140 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005141 TrueBlock = StartBlock;
5142 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005143 TT = TrueBlock;
5144 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005145 FalseBlock = StartBlock;
5146 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00005147 TT = TrueBlock;
5148 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00005149 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00005150 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005151
Dehao Chen9bbb9412016-09-12 20:23:28 +00005152 SmallPtrSet<const Instruction *, 2> INS;
5153 INS.insert(ASI.begin(), ASI.end());
5154 // Use reverse iterator because later select may use the value of the
5155 // earlier select, and we need to propagate value through earlier select
5156 // to get the PHI operand.
5157 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
5158 SelectInst *SI = *It;
5159 // The select itself is replaced with a PHI Node.
5160 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
5161 PN->takeName(SI);
5162 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
5163 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00005164
Dehao Chen9bbb9412016-09-12 20:23:28 +00005165 SI->replaceAllUsesWith(PN);
5166 SI->eraseFromParent();
5167 INS.erase(SI);
5168 ++NumSelectsExpanded;
5169 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005170
5171 // Instruct OptimizeBlock to skip to the next block.
5172 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005173 return true;
5174}
5175
Benjamin Kramer573ff362014-03-01 17:24:40 +00005176static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005177 SmallVector<int, 16> Mask(SVI->getShuffleMask());
5178 int SplatElem = -1;
5179 for (unsigned i = 0; i < Mask.size(); ++i) {
5180 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
5181 return false;
5182 SplatElem = Mask[i];
5183 }
5184
5185 return true;
5186}
5187
5188/// Some targets have expensive vector shifts if the lanes aren't all the same
5189/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
5190/// it's often worth sinking a shufflevector splat down to its use so that
5191/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005192bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00005193 BasicBlock *DefBB = SVI->getParent();
5194
5195 // Only do this xform if variable vector shifts are particularly expensive.
5196 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
5197 return false;
5198
5199 // We only expect better codegen by sinking a shuffle if we can recognise a
5200 // constant splat.
5201 if (!isBroadcastShuffle(SVI))
5202 return false;
5203
5204 // InsertedShuffles - Only insert a shuffle in each block once.
5205 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
5206
5207 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00005208 for (User *U : SVI->users()) {
5209 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005210
5211 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005212 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00005213 if (UserBB == DefBB) continue;
5214
5215 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00005216 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00005217
5218 // Everything checks out, sink the shuffle if the user's block doesn't
5219 // already have a copy.
5220 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
5221
5222 if (!InsertedShuffle) {
5223 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005224 assert(InsertPt != UserBB->end());
5225 InsertedShuffle =
5226 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
5227 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005228 }
5229
Chandler Carruthcdf47882014-03-09 03:16:01 +00005230 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005231 MadeChange = true;
5232 }
5233
5234 // If we removed all uses, nuke the shuffle.
5235 if (SVI->use_empty()) {
5236 SVI->eraseFromParent();
5237 MadeChange = true;
5238 }
5239
5240 return MadeChange;
5241}
5242
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005243bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
5244 if (!TLI || !DL)
5245 return false;
5246
5247 Value *Cond = SI->getCondition();
5248 Type *OldType = Cond->getType();
5249 LLVMContext &Context = Cond->getContext();
5250 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
5251 unsigned RegWidth = RegType.getSizeInBits();
5252
5253 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
5254 return false;
5255
5256 // If the register width is greater than the type width, expand the condition
5257 // of the switch instruction and each case constant to the width of the
5258 // register. By widening the type of the switch condition, subsequent
5259 // comparisons (for case comparisons) will not need to be extended to the
5260 // preferred register width, so we will potentially eliminate N-1 extends,
5261 // where N is the number of cases in the switch.
5262 auto *NewType = Type::getIntNTy(Context, RegWidth);
5263
5264 // Zero-extend the switch condition and case constants unless the switch
5265 // condition is a function argument that is already being sign-extended.
5266 // In that case, we can avoid an unnecessary mask/extension by sign-extending
5267 // everything instead.
5268 Instruction::CastOps ExtType = Instruction::ZExt;
5269 if (auto *Arg = dyn_cast<Argument>(Cond))
5270 if (Arg->hasSExtAttr())
5271 ExtType = Instruction::SExt;
5272
5273 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
5274 ExtInst->insertBefore(SI);
5275 SI->setCondition(ExtInst);
5276 for (SwitchInst::CaseIt Case : SI->cases()) {
5277 APInt NarrowConst = Case.getCaseValue()->getValue();
5278 APInt WideConst = (ExtType == Instruction::ZExt) ?
5279 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
5280 Case.setValue(ConstantInt::get(Context, WideConst));
5281 }
5282
5283 return true;
5284}
5285
Quentin Colombetc32615d2014-10-31 17:52:53 +00005286namespace {
5287/// \brief Helper class to promote a scalar operation to a vector one.
5288/// This class is used to move downward extractelement transition.
5289/// E.g.,
5290/// a = vector_op <2 x i32>
5291/// b = extractelement <2 x i32> a, i32 0
5292/// c = scalar_op b
5293/// store c
5294///
5295/// =>
5296/// a = vector_op <2 x i32>
5297/// c = vector_op a (equivalent to scalar_op on the related lane)
5298/// * d = extractelement <2 x i32> c, i32 0
5299/// * store d
5300/// Assuming both extractelement and store can be combine, we get rid of the
5301/// transition.
5302class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005303 /// DataLayout associated with the current module.
5304 const DataLayout &DL;
5305
Quentin Colombetc32615d2014-10-31 17:52:53 +00005306 /// Used to perform some checks on the legality of vector operations.
5307 const TargetLowering &TLI;
5308
5309 /// Used to estimated the cost of the promoted chain.
5310 const TargetTransformInfo &TTI;
5311
5312 /// The transition being moved downwards.
5313 Instruction *Transition;
5314 /// The sequence of instructions to be promoted.
5315 SmallVector<Instruction *, 4> InstsToBePromoted;
5316 /// Cost of combining a store and an extract.
5317 unsigned StoreExtractCombineCost;
5318 /// Instruction that will be combined with the transition.
5319 Instruction *CombineInst;
5320
5321 /// \brief The instruction that represents the current end of the transition.
5322 /// Since we are faking the promotion until we reach the end of the chain
5323 /// of computation, we need a way to get the current end of the transition.
5324 Instruction *getEndOfTransition() const {
5325 if (InstsToBePromoted.empty())
5326 return Transition;
5327 return InstsToBePromoted.back();
5328 }
5329
5330 /// \brief Return the index of the original value in the transition.
5331 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5332 /// c, is at index 0.
5333 unsigned getTransitionOriginalValueIdx() const {
5334 assert(isa<ExtractElementInst>(Transition) &&
5335 "Other kind of transitions are not supported yet");
5336 return 0;
5337 }
5338
5339 /// \brief Return the index of the index in the transition.
5340 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5341 /// is at index 1.
5342 unsigned getTransitionIdx() const {
5343 assert(isa<ExtractElementInst>(Transition) &&
5344 "Other kind of transitions are not supported yet");
5345 return 1;
5346 }
5347
5348 /// \brief Get the type of the transition.
5349 /// This is the type of the original value.
5350 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5351 /// transition is <2 x i32>.
5352 Type *getTransitionType() const {
5353 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5354 }
5355
5356 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5357 /// I.e., we have the following sequence:
5358 /// Def = Transition <ty1> a to <ty2>
5359 /// b = ToBePromoted <ty2> Def, ...
5360 /// =>
5361 /// b = ToBePromoted <ty1> a, ...
5362 /// Def = Transition <ty1> ToBePromoted to <ty2>
5363 void promoteImpl(Instruction *ToBePromoted);
5364
5365 /// \brief Check whether or not it is profitable to promote all the
5366 /// instructions enqueued to be promoted.
5367 bool isProfitableToPromote() {
5368 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5369 unsigned Index = isa<ConstantInt>(ValIdx)
5370 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5371 : -1;
5372 Type *PromotedType = getTransitionType();
5373
5374 StoreInst *ST = cast<StoreInst>(CombineInst);
5375 unsigned AS = ST->getPointerAddressSpace();
5376 unsigned Align = ST->getAlignment();
5377 // Check if this store is supported.
5378 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005379 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5380 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005381 // If this is not supported, there is no way we can combine
5382 // the extract with the store.
5383 return false;
5384 }
5385
5386 // The scalar chain of computation has to pay for the transition
5387 // scalar to vector.
5388 // The vector chain has to account for the combining cost.
5389 uint64_t ScalarCost =
5390 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5391 uint64_t VectorCost = StoreExtractCombineCost;
5392 for (const auto &Inst : InstsToBePromoted) {
5393 // Compute the cost.
5394 // By construction, all instructions being promoted are arithmetic ones.
5395 // Moreover, one argument is a constant that can be viewed as a splat
5396 // constant.
5397 Value *Arg0 = Inst->getOperand(0);
5398 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5399 isa<ConstantFP>(Arg0);
5400 TargetTransformInfo::OperandValueKind Arg0OVK =
5401 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5402 : TargetTransformInfo::OK_AnyValue;
5403 TargetTransformInfo::OperandValueKind Arg1OVK =
5404 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5405 : TargetTransformInfo::OK_AnyValue;
5406 ScalarCost += TTI.getArithmeticInstrCost(
5407 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5408 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5409 Arg0OVK, Arg1OVK);
5410 }
5411 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5412 << ScalarCost << "\nVector: " << VectorCost << '\n');
5413 return ScalarCost > VectorCost;
5414 }
5415
5416 /// \brief Generate a constant vector with \p Val with the same
5417 /// number of elements as the transition.
5418 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005419 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005420 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5421 /// otherwise we generate a vector with as many undef as possible:
5422 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5423 /// used at the index of the extract.
5424 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5425 unsigned ExtractIdx = UINT_MAX;
5426 if (!UseSplat) {
5427 // If we cannot determine where the constant must be, we have to
5428 // use a splat constant.
5429 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5430 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5431 ExtractIdx = CstVal->getSExtValue();
5432 else
5433 UseSplat = true;
5434 }
5435
5436 unsigned End = getTransitionType()->getVectorNumElements();
5437 if (UseSplat)
5438 return ConstantVector::getSplat(End, Val);
5439
5440 SmallVector<Constant *, 4> ConstVec;
5441 UndefValue *UndefVal = UndefValue::get(Val->getType());
5442 for (unsigned Idx = 0; Idx != End; ++Idx) {
5443 if (Idx == ExtractIdx)
5444 ConstVec.push_back(Val);
5445 else
5446 ConstVec.push_back(UndefVal);
5447 }
5448 return ConstantVector::get(ConstVec);
5449 }
5450
5451 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5452 /// in \p Use can trigger undefined behavior.
5453 static bool canCauseUndefinedBehavior(const Instruction *Use,
5454 unsigned OperandIdx) {
5455 // This is not safe to introduce undef when the operand is on
5456 // the right hand side of a division-like instruction.
5457 if (OperandIdx != 1)
5458 return false;
5459 switch (Use->getOpcode()) {
5460 default:
5461 return false;
5462 case Instruction::SDiv:
5463 case Instruction::UDiv:
5464 case Instruction::SRem:
5465 case Instruction::URem:
5466 return true;
5467 case Instruction::FDiv:
5468 case Instruction::FRem:
5469 return !Use->hasNoNaNs();
5470 }
5471 llvm_unreachable(nullptr);
5472 }
5473
5474public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005475 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5476 const TargetTransformInfo &TTI, Instruction *Transition,
5477 unsigned CombineCost)
5478 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005479 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5480 assert(Transition && "Do not know how to promote null");
5481 }
5482
5483 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5484 bool canPromote(const Instruction *ToBePromoted) const {
5485 // We could support CastInst too.
5486 return isa<BinaryOperator>(ToBePromoted);
5487 }
5488
5489 /// \brief Check if it is profitable to promote \p ToBePromoted
5490 /// by moving downward the transition through.
5491 bool shouldPromote(const Instruction *ToBePromoted) const {
5492 // Promote only if all the operands can be statically expanded.
5493 // Indeed, we do not want to introduce any new kind of transitions.
5494 for (const Use &U : ToBePromoted->operands()) {
5495 const Value *Val = U.get();
5496 if (Val == getEndOfTransition()) {
5497 // If the use is a division and the transition is on the rhs,
5498 // we cannot promote the operation, otherwise we may create a
5499 // division by zero.
5500 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5501 return false;
5502 continue;
5503 }
5504 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5505 !isa<ConstantFP>(Val))
5506 return false;
5507 }
5508 // Check that the resulting operation is legal.
5509 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5510 if (!ISDOpcode)
5511 return false;
5512 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005513 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005514 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005515 }
5516
5517 /// \brief Check whether or not \p Use can be combined
5518 /// with the transition.
5519 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5520 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5521
5522 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5523 void enqueueForPromotion(Instruction *ToBePromoted) {
5524 InstsToBePromoted.push_back(ToBePromoted);
5525 }
5526
5527 /// \brief Set the instruction that will be combined with the transition.
5528 void recordCombineInstruction(Instruction *ToBeCombined) {
5529 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5530 CombineInst = ToBeCombined;
5531 }
5532
5533 /// \brief Promote all the instructions enqueued for promotion if it is
5534 /// is profitable.
5535 /// \return True if the promotion happened, false otherwise.
5536 bool promote() {
5537 // Check if there is something to promote.
5538 // Right now, if we do not have anything to combine with,
5539 // we assume the promotion is not profitable.
5540 if (InstsToBePromoted.empty() || !CombineInst)
5541 return false;
5542
5543 // Check cost.
5544 if (!StressStoreExtract && !isProfitableToPromote())
5545 return false;
5546
5547 // Promote.
5548 for (auto &ToBePromoted : InstsToBePromoted)
5549 promoteImpl(ToBePromoted);
5550 InstsToBePromoted.clear();
5551 return true;
5552 }
5553};
5554} // End of anonymous namespace.
5555
5556void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5557 // At this point, we know that all the operands of ToBePromoted but Def
5558 // can be statically promoted.
5559 // For Def, we need to use its parameter in ToBePromoted:
5560 // b = ToBePromoted ty1 a
5561 // Def = Transition ty1 b to ty2
5562 // Move the transition down.
5563 // 1. Replace all uses of the promoted operation by the transition.
5564 // = ... b => = ... Def.
5565 assert(ToBePromoted->getType() == Transition->getType() &&
5566 "The type of the result of the transition does not match "
5567 "the final type");
5568 ToBePromoted->replaceAllUsesWith(Transition);
5569 // 2. Update the type of the uses.
5570 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5571 Type *TransitionTy = getTransitionType();
5572 ToBePromoted->mutateType(TransitionTy);
5573 // 3. Update all the operands of the promoted operation with promoted
5574 // operands.
5575 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5576 for (Use &U : ToBePromoted->operands()) {
5577 Value *Val = U.get();
5578 Value *NewVal = nullptr;
5579 if (Val == Transition)
5580 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5581 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5582 isa<ConstantFP>(Val)) {
5583 // Use a splat constant if it is not safe to use undef.
5584 NewVal = getConstantVector(
5585 cast<Constant>(Val),
5586 isa<UndefValue>(Val) ||
5587 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5588 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005589 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5590 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005591 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5592 }
5593 Transition->removeFromParent();
5594 Transition->insertAfter(ToBePromoted);
5595 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5596}
5597
5598/// Some targets can do store(extractelement) with one instruction.
5599/// Try to push the extractelement towards the stores when the target
5600/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005601bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005602 unsigned CombineCost = UINT_MAX;
5603 if (DisableStoreExtract || !TLI ||
5604 (!StressStoreExtract &&
5605 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5606 Inst->getOperand(1), CombineCost)))
5607 return false;
5608
5609 // At this point we know that Inst is a vector to scalar transition.
5610 // Try to move it down the def-use chain, until:
5611 // - We can combine the transition with its single use
5612 // => we got rid of the transition.
5613 // - We escape the current basic block
5614 // => we would need to check that we are moving it at a cheaper place and
5615 // we do not do that for now.
5616 BasicBlock *Parent = Inst->getParent();
5617 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005618 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005619 // If the transition has more than one use, assume this is not going to be
5620 // beneficial.
5621 while (Inst->hasOneUse()) {
5622 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5623 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5624
5625 if (ToBePromoted->getParent() != Parent) {
5626 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5627 << ToBePromoted->getParent()->getName()
5628 << ") than the transition (" << Parent->getName() << ").\n");
5629 return false;
5630 }
5631
5632 if (VPH.canCombine(ToBePromoted)) {
5633 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5634 << "will be combined with: " << *ToBePromoted << '\n');
5635 VPH.recordCombineInstruction(ToBePromoted);
5636 bool Changed = VPH.promote();
5637 NumStoreExtractExposed += Changed;
5638 return Changed;
5639 }
5640
5641 DEBUG(dbgs() << "Try promoting.\n");
5642 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5643 return false;
5644
5645 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5646
5647 VPH.enqueueForPromotion(ToBePromoted);
5648 Inst = ToBePromoted;
5649 }
5650 return false;
5651}
5652
Wei Mia2f0b592016-12-22 19:44:45 +00005653/// For the instruction sequence of store below, F and I values
5654/// are bundled together as an i64 value before being stored into memory.
5655/// Sometimes it is more efficent to generate separate stores for F and I,
5656/// which can remove the bitwise instructions or sink them to colder places.
5657///
5658/// (store (or (zext (bitcast F to i32) to i64),
5659/// (shl (zext I to i64), 32)), addr) -->
5660/// (store F, addr) and (store I, addr+4)
5661///
5662/// Similarly, splitting for other merged store can also be beneficial, like:
5663/// For pair of {i32, i32}, i64 store --> two i32 stores.
5664/// For pair of {i32, i16}, i64 store --> two i32 stores.
5665/// For pair of {i16, i16}, i32 store --> two i16 stores.
5666/// For pair of {i16, i8}, i32 store --> two i16 stores.
5667/// For pair of {i8, i8}, i16 store --> two i8 stores.
5668///
5669/// We allow each target to determine specifically which kind of splitting is
5670/// supported.
5671///
5672/// The store patterns are commonly seen from the simple code snippet below
5673/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5674/// void goo(const std::pair<int, float> &);
5675/// hoo() {
5676/// ...
5677/// goo(std::make_pair(tmp, ftmp));
5678/// ...
5679/// }
5680///
5681/// Although we already have similar splitting in DAG Combine, we duplicate
5682/// it in CodeGenPrepare to catch the case in which pattern is across
5683/// multiple BBs. The logic in DAG Combine is kept to catch case generated
5684/// during code expansion.
5685static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5686 const TargetLowering &TLI) {
5687 // Handle simple but common cases only.
5688 Type *StoreType = SI.getValueOperand()->getType();
5689 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5690 DL.getTypeSizeInBits(StoreType) == 0)
5691 return false;
5692
5693 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5694 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5695 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5696 DL.getTypeSizeInBits(SplitStoreType))
5697 return false;
5698
5699 // Match the following patterns:
5700 // (store (or (zext LValue to i64),
5701 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5702 // or
5703 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5704 // (zext LValue to i64),
5705 // Expect both operands of OR and the first operand of SHL have only
5706 // one use.
5707 Value *LValue, *HValue;
5708 if (!match(SI.getValueOperand(),
5709 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5710 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5711 m_SpecificInt(HalfValBitSize))))))
5712 return false;
5713
5714 // Check LValue and HValue are int with size less or equal than 32.
5715 if (!LValue->getType()->isIntegerTy() ||
5716 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5717 !HValue->getType()->isIntegerTy() ||
5718 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5719 return false;
5720
5721 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5722 // as the input of target query.
5723 auto *LBC = dyn_cast<BitCastInst>(LValue);
5724 auto *HBC = dyn_cast<BitCastInst>(HValue);
5725 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5726 : EVT::getEVT(LValue->getType());
5727 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5728 : EVT::getEVT(HValue->getType());
5729 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5730 return false;
5731
5732 // Start to split store.
5733 IRBuilder<> Builder(SI.getContext());
5734 Builder.SetInsertPoint(&SI);
5735
5736 // If LValue/HValue is a bitcast in another BB, create a new one in current
5737 // BB so it may be merged with the splitted stores by dag combiner.
5738 if (LBC && LBC->getParent() != SI.getParent())
5739 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5740 if (HBC && HBC->getParent() != SI.getParent())
5741 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
5742
5743 auto CreateSplitStore = [&](Value *V, bool Upper) {
5744 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
5745 Value *Addr = Builder.CreateBitCast(
5746 SI.getOperand(1),
5747 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
5748 if (Upper)
5749 Addr = Builder.CreateGEP(
5750 SplitStoreType, Addr,
5751 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
5752 Builder.CreateAlignedStore(
5753 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
5754 };
5755
5756 CreateSplitStore(LValue, false);
5757 CreateSplitStore(HValue, true);
5758
5759 // Delete the old store.
5760 SI.eraseFromParent();
5761 return true;
5762}
5763
Sanjay Patelfc580a62015-09-21 23:03:16 +00005764bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005765 // Bail out if we inserted the instruction to prevent optimizations from
5766 // stepping on each other's toes.
5767 if (InsertedInsts.count(I))
5768 return false;
5769
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005770 if (PHINode *P = dyn_cast<PHINode>(I)) {
5771 // It is possible for very late stage optimizations (such as SimplifyCFG)
5772 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5773 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005774 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005775 P->replaceAllUsesWith(V);
5776 P->eraseFromParent();
5777 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005778 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005779 }
Chris Lattneree588de2011-01-15 07:29:01 +00005780 return false;
5781 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005782
Chris Lattneree588de2011-01-15 07:29:01 +00005783 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005784 // If the source of the cast is a constant, then this should have
5785 // already been constant folded. The only reason NOT to constant fold
5786 // it is if something (e.g. LSR) was careful to place the constant
5787 // evaluation in a block other than then one that uses it (e.g. to hoist
5788 // the address of globals out of a loop). If this is the case, we don't
5789 // want to forward-subst the cast.
5790 if (isa<Constant>(CI->getOperand(0)))
5791 return false;
5792
Mehdi Amini44ede332015-07-09 02:09:04 +00005793 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005794 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005795
Chris Lattneree588de2011-01-15 07:29:01 +00005796 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005797 /// Sink a zext or sext into its user blocks if the target type doesn't
5798 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005799 if (TLI &&
5800 TLI->getTypeAction(CI->getContext(),
5801 TLI->getValueType(*DL, CI->getType())) ==
5802 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005803 return SinkCast(CI);
5804 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005805 bool MadeChange = moveExtToFormExtLoad(I);
5806 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005807 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005808 }
Chris Lattneree588de2011-01-15 07:29:01 +00005809 return false;
5810 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005811
Chris Lattneree588de2011-01-15 07:29:01 +00005812 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005813 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005814 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005815
Chris Lattneree588de2011-01-15 07:29:01 +00005816 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00005817 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005818 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005819 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005820 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005821 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5822 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005823 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005824 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005825 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005826
Chris Lattneree588de2011-01-15 07:29:01 +00005827 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00005828 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
5829 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00005830 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005831 if (TLI) {
5832 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005833 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005834 SI->getOperand(0)->getType(), AS);
5835 }
Chris Lattneree588de2011-01-15 07:29:01 +00005836 return false;
5837 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005838
Matt Arsenault02d915b2017-03-15 22:35:20 +00005839 if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
5840 unsigned AS = RMW->getPointerAddressSpace();
5841 return optimizeMemoryInst(I, RMW->getPointerOperand(),
5842 RMW->getType(), AS);
5843 }
5844
5845 if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
5846 unsigned AS = CmpX->getPointerAddressSpace();
5847 return optimizeMemoryInst(I, CmpX->getPointerOperand(),
5848 CmpX->getCompareOperand()->getType(), AS);
5849 }
5850
Yi Jiangd069f632014-04-21 19:34:27 +00005851 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5852
Geoff Berry5d534b62017-02-21 18:53:14 +00005853 if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
5854 EnableAndCmpSinking && TLI)
5855 return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
5856
Yi Jiangd069f632014-04-21 19:34:27 +00005857 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5858 BinOp->getOpcode() == Instruction::LShr)) {
5859 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5860 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005861 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005862
5863 return false;
5864 }
5865
Chris Lattneree588de2011-01-15 07:29:01 +00005866 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005867 if (GEPI->hasAllZeroIndices()) {
5868 /// The GEP operand must be a pointer, so must its result -> BitCast
5869 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5870 GEPI->getName(), GEPI);
5871 GEPI->replaceAllUsesWith(NC);
5872 GEPI->eraseFromParent();
5873 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005874 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005875 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005876 }
Chris Lattneree588de2011-01-15 07:29:01 +00005877 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005878 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005879
Chris Lattneree588de2011-01-15 07:29:01 +00005880 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005881 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005882
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005883 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005884 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005885
Tim Northoveraeb8e062014-02-19 10:02:43 +00005886 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005887 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005888
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005889 if (auto *Switch = dyn_cast<SwitchInst>(I))
5890 return optimizeSwitchInst(Switch);
5891
Quentin Colombetc32615d2014-10-31 17:52:53 +00005892 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005893 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005894
Chris Lattneree588de2011-01-15 07:29:01 +00005895 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005896}
5897
James Molloyf01488e2016-01-15 09:20:19 +00005898/// Given an OR instruction, check to see if this is a bitreverse
5899/// idiom. If so, insert the new intrinsic and return true.
5900static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5901 const TargetLowering &TLI) {
5902 if (!I.getType()->isIntegerTy() ||
5903 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5904 TLI.getValueType(DL, I.getType(), true)))
5905 return false;
5906
5907 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005908 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005909 return false;
5910 Instruction *LastInst = Insts.back();
5911 I.replaceAllUsesWith(LastInst);
5912 RecursivelyDeleteTriviallyDeadInstructions(&I);
5913 return true;
5914}
5915
Chris Lattnerf2836d12007-03-31 04:06:36 +00005916// In this pass we look for GEP and cast instructions that are used
5917// across basic blocks and rewrite them to improve basic-block-at-a-time
5918// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005919bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005920 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005921 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005922
Chris Lattner7a277142011-01-15 07:14:54 +00005923 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005924 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005925 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005926 if (ModifiedDT)
5927 return true;
5928 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005929
James Molloyf01488e2016-01-15 09:20:19 +00005930 bool MadeBitReverse = true;
5931 while (TLI && MadeBitReverse) {
5932 MadeBitReverse = false;
5933 for (auto &I : reverse(BB)) {
5934 if (makeBitReverse(I, *DL, *TLI)) {
5935 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005936 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005937 break;
5938 }
5939 }
5940 }
James Molloy3ef84c42016-01-15 10:36:01 +00005941 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005942
Chris Lattnerf2836d12007-03-31 04:06:36 +00005943 return MadeChange;
5944}
Devang Patel53771ba2011-08-18 00:50:51 +00005945
5946// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005947// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005948// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005949bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005950 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005951 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005952 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005953 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005954 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005955 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005956 // Leave dbg.values that refer to an alloca alone. These
5957 // instrinsics describe the address of a variable (= the alloca)
5958 // being taken. They should not be moved next to the alloca
5959 // (and to the beginning of the scope), but rather stay close to
5960 // where said address is used.
5961 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005962 PrevNonDbgInst = Insn;
5963 continue;
5964 }
5965
5966 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5967 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005968 // If VI is a phi in a block with an EHPad terminator, we can't insert
5969 // after it.
5970 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5971 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005972 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5973 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005974 if (isa<PHINode>(VI))
5975 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5976 else
5977 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005978 MadeChange = true;
5979 ++NumDbgValueMoved;
5980 }
5981 }
5982 }
5983 return MadeChange;
5984}
Tim Northovercea0abb2014-03-29 08:22:29 +00005985
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005986/// \brief Scale down both weights to fit into uint32_t.
5987static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5988 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5989 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5990 NewTrue = NewTrue / Scale;
5991 NewFalse = NewFalse / Scale;
5992}
5993
5994/// \brief Some targets prefer to split a conditional branch like:
5995/// \code
5996/// %0 = icmp ne i32 %a, 0
5997/// %1 = icmp ne i32 %b, 0
5998/// %or.cond = or i1 %0, %1
5999/// br i1 %or.cond, label %TrueBB, label %FalseBB
6000/// \endcode
6001/// into multiple branch instructions like:
6002/// \code
6003/// bb1:
6004/// %0 = icmp ne i32 %a, 0
6005/// br i1 %0, label %TrueBB, label %bb2
6006/// bb2:
6007/// %1 = icmp ne i32 %b, 0
6008/// br i1 %1, label %TrueBB, label %FalseBB
6009/// \endcode
6010/// This usually allows instruction selection to do even further optimizations
6011/// and combine the compare with the branch instruction. Currently this is
6012/// applied for targets which have "cheap" jump instructions.
6013///
6014/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
6015///
6016bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00006017 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006018 return false;
6019
6020 bool MadeChange = false;
6021 for (auto &BB : F) {
6022 // Does this BB end with the following?
6023 // %cond1 = icmp|fcmp|binary instruction ...
6024 // %cond2 = icmp|fcmp|binary instruction ...
6025 // %cond.or = or|and i1 %cond1, cond2
6026 // br i1 %cond.or label %dest1, label %dest2"
6027 BinaryOperator *LogicOp;
6028 BasicBlock *TBB, *FBB;
6029 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
6030 continue;
6031
Sanjay Patel42574202015-09-02 19:23:23 +00006032 auto *Br1 = cast<BranchInst>(BB.getTerminator());
6033 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
6034 continue;
6035
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006036 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006037 Value *Cond1, *Cond2;
6038 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
6039 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006040 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006041 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
6042 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006043 Opc = Instruction::Or;
6044 else
6045 continue;
6046
6047 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
6048 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
6049 continue;
6050
6051 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
6052
6053 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00006054 auto TmpBB =
6055 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
6056 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006057
6058 // Update original basic block by using the first condition directly by the
6059 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006060 Br1->setCondition(Cond1);
6061 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006062
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006063 // Depending on the conditon we have to either replace the true or the false
6064 // successor of the original branch instruction.
6065 if (Opc == Instruction::And)
6066 Br1->setSuccessor(0, TmpBB);
6067 else
6068 Br1->setSuccessor(1, TmpBB);
6069
6070 // Fill in the new basic block.
6071 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00006072 if (auto *I = dyn_cast<Instruction>(Cond2)) {
6073 I->removeFromParent();
6074 I->insertBefore(Br2);
6075 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006076
6077 // Update PHI nodes in both successors. The original BB needs to be
6078 // replaced in one succesor's PHI nodes, because the branch comes now from
6079 // the newly generated BB (NewBB). In the other successor we need to add one
6080 // incoming edge to the PHI nodes, because both branch instructions target
6081 // now the same successor. Depending on the original branch condition
6082 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00006083 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006084 // This doesn't change the successor order of the just created branch
6085 // instruction (or any other instruction).
6086 if (Opc == Instruction::Or)
6087 std::swap(TBB, FBB);
6088
6089 // Replace the old BB with the new BB.
6090 for (auto &I : *TBB) {
6091 PHINode *PN = dyn_cast<PHINode>(&I);
6092 if (!PN)
6093 break;
6094 int i;
6095 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
6096 PN->setIncomingBlock(i, TmpBB);
6097 }
6098
6099 // Add another incoming edge form the new BB.
6100 for (auto &I : *FBB) {
6101 PHINode *PN = dyn_cast<PHINode>(&I);
6102 if (!PN)
6103 break;
6104 auto *Val = PN->getIncomingValueForBlock(&BB);
6105 PN->addIncoming(Val, TmpBB);
6106 }
6107
6108 // Update the branch weights (from SelectionDAGBuilder::
6109 // FindMergedConditions).
6110 if (Opc == Instruction::Or) {
6111 // Codegen X | Y as:
6112 // BB1:
6113 // jmp_if_X TBB
6114 // jmp TmpBB
6115 // TmpBB:
6116 // jmp_if_Y TBB
6117 // jmp FBB
6118 //
6119
6120 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
6121 // The requirement is that
6122 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
6123 // = TrueProb for orignal BB.
6124 // Assuming the orignal weights are A and B, one choice is to set BB1's
6125 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
6126 // assumes that
6127 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
6128 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
6129 // TmpBB, but the math is more complicated.
6130 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006131 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006132 uint64_t NewTrueWeight = TrueWeight;
6133 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
6134 scaleWeights(NewTrueWeight, NewFalseWeight);
6135 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6136 .createBranchWeights(TrueWeight, FalseWeight));
6137
6138 NewTrueWeight = TrueWeight;
6139 NewFalseWeight = 2 * FalseWeight;
6140 scaleWeights(NewTrueWeight, NewFalseWeight);
6141 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6142 .createBranchWeights(TrueWeight, FalseWeight));
6143 }
6144 } else {
6145 // Codegen X & Y as:
6146 // BB1:
6147 // jmp_if_X TmpBB
6148 // jmp FBB
6149 // TmpBB:
6150 // jmp_if_Y TBB
6151 // jmp FBB
6152 //
6153 // This requires creation of TmpBB after CurBB.
6154
6155 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
6156 // The requirement is that
6157 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
6158 // = FalseProb for orignal BB.
6159 // Assuming the orignal weights are A and B, one choice is to set BB1's
6160 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
6161 // assumes that
6162 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
6163 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00006164 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006165 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
6166 uint64_t NewFalseWeight = FalseWeight;
6167 scaleWeights(NewTrueWeight, NewFalseWeight);
6168 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
6169 .createBranchWeights(TrueWeight, FalseWeight));
6170
6171 NewTrueWeight = 2 * TrueWeight;
6172 NewFalseWeight = FalseWeight;
6173 scaleWeights(NewTrueWeight, NewFalseWeight);
6174 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
6175 .createBranchWeights(TrueWeight, FalseWeight));
6176 }
6177 }
6178
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006179 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00006180 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00006181 ModifiedDT = true;
6182
6183 MadeChange = true;
6184
6185 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
6186 TmpBB->dump());
6187 }
6188 return MadeChange;
6189}