blob: 68f090ccee20d56b590e6d7fea4c6b3301a6bb03 [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"
18#include "llvm/ADT/SmallSet.h"
19#include "llvm/ADT/Statistic.h"
Jun Bum Lim82f55c52016-11-21 16:47:28 +000020#include "llvm/Analysis/BlockFrequencyInfo.h"
21#include "llvm/Analysis/BranchProbabilityInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000023#include "llvm/Analysis/LoopInfo.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000024#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000025#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000026#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000027#include "llvm/Analysis/ValueTracking.h"
Petar Jovanovic644b8c12016-04-13 12:25:25 +000028#include "llvm/Analysis/MemoryBuiltins.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000029#include "llvm/CodeGen/Analysis.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000030#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000034#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000036#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000037#include "llvm/IR/IRBuilder.h"
38#include "llvm/IR/InlineAsm.h"
39#include "llvm/IR/Instructions.h"
40#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000041#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000042#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000043#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000044#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000045#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000046#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000047#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000048#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000049#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000050#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000051#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000052#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000053#include "llvm/Transforms/Utils/BasicBlockUtils.h"
54#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000055#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000056#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000057#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000058using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000059using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000060
Chandler Carruth1b9dde02014-04-22 02:02:50 +000061#define DEBUG_TYPE "codegenprepare"
62
Cameron Zwarichced753f2011-01-05 17:27:27 +000063STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000064STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
65STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000066STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
67 "sunken Cmps");
68STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
69 "of sunken Casts");
70STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
71 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000072STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
73STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000074STATISTIC(NumAndsAdded,
75 "Number of and mask instructions added to form ext loads");
76STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000077STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000078STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000079STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000080STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000081STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000082
Cameron Zwarich338d3622011-03-11 21:52:04 +000083static cl::opt<bool> DisableBranchOpts(
84 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
85 cl::desc("Disable branch optimizations in CodeGenPrepare"));
86
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000087static cl::opt<bool>
88 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
89 cl::desc("Disable GC optimizations in CodeGenPrepare"));
90
Benjamin Kramer3d38c172012-05-06 14:25:16 +000091static cl::opt<bool> DisableSelectToBranch(
92 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
93 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000094
Hal Finkelc3998302014-04-12 00:59:48 +000095static cl::opt<bool> AddrSinkUsingGEPs(
96 "addr-sink-using-gep", cl::Hidden, cl::init(false),
97 cl::desc("Address sinking in CGP using GEPs."));
98
Tim Northovercea0abb2014-03-29 08:22:29 +000099static cl::opt<bool> EnableAndCmpSinking(
100 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
101 cl::desc("Enable sinkinig and/cmp into branches."));
102
Quentin Colombetc32615d2014-10-31 17:52:53 +0000103static cl::opt<bool> DisableStoreExtract(
104 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
105 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
106
107static cl::opt<bool> StressStoreExtract(
108 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
109 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
110
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000111static cl::opt<bool> DisableExtLdPromotion(
112 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
113 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
114 "CodeGenPrepare"));
115
116static cl::opt<bool> StressExtLdPromotion(
117 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
118 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
119 "optimization in CodeGenPrepare"));
120
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000121static cl::opt<bool> DisablePreheaderProtect(
122 "disable-preheader-prot", cl::Hidden, cl::init(false),
123 cl::desc("Disable protection against removing loop preheaders"));
124
Dehao Chen302b69c2016-10-18 20:42:47 +0000125static cl::opt<bool> ProfileGuidedSectionPrefix(
126 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
127 cl::desc("Use profile info to add section prefix for hot/cold functions"));
128
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000129static cl::opt<unsigned> FreqRatioToSkipMerge(
130 "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
131 cl::desc("Skip merging empty blocks if (frequency of empty block) / "
132 "(frequency of destination block) is greater than this ratio"));
133
Eric Christopherc1ea1492008-09-24 05:32:41 +0000134namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000135typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000136typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000137typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000138class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000139
Chris Lattner2dd09db2009-09-02 06:11:42 +0000140 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000141 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000142 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000143 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000144 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000145 const LoopInfo *LI;
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000146 std::unique_ptr<BlockFrequencyInfo> BFI;
147 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000148
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000149 /// As we scan instructions optimizing them, this is the next instruction
150 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000151 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000152
Evan Cheng0663f232011-03-21 01:19:09 +0000153 /// Keeps track of non-local addresses that have been sunk into a block.
154 /// This allows us to avoid inserting duplicate code for blocks with
155 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000156 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000157
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000158 /// Keeps track of all instructions inserted for the current function.
159 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000160 /// Keeps track of the type of the related instruction before their
161 /// promotion for the current function.
162 InstrToOrigTy PromotedInsts;
163
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000164 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000165 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000166
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000167 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000168 bool OptSize;
169
Mehdi Amini4fe37982015-07-07 18:45:17 +0000170 /// DataLayout for the Function being processed.
171 const DataLayout *DL;
172
Chris Lattnerf2836d12007-03-31 04:06:36 +0000173 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000174 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000175 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000176 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000177 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
178 }
Craig Topper4584cd52014-03-07 09:26:03 +0000179 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000180
Mehdi Amini117296c2016-10-01 02:56:57 +0000181 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000182
Craig Topper4584cd52014-03-07 09:26:03 +0000183 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000184 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000185 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000186 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000187 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000188 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000189 }
190
Chris Lattnerf2836d12007-03-31 04:06:36 +0000191 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000192 bool eliminateFallThrough(Function &F);
193 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000194 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000195 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
196 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000197 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
198 bool isPreheader);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000199 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
200 bool optimizeInst(Instruction *I, bool& ModifiedDT);
201 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000202 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000203 bool optimizeInlineAsmInst(CallInst *CS);
204 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
205 bool moveExtToFormExtLoad(Instruction *&I);
206 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000207 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000208 bool optimizeSelectInst(SelectInst *SI);
209 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000210 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000211 bool optimizeExtractElementInst(Instruction *Inst);
212 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
213 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000214 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000215 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000216 Instruction *&Inst,
217 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000218 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000219 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000220 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000221 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000222 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000223}
Devang Patel09f162c2007-05-01 21:15:47 +0000224
Devang Patel8c78a0b2007-05-03 01:11:54 +0000225char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000226INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
227 "Optimize for code generation", false, false)
228INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
229INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
230 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000231
Bill Wendling7a639ea2013-06-19 21:07:11 +0000232FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
233 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000234}
235
Chris Lattnerf2836d12007-03-31 04:06:36 +0000236bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000237 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000238 return false;
239
Mehdi Amini4fe37982015-07-07 18:45:17 +0000240 DL = &F.getParent()->getDataLayout();
241
Chris Lattnerf2836d12007-03-31 04:06:36 +0000242 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000243 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000244 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000245 PromotedInsts.clear();
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000246 BFI.reset();
247 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000248
Devang Patel8f606d72011-03-24 15:35:25 +0000249 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000250 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000251 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000252 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000253 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000254 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000255 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000256
Dehao Chen302b69c2016-10-18 20:42:47 +0000257 if (ProfileGuidedSectionPrefix) {
258 ProfileSummaryInfo *PSI =
259 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
260 if (PSI->isFunctionEntryHot(&F))
261 F.setSectionPrefix(".hot");
262 else if (PSI->isFunctionEntryCold(&F))
263 F.setSectionPrefix(".cold");
264 }
265
Preston Gurdcdf540d2012-09-04 18:22:17 +0000266 /// This optimization identifies DIV instructions that can be
267 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000268 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000269 const DenseMap<unsigned int, unsigned int> &BypassWidths =
270 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000271 BasicBlock* BB = &*F.begin();
272 while (BB != nullptr) {
273 // bypassSlowDivision may create new BBs, but we don't want to reapply the
274 // optimization to those blocks.
275 BasicBlock* Next = BB->getNextNode();
276 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
277 BB = Next;
278 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000279 }
280
281 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000282 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000283 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000284
Devang Patel53771ba2011-08-18 00:50:51 +0000285 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000286 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000287 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000288 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000289
Tim Northovercea0abb2014-03-29 08:22:29 +0000290 // If there is a mask, compare against zero, and branch that can be combined
291 // into a single target instruction, push the mask and compare into branch
292 // users. Do this before OptimizeBlock -> OptimizeInst ->
293 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000294 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000295 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000296 EverMadeChange |= splitBranchCondition(F);
297 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000298
Chris Lattnerc3748562007-04-02 01:35:34 +0000299 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000300 while (MadeChange) {
301 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000302 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000303 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000304 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000305 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000306
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000307 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000308 if (ModifiedDTOnIteration)
309 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000310 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000311 EverMadeChange |= MadeChange;
312 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000313
314 SunkAddrs.clear();
315
Cameron Zwarich338d3622011-03-11 21:52:04 +0000316 if (!DisableBranchOpts) {
317 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000318 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000319 for (BasicBlock &BB : F) {
320 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
321 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000322 if (!MadeChange) continue;
323
324 for (SmallVectorImpl<BasicBlock*>::iterator
325 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
326 if (pred_begin(*II) == pred_end(*II))
327 WorkList.insert(*II);
328 }
329
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000330 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000331 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000332 while (!WorkList.empty()) {
333 BasicBlock *BB = *WorkList.begin();
334 WorkList.erase(BB);
335 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
336
337 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000338
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000339 for (SmallVectorImpl<BasicBlock*>::iterator
340 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
341 if (pred_begin(*II) == pred_end(*II))
342 WorkList.insert(*II);
343 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000344
Nadav Rotem70409992012-08-14 05:19:07 +0000345 // Merge pairs of basic blocks with unconditional branches, connected by
346 // a single edge.
347 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000348 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000349
Cameron Zwarich338d3622011-03-11 21:52:04 +0000350 EverMadeChange |= MadeChange;
351 }
352
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000353 if (!DisableGCOpts) {
354 SmallVector<Instruction *, 2> Statepoints;
355 for (BasicBlock &BB : F)
356 for (Instruction &I : BB)
357 if (isStatepoint(I))
358 Statepoints.push_back(&I);
359 for (auto &I : Statepoints)
360 EverMadeChange |= simplifyOffsetableRelocate(*I);
361 }
362
Chris Lattnerf2836d12007-03-31 04:06:36 +0000363 return EverMadeChange;
364}
365
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000366/// Merge basic blocks which are connected by a single edge, where one of the
367/// basic blocks has a single successor pointing to the other basic block,
368/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000369bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000370 bool Changed = false;
371 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000372 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000373 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000374 // If the destination block has a single pred, then this is a trivial
375 // edge, just collapse it.
376 BasicBlock *SinglePred = BB->getSinglePredecessor();
377
Evan Cheng64a223a2012-09-28 23:58:57 +0000378 // Don't merge if BB's address is taken.
379 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000380
381 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
382 if (Term && !Term->isConditional()) {
383 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000384 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000385 // Remember if SinglePred was the entry block of the function.
386 // If so, we will need to move BB back to the entry position.
387 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000388 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000389
390 if (isEntry && BB != &BB->getParent()->getEntryBlock())
391 BB->moveBefore(&BB->getParent()->getEntryBlock());
392
393 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000394 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000395 }
396 }
397 return Changed;
398}
399
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000400/// Find a destination block from BB if BB is mergeable empty block.
401BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
402 // If this block doesn't end with an uncond branch, ignore it.
403 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
404 if (!BI || !BI->isUnconditional())
405 return nullptr;
406
407 // If the instruction before the branch (skipping debug info) isn't a phi
408 // node, then other stuff is happening here.
409 BasicBlock::iterator BBI = BI->getIterator();
410 if (BBI != BB->begin()) {
411 --BBI;
412 while (isa<DbgInfoIntrinsic>(BBI)) {
413 if (BBI == BB->begin())
414 break;
415 --BBI;
416 }
417 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
418 return nullptr;
419 }
420
421 // Do not break infinite loops.
422 BasicBlock *DestBB = BI->getSuccessor(0);
423 if (DestBB == BB)
424 return nullptr;
425
426 if (!canMergeBlocks(BB, DestBB))
427 DestBB = nullptr;
428
429 return DestBB;
430}
431
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000432/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
433/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
434/// edges in ways that are non-optimal for isel. Start by eliminating these
435/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000436bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000437 SmallPtrSet<BasicBlock *, 16> Preheaders;
438 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
439 while (!LoopList.empty()) {
440 Loop *L = LoopList.pop_back_val();
441 LoopList.insert(LoopList.end(), L->begin(), L->end());
442 if (BasicBlock *Preheader = L->getLoopPreheader())
443 Preheaders.insert(Preheader);
444 }
445
Chris Lattnerc3748562007-04-02 01:35:34 +0000446 bool MadeChange = false;
447 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000448 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000449 BasicBlock *BB = &*I++;
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000450 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
451 if (!DestBB ||
452 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000453 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000454
Sanjay Patelfc580a62015-09-21 23:03:16 +0000455 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000456 MadeChange = true;
457 }
458 return MadeChange;
459}
460
Jun Bum Lim82f55c52016-11-21 16:47:28 +0000461bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
462 BasicBlock *DestBB,
463 bool isPreheader) {
464 // Do not delete loop preheaders if doing so would create a critical edge.
465 // Loop preheaders can be good locations to spill registers. If the
466 // preheader is deleted and we create a critical edge, registers may be
467 // spilled in the loop body instead.
468 if (!DisablePreheaderProtect && isPreheader &&
469 !(BB->getSinglePredecessor() &&
470 BB->getSinglePredecessor()->getSingleSuccessor()))
471 return false;
472
473 // Try to skip merging if the unique predecessor of BB is terminated by a
474 // switch or indirect branch instruction, and BB is used as an incoming block
475 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
476 // add COPY instructions in the predecessor of BB instead of BB (if it is not
477 // merged). Note that the critical edge created by merging such blocks wont be
478 // split in MachineSink because the jump table is not analyzable. By keeping
479 // such empty block (BB), ISel will place COPY instructions in BB, not in the
480 // predecessor of BB.
481 BasicBlock *Pred = BB->getUniquePredecessor();
482 if (!Pred ||
483 !(isa<SwitchInst>(Pred->getTerminator()) ||
484 isa<IndirectBrInst>(Pred->getTerminator())))
485 return true;
486
487 if (BB->getTerminator() != BB->getFirstNonPHI())
488 return true;
489
490 // We use a simple cost heuristic which determine skipping merging is
491 // profitable if the cost of skipping merging is less than the cost of
492 // merging : Cost(skipping merging) < Cost(merging BB), where the
493 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
494 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
495 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
496 // Freq(Pred) / Freq(BB) > 2.
497 // Note that if there are multiple empty blocks sharing the same incoming
498 // value for the PHIs in the DestBB, we consider them together. In such
499 // case, Cost(merging BB) will be the sum of their frequencies.
500
501 if (!isa<PHINode>(DestBB->begin()))
502 return true;
503
504 if (!BFI) {
505 BPI.reset(new BranchProbabilityInfo(*BB->getParent(), *LI));
506 BFI.reset(new BlockFrequencyInfo(*BB->getParent(), *BPI, *LI));
507 }
508
509 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
510 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
511 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
512
513 // Find all other incoming blocks from which incoming values of all PHIs in
514 // DestBB are the same as the ones from BB.
515 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
516 ++PI) {
517 BasicBlock *DestBBPred = *PI;
518 if (DestBBPred == BB)
519 continue;
520
521 bool HasAllSameValue = true;
522 BasicBlock::const_iterator DestBBI = DestBB->begin();
523 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
524 if (DestPN->getIncomingValueForBlock(BB) !=
525 DestPN->getIncomingValueForBlock(DestBBPred)) {
526 HasAllSameValue = false;
527 break;
528 }
529 }
530 if (HasAllSameValue)
531 SameIncomingValueBBs.insert(DestBBPred);
532 }
533
534 // See if all BB's incoming values are same as the value from Pred. In this
535 // case, no reason to skip merging because COPYs are expected to be place in
536 // Pred already.
537 if (SameIncomingValueBBs.count(Pred))
538 return true;
539
540 for (auto SameValueBB : SameIncomingValueBBs)
541 if (SameValueBB->getUniquePredecessor() == Pred &&
542 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
543 BBFreq += BFI->getBlockFreq(SameValueBB);
544
545 return PredFreq.getFrequency() <=
546 BBFreq.getFrequency() * FreqRatioToSkipMerge;
547}
548
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000549/// Return true if we can merge BB into DestBB if there is a single
550/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000551/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000552bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000553 const BasicBlock *DestBB) const {
554 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
555 // the successor. If there are more complex condition (e.g. preheaders),
556 // don't mess around with them.
557 BasicBlock::const_iterator BBI = BB->begin();
558 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000559 for (const User *U : PN->users()) {
560 const Instruction *UI = cast<Instruction>(U);
561 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000562 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000563 // If User is inside DestBB block and it is a PHINode then check
564 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000565 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000566 if (UI->getParent() == DestBB) {
567 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000568 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
569 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
570 if (Insn && Insn->getParent() == BB &&
571 Insn->getParent() != UPN->getIncomingBlock(I))
572 return false;
573 }
574 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000575 }
576 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000577
Chris Lattnerc3748562007-04-02 01:35:34 +0000578 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
579 // and DestBB may have conflicting incoming values for the block. If so, we
580 // can't merge the block.
581 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
582 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000583
Chris Lattnerc3748562007-04-02 01:35:34 +0000584 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000585 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000586 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
587 // It is faster to get preds from a PHI than with pred_iterator.
588 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
589 BBPreds.insert(BBPN->getIncomingBlock(i));
590 } else {
591 BBPreds.insert(pred_begin(BB), pred_end(BB));
592 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000593
Chris Lattnerc3748562007-04-02 01:35:34 +0000594 // Walk the preds of DestBB.
595 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
596 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
597 if (BBPreds.count(Pred)) { // Common predecessor?
598 BBI = DestBB->begin();
599 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
600 const Value *V1 = PN->getIncomingValueForBlock(Pred);
601 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000602
Chris Lattnerc3748562007-04-02 01:35:34 +0000603 // If V2 is a phi node in BB, look up what the mapped value will be.
604 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
605 if (V2PN->getParent() == BB)
606 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000607
Chris Lattnerc3748562007-04-02 01:35:34 +0000608 // If there is a conflict, bail out.
609 if (V1 != V2) return false;
610 }
611 }
612 }
613
614 return true;
615}
616
617
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000618/// Eliminate a basic block that has only phi's and an unconditional branch in
619/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000620void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000621 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
622 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000623
David Greene74e2d492010-01-05 01:27:11 +0000624 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000625
Chris Lattnerc3748562007-04-02 01:35:34 +0000626 // If the destination block has a single pred, then this is a trivial edge,
627 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000628 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000629 if (SinglePred != DestBB) {
630 // Remember if SinglePred was the entry block of the function. If so, we
631 // will need to move BB back to the entry position.
632 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000633 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000634
Chris Lattner8a172da2008-11-28 19:54:49 +0000635 if (isEntry && BB != &BB->getParent()->getEntryBlock())
636 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000637
David Greene74e2d492010-01-05 01:27:11 +0000638 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000639 return;
640 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000641 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000642
Chris Lattnerc3748562007-04-02 01:35:34 +0000643 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
644 // to handle the new incoming edges it is about to have.
645 PHINode *PN;
646 for (BasicBlock::iterator BBI = DestBB->begin();
647 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
648 // Remove the incoming value for BB, and remember it.
649 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000650
Chris Lattnerc3748562007-04-02 01:35:34 +0000651 // Two options: either the InVal is a phi node defined in BB or it is some
652 // value that dominates BB.
653 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
654 if (InValPhi && InValPhi->getParent() == BB) {
655 // Add all of the input values of the input PHI as inputs of this phi.
656 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
657 PN->addIncoming(InValPhi->getIncomingValue(i),
658 InValPhi->getIncomingBlock(i));
659 } else {
660 // Otherwise, add one instance of the dominating value for each edge that
661 // we will be adding.
662 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
663 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
664 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
665 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000666 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
667 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000668 }
669 }
670 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000671
Chris Lattnerc3748562007-04-02 01:35:34 +0000672 // The PHIs are now updated, change everything that refers to BB to use
673 // DestBB and remove BB.
674 BB->replaceAllUsesWith(DestBB);
675 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000676 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000677
David Greene74e2d492010-01-05 01:27:11 +0000678 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000679}
680
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000681// Computes a map of base pointer relocation instructions to corresponding
682// derived pointer relocation instructions given a vector of all relocate calls
683static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000684 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
685 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
686 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000687 // Collect information in two maps: one primarily for locating the base object
688 // while filling the second map; the second map is the final structure holding
689 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000690 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
691 for (auto *ThisRelocate : AllRelocateCalls) {
692 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
693 ThisRelocate->getDerivedPtrIndex());
694 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000695 }
696 for (auto &Item : RelocateIdxMap) {
697 std::pair<unsigned, unsigned> Key = Item.first;
698 if (Key.first == Key.second)
699 // Base relocation: nothing to insert
700 continue;
701
Manuel Jacob83eefa62016-01-05 04:03:00 +0000702 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000703 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000704
705 // We're iterating over RelocateIdxMap so we cannot modify it.
706 auto MaybeBase = RelocateIdxMap.find(BaseKey);
707 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000708 // TODO: We might want to insert a new base object relocate and gep off
709 // that, if there are enough derived object relocates.
710 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000711
712 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000713 }
714}
715
716// Accepts a GEP and extracts the operands into a vector provided they're all
717// small integer constants
718static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
719 SmallVectorImpl<Value *> &OffsetV) {
720 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
721 // Only accept small constant integer operands
722 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
723 if (!Op || Op->getZExtValue() > 20)
724 return false;
725 }
726
727 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
728 OffsetV.push_back(GEP->getOperand(i));
729 return true;
730}
731
732// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
733// replace, computes a replacement, and affects it.
734static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000735simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
736 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000737 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000738 for (GCRelocateInst *ToReplace : Targets) {
739 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000740 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000741 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000742 // A duplicate relocate call. TODO: coalesce duplicates.
743 continue;
744 }
745
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000746 if (RelocatedBase->getParent() != ToReplace->getParent()) {
747 // Base and derived relocates are in different basic blocks.
748 // In this case transform is only valid when base dominates derived
749 // relocate. However it would be too expensive to check dominance
750 // for each such relocate, so we skip the whole transformation.
751 continue;
752 }
753
Manuel Jacob83eefa62016-01-05 04:03:00 +0000754 Value *Base = ToReplace->getBasePtr();
755 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000756 if (!Derived || Derived->getPointerOperand() != Base)
757 continue;
758
759 SmallVector<Value *, 2> OffsetV;
760 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
761 continue;
762
763 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000764 assert(RelocatedBase->getNextNode() &&
765 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000766
767 // Insert after RelocatedBase
768 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000769 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000770
771 // If gc_relocate does not match the actual type, cast it to the right type.
772 // In theory, there must be a bitcast after gc_relocate if the type does not
773 // match, and we should reuse it to get the derived pointer. But it could be
774 // cases like this:
775 // bb1:
776 // ...
777 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
778 // br label %merge
779 //
780 // bb2:
781 // ...
782 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
783 // br label %merge
784 //
785 // merge:
786 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
787 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
788 //
789 // In this case, we can not find the bitcast any more. So we insert a new bitcast
790 // no matter there is already one or not. In this way, we can handle all cases, and
791 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000792 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000793 if (RelocatedBase->getType() != Base->getType()) {
794 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000795 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000796 }
David Blaikie68d535c2015-03-24 22:38:16 +0000797 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000798 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000799 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000800 // If the newly generated derived pointer's type does not match the original derived
801 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000802 Value *ActualReplacement = Replacement;
803 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000804 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000805 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000806 }
807 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000808 ToReplace->eraseFromParent();
809
810 MadeChange = true;
811 }
812 return MadeChange;
813}
814
815// Turns this:
816//
817// %base = ...
818// %ptr = gep %base + 15
819// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
820// %base' = relocate(%tok, i32 4, i32 4)
821// %ptr' = relocate(%tok, i32 4, i32 5)
822// %val = load %ptr'
823//
824// into this:
825//
826// %base = ...
827// %ptr = gep %base + 15
828// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
829// %base' = gc.relocate(%tok, i32 4, i32 4)
830// %ptr' = gep %base' + 15
831// %val = load %ptr'
832bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
833 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000834 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000835
836 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000837 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000838 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000839 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000840
841 // We need atleast one base pointer relocation + one derived pointer
842 // relocation to mangle
843 if (AllRelocateCalls.size() < 2)
844 return false;
845
846 // RelocateInstMap is a mapping from the base relocate instruction to the
847 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000848 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000849 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
850 if (RelocateInstMap.empty())
851 return false;
852
853 for (auto &Item : RelocateInstMap)
854 // Item.first is the RelocatedBase to offset against
855 // Item.second is the vector of Targets to replace
856 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
857 return MadeChange;
858}
859
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000860/// SinkCast - Sink the specified cast instruction into its user blocks
861static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000862 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000863
Chris Lattnerf2836d12007-03-31 04:06:36 +0000864 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000865 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000866
Chris Lattnerf2836d12007-03-31 04:06:36 +0000867 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000868 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000869 UI != E; ) {
870 Use &TheUse = UI.getUse();
871 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000872
Chris Lattnerf2836d12007-03-31 04:06:36 +0000873 // Figure out which BB this cast is used in. For PHI's this is the
874 // appropriate predecessor block.
875 BasicBlock *UserBB = User->getParent();
876 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000877 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000878 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000879
Chris Lattnerf2836d12007-03-31 04:06:36 +0000880 // Preincrement use iterator so we don't invalidate it.
881 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000882
David Majnemer0c80e2e2016-04-27 19:36:38 +0000883 // The first insertion point of a block containing an EH pad is after the
884 // pad. If the pad is the user, we cannot sink the cast past the pad.
885 if (User->isEHPad())
886 continue;
887
Andrew Kaylord0430e82015-11-23 19:16:15 +0000888 // If the block selected to receive the cast is an EH pad that does not
889 // allow non-PHI instructions before the terminator, we can't sink the
890 // cast.
891 if (UserBB->getTerminator()->isEHPad())
892 continue;
893
Chris Lattnerf2836d12007-03-31 04:06:36 +0000894 // If this user is in the same block as the cast, don't change the cast.
895 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000896
Chris Lattnerf2836d12007-03-31 04:06:36 +0000897 // If we have already inserted a cast into this block, use it.
898 CastInst *&InsertedCast = InsertedCasts[UserBB];
899
900 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000901 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000902 assert(InsertPt != UserBB->end());
903 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
904 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000905 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000906
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000907 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000908 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000909 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000910 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000911 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000912
Chris Lattnerf2836d12007-03-31 04:06:36 +0000913 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000914 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000915 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000916 MadeChange = true;
917 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000918
Chris Lattnerf2836d12007-03-31 04:06:36 +0000919 return MadeChange;
920}
921
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000922/// If the specified cast instruction is a noop copy (e.g. it's casting from
923/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
924/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000925///
926/// Return true if any changes are made.
927///
Mehdi Amini44ede332015-07-09 02:09:04 +0000928static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
929 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +0000930 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
931 // than sinking only nop casts, but is helpful on some platforms.
932 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
933 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
934 ASC->getDestAddressSpace()))
935 return false;
936 }
937
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000938 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000939 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
940 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000941
942 // This is an fp<->int conversion?
943 if (SrcVT.isInteger() != DstVT.isInteger())
944 return false;
945
946 // If this is an extension, it will be a zero or sign extension, which
947 // isn't a noop.
948 if (SrcVT.bitsLT(DstVT)) return false;
949
950 // If these values will be promoted, find out what they will be promoted
951 // to. This helps us consider truncates on PPC as noop copies when they
952 // are.
953 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
954 TargetLowering::TypePromoteInteger)
955 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
956 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
957 TargetLowering::TypePromoteInteger)
958 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
959
960 // If, after promotion, these are the same types, this is a noop copy.
961 if (SrcVT != DstVT)
962 return false;
963
964 return SinkCast(CI);
965}
966
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000967/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
968/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000969///
970/// Return true if any changes were made.
971static bool CombineUAddWithOverflow(CmpInst *CI) {
972 Value *A, *B;
973 Instruction *AddI;
974 if (!match(CI,
975 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
976 return false;
977
978 Type *Ty = AddI->getType();
979 if (!isa<IntegerType>(Ty))
980 return false;
981
982 // We don't want to move around uses of condition values this late, so we we
983 // check if it is legal to create the call to the intrinsic in the basic
984 // block containing the icmp:
985
986 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
987 return false;
988
989#ifndef NDEBUG
990 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
991 // for now:
992 if (AddI->hasOneUse())
993 assert(*AddI->user_begin() == CI && "expected!");
994#endif
995
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000996 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000997 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
998
999 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1000
1001 auto *UAddWithOverflow =
1002 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1003 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1004 auto *Overflow =
1005 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1006
1007 CI->replaceAllUsesWith(Overflow);
1008 AddI->replaceAllUsesWith(UAdd);
1009 CI->eraseFromParent();
1010 AddI->eraseFromParent();
1011 return true;
1012}
1013
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001014/// Sink the given CmpInst into user blocks to reduce the number of virtual
1015/// registers that must be created and coalesced. This is a clear win except on
1016/// targets with multiple condition code registers (PowerPC), where it might
1017/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001018///
1019/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001020static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001021 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001022
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001023 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001024 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001025 return false;
1026
1027 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001028 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001029
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001030 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001031 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001032 UI != E; ) {
1033 Use &TheUse = UI.getUse();
1034 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001035
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001036 // Preincrement use iterator so we don't invalidate it.
1037 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001038
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001039 // Don't bother for PHI nodes.
1040 if (isa<PHINode>(User))
1041 continue;
1042
1043 // Figure out which BB this cmp is used in.
1044 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001045
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001046 // If this user is in the same block as the cmp, don't change the cmp.
1047 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001048
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001049 // If we have already inserted a cmp into this block, use it.
1050 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1051
1052 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001053 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001054 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001055 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001056 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1057 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001058 // Propagate the debug info.
1059 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001060 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001061
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001062 // Replace a use of the cmp with a use of the new cmp.
1063 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001064 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001065 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001066 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001067
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001068 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001069 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001070 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001071 MadeChange = true;
1072 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001073
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001074 return MadeChange;
1075}
1076
Peter Zotovf87e5502016-04-03 17:11:53 +00001077static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001078 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001079 return true;
1080
1081 if (CombineUAddWithOverflow(CI))
1082 return true;
1083
1084 return false;
1085}
1086
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001087/// Check if the candidates could be combined with a shift instruction, which
1088/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001089/// 1. Truncate instruction
1090/// 2. And instruction and the imm is a mask of the low bits:
1091/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001092static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001093 if (!isa<TruncInst>(User)) {
1094 if (User->getOpcode() != Instruction::And ||
1095 !isa<ConstantInt>(User->getOperand(1)))
1096 return false;
1097
Quentin Colombetd4f44692014-04-22 01:20:34 +00001098 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001099
Quentin Colombetd4f44692014-04-22 01:20:34 +00001100 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001101 return false;
1102 }
1103 return true;
1104}
1105
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001106/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001107static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001108SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1109 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001110 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001111 BasicBlock *UserBB = User->getParent();
1112 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1113 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1114 bool MadeChange = false;
1115
1116 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1117 TruncE = TruncI->user_end();
1118 TruncUI != TruncE;) {
1119
1120 Use &TruncTheUse = TruncUI.getUse();
1121 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1122 // Preincrement use iterator so we don't invalidate it.
1123
1124 ++TruncUI;
1125
1126 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1127 if (!ISDOpcode)
1128 continue;
1129
Tim Northovere2239ff2014-07-29 10:20:22 +00001130 // If the use is actually a legal node, there will not be an
1131 // implicit truncate.
1132 // FIXME: always querying the result type is just an
1133 // approximation; some nodes' legality is determined by the
1134 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001135 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001136 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001137 continue;
1138
1139 // Don't bother for PHI nodes.
1140 if (isa<PHINode>(TruncUser))
1141 continue;
1142
1143 BasicBlock *TruncUserBB = TruncUser->getParent();
1144
1145 if (UserBB == TruncUserBB)
1146 continue;
1147
1148 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1149 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1150
1151 if (!InsertedShift && !InsertedTrunc) {
1152 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001153 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001154 // Sink the shift
1155 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001156 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1157 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001158 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001159 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1160 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001161
1162 // Sink the trunc
1163 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1164 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001165 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001166
1167 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001168 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001169
1170 MadeChange = true;
1171
1172 TruncTheUse = InsertedTrunc;
1173 }
1174 }
1175 return MadeChange;
1176}
1177
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001178/// Sink the shift *right* instruction into user blocks if the uses could
1179/// potentially be combined with this shift instruction and generate BitExtract
1180/// instruction. It will only be applied if the architecture supports BitExtract
1181/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001182/// BB1:
1183/// %x.extract.shift = lshr i64 %arg1, 32
1184/// BB2:
1185/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1186/// ==>
1187///
1188/// BB2:
1189/// %x.extract.shift.1 = lshr i64 %arg1, 32
1190/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1191///
1192/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1193/// instruction.
1194/// Return true if any changes are made.
1195static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001196 const TargetLowering &TLI,
1197 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001198 BasicBlock *DefBB = ShiftI->getParent();
1199
1200 /// Only insert instructions in each block once.
1201 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1202
Mehdi Amini44ede332015-07-09 02:09:04 +00001203 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001204
1205 bool MadeChange = false;
1206 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1207 UI != E;) {
1208 Use &TheUse = UI.getUse();
1209 Instruction *User = cast<Instruction>(*UI);
1210 // Preincrement use iterator so we don't invalidate it.
1211 ++UI;
1212
1213 // Don't bother for PHI nodes.
1214 if (isa<PHINode>(User))
1215 continue;
1216
1217 if (!isExtractBitsCandidateUse(User))
1218 continue;
1219
1220 BasicBlock *UserBB = User->getParent();
1221
1222 if (UserBB == DefBB) {
1223 // If the shift and truncate instruction are in the same BB. The use of
1224 // the truncate(TruncUse) may still introduce another truncate if not
1225 // legal. In this case, we would like to sink both shift and truncate
1226 // instruction to the BB of TruncUse.
1227 // for example:
1228 // BB1:
1229 // i64 shift.result = lshr i64 opnd, imm
1230 // trunc.result = trunc shift.result to i16
1231 //
1232 // BB2:
1233 // ----> We will have an implicit truncate here if the architecture does
1234 // not have i16 compare.
1235 // cmp i16 trunc.result, opnd2
1236 //
1237 if (isa<TruncInst>(User) && shiftIsLegal
1238 // If the type of the truncate is legal, no trucate will be
1239 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001240 &&
1241 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001242 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001243 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001244
1245 continue;
1246 }
1247 // If we have already inserted a shift into this block, use it.
1248 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1249
1250 if (!InsertedShift) {
1251 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001252 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001253
1254 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001255 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1256 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001257 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001258 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1259 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001260
1261 MadeChange = true;
1262 }
1263
1264 // Replace a use of the shift with a use of the new shift.
1265 TheUse = InsertedShift;
1266 }
1267
1268 // If we removed all uses, nuke the shift.
1269 if (ShiftI->use_empty())
1270 ShiftI->eraseFromParent();
1271
1272 return MadeChange;
1273}
1274
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001275// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001276// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1277// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001278// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001279// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001280//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001281// %1 = bitcast i8* %addr to i32*
1282// %2 = extractelement <16 x i1> %mask, i32 0
1283// %3 = icmp eq i1 %2, true
1284// br i1 %3, label %cond.load, label %else
1285//
1286//cond.load: ; preds = %0
1287// %4 = getelementptr i32* %1, i32 0
1288// %5 = load i32* %4
1289// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1290// br label %else
1291//
1292//else: ; preds = %0, %cond.load
1293// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1294// %7 = extractelement <16 x i1> %mask, i32 1
1295// %8 = icmp eq i1 %7, true
1296// br i1 %8, label %cond.load1, label %else2
1297//
1298//cond.load1: ; preds = %else
1299// %9 = getelementptr i32* %1, i32 1
1300// %10 = load i32* %9
1301// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1302// br label %else2
1303//
1304//else2: ; preds = %else, %cond.load1
1305// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1306// %12 = extractelement <16 x i1> %mask, i32 2
1307// %13 = icmp eq i1 %12, true
1308// br i1 %13, label %cond.load4, label %else5
1309//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001310static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001311 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001312 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001313 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001314 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001315
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001316 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1317 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001318 assert(VecType && "Unexpected return type of masked load intrinsic");
1319
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001320 Type *EltTy = CI->getType()->getVectorElementType();
1321
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001322 IRBuilder<> Builder(CI->getContext());
1323 Instruction *InsertPt = CI;
1324 BasicBlock *IfBlock = CI->getParent();
1325 BasicBlock *CondBlock = nullptr;
1326 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001327
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001328 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001329 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1330
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001331 // Short-cut if the mask is all-true.
1332 bool IsAllOnesMask = isa<Constant>(Mask) &&
1333 cast<Constant>(Mask)->isAllOnesValue();
1334
1335 if (IsAllOnesMask) {
1336 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1337 CI->replaceAllUsesWith(NewI);
1338 CI->eraseFromParent();
1339 return;
1340 }
1341
1342 // Adjust alignment for the scalar instruction.
1343 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001344 // Bitcast %addr fron i8* to EltTy*
1345 Type *NewPtrType =
1346 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1347 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001348 unsigned VectorWidth = VecType->getNumElements();
1349
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001350 Value *UndefVal = UndefValue::get(VecType);
1351
1352 // The result vector
1353 Value *VResult = UndefVal;
1354
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001355 if (isa<ConstantVector>(Mask)) {
1356 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1357 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1358 continue;
1359 Value *Gep =
1360 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1361 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1362 VResult = Builder.CreateInsertElement(VResult, Load,
1363 Builder.getInt32(Idx));
1364 }
1365 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1366 CI->replaceAllUsesWith(NewI);
1367 CI->eraseFromParent();
1368 return;
1369 }
1370
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001371 PHINode *Phi = nullptr;
1372 Value *PrevPhi = UndefVal;
1373
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001374 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1375
1376 // Fill the "else" block, created in the previous iteration
1377 //
1378 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1379 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1380 // %to_load = icmp eq i1 %mask_1, true
1381 // br i1 %to_load, label %cond.load, label %else
1382 //
1383 if (Idx > 0) {
1384 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1385 Phi->addIncoming(VResult, CondBlock);
1386 Phi->addIncoming(PrevPhi, PrevIfBlock);
1387 PrevPhi = Phi;
1388 VResult = Phi;
1389 }
1390
1391 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1392 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1393 ConstantInt::get(Predicate->getType(), 1));
1394
1395 // Create "cond" block
1396 //
1397 // %EltAddr = getelementptr i32* %1, i32 0
1398 // %Elt = load i32* %EltAddr
1399 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1400 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001401 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001402 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001403
1404 Value *Gep =
1405 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001406 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001407 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1408
1409 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001410 BasicBlock *NewIfBlock =
1411 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001412 Builder.SetInsertPoint(InsertPt);
1413 Instruction *OldBr = IfBlock->getTerminator();
1414 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1415 OldBr->eraseFromParent();
1416 PrevIfBlock = IfBlock;
1417 IfBlock = NewIfBlock;
1418 }
1419
1420 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1421 Phi->addIncoming(VResult, CondBlock);
1422 Phi->addIncoming(PrevPhi, PrevIfBlock);
1423 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1424 CI->replaceAllUsesWith(NewI);
1425 CI->eraseFromParent();
1426}
1427
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001428// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001429// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1430// <16 x i1> %mask)
1431// to a chain of basic blocks, that stores element one-by-one if
1432// the appropriate mask bit is set
1433//
1434// %1 = bitcast i8* %addr to i32*
1435// %2 = extractelement <16 x i1> %mask, i32 0
1436// %3 = icmp eq i1 %2, true
1437// br i1 %3, label %cond.store, label %else
1438//
1439// cond.store: ; preds = %0
1440// %4 = extractelement <16 x i32> %val, i32 0
1441// %5 = getelementptr i32* %1, i32 0
1442// store i32 %4, i32* %5
1443// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001444//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001445// else: ; preds = %0, %cond.store
1446// %6 = extractelement <16 x i1> %mask, i32 1
1447// %7 = icmp eq i1 %6, true
1448// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001449//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001450// cond.store1: ; preds = %else
1451// %8 = extractelement <16 x i32> %val, i32 1
1452// %9 = getelementptr i32* %1, i32 1
1453// store i32 %8, i32* %9
1454// br label %else2
1455// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001456static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001457 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001458 Value *Ptr = CI->getArgOperand(1);
1459 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001460 Value *Mask = CI->getArgOperand(3);
1461
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001462 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001463 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001464 assert(VecType && "Unexpected data type in masked store intrinsic");
1465
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001466 Type *EltTy = VecType->getElementType();
1467
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001468 IRBuilder<> Builder(CI->getContext());
1469 Instruction *InsertPt = CI;
1470 BasicBlock *IfBlock = CI->getParent();
1471 Builder.SetInsertPoint(InsertPt);
1472 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1473
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001474 // Short-cut if the mask is all-true.
1475 bool IsAllOnesMask = isa<Constant>(Mask) &&
1476 cast<Constant>(Mask)->isAllOnesValue();
1477
1478 if (IsAllOnesMask) {
1479 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1480 CI->eraseFromParent();
1481 return;
1482 }
1483
1484 // Adjust alignment for the scalar instruction.
1485 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001486 // Bitcast %addr fron i8* to EltTy*
1487 Type *NewPtrType =
1488 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1489 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001490 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001491
1492 if (isa<ConstantVector>(Mask)) {
1493 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1494 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1495 continue;
1496 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1497 Value *Gep =
1498 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1499 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1500 }
1501 CI->eraseFromParent();
1502 return;
1503 }
1504
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001505 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1506
1507 // Fill the "else" block, created in the previous iteration
1508 //
1509 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1510 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001511 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001512 //
1513 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1514 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1515 ConstantInt::get(Predicate->getType(), 1));
1516
1517 // Create "cond" block
1518 //
1519 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1520 // %EltAddr = getelementptr i32* %1, i32 0
1521 // %store i32 %OneElt, i32* %EltAddr
1522 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001523 BasicBlock *CondBlock =
1524 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001525 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001526
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001527 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001528 Value *Gep =
1529 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001530 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001531
1532 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001533 BasicBlock *NewIfBlock =
1534 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001535 Builder.SetInsertPoint(InsertPt);
1536 Instruction *OldBr = IfBlock->getTerminator();
1537 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1538 OldBr->eraseFromParent();
1539 IfBlock = NewIfBlock;
1540 }
1541 CI->eraseFromParent();
1542}
1543
Elena Demikhovsky09285852015-10-25 15:37:55 +00001544// Translate a masked gather intrinsic like
1545// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1546// <16 x i1> %Mask, <16 x i32> %Src)
1547// to a chain of basic blocks, with loading element one-by-one if
1548// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001549//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001550// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1551// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1552// % ToLoad0 = icmp eq i1 % Mask0, true
1553// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001554//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001555// cond.load:
1556// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1557// % Load0 = load i32, i32* % Ptr0, align 4
1558// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1559// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001560//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001561// else:
1562// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1563// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1564// % ToLoad1 = icmp eq i1 % Mask1, true
1565// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001566//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001567// cond.load1:
1568// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1569// % Load1 = load i32, i32* % Ptr1, align 4
1570// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1571// br label %else2
1572// . . .
1573// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1574// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001575static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001576 Value *Ptrs = CI->getArgOperand(0);
1577 Value *Alignment = CI->getArgOperand(1);
1578 Value *Mask = CI->getArgOperand(2);
1579 Value *Src0 = CI->getArgOperand(3);
1580
1581 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1582
1583 assert(VecType && "Unexpected return type of masked load intrinsic");
1584
1585 IRBuilder<> Builder(CI->getContext());
1586 Instruction *InsertPt = CI;
1587 BasicBlock *IfBlock = CI->getParent();
1588 BasicBlock *CondBlock = nullptr;
1589 BasicBlock *PrevIfBlock = CI->getParent();
1590 Builder.SetInsertPoint(InsertPt);
1591 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1592
1593 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1594
1595 Value *UndefVal = UndefValue::get(VecType);
1596
1597 // The result vector
1598 Value *VResult = UndefVal;
1599 unsigned VectorWidth = VecType->getNumElements();
1600
1601 // Shorten the way if the mask is a vector of constants.
1602 bool IsConstMask = isa<ConstantVector>(Mask);
1603
1604 if (IsConstMask) {
1605 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1606 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1607 continue;
1608 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1609 "Ptr" + Twine(Idx));
1610 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1611 "Load" + Twine(Idx));
1612 VResult = Builder.CreateInsertElement(VResult, Load,
1613 Builder.getInt32(Idx),
1614 "Res" + Twine(Idx));
1615 }
1616 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1617 CI->replaceAllUsesWith(NewI);
1618 CI->eraseFromParent();
1619 return;
1620 }
1621
1622 PHINode *Phi = nullptr;
1623 Value *PrevPhi = UndefVal;
1624
1625 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1626
1627 // Fill the "else" block, created in the previous iteration
1628 //
1629 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1630 // %ToLoad1 = icmp eq i1 %Mask1, true
1631 // br i1 %ToLoad1, label %cond.load, label %else
1632 //
1633 if (Idx > 0) {
1634 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1635 Phi->addIncoming(VResult, CondBlock);
1636 Phi->addIncoming(PrevPhi, PrevIfBlock);
1637 PrevPhi = Phi;
1638 VResult = Phi;
1639 }
1640
1641 Value *Predicate = Builder.CreateExtractElement(Mask,
1642 Builder.getInt32(Idx),
1643 "Mask" + Twine(Idx));
1644 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1645 ConstantInt::get(Predicate->getType(), 1),
1646 "ToLoad" + Twine(Idx));
1647
1648 // Create "cond" block
1649 //
1650 // %EltAddr = getelementptr i32* %1, i32 0
1651 // %Elt = load i32* %EltAddr
1652 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1653 //
1654 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1655 Builder.SetInsertPoint(InsertPt);
1656
1657 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1658 "Ptr" + Twine(Idx));
1659 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1660 "Load" + Twine(Idx));
1661 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1662 "Res" + Twine(Idx));
1663
1664 // Create "else" block, fill it in the next iteration
1665 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1666 Builder.SetInsertPoint(InsertPt);
1667 Instruction *OldBr = IfBlock->getTerminator();
1668 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1669 OldBr->eraseFromParent();
1670 PrevIfBlock = IfBlock;
1671 IfBlock = NewIfBlock;
1672 }
1673
1674 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1675 Phi->addIncoming(VResult, CondBlock);
1676 Phi->addIncoming(PrevPhi, PrevIfBlock);
1677 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1678 CI->replaceAllUsesWith(NewI);
1679 CI->eraseFromParent();
1680}
1681
1682// Translate a masked scatter intrinsic, like
1683// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1684// <16 x i1> %Mask)
1685// to a chain of basic blocks, that stores element one-by-one if
1686// the appropriate mask bit is set.
1687//
1688// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1689// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1690// % ToStore0 = icmp eq i1 % Mask0, true
1691// br i1 %ToStore0, label %cond.store, label %else
1692//
1693// cond.store:
1694// % Elt0 = extractelement <16 x i32> %Src, i32 0
1695// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1696// store i32 %Elt0, i32* % Ptr0, align 4
1697// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001698//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001699// else:
1700// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1701// % ToStore1 = icmp eq i1 % Mask1, true
1702// br i1 % ToStore1, label %cond.store1, label %else2
1703//
1704// cond.store1:
1705// % Elt1 = extractelement <16 x i32> %Src, i32 1
1706// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1707// store i32 % Elt1, i32* % Ptr1, align 4
1708// br label %else2
1709// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001710static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001711 Value *Src = CI->getArgOperand(0);
1712 Value *Ptrs = CI->getArgOperand(1);
1713 Value *Alignment = CI->getArgOperand(2);
1714 Value *Mask = CI->getArgOperand(3);
1715
1716 assert(isa<VectorType>(Src->getType()) &&
1717 "Unexpected data type in masked scatter intrinsic");
1718 assert(isa<VectorType>(Ptrs->getType()) &&
1719 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1720 "Vector of pointers is expected in masked scatter intrinsic");
1721
1722 IRBuilder<> Builder(CI->getContext());
1723 Instruction *InsertPt = CI;
1724 BasicBlock *IfBlock = CI->getParent();
1725 Builder.SetInsertPoint(InsertPt);
1726 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1727
1728 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1729 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1730
1731 // Shorten the way if the mask is a vector of constants.
1732 bool IsConstMask = isa<ConstantVector>(Mask);
1733
1734 if (IsConstMask) {
1735 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1736 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1737 continue;
1738 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1739 "Elt" + Twine(Idx));
1740 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1741 "Ptr" + Twine(Idx));
1742 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1743 }
1744 CI->eraseFromParent();
1745 return;
1746 }
1747 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1748 // Fill the "else" block, created in the previous iteration
1749 //
1750 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1751 // % ToStore = icmp eq i1 % Mask1, true
1752 // br i1 % ToStore, label %cond.store, label %else
1753 //
1754 Value *Predicate = Builder.CreateExtractElement(Mask,
1755 Builder.getInt32(Idx),
1756 "Mask" + Twine(Idx));
1757 Value *Cmp =
1758 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1759 ConstantInt::get(Predicate->getType(), 1),
1760 "ToStore" + Twine(Idx));
1761
1762 // Create "cond" block
1763 //
1764 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1765 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1766 // %store i32 % Elt1, i32* % Ptr1
1767 //
1768 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1769 Builder.SetInsertPoint(InsertPt);
1770
1771 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1772 "Elt" + Twine(Idx));
1773 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1774 "Ptr" + Twine(Idx));
1775 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1776
1777 // Create "else" block, fill it in the next iteration
1778 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1779 Builder.SetInsertPoint(InsertPt);
1780 Instruction *OldBr = IfBlock->getTerminator();
1781 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1782 OldBr->eraseFromParent();
1783 IfBlock = NewIfBlock;
1784 }
1785 CI->eraseFromParent();
1786}
1787
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001788/// If counting leading or trailing zeros is an expensive operation and a zero
1789/// input is defined, add a check for zero to avoid calling the intrinsic.
1790///
1791/// We want to transform:
1792/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1793///
1794/// into:
1795/// entry:
1796/// %cmpz = icmp eq i64 %A, 0
1797/// br i1 %cmpz, label %cond.end, label %cond.false
1798/// cond.false:
1799/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1800/// br label %cond.end
1801/// cond.end:
1802/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1803///
1804/// If the transform is performed, return true and set ModifiedDT to true.
1805static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1806 const TargetLowering *TLI,
1807 const DataLayout *DL,
1808 bool &ModifiedDT) {
1809 if (!TLI || !DL)
1810 return false;
1811
1812 // If a zero input is undefined, it doesn't make sense to despeculate that.
1813 if (match(CountZeros->getOperand(1), m_One()))
1814 return false;
1815
1816 // If it's cheap to speculate, there's nothing to do.
1817 auto IntrinsicID = CountZeros->getIntrinsicID();
1818 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1819 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1820 return false;
1821
1822 // Only handle legal scalar cases. Anything else requires too much work.
1823 Type *Ty = CountZeros->getType();
1824 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001825 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001826 return false;
1827
1828 // The intrinsic will be sunk behind a compare against zero and branch.
1829 BasicBlock *StartBlock = CountZeros->getParent();
1830 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1831
1832 // Create another block after the count zero intrinsic. A PHI will be added
1833 // in this block to select the result of the intrinsic or the bit-width
1834 // constant if the input to the intrinsic is zero.
1835 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1836 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1837
1838 // Set up a builder to create a compare, conditional branch, and PHI.
1839 IRBuilder<> Builder(CountZeros->getContext());
1840 Builder.SetInsertPoint(StartBlock->getTerminator());
1841 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1842
1843 // Replace the unconditional branch that was created by the first split with
1844 // a compare against zero and a conditional branch.
1845 Value *Zero = Constant::getNullValue(Ty);
1846 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1847 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1848 StartBlock->getTerminator()->eraseFromParent();
1849
1850 // Create a PHI in the end block to select either the output of the intrinsic
1851 // or the bit width of the operand.
1852 Builder.SetInsertPoint(&EndBlock->front());
1853 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1854 CountZeros->replaceAllUsesWith(PN);
1855 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1856 PN->addIncoming(BitWidth, StartBlock);
1857 PN->addIncoming(CountZeros, CallBlock);
1858
1859 // We are explicitly handling the zero case, so we can set the intrinsic's
1860 // undefined zero argument to 'true'. This will also prevent reprocessing the
1861 // intrinsic; we only despeculate when a zero input is defined.
1862 CountZeros->setArgOperand(1, Builder.getTrue());
1863 ModifiedDT = true;
1864 return true;
1865}
1866
Sanjay Patelfc580a62015-09-21 23:03:16 +00001867bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001868 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001869
Chris Lattner7a277142011-01-15 07:14:54 +00001870 // Lower inline assembly if we can.
1871 // If we found an inline asm expession, and if the target knows how to
1872 // lower it to normal LLVM code, do so now.
1873 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1874 if (TLI->ExpandInlineAsm(CI)) {
1875 // Avoid invalidating the iterator.
1876 CurInstIterator = BB->begin();
1877 // Avoid processing instructions out of order, which could cause
1878 // reuse before a value is defined.
1879 SunkAddrs.clear();
1880 return true;
1881 }
1882 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001883 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001884 return true;
1885 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001886
John Brawn0dbcd652015-03-18 12:01:59 +00001887 // Align the pointer arguments to this call if the target thinks it's a good
1888 // idea
1889 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001890 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001891 for (auto &Arg : CI->arg_operands()) {
1892 // We want to align both objects whose address is used directly and
1893 // objects whose address is used in casts and GEPs, though it only makes
1894 // sense for GEPs if the offset is a multiple of the desired alignment and
1895 // if size - offset meets the size threshold.
1896 if (!Arg->getType()->isPointerTy())
1897 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001898 APInt Offset(DL->getPointerSizeInBits(
1899 cast<PointerType>(Arg->getType())->getAddressSpace()),
1900 0);
1901 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001902 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001903 if ((Offset2 & (PrefAlign-1)) != 0)
1904 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001905 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001906 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1907 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001908 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001909 // Global variables can only be aligned if they are defined in this
1910 // object (i.e. they are uniquely initialized in this object), and
1911 // over-aligning global variables that have an explicit section is
1912 // forbidden.
1913 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001914 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001915 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001916 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001917 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001918 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001919 }
1920 // If this is a memcpy (or similar) then we may be able to improve the
1921 // alignment
1922 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001923 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001924 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001925 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001926 if (Align > MI->getAlignment())
1927 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001928 }
1929 }
1930
Philip Reamesac115ed2016-03-09 23:13:12 +00001931 // If we have a cold call site, try to sink addressing computation into the
1932 // cold block. This interacts with our handling for loads and stores to
1933 // ensure that we can fold all uses of a potential addressing computation
1934 // into their uses. TODO: generalize this to work over profiling data
1935 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1936 for (auto &Arg : CI->arg_operands()) {
1937 if (!Arg->getType()->isPointerTy())
1938 continue;
1939 unsigned AS = Arg->getType()->getPointerAddressSpace();
1940 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1941 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001942
Eric Christopher4b7948e2010-03-11 02:41:03 +00001943 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001944 if (II) {
1945 switch (II->getIntrinsicID()) {
1946 default: break;
1947 case Intrinsic::objectsize: {
1948 // Lower all uses of llvm.objectsize.*
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001949 uint64_t Size;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001950 Type *ReturnTy = CI->getType();
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001951 Constant *RetVal = nullptr;
1952 ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1));
1953 ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min;
1954 if (getObjectSize(II->getArgOperand(0),
1955 Size, *DL, TLInfo, false, Mode)) {
1956 RetVal = ConstantInt::get(ReturnTy, Size);
1957 } else {
1958 RetVal = ConstantInt::get(ReturnTy,
1959 Mode == ObjSizeMode::Min ? 0 : -1ULL);
1960 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001961 // Substituting this can cause recursive simplifications, which can
1962 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1963 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001964 Value *CurValue = &*CurInstIterator;
1965 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001966
Sanjay Patel545a4562016-01-20 18:59:16 +00001967 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001968
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001969 // If the iterator instruction was recursively deleted, start over at the
1970 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001971 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001972 CurInstIterator = BB->begin();
1973 SunkAddrs.clear();
1974 }
1975 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001976 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001977 case Intrinsic::masked_load: {
1978 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001979 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001980 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001981 ModifiedDT = true;
1982 return true;
1983 }
1984 return false;
1985 }
1986 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001987 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001988 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001989 ModifiedDT = true;
1990 return true;
1991 }
1992 return false;
1993 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001994 case Intrinsic::masked_gather: {
1995 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001996 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001997 ModifiedDT = true;
1998 return true;
1999 }
2000 return false;
2001 }
2002 case Intrinsic::masked_scatter: {
2003 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002004 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002005 ModifiedDT = true;
2006 return true;
2007 }
2008 return false;
2009 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002010 case Intrinsic::aarch64_stlxr:
2011 case Intrinsic::aarch64_stxr: {
2012 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2013 if (!ExtVal || !ExtVal->hasOneUse() ||
2014 ExtVal->getParent() == CI->getParent())
2015 return false;
2016 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2017 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002018 // Mark this instruction as "inserted by CGP", so that other
2019 // optimizations don't touch it.
2020 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002021 return true;
2022 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002023 case Intrinsic::invariant_group_barrier:
2024 II->replaceAllUsesWith(II->getArgOperand(0));
2025 II->eraseFromParent();
2026 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002027
2028 case Intrinsic::cttz:
2029 case Intrinsic::ctlz:
2030 // If counting zeros is expensive, try to avoid it.
2031 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002032 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002033
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002034 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002035 // Unknown address space.
2036 // TODO: Target hook to pick which address space the intrinsic cares
2037 // about?
2038 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002039 SmallVector<Value*, 2> PtrOps;
2040 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002041 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002042 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00002043 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002044 return true;
2045 }
Pete Cooper615fd892012-03-13 20:59:56 +00002046 }
2047
Eric Christopher4b7948e2010-03-11 02:41:03 +00002048 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002049 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002050
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002051 // Lower all default uses of _chk calls. This is very similar
2052 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002053 // to fortified library functions (e.g. __memcpy_chk) that have the default
2054 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002055 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002056 if (Value *V = Simplifier.optimizeCall(CI)) {
2057 CI->replaceAllUsesWith(V);
2058 CI->eraseFromParent();
2059 return true;
2060 }
2061 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002062}
Chris Lattner1b93be52011-01-15 07:25:29 +00002063
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002064/// Look for opportunities to duplicate return instructions to the predecessor
2065/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002066/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002067/// bb0:
2068/// %tmp0 = tail call i32 @f0()
2069/// br label %return
2070/// bb1:
2071/// %tmp1 = tail call i32 @f1()
2072/// br label %return
2073/// bb2:
2074/// %tmp2 = tail call i32 @f2()
2075/// br label %return
2076/// return:
2077/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2078/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002079/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002080///
2081/// =>
2082///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002083/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002084/// bb0:
2085/// %tmp0 = tail call i32 @f0()
2086/// ret i32 %tmp0
2087/// bb1:
2088/// %tmp1 = tail call i32 @f1()
2089/// ret i32 %tmp1
2090/// bb2:
2091/// %tmp2 = tail call i32 @f2()
2092/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002093/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002094bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002095 if (!TLI)
2096 return false;
2097
Michael Kuperstein71321562016-09-07 20:29:49 +00002098 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2099 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002100 return false;
2101
Craig Topperc0196b12014-04-14 00:51:57 +00002102 PHINode *PN = nullptr;
2103 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002104 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002105 if (V) {
2106 BCI = dyn_cast<BitCastInst>(V);
2107 if (BCI)
2108 V = BCI->getOperand(0);
2109
2110 PN = dyn_cast<PHINode>(V);
2111 if (!PN)
2112 return false;
2113 }
Evan Cheng0663f232011-03-21 01:19:09 +00002114
Cameron Zwarich4649f172011-03-24 04:52:10 +00002115 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002116 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002117
Cameron Zwarich4649f172011-03-24 04:52:10 +00002118 // Make sure there are no instructions between the PHI and return, or that the
2119 // return is the first instruction in the block.
2120 if (PN) {
2121 BasicBlock::iterator BI = BB->begin();
2122 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002123 if (&*BI == BCI)
2124 // Also skip over the bitcast.
2125 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002126 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002127 return false;
2128 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002129 BasicBlock::iterator BI = BB->begin();
2130 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002131 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002132 return false;
2133 }
Evan Cheng0663f232011-03-21 01:19:09 +00002134
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002135 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2136 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002137 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002138 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002139 if (PN) {
2140 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2141 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2142 // Make sure the phi value is indeed produced by the tail call.
2143 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002144 TLI->mayBeEmittedAsTailCall(CI) &&
2145 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002146 TailCalls.push_back(CI);
2147 }
2148 } else {
2149 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002150 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002151 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002152 continue;
2153
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002154 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002155 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2156 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002157 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2158 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002159 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002160
Cameron Zwarich4649f172011-03-24 04:52:10 +00002161 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002162 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2163 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002164 TailCalls.push_back(CI);
2165 }
Evan Cheng0663f232011-03-21 01:19:09 +00002166 }
2167
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002168 bool Changed = false;
2169 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2170 CallInst *CI = TailCalls[i];
2171 CallSite CS(CI);
2172
2173 // Conservatively require the attributes of the call to match those of the
2174 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002175 AttributeSet CalleeAttrs = CS.getAttributes();
2176 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002177 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002178 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002179 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002180 continue;
2181
2182 // Make sure the call instruction is followed by an unconditional branch to
2183 // the return block.
2184 BasicBlock *CallBB = CI->getParent();
2185 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2186 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2187 continue;
2188
2189 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002190 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002191 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002192 ++NumRetsDup;
2193 }
2194
2195 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002196 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002197 BB->eraseFromParent();
2198
2199 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002200}
2201
Chris Lattner728f9022008-11-25 07:09:13 +00002202//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002203// Memory Optimization
2204//===----------------------------------------------------------------------===//
2205
Chandler Carruthc8925912013-01-05 02:09:22 +00002206namespace {
2207
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002208/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002209/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002210struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002211 Value *BaseReg;
2212 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002213 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002214 void print(raw_ostream &OS) const;
2215 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002216
Chandler Carruthc8925912013-01-05 02:09:22 +00002217 bool operator==(const ExtAddrMode& O) const {
2218 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2219 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2220 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2221 }
2222};
2223
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002224#ifndef NDEBUG
2225static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2226 AM.print(OS);
2227 return OS;
2228}
2229#endif
2230
Chandler Carruthc8925912013-01-05 02:09:22 +00002231void ExtAddrMode::print(raw_ostream &OS) const {
2232 bool NeedPlus = false;
2233 OS << "[";
2234 if (BaseGV) {
2235 OS << (NeedPlus ? " + " : "")
2236 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002237 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002238 NeedPlus = true;
2239 }
2240
Richard Trieuc0f91212014-05-30 03:15:17 +00002241 if (BaseOffs) {
2242 OS << (NeedPlus ? " + " : "")
2243 << BaseOffs;
2244 NeedPlus = true;
2245 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002246
2247 if (BaseReg) {
2248 OS << (NeedPlus ? " + " : "")
2249 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002250 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002251 NeedPlus = true;
2252 }
2253 if (Scale) {
2254 OS << (NeedPlus ? " + " : "")
2255 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002256 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002257 }
2258
2259 OS << ']';
2260}
2261
2262#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002263LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002264 print(dbgs());
2265 dbgs() << '\n';
2266}
2267#endif
2268
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002269/// \brief This class provides transaction based operation on the IR.
2270/// Every change made through this class is recorded in the internal state and
2271/// can be undone (rollback) until commit is called.
2272class TypePromotionTransaction {
2273
2274 /// \brief This represents the common interface of the individual transaction.
2275 /// Each class implements the logic for doing one specific modification on
2276 /// the IR via the TypePromotionTransaction.
2277 class TypePromotionAction {
2278 protected:
2279 /// The Instruction modified.
2280 Instruction *Inst;
2281
2282 public:
2283 /// \brief Constructor of the action.
2284 /// The constructor performs the related action on the IR.
2285 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2286
2287 virtual ~TypePromotionAction() {}
2288
2289 /// \brief Undo the modification done by this action.
2290 /// When this method is called, the IR must be in the same state as it was
2291 /// before this action was applied.
2292 /// \pre Undoing the action works if and only if the IR is in the exact same
2293 /// state as it was directly after this action was applied.
2294 virtual void undo() = 0;
2295
2296 /// \brief Advocate every change made by this action.
2297 /// When the results on the IR of the action are to be kept, it is important
2298 /// to call this function, otherwise hidden information may be kept forever.
2299 virtual void commit() {
2300 // Nothing to be done, this action is not doing anything.
2301 }
2302 };
2303
2304 /// \brief Utility to remember the position of an instruction.
2305 class InsertionHandler {
2306 /// Position of an instruction.
2307 /// Either an instruction:
2308 /// - Is the first in a basic block: BB is used.
2309 /// - Has a previous instructon: PrevInst is used.
2310 union {
2311 Instruction *PrevInst;
2312 BasicBlock *BB;
2313 } Point;
2314 /// Remember whether or not the instruction had a previous instruction.
2315 bool HasPrevInstruction;
2316
2317 public:
2318 /// \brief Record the position of \p Inst.
2319 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002320 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002321 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2322 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002323 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002324 else
2325 Point.BB = Inst->getParent();
2326 }
2327
2328 /// \brief Insert \p Inst at the recorded position.
2329 void insert(Instruction *Inst) {
2330 if (HasPrevInstruction) {
2331 if (Inst->getParent())
2332 Inst->removeFromParent();
2333 Inst->insertAfter(Point.PrevInst);
2334 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002335 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002336 if (Inst->getParent())
2337 Inst->moveBefore(Position);
2338 else
2339 Inst->insertBefore(Position);
2340 }
2341 }
2342 };
2343
2344 /// \brief Move an instruction before another.
2345 class InstructionMoveBefore : public TypePromotionAction {
2346 /// Original position of the instruction.
2347 InsertionHandler Position;
2348
2349 public:
2350 /// \brief Move \p Inst before \p Before.
2351 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2352 : TypePromotionAction(Inst), Position(Inst) {
2353 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2354 Inst->moveBefore(Before);
2355 }
2356
2357 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002358 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002359 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2360 Position.insert(Inst);
2361 }
2362 };
2363
2364 /// \brief Set the operand of an instruction with a new value.
2365 class OperandSetter : public TypePromotionAction {
2366 /// Original operand of the instruction.
2367 Value *Origin;
2368 /// Index of the modified instruction.
2369 unsigned Idx;
2370
2371 public:
2372 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2373 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2374 : TypePromotionAction(Inst), Idx(Idx) {
2375 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2376 << "for:" << *Inst << "\n"
2377 << "with:" << *NewVal << "\n");
2378 Origin = Inst->getOperand(Idx);
2379 Inst->setOperand(Idx, NewVal);
2380 }
2381
2382 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002383 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002384 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2385 << "for: " << *Inst << "\n"
2386 << "with: " << *Origin << "\n");
2387 Inst->setOperand(Idx, Origin);
2388 }
2389 };
2390
2391 /// \brief Hide the operands of an instruction.
2392 /// Do as if this instruction was not using any of its operands.
2393 class OperandsHider : public TypePromotionAction {
2394 /// The list of original operands.
2395 SmallVector<Value *, 4> OriginalValues;
2396
2397 public:
2398 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2399 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2400 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2401 unsigned NumOpnds = Inst->getNumOperands();
2402 OriginalValues.reserve(NumOpnds);
2403 for (unsigned It = 0; It < NumOpnds; ++It) {
2404 // Save the current operand.
2405 Value *Val = Inst->getOperand(It);
2406 OriginalValues.push_back(Val);
2407 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002408 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002409 // that we are not willing to pay.
2410 Inst->setOperand(It, UndefValue::get(Val->getType()));
2411 }
2412 }
2413
2414 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002415 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002416 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2417 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2418 Inst->setOperand(It, OriginalValues[It]);
2419 }
2420 };
2421
2422 /// \brief Build a truncate instruction.
2423 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002424 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002425 public:
2426 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2427 /// result.
2428 /// trunc Opnd to Ty.
2429 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2430 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002431 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2432 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433 }
2434
Quentin Colombetac55b152014-09-16 22:36:07 +00002435 /// \brief Get the built value.
2436 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002437
2438 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002439 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002440 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2441 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2442 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443 }
2444 };
2445
2446 /// \brief Build a sign extension instruction.
2447 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002448 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002449 public:
2450 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2451 /// result.
2452 /// sext Opnd to Ty.
2453 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002454 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002456 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2457 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002458 }
2459
Quentin Colombetac55b152014-09-16 22:36:07 +00002460 /// \brief Get the built value.
2461 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002462
2463 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002464 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002465 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2466 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2467 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002468 }
2469 };
2470
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002471 /// \brief Build a zero extension instruction.
2472 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002473 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002474 public:
2475 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2476 /// result.
2477 /// zext Opnd to Ty.
2478 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002479 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002480 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002481 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2482 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002483 }
2484
Quentin Colombetac55b152014-09-16 22:36:07 +00002485 /// \brief Get the built value.
2486 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002487
2488 /// \brief Remove the built instruction.
2489 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002490 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2491 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2492 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002493 }
2494 };
2495
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002496 /// \brief Mutate an instruction to another type.
2497 class TypeMutator : public TypePromotionAction {
2498 /// Record the original type.
2499 Type *OrigTy;
2500
2501 public:
2502 /// \brief Mutate the type of \p Inst into \p NewTy.
2503 TypeMutator(Instruction *Inst, Type *NewTy)
2504 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2505 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2506 << "\n");
2507 Inst->mutateType(NewTy);
2508 }
2509
2510 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002511 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002512 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2513 << "\n");
2514 Inst->mutateType(OrigTy);
2515 }
2516 };
2517
2518 /// \brief Replace the uses of an instruction by another instruction.
2519 class UsesReplacer : public TypePromotionAction {
2520 /// Helper structure to keep track of the replaced uses.
2521 struct InstructionAndIdx {
2522 /// The instruction using the instruction.
2523 Instruction *Inst;
2524 /// The index where this instruction is used for Inst.
2525 unsigned Idx;
2526 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2527 : Inst(Inst), Idx(Idx) {}
2528 };
2529
2530 /// Keep track of the original uses (pair Instruction, Index).
2531 SmallVector<InstructionAndIdx, 4> OriginalUses;
2532 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2533
2534 public:
2535 /// \brief Replace all the use of \p Inst by \p New.
2536 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2537 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2538 << "\n");
2539 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002540 for (Use &U : Inst->uses()) {
2541 Instruction *UserI = cast<Instruction>(U.getUser());
2542 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002543 }
2544 // Now, we can replace the uses.
2545 Inst->replaceAllUsesWith(New);
2546 }
2547
2548 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002549 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002550 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2551 for (use_iterator UseIt = OriginalUses.begin(),
2552 EndIt = OriginalUses.end();
2553 UseIt != EndIt; ++UseIt) {
2554 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2555 }
2556 }
2557 };
2558
2559 /// \brief Remove an instruction from the IR.
2560 class InstructionRemover : public TypePromotionAction {
2561 /// Original position of the instruction.
2562 InsertionHandler Inserter;
2563 /// Helper structure to hide all the link to the instruction. In other
2564 /// words, this helps to do as if the instruction was removed.
2565 OperandsHider Hider;
2566 /// Keep track of the uses replaced, if any.
2567 UsesReplacer *Replacer;
2568
2569 public:
2570 /// \brief Remove all reference of \p Inst and optinally replace all its
2571 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002572 /// \pre If !Inst->use_empty(), then New != nullptr
2573 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002574 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002575 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002576 if (New)
2577 Replacer = new UsesReplacer(Inst, New);
2578 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2579 Inst->removeFromParent();
2580 }
2581
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002582 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002583
2584 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002585 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002586
2587 /// \brief Resurrect the instruction and reassign it to the proper uses if
2588 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002589 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002590 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2591 Inserter.insert(Inst);
2592 if (Replacer)
2593 Replacer->undo();
2594 Hider.undo();
2595 }
2596 };
2597
2598public:
2599 /// Restoration point.
2600 /// The restoration point is a pointer to an action instead of an iterator
2601 /// because the iterator may be invalidated but not the pointer.
2602 typedef const TypePromotionAction *ConstRestorationPt;
2603 /// Advocate every changes made in that transaction.
2604 void commit();
2605 /// Undo all the changes made after the given point.
2606 void rollback(ConstRestorationPt Point);
2607 /// Get the current restoration point.
2608 ConstRestorationPt getRestorationPoint() const;
2609
2610 /// \name API for IR modification with state keeping to support rollback.
2611 /// @{
2612 /// Same as Instruction::setOperand.
2613 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2614 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002615 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002616 /// Same as Value::replaceAllUsesWith.
2617 void replaceAllUsesWith(Instruction *Inst, Value *New);
2618 /// Same as Value::mutateType.
2619 void mutateType(Instruction *Inst, Type *NewTy);
2620 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002621 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002622 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002623 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002624 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002625 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002626 /// Same as Instruction::moveBefore.
2627 void moveBefore(Instruction *Inst, Instruction *Before);
2628 /// @}
2629
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002630private:
2631 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002632 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2633 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002634};
2635
2636void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2637 Value *NewVal) {
2638 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002639 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002640}
2641
2642void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2643 Value *NewVal) {
2644 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002645 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002646}
2647
2648void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2649 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002650 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002651}
2652
2653void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002654 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002655}
2656
Quentin Colombetac55b152014-09-16 22:36:07 +00002657Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2658 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002659 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002660 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002661 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002662 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002663}
2664
Quentin Colombetac55b152014-09-16 22:36:07 +00002665Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2666 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002667 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002668 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002669 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002670 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002671}
2672
Quentin Colombetac55b152014-09-16 22:36:07 +00002673Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2674 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002675 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002676 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002677 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002678 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002679}
2680
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002681void TypePromotionTransaction::moveBefore(Instruction *Inst,
2682 Instruction *Before) {
2683 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002684 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002685}
2686
2687TypePromotionTransaction::ConstRestorationPt
2688TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002689 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002690}
2691
2692void TypePromotionTransaction::commit() {
2693 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002694 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002695 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002696 Actions.clear();
2697}
2698
2699void TypePromotionTransaction::rollback(
2700 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002701 while (!Actions.empty() && Point != Actions.back().get()) {
2702 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002703 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002704 }
2705}
2706
Chandler Carruthc8925912013-01-05 02:09:22 +00002707/// \brief A helper class for matching addressing modes.
2708///
2709/// This encapsulates the logic for matching the target-legal addressing modes.
2710class AddressingModeMatcher {
2711 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002712 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002713 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002714 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002715
2716 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2717 /// the memory instruction that we're computing this address for.
2718 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002719 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002720 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002721
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002722 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002723 /// part of the return value of this addressing mode matching stuff.
2724 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002725
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002726 /// The instructions inserted by other CodeGenPrepare optimizations.
2727 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002728 /// A map from the instructions to their type before promotion.
2729 InstrToOrigTy &PromotedInsts;
2730 /// The ongoing transaction where every action should be registered.
2731 TypePromotionTransaction &TPT;
2732
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002733 /// This is set to true when we should not do profitability checks.
2734 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002735 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002736
Eric Christopherd75c00c2015-02-26 22:38:34 +00002737 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002738 const TargetMachine &TM, Type *AT, unsigned AS,
2739 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002740 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002741 InstrToOrigTy &PromotedInsts,
2742 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002743 : AddrModeInsts(AMI), TM(TM),
2744 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2745 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002746 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2747 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2748 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002749 IgnoreProfitability = false;
2750 }
2751public:
Stephen Lin837bba12013-07-15 17:55:02 +00002752
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002753 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002754 /// give an access type of AccessTy. This returns a list of involved
2755 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002756 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002757 /// optimizations.
2758 /// \p PromotedInsts maps the instructions to their type before promotion.
2759 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002760 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002761 Instruction *MemoryInst,
2762 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002763 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002764 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002765 InstrToOrigTy &PromotedInsts,
2766 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002767 ExtAddrMode Result;
2768
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002769 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002770 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002771 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002772 (void)Success; assert(Success && "Couldn't select *anything*?");
2773 return Result;
2774 }
2775private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002776 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2777 bool matchAddr(Value *V, unsigned Depth);
2778 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002779 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002780 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002781 ExtAddrMode &AMBefore,
2782 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002783 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2784 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002785 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002786};
2787
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002788/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002789/// Return true and update AddrMode if this addr mode is legal for the target,
2790/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002791bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002792 unsigned Depth) {
2793 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2794 // mode. Just process that directly.
2795 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002796 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002797
Chandler Carruthc8925912013-01-05 02:09:22 +00002798 // If the scale is 0, it takes nothing to add this.
2799 if (Scale == 0)
2800 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002801
Chandler Carruthc8925912013-01-05 02:09:22 +00002802 // If we already have a scale of this value, we can add to it, otherwise, we
2803 // need an available scale field.
2804 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2805 return false;
2806
2807 ExtAddrMode TestAddrMode = AddrMode;
2808
2809 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2810 // [A+B + A*7] -> [B+A*8].
2811 TestAddrMode.Scale += Scale;
2812 TestAddrMode.ScaledReg = ScaleReg;
2813
2814 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002815 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002816 return false;
2817
2818 // It was legal, so commit it.
2819 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002820
Chandler Carruthc8925912013-01-05 02:09:22 +00002821 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2822 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2823 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002824 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002825 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2826 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2827 TestAddrMode.ScaledReg = AddLHS;
2828 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002829
Chandler Carruthc8925912013-01-05 02:09:22 +00002830 // If this addressing mode is legal, commit it and remember that we folded
2831 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002832 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002833 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2834 AddrMode = TestAddrMode;
2835 return true;
2836 }
2837 }
2838
2839 // Otherwise, not (x+c)*scale, just return what we have.
2840 return true;
2841}
2842
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002843/// This is a little filter, which returns true if an addressing computation
2844/// involving I might be folded into a load/store accessing it.
2845/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002846/// the set of instructions that MatchOperationAddr can.
2847static bool MightBeFoldableInst(Instruction *I) {
2848 switch (I->getOpcode()) {
2849 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002850 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002851 // Don't touch identity bitcasts.
2852 if (I->getType() == I->getOperand(0)->getType())
2853 return false;
2854 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2855 case Instruction::PtrToInt:
2856 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2857 return true;
2858 case Instruction::IntToPtr:
2859 // We know the input is intptr_t, so this is foldable.
2860 return true;
2861 case Instruction::Add:
2862 return true;
2863 case Instruction::Mul:
2864 case Instruction::Shl:
2865 // Can only handle X*C and X << C.
2866 return isa<ConstantInt>(I->getOperand(1));
2867 case Instruction::GetElementPtr:
2868 return true;
2869 default:
2870 return false;
2871 }
2872}
2873
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002874/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2875/// \note \p Val is assumed to be the product of some type promotion.
2876/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2877/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002878static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2879 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002880 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2881 if (!PromotedInst)
2882 return false;
2883 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2884 // If the ISDOpcode is undefined, it was undefined before the promotion.
2885 if (!ISDOpcode)
2886 return true;
2887 // Otherwise, check if the promoted instruction is legal or not.
2888 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002889 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002890}
2891
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002892/// \brief Hepler class to perform type promotion.
2893class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002894 /// \brief Utility function to check whether or not a sign or zero extension
2895 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2896 /// either using the operands of \p Inst or promoting \p Inst.
2897 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002898 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002899 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002900 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002901 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002902 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002903 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002904 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002905 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2906 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002907
2908 /// \brief Utility function to determine if \p OpIdx should be promoted when
2909 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002910 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002911 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002912 }
2913
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002914 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002915 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002916 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002917 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002918 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002919 /// Newly added extensions are inserted in \p Exts.
2920 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002921 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002922 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002923 static Value *promoteOperandForTruncAndAnyExt(
2924 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002925 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002926 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002927 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002928
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002929 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002930 /// operand is promotable and is not a supported trunc or sext.
2931 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002932 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002933 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002934 /// Newly added extensions are inserted in \p Exts.
2935 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002936 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002937 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002938 static Value *promoteOperandForOther(Instruction *Ext,
2939 TypePromotionTransaction &TPT,
2940 InstrToOrigTy &PromotedInsts,
2941 unsigned &CreatedInstsCost,
2942 SmallVectorImpl<Instruction *> *Exts,
2943 SmallVectorImpl<Instruction *> *Truncs,
2944 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002945
2946 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002947 static Value *signExtendOperandForOther(
2948 Instruction *Ext, TypePromotionTransaction &TPT,
2949 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2950 SmallVectorImpl<Instruction *> *Exts,
2951 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2952 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2953 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002954 }
2955
2956 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002957 static Value *zeroExtendOperandForOther(
2958 Instruction *Ext, TypePromotionTransaction &TPT,
2959 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2960 SmallVectorImpl<Instruction *> *Exts,
2961 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2962 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2963 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002964 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002965
2966public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002967 /// Type for the utility function that promotes the operand of Ext.
2968 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002969 InstrToOrigTy &PromotedInsts,
2970 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002971 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002972 SmallVectorImpl<Instruction *> *Truncs,
2973 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002974 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2975 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002976 /// \return NULL if no promotable action is possible with the current
2977 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002978 /// \p InsertedInsts keeps track of all the instructions inserted by the
2979 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002980 /// because we do not want to promote these instructions as CodeGenPrepare
2981 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2982 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002983 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002984 const TargetLowering &TLI,
2985 const InstrToOrigTy &PromotedInsts);
2986};
2987
2988bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002989 Type *ConsideredExtType,
2990 const InstrToOrigTy &PromotedInsts,
2991 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002992 // The promotion helper does not know how to deal with vector types yet.
2993 // To be able to fix that, we would need to fix the places where we
2994 // statically extend, e.g., constants and such.
2995 if (Inst->getType()->isVectorTy())
2996 return false;
2997
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002998 // We can always get through zext.
2999 if (isa<ZExtInst>(Inst))
3000 return true;
3001
3002 // sext(sext) is ok too.
3003 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003004 return true;
3005
3006 // We can get through binary operator, if it is legal. In other words, the
3007 // binary operator must have a nuw or nsw flag.
3008 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3009 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003010 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3011 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003012 return true;
3013
3014 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003015 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003016 if (!isa<TruncInst>(Inst))
3017 return false;
3018
3019 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003020 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003021 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003022 if (!OpndVal->getType()->isIntegerTy() ||
3023 OpndVal->getType()->getIntegerBitWidth() >
3024 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003025 return false;
3026
3027 // If the operand of the truncate is not an instruction, we will not have
3028 // any information on the dropped bits.
3029 // (Actually we could for constant but it is not worth the extra logic).
3030 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3031 if (!Opnd)
3032 return false;
3033
3034 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003035 // I.e., check that trunc just drops extended bits of the same kind of
3036 // the extension.
3037 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003038 const Type *OpndType;
3039 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003040 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3041 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003042 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3043 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003044 else
3045 return false;
3046
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003047 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003048 return Inst->getType()->getIntegerBitWidth() >=
3049 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003050}
3051
3052TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003053 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003054 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003055 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3056 "Unexpected instruction type");
3057 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3058 Type *ExtTy = Ext->getType();
3059 bool IsSExt = isa<SExtInst>(Ext);
3060 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003061 // get through.
3062 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003063 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003064 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003065
3066 // Do not promote if the operand has been added by codegenprepare.
3067 // Otherwise, it means we are undoing an optimization that is likely to be
3068 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003069 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003070 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003071
3072 // SExt or Trunc instructions.
3073 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003074 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3075 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003076 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003077
3078 // Regular instruction.
3079 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003080 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003081 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003082 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003083}
3084
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003085Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003086 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003087 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003088 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003089 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003090 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3091 // get through it and this method should not be called.
3092 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003093 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003094 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003095 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003096 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003097 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003098 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003099 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003100 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3101 TPT.replaceAllUsesWith(SExt, ZExt);
3102 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003103 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003104 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003105 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3106 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003107 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3108 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003109 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003110
3111 // Remove dead code.
3112 if (SExtOpnd->use_empty())
3113 TPT.eraseInstruction(SExtOpnd);
3114
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003115 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003116 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003117 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003118 if (ExtInst) {
3119 if (Exts)
3120 Exts->push_back(ExtInst);
3121 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3122 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003123 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003124 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003125
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003126 // At this point we have: ext ty opnd to ty.
3127 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3128 Value *NextVal = ExtInst->getOperand(0);
3129 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003130 return NextVal;
3131}
3132
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003133Value *TypePromotionHelper::promoteOperandForOther(
3134 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003135 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003136 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003137 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3138 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003139 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003140 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003141 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003142 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003143 if (!ExtOpnd->hasOneUse()) {
3144 // ExtOpnd will be promoted.
3145 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003146 // promoted version.
3147 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003148 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003149 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3150 ITrunc->removeFromParent();
3151 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003152 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003153 if (Truncs)
3154 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003155 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003156
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003157 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003158 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003159 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003160 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003161 }
3162
3163 // Get through the Instruction:
3164 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003165 // 2. Replace the uses of Ext by Inst.
3166 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003167
3168 // Remember the original type of the instruction before promotion.
3169 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003170 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3171 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003172 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003173 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003174 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003175 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003176 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003177 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003178
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003179 DEBUG(dbgs() << "Propagate Ext to operands\n");
3180 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003181 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003182 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3183 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3184 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003185 DEBUG(dbgs() << "No need to propagate\n");
3186 continue;
3187 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003188 // Check if we can statically extend the operand.
3189 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003190 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003191 DEBUG(dbgs() << "Statically extend\n");
3192 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3193 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3194 : Cst->getValue().zext(BitWidth);
3195 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003196 continue;
3197 }
3198 // UndefValue are typed, so we have to statically sign extend them.
3199 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003200 DEBUG(dbgs() << "Statically extend\n");
3201 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003202 continue;
3203 }
3204
3205 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003206 // Check if Ext was reused to extend an operand.
3207 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003208 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003209 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003210 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3211 : TPT.createZExt(Ext, Opnd, Ext->getType());
3212 if (!isa<Instruction>(ValForExtOpnd)) {
3213 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3214 continue;
3215 }
3216 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003217 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003218 if (Exts)
3219 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003220 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003221
3222 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003223 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3224 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003225 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003226 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003227 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003228 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003229 if (ExtForOpnd == Ext) {
3230 DEBUG(dbgs() << "Extension is useless now\n");
3231 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003232 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003233 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003234}
3235
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003236/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003237/// \p NewCost gives the cost of extension instructions created by the
3238/// promotion.
3239/// \p OldCost gives the cost of extension instructions before the promotion
3240/// plus the number of instructions that have been
3241/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003242/// \p PromotedOperand is the value that has been promoted.
3243/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003244bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003245 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3246 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3247 // The cost of the new extensions is greater than the cost of the
3248 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003249 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003250 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003251 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003252 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003253 return true;
3254 // The promotion is neutral but it may help folding the sign extension in
3255 // loads for instance.
3256 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003257 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003258}
3259
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003260/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003261/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003262/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003263/// If \p MovedAway is not NULL, it contains the information of whether or
3264/// not AddrInst has to be folded into the addressing mode on success.
3265/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3266/// because it has been moved away.
3267/// Thus AddrInst must not be added in the matched instructions.
3268/// This state can happen when AddrInst is a sext, since it may be moved away.
3269/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3270/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003271bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003272 unsigned Depth,
3273 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003274 // Avoid exponential behavior on extremely deep expression trees.
3275 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003276
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003277 // By default, all matched instructions stay in place.
3278 if (MovedAway)
3279 *MovedAway = false;
3280
Chandler Carruthc8925912013-01-05 02:09:22 +00003281 switch (Opcode) {
3282 case Instruction::PtrToInt:
3283 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003284 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003285 case Instruction::IntToPtr: {
3286 auto AS = AddrInst->getType()->getPointerAddressSpace();
3287 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003288 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003289 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003290 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003291 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003292 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003293 case Instruction::BitCast:
3294 // BitCast is always a noop, and we can handle it as long as it is
3295 // int->int or pointer->pointer (we don't want int<->fp or something).
3296 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3297 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3298 // Don't touch identity bitcasts. These were probably put here by LSR,
3299 // and we don't want to mess around with them. Assume it knows what it
3300 // is doing.
3301 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003302 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003303 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003304 case Instruction::AddrSpaceCast: {
3305 unsigned SrcAS
3306 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3307 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3308 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003309 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003310 return false;
3311 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003312 case Instruction::Add: {
3313 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3314 ExtAddrMode BackupAddrMode = AddrMode;
3315 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003316 // Start a transaction at this point.
3317 // The LHS may match but not the RHS.
3318 // Therefore, we need a higher level restoration point to undo partially
3319 // matched operation.
3320 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3321 TPT.getRestorationPoint();
3322
Sanjay Patelfc580a62015-09-21 23:03:16 +00003323 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3324 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003325 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003326
Chandler Carruthc8925912013-01-05 02:09:22 +00003327 // Restore the old addr mode info.
3328 AddrMode = BackupAddrMode;
3329 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003330 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003331
Chandler Carruthc8925912013-01-05 02:09:22 +00003332 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003333 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3334 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003335 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003336
Chandler Carruthc8925912013-01-05 02:09:22 +00003337 // Otherwise we definitely can't merge the ADD in.
3338 AddrMode = BackupAddrMode;
3339 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003340 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003341 break;
3342 }
3343 //case Instruction::Or:
3344 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3345 //break;
3346 case Instruction::Mul:
3347 case Instruction::Shl: {
3348 // Can only handle X*C and X << C.
3349 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003350 if (!RHS)
3351 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003352 int64_t Scale = RHS->getSExtValue();
3353 if (Opcode == Instruction::Shl)
3354 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003355
Sanjay Patelfc580a62015-09-21 23:03:16 +00003356 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003357 }
3358 case Instruction::GetElementPtr: {
3359 // Scan the GEP. We check it if it contains constant offsets and at most
3360 // one variable offset.
3361 int VariableOperand = -1;
3362 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003363
Chandler Carruthc8925912013-01-05 02:09:22 +00003364 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003365 gep_type_iterator GTI = gep_type_begin(AddrInst);
3366 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3367 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003368 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003369 unsigned Idx =
3370 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3371 ConstantOffset += SL->getElementOffset(Idx);
3372 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003373 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003374 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3375 ConstantOffset += CI->getSExtValue()*TypeSize;
3376 } else if (TypeSize) { // Scales of zero don't do anything.
3377 // We only allow one variable index at the moment.
3378 if (VariableOperand != -1)
3379 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003380
Chandler Carruthc8925912013-01-05 02:09:22 +00003381 // Remember the variable index.
3382 VariableOperand = i;
3383 VariableScale = TypeSize;
3384 }
3385 }
3386 }
Stephen Lin837bba12013-07-15 17:55:02 +00003387
Chandler Carruthc8925912013-01-05 02:09:22 +00003388 // A common case is for the GEP to only do a constant offset. In this case,
3389 // just add it to the disp field and check validity.
3390 if (VariableOperand == -1) {
3391 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003392 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003393 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003394 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003395 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003396 return true;
3397 }
3398 AddrMode.BaseOffs -= ConstantOffset;
3399 return false;
3400 }
3401
3402 // Save the valid addressing mode in case we can't match.
3403 ExtAddrMode BackupAddrMode = AddrMode;
3404 unsigned OldSize = AddrModeInsts.size();
3405
3406 // See if the scale and offset amount is valid for this target.
3407 AddrMode.BaseOffs += ConstantOffset;
3408
3409 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003410 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003411 // If it couldn't be matched, just stuff the value in a register.
3412 if (AddrMode.HasBaseReg) {
3413 AddrMode = BackupAddrMode;
3414 AddrModeInsts.resize(OldSize);
3415 return false;
3416 }
3417 AddrMode.HasBaseReg = true;
3418 AddrMode.BaseReg = AddrInst->getOperand(0);
3419 }
3420
3421 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003422 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003423 Depth)) {
3424 // If it couldn't be matched, try stuffing the base into a register
3425 // instead of matching it, and retrying the match of the scale.
3426 AddrMode = BackupAddrMode;
3427 AddrModeInsts.resize(OldSize);
3428 if (AddrMode.HasBaseReg)
3429 return false;
3430 AddrMode.HasBaseReg = true;
3431 AddrMode.BaseReg = AddrInst->getOperand(0);
3432 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003433 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003434 VariableScale, Depth)) {
3435 // If even that didn't work, bail.
3436 AddrMode = BackupAddrMode;
3437 AddrModeInsts.resize(OldSize);
3438 return false;
3439 }
3440 }
3441
3442 return true;
3443 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003444 case Instruction::SExt:
3445 case Instruction::ZExt: {
3446 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3447 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003448 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003449
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003450 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003451 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003452 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003453 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003454 if (!TPH)
3455 return false;
3456
3457 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3458 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003459 unsigned CreatedInstsCost = 0;
3460 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003461 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003462 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003463 // SExt has been moved away.
3464 // Thus either it will be rematched later in the recursive calls or it is
3465 // gone. Anyway, we must not fold it into the addressing mode at this point.
3466 // E.g.,
3467 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003468 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003469 // addr = gep base, idx
3470 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003471 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003472 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3473 // addr = gep base, op <- match
3474 if (MovedAway)
3475 *MovedAway = true;
3476
3477 assert(PromotedOperand &&
3478 "TypePromotionHelper should have filtered out those cases");
3479
3480 ExtAddrMode BackupAddrMode = AddrMode;
3481 unsigned OldSize = AddrModeInsts.size();
3482
Sanjay Patelfc580a62015-09-21 23:03:16 +00003483 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003484 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003485 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003486 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003487 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003488 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003489 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003490 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003491 AddrMode = BackupAddrMode;
3492 AddrModeInsts.resize(OldSize);
3493 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3494 TPT.rollback(LastKnownGood);
3495 return false;
3496 }
3497 return true;
3498 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003499 }
3500 return false;
3501}
3502
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003503/// If we can, try to add the value of 'Addr' into the current addressing mode.
3504/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3505/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3506/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003507///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003508bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003509 // Start a transaction at this point that we will rollback if the matching
3510 // fails.
3511 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3512 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003513 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3514 // Fold in immediates if legal for the target.
3515 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003516 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003517 return true;
3518 AddrMode.BaseOffs -= CI->getSExtValue();
3519 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3520 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003521 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003522 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003523 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003524 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003525 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003526 }
3527 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3528 ExtAddrMode BackupAddrMode = AddrMode;
3529 unsigned OldSize = AddrModeInsts.size();
3530
3531 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003532 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003533 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003534 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003535 // to check here.
3536 if (MovedAway)
3537 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003538 // Okay, it's possible to fold this. Check to see if it is actually
3539 // *profitable* to do so. We use a simple cost model to avoid increasing
3540 // register pressure too much.
3541 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003542 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003543 AddrModeInsts.push_back(I);
3544 return true;
3545 }
Stephen Lin837bba12013-07-15 17:55:02 +00003546
Chandler Carruthc8925912013-01-05 02:09:22 +00003547 // It isn't profitable to do this, roll back.
3548 //cerr << "NOT FOLDING: " << *I;
3549 AddrMode = BackupAddrMode;
3550 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003551 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003552 }
3553 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003554 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003555 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003556 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003557 } else if (isa<ConstantPointerNull>(Addr)) {
3558 // Null pointer gets folded without affecting the addressing mode.
3559 return true;
3560 }
3561
3562 // Worse case, the target should support [reg] addressing modes. :)
3563 if (!AddrMode.HasBaseReg) {
3564 AddrMode.HasBaseReg = true;
3565 AddrMode.BaseReg = Addr;
3566 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003567 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003568 return true;
3569 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003570 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003571 }
3572
3573 // If the base register is already taken, see if we can do [r+r].
3574 if (AddrMode.Scale == 0) {
3575 AddrMode.Scale = 1;
3576 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003577 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003578 return true;
3579 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003580 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003581 }
3582 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003583 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003584 return false;
3585}
3586
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003587/// Check to see if all uses of OpVal by the specified inline asm call are due
3588/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003589static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003590 const TargetMachine &TM) {
3591 const Function *F = CI->getParent()->getParent();
3592 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3593 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003594 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003595 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3596 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003597 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3598 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003599
Chandler Carruthc8925912013-01-05 02:09:22 +00003600 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003601 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003602
3603 // If this asm operand is our Value*, and if it isn't an indirect memory
3604 // operand, we can't fold it!
3605 if (OpInfo.CallOperandVal == OpVal &&
3606 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3607 !OpInfo.isIndirect))
3608 return false;
3609 }
3610
3611 return true;
3612}
3613
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003614/// Recursively walk all the uses of I until we find a memory use.
3615/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003616/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003617static bool FindAllMemoryUses(
3618 Instruction *I,
3619 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3620 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003621 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003622 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003623 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003624
Chandler Carruthc8925912013-01-05 02:09:22 +00003625 // If this is an obviously unfoldable instruction, bail out.
3626 if (!MightBeFoldableInst(I))
3627 return true;
3628
Philip Reamesac115ed2016-03-09 23:13:12 +00003629 const bool OptSize = I->getFunction()->optForSize();
3630
Chandler Carruthc8925912013-01-05 02:09:22 +00003631 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003632 for (Use &U : I->uses()) {
3633 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003634
Chandler Carruthcdf47882014-03-09 03:16:01 +00003635 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3636 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003637 continue;
3638 }
Stephen Lin837bba12013-07-15 17:55:02 +00003639
Chandler Carruthcdf47882014-03-09 03:16:01 +00003640 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3641 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003642 if (opNo == 0) return true; // Storing addr, not into addr.
3643 MemoryUses.push_back(std::make_pair(SI, opNo));
3644 continue;
3645 }
Stephen Lin837bba12013-07-15 17:55:02 +00003646
Chandler Carruthcdf47882014-03-09 03:16:01 +00003647 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003648 // If this is a cold call, we can sink the addressing calculation into
3649 // the cold path. See optimizeCallInst
3650 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3651 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003652
Chandler Carruthc8925912013-01-05 02:09:22 +00003653 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3654 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003655
Chandler Carruthc8925912013-01-05 02:09:22 +00003656 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003657 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003658 return true;
3659 continue;
3660 }
Stephen Lin837bba12013-07-15 17:55:02 +00003661
Eric Christopher11e4df72015-02-26 22:38:43 +00003662 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003663 return true;
3664 }
3665
3666 return false;
3667}
3668
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003669/// Return true if Val is already known to be live at the use site that we're
3670/// folding it into. If so, there is no cost to include it in the addressing
3671/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3672/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003673bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003674 Value *KnownLive2) {
3675 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003676 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003677 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003678
Chandler Carruthc8925912013-01-05 02:09:22 +00003679 // All values other than instructions and arguments (e.g. constants) are live.
3680 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003681
Chandler Carruthc8925912013-01-05 02:09:22 +00003682 // If Val is a constant sized alloca in the entry block, it is live, this is
3683 // true because it is just a reference to the stack/frame pointer, which is
3684 // live for the whole function.
3685 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3686 if (AI->isStaticAlloca())
3687 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003688
Chandler Carruthc8925912013-01-05 02:09:22 +00003689 // Check to see if this value is already used in the memory instruction's
3690 // block. If so, it's already live into the block at the very least, so we
3691 // can reasonably fold it.
3692 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3693}
3694
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003695/// It is possible for the addressing mode of the machine to fold the specified
3696/// instruction into a load or store that ultimately uses it.
3697/// However, the specified instruction has multiple uses.
3698/// Given this, it may actually increase register pressure to fold it
3699/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003700///
3701/// X = ...
3702/// Y = X+1
3703/// use(Y) -> nonload/store
3704/// Z = Y+1
3705/// load Z
3706///
3707/// In this case, Y has multiple uses, and can be folded into the load of Z
3708/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3709/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3710/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3711/// number of computations either.
3712///
3713/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3714/// X was live across 'load Z' for other reasons, we actually *would* want to
3715/// fold the addressing mode in the Z case. This would make Y die earlier.
3716bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003717isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003718 ExtAddrMode &AMAfter) {
3719 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003720
Chandler Carruthc8925912013-01-05 02:09:22 +00003721 // AMBefore is the addressing mode before this instruction was folded into it,
3722 // and AMAfter is the addressing mode after the instruction was folded. Get
3723 // the set of registers referenced by AMAfter and subtract out those
3724 // referenced by AMBefore: this is the set of values which folding in this
3725 // address extends the lifetime of.
3726 //
3727 // Note that there are only two potential values being referenced here,
3728 // BaseReg and ScaleReg (global addresses are always available, as are any
3729 // folded immediates).
3730 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003731
Chandler Carruthc8925912013-01-05 02:09:22 +00003732 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3733 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003734 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003735 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003736 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003737 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003738
3739 // If folding this instruction (and it's subexprs) didn't extend any live
3740 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003741 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003742 return true;
3743
Philip Reamesac115ed2016-03-09 23:13:12 +00003744 // If all uses of this instruction can have the address mode sunk into them,
3745 // we can remove the addressing mode and effectively trade one live register
3746 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003747 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003748 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3749 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003750 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003751 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003752
Chandler Carruthc8925912013-01-05 02:09:22 +00003753 // Now that we know that all uses of this instruction are part of a chain of
3754 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003755 // into a memory use, loop over each of these memory operation uses and see
3756 // if they could *actually* fold the instruction. The assumption is that
3757 // addressing modes are cheap and that duplicating the computation involved
3758 // many times is worthwhile, even on a fastpath. For sinking candidates
3759 // (i.e. cold call sites), this serves as a way to prevent excessive code
3760 // growth since most architectures have some reasonable small and fast way to
3761 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003762 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3763 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3764 Instruction *User = MemoryUses[i].first;
3765 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003766
Chandler Carruthc8925912013-01-05 02:09:22 +00003767 // Get the access type of this use. If the use isn't a pointer, we don't
3768 // know what it accesses.
3769 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003770 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3771 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003772 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003773 Type *AddressAccessTy = AddrTy->getElementType();
3774 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003775
Chandler Carruthc8925912013-01-05 02:09:22 +00003776 // Do a match against the root of this address, ignoring profitability. This
3777 // will tell us if the addressing mode for the memory operation will
3778 // *actually* cover the shared instruction.
3779 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003780 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3781 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003782 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003783 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003784 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003785 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003786 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003787 (void)Success; assert(Success && "Couldn't select *anything*?");
3788
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003789 // The match was to check the profitability, the changes made are not
3790 // part of the original matcher. Therefore, they should be dropped
3791 // otherwise the original matcher will not present the right state.
3792 TPT.rollback(LastKnownGood);
3793
Chandler Carruthc8925912013-01-05 02:09:22 +00003794 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003795 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003796 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003797
Chandler Carruthc8925912013-01-05 02:09:22 +00003798 MatchedAddrModeInsts.clear();
3799 }
Stephen Lin837bba12013-07-15 17:55:02 +00003800
Chandler Carruthc8925912013-01-05 02:09:22 +00003801 return true;
3802}
3803
3804} // end anonymous namespace
3805
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003806/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003807/// different basic block than BB.
3808static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3809 if (Instruction *I = dyn_cast<Instruction>(V))
3810 return I->getParent() != BB;
3811 return false;
3812}
3813
Philip Reamesac115ed2016-03-09 23:13:12 +00003814/// Sink addressing mode computation immediate before MemoryInst if doing so
3815/// can be done without increasing register pressure. The need for the
3816/// register pressure constraint means this can end up being an all or nothing
3817/// decision for all uses of the same addressing computation.
3818///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003819/// Load and Store Instructions often have addressing modes that can do
3820/// significant amounts of computation. As such, instruction selection will try
3821/// to get the load or store to do as much computation as possible for the
3822/// program. The problem is that isel can only see within a single block. As
3823/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003824///
3825/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003826/// operands. It's also used to sink addressing computations feeding into cold
3827/// call sites into their (cold) basic block.
3828///
3829/// The motivation for handling sinking into cold blocks is that doing so can
3830/// both enable other address mode sinking (by satisfying the register pressure
3831/// constraint above), and reduce register pressure globally (by removing the
3832/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003833bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003834 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003835 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003836
3837 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003838 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003839 SmallVector<Value*, 8> worklist;
3840 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003841 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003842
Owen Anderson8ba5f392010-11-27 08:15:55 +00003843 // Use a worklist to iteratively look through PHI nodes, and ensure that
3844 // the addressing mode obtained from the non-PHI roots of the graph
3845 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003846 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003847 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003848 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003849 SmallVector<Instruction*, 16> AddrModeInsts;
3850 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003851 TypePromotionTransaction TPT;
3852 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3853 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003854 while (!worklist.empty()) {
3855 Value *V = worklist.back();
3856 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003857
Owen Anderson8ba5f392010-11-27 08:15:55 +00003858 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003859 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003860 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003861 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003862 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003863
Owen Anderson8ba5f392010-11-27 08:15:55 +00003864 // For a PHI node, push all of its incoming values.
3865 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003866 for (Value *IncValue : P->incoming_values())
3867 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003868 continue;
3869 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003870
Philip Reamesac115ed2016-03-09 23:13:12 +00003871 // For non-PHIs, determine the addressing mode being computed. Note that
3872 // the result may differ depending on what other uses our candidate
3873 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003874 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003875 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003876 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003877 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003878
3879 // This check is broken into two cases with very similar code to avoid using
3880 // getNumUses() as much as possible. Some values have a lot of uses, so
3881 // calling getNumUses() unconditionally caused a significant compile-time
3882 // regression.
3883 if (!Consensus) {
3884 Consensus = V;
3885 AddrMode = NewAddrMode;
3886 AddrModeInsts = NewAddrModeInsts;
3887 continue;
3888 } else if (NewAddrMode == AddrMode) {
3889 if (!IsNumUsesConsensusValid) {
3890 NumUsesConsensus = Consensus->getNumUses();
3891 IsNumUsesConsensusValid = true;
3892 }
3893
3894 // Ensure that the obtained addressing mode is equivalent to that obtained
3895 // for all other roots of the PHI traversal. Also, when choosing one
3896 // such root as representative, select the one with the most uses in order
3897 // to keep the cost modeling heuristics in AddressingModeMatcher
3898 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003899 unsigned NumUses = V->getNumUses();
3900 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003901 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003902 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003903 AddrModeInsts = NewAddrModeInsts;
3904 }
3905 continue;
3906 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003907
Craig Topperc0196b12014-04-14 00:51:57 +00003908 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003909 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003910 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003911
Owen Anderson8ba5f392010-11-27 08:15:55 +00003912 // If the addressing mode couldn't be determined, or if multiple different
3913 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003914 if (!Consensus) {
3915 TPT.rollback(LastKnownGood);
3916 return false;
3917 }
3918 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003919
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003920 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00003921 if (none_of(AddrModeInsts, [&](Value *V) {
3922 return IsNonLocalValue(V, MemoryInst->getParent());
3923 })) {
David Greene74e2d492010-01-05 01:27:11 +00003924 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003925 return false;
3926 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003927
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003928 // Insert this computation right after this user. Since our caller is
3929 // scanning from the top of the BB to the bottom, reuse of the expr are
3930 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003931 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003932
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003933 // Now that we determined the addressing expression we want to use and know
3934 // that we have to sink it into this block. Check to see if we have already
3935 // done this for some other load/store instr in this block. If so, reuse the
3936 // computation.
3937 Value *&SunkAddr = SunkAddrs[Addr];
3938 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003939 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003940 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003941 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003942 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003943 } else if (AddrSinkUsingGEPs ||
3944 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003945 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3946 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003947 // By default, we use the GEP-based method when AA is used later. This
3948 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3949 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003950 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003951 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003952 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003953
3954 // First, find the pointer.
3955 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3956 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003957 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003958 }
3959
3960 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3961 // We can't add more than one pointer together, nor can we scale a
3962 // pointer (both of which seem meaningless).
3963 if (ResultPtr || AddrMode.Scale != 1)
3964 return false;
3965
3966 ResultPtr = AddrMode.ScaledReg;
3967 AddrMode.Scale = 0;
3968 }
3969
3970 if (AddrMode.BaseGV) {
3971 if (ResultPtr)
3972 return false;
3973
3974 ResultPtr = AddrMode.BaseGV;
3975 }
3976
3977 // If the real base value actually came from an inttoptr, then the matcher
3978 // will look through it and provide only the integer value. In that case,
3979 // use it here.
3980 if (!ResultPtr && AddrMode.BaseReg) {
3981 ResultPtr =
3982 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003983 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003984 } else if (!ResultPtr && AddrMode.Scale == 1) {
3985 ResultPtr =
3986 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3987 AddrMode.Scale = 0;
3988 }
3989
3990 if (!ResultPtr &&
3991 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3992 SunkAddr = Constant::getNullValue(Addr->getType());
3993 } else if (!ResultPtr) {
3994 return false;
3995 } else {
3996 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003997 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3998 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003999
4000 // Start with the base register. Do this first so that subsequent address
4001 // matching finds it last, which will prevent it from trying to match it
4002 // as the scaled value in case it happens to be a mul. That would be
4003 // problematic if we've sunk a different mul for the scale, because then
4004 // we'd end up sinking both muls.
4005 if (AddrMode.BaseReg) {
4006 Value *V = AddrMode.BaseReg;
4007 if (V->getType() != IntPtrTy)
4008 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4009
4010 ResultIndex = V;
4011 }
4012
4013 // Add the scale value.
4014 if (AddrMode.Scale) {
4015 Value *V = AddrMode.ScaledReg;
4016 if (V->getType() == IntPtrTy) {
4017 // done.
4018 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4019 cast<IntegerType>(V->getType())->getBitWidth()) {
4020 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4021 } else {
4022 // It is only safe to sign extend the BaseReg if we know that the math
4023 // required to create it did not overflow before we extend it. Since
4024 // the original IR value was tossed in favor of a constant back when
4025 // the AddrMode was created we need to bail out gracefully if widths
4026 // do not match instead of extending it.
4027 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4028 if (I && (ResultIndex != AddrMode.BaseReg))
4029 I->eraseFromParent();
4030 return false;
4031 }
4032
4033 if (AddrMode.Scale != 1)
4034 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4035 "sunkaddr");
4036 if (ResultIndex)
4037 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4038 else
4039 ResultIndex = V;
4040 }
4041
4042 // Add in the Base Offset if present.
4043 if (AddrMode.BaseOffs) {
4044 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4045 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004046 // We need to add this separately from the scale above to help with
4047 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004048 if (ResultPtr->getType() != I8PtrTy)
4049 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004050 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004051 }
4052
4053 ResultIndex = V;
4054 }
4055
4056 if (!ResultIndex) {
4057 SunkAddr = ResultPtr;
4058 } else {
4059 if (ResultPtr->getType() != I8PtrTy)
4060 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004061 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004062 }
4063
4064 if (SunkAddr->getType() != Addr->getType())
4065 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4066 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004067 } else {
David Greene74e2d492010-01-05 01:27:11 +00004068 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004069 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004070 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004071 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004072
4073 // Start with the base register. Do this first so that subsequent address
4074 // matching finds it last, which will prevent it from trying to match it
4075 // as the scaled value in case it happens to be a mul. That would be
4076 // problematic if we've sunk a different mul for the scale, because then
4077 // we'd end up sinking both muls.
4078 if (AddrMode.BaseReg) {
4079 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004080 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004081 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004082 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004083 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004084 Result = V;
4085 }
4086
4087 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004088 if (AddrMode.Scale) {
4089 Value *V = AddrMode.ScaledReg;
4090 if (V->getType() == IntPtrTy) {
4091 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004092 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004093 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004094 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4095 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004096 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004097 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004098 // It is only safe to sign extend the BaseReg if we know that the math
4099 // required to create it did not overflow before we extend it. Since
4100 // the original IR value was tossed in favor of a constant back when
4101 // the AddrMode was created we need to bail out gracefully if widths
4102 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004103 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004104 if (I && (Result != AddrMode.BaseReg))
4105 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004106 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004107 }
4108 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004109 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4110 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004111 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004112 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004113 else
4114 Result = V;
4115 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004116
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004117 // Add in the BaseGV if present.
4118 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004119 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004120 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004121 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004122 else
4123 Result = V;
4124 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004125
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004126 // Add in the Base Offset if present.
4127 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004128 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004129 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004130 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004131 else
4132 Result = V;
4133 }
4134
Craig Topperc0196b12014-04-14 00:51:57 +00004135 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004136 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004137 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004138 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004139 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004140
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004141 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004142
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004143 // If we have no uses, recursively delete the value and all dead instructions
4144 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004145 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004146 // This can cause recursive deletion, which can invalidate our iterator.
4147 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004148 Value *CurValue = &*CurInstIterator;
4149 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004150 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004151
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004152 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004153
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004154 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004155 // If the iterator instruction was recursively deleted, start over at the
4156 // start of the block.
4157 CurInstIterator = BB->begin();
4158 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004159 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004160 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004161 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004162 return true;
4163}
4164
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004165/// If there are any memory operands, use OptimizeMemoryInst to sink their
4166/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004167bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004168 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004169
Eric Christopher11e4df72015-02-26 22:38:43 +00004170 const TargetRegisterInfo *TRI =
4171 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004172 TargetLowering::AsmOperandInfoVector TargetConstraints =
4173 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004174 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004175 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4176 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004177
Evan Cheng1da25002008-02-26 02:42:37 +00004178 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004179 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004180
Eli Friedman666bbe32008-02-26 18:37:49 +00004181 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4182 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004183 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004184 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004185 } else if (OpInfo.Type == InlineAsm::isInput)
4186 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004187 }
4188
4189 return MadeChange;
4190}
4191
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004192/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4193/// sign extensions.
4194static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4195 assert(!Inst->use_empty() && "Input must have at least one use");
4196 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4197 bool IsSExt = isa<SExtInst>(FirstUser);
4198 Type *ExtTy = FirstUser->getType();
4199 for (const User *U : Inst->users()) {
4200 const Instruction *UI = cast<Instruction>(U);
4201 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4202 return false;
4203 Type *CurTy = UI->getType();
4204 // Same input and output types: Same instruction after CSE.
4205 if (CurTy == ExtTy)
4206 continue;
4207
4208 // If IsSExt is true, we are in this situation:
4209 // a = Inst
4210 // b = sext ty1 a to ty2
4211 // c = sext ty1 a to ty3
4212 // Assuming ty2 is shorter than ty3, this could be turned into:
4213 // a = Inst
4214 // b = sext ty1 a to ty2
4215 // c = sext ty2 b to ty3
4216 // However, the last sext is not free.
4217 if (IsSExt)
4218 return false;
4219
4220 // This is a ZExt, maybe this is free to extend from one type to another.
4221 // In that case, we would not account for a different use.
4222 Type *NarrowTy;
4223 Type *LargeTy;
4224 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4225 CurTy->getScalarType()->getIntegerBitWidth()) {
4226 NarrowTy = CurTy;
4227 LargeTy = ExtTy;
4228 } else {
4229 NarrowTy = ExtTy;
4230 LargeTy = CurTy;
4231 }
4232
4233 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4234 return false;
4235 }
4236 // All uses are the same or can be derived from one another for free.
4237 return true;
4238}
4239
4240/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4241/// load instruction.
4242/// If an ext(load) can be formed, it is returned via \p LI for the load
4243/// and \p Inst for the extension.
4244/// Otherwise LI == nullptr and Inst == nullptr.
4245/// When some promotion happened, \p TPT contains the proper state to
4246/// revert them.
4247///
4248/// \return true when promoting was necessary to expose the ext(load)
4249/// opportunity, false otherwise.
4250///
4251/// Example:
4252/// \code
4253/// %ld = load i32* %addr
4254/// %add = add nuw i32 %ld, 4
4255/// %zext = zext i32 %add to i64
4256/// \endcode
4257/// =>
4258/// \code
4259/// %ld = load i32* %addr
4260/// %zext = zext i32 %ld to i64
4261/// %add = add nuw i64 %zext, 4
4262/// \encode
4263/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004264bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004265 LoadInst *&LI, Instruction *&Inst,
4266 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004267 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004268 // Iterate over all the extensions to see if one form an ext(load).
4269 for (auto I : Exts) {
4270 // Check if we directly have ext(load).
4271 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4272 Inst = I;
4273 // No promotion happened here.
4274 return false;
4275 }
4276 // Check whether or not we want to do any promotion.
4277 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4278 continue;
4279 // Get the action to perform the promotion.
4280 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004281 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004282 // Check if we can promote.
4283 if (!TPH)
4284 continue;
4285 // Save the current state.
4286 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4287 TPT.getRestorationPoint();
4288 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004289 unsigned NewCreatedInstsCost = 0;
4290 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004291 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004292 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4293 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004294 assert(PromotedVal &&
4295 "TypePromotionHelper should have filtered out those cases");
4296
4297 // We would be able to merge only one extension in a load.
4298 // Therefore, if we have more than 1 new extension we heuristically
4299 // cut this search path, because it means we degrade the code quality.
4300 // With exactly 2, the transformation is neutral, because we will merge
4301 // one extension but leave one. However, we optimistically keep going,
4302 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004303 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4304 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004305 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004306 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004307 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004308 // The promotion is not profitable, rollback to the previous state.
4309 TPT.rollback(LastKnownGood);
4310 continue;
4311 }
4312 // The promotion is profitable.
4313 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004314 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004315 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004316 // If we have created a new extension, i.e., now we have two
4317 // extensions. We must make sure one of them is merged with
4318 // the load, otherwise we may degrade the code quality.
4319 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4320 // Promotion happened.
4321 return true;
4322 // If this does not help to expose an ext(load) then, rollback.
4323 TPT.rollback(LastKnownGood);
4324 }
4325 // None of the extension can form an ext(load).
4326 LI = nullptr;
4327 Inst = nullptr;
4328 return false;
4329}
4330
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004331/// Move a zext or sext fed by a load into the same basic block as the load,
4332/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4333/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004334/// \p I[in/out] the extension may be modified during the process if some
4335/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004336///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004337bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004338 // ExtLoad formation infrastructure requires TLI to be effective.
4339 if (!TLI)
4340 return false;
4341
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004342 // Try to promote a chain of computation if it allows to form
4343 // an extended load.
4344 TypePromotionTransaction TPT;
4345 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4346 TPT.getRestorationPoint();
4347 SmallVector<Instruction *, 1> Exts;
4348 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004349 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004350 LoadInst *LI = nullptr;
4351 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004352 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004353 if (!LI || !I) {
4354 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4355 "the code must remain the same");
4356 I = OldExt;
4357 return false;
4358 }
Dan Gohman99429a02009-10-16 20:59:35 +00004359
4360 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004361 // Make the cheap checks first if we did not promote.
4362 // If we promoted, we need to check if it is indeed profitable.
4363 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004364 return false;
4365
Mehdi Amini44ede332015-07-09 02:09:04 +00004366 EVT VT = TLI->getValueType(*DL, I->getType());
4367 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004368
Dan Gohman99429a02009-10-16 20:59:35 +00004369 // If the load has other users and the truncate is not free, this probably
4370 // isn't worthwhile.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004371 if (!LI->hasOneUse() &&
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004372 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004373 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4374 I = OldExt;
4375 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004376 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004377 }
Dan Gohman99429a02009-10-16 20:59:35 +00004378
4379 // Check whether the target supports casts folded into loads.
4380 unsigned LType;
4381 if (isa<ZExtInst>(I))
4382 LType = ISD::ZEXTLOAD;
4383 else {
4384 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4385 LType = ISD::SEXTLOAD;
4386 }
Chandler Carruth0f139b42016-11-04 06:54:00 +00004387 if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004388 I = OldExt;
4389 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004390 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004391 }
Dan Gohman99429a02009-10-16 20:59:35 +00004392
4393 // Move the extend into the same block as the load, so that SelectionDAG
4394 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004395 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004396 I->removeFromParent();
4397 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004398 // CGP does not check if the zext would be speculatively executed when moved
4399 // to the same basic block as the load. Preserving its original location would
4400 // pessimize the debugging experience, as well as negatively impact the
4401 // quality of sample pgo. We don't want to use "line 0" as that has a
4402 // size cost in the line-table section and logically the zext can be seen as
4403 // part of the load. Therefore we conservatively reuse the same debug location
4404 // for the load and the zext.
4405 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004406 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004407 return true;
4408}
4409
Sanjay Patelfc580a62015-09-21 23:03:16 +00004410bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004411 BasicBlock *DefBB = I->getParent();
4412
Bob Wilsonff714f92010-09-21 21:44:14 +00004413 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004414 // other uses of the source with result of extension.
4415 Value *Src = I->getOperand(0);
4416 if (Src->hasOneUse())
4417 return false;
4418
Evan Cheng2011df42007-12-13 07:50:36 +00004419 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004420 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004421 return false;
4422
Evan Cheng7bc89422007-12-12 00:51:06 +00004423 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004424 // this block.
4425 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004426 return false;
4427
Evan Chengd3d80172007-12-05 23:58:20 +00004428 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004429 for (User *U : I->users()) {
4430 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004431
4432 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004433 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004434 if (UserBB == DefBB) continue;
4435 DefIsLiveOut = true;
4436 break;
4437 }
4438 if (!DefIsLiveOut)
4439 return false;
4440
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004441 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004442 for (User *U : Src->users()) {
4443 Instruction *UI = cast<Instruction>(U);
4444 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004445 if (UserBB == DefBB) continue;
4446 // Be conservative. We don't want this xform to end up introducing
4447 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004448 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004449 return false;
4450 }
4451
Evan Chengd3d80172007-12-05 23:58:20 +00004452 // InsertedTruncs - Only insert one trunc in each block once.
4453 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4454
4455 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004456 for (Use &U : Src->uses()) {
4457 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004458
4459 // Figure out which BB this ext is used in.
4460 BasicBlock *UserBB = User->getParent();
4461 if (UserBB == DefBB) continue;
4462
4463 // Both src and def are live in this block. Rewrite the use.
4464 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4465
4466 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004467 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004468 assert(InsertPt != UserBB->end());
4469 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004470 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004471 }
4472
4473 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004474 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004475 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004476 MadeChange = true;
4477 }
4478
4479 return MadeChange;
4480}
4481
Geoff Berry5256fca2015-11-20 22:34:39 +00004482// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4483// just after the load if the target can fold this into one extload instruction,
4484// with the hope of eliminating some of the other later "and" instructions using
4485// the loaded value. "and"s that are made trivially redundant by the insertion
4486// of the new "and" are removed by this function, while others (e.g. those whose
4487// path from the load goes through a phi) are left for isel to potentially
4488// remove.
4489//
4490// For example:
4491//
4492// b0:
4493// x = load i32
4494// ...
4495// b1:
4496// y = and x, 0xff
4497// z = use y
4498//
4499// becomes:
4500//
4501// b0:
4502// x = load i32
4503// x' = and x, 0xff
4504// ...
4505// b1:
4506// z = use x'
4507//
4508// whereas:
4509//
4510// b0:
4511// x1 = load i32
4512// ...
4513// b1:
4514// x2 = load i32
4515// ...
4516// b2:
4517// x = phi x1, x2
4518// y = and x, 0xff
4519//
4520// becomes (after a call to optimizeLoadExt for each load):
4521//
4522// b0:
4523// x1 = load i32
4524// x1' = and x1, 0xff
4525// ...
4526// b1:
4527// x2 = load i32
4528// x2' = and x2, 0xff
4529// ...
4530// b2:
4531// x = phi x1', x2'
4532// y = and x, 0xff
4533//
4534
4535bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4536
4537 if (!Load->isSimple() ||
4538 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4539 return false;
4540
4541 // Skip loads we've already transformed or have no reason to transform.
4542 if (Load->hasOneUse()) {
4543 User *LoadUser = *Load->user_begin();
4544 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4545 !dyn_cast<PHINode>(LoadUser))
4546 return false;
4547 }
4548
4549 // Look at all uses of Load, looking through phis, to determine how many bits
4550 // of the loaded value are needed.
4551 SmallVector<Instruction *, 8> WorkList;
4552 SmallPtrSet<Instruction *, 16> Visited;
4553 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4554 for (auto *U : Load->users())
4555 WorkList.push_back(cast<Instruction>(U));
4556
4557 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4558 unsigned BitWidth = LoadResultVT.getSizeInBits();
4559 APInt DemandBits(BitWidth, 0);
4560 APInt WidestAndBits(BitWidth, 0);
4561
4562 while (!WorkList.empty()) {
4563 Instruction *I = WorkList.back();
4564 WorkList.pop_back();
4565
4566 // Break use-def graph loops.
4567 if (!Visited.insert(I).second)
4568 continue;
4569
4570 // For a PHI node, push all of its users.
4571 if (auto *Phi = dyn_cast<PHINode>(I)) {
4572 for (auto *U : Phi->users())
4573 WorkList.push_back(cast<Instruction>(U));
4574 continue;
4575 }
4576
4577 switch (I->getOpcode()) {
4578 case llvm::Instruction::And: {
4579 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4580 if (!AndC)
4581 return false;
4582 APInt AndBits = AndC->getValue();
4583 DemandBits |= AndBits;
4584 // Keep track of the widest and mask we see.
4585 if (AndBits.ugt(WidestAndBits))
4586 WidestAndBits = AndBits;
4587 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4588 AndsToMaybeRemove.push_back(I);
4589 break;
4590 }
4591
4592 case llvm::Instruction::Shl: {
4593 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4594 if (!ShlC)
4595 return false;
4596 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4597 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4598 DemandBits |= ShlDemandBits;
4599 break;
4600 }
4601
4602 case llvm::Instruction::Trunc: {
4603 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4604 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4605 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4606 DemandBits |= TruncBits;
4607 break;
4608 }
4609
4610 default:
4611 return false;
4612 }
4613 }
4614
4615 uint32_t ActiveBits = DemandBits.getActiveBits();
4616 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4617 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4618 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4619 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4620 // followed by an AND.
4621 // TODO: Look into removing this restriction by fixing backends to either
4622 // return false for isLoadExtLegal for i1 or have them select this pattern to
4623 // a single instruction.
4624 //
4625 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4626 // mask, since these are the only ands that will be removed by isel.
4627 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4628 WidestAndBits != DemandBits)
4629 return false;
4630
4631 LLVMContext &Ctx = Load->getType()->getContext();
4632 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4633 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4634
4635 // Reject cases that won't be matched as extloads.
4636 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4637 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4638 return false;
4639
4640 IRBuilder<> Builder(Load->getNextNode());
4641 auto *NewAnd = dyn_cast<Instruction>(
4642 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4643
4644 // Replace all uses of load with new and (except for the use of load in the
4645 // new and itself).
4646 Load->replaceAllUsesWith(NewAnd);
4647 NewAnd->setOperand(0, Load);
4648
4649 // Remove any and instructions that are now redundant.
4650 for (auto *And : AndsToMaybeRemove)
4651 // Check that the and mask is the same as the one we decided to put on the
4652 // new and.
4653 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4654 And->replaceAllUsesWith(NewAnd);
4655 if (&*CurInstIterator == And)
4656 CurInstIterator = std::next(And->getIterator());
4657 And->eraseFromParent();
4658 ++NumAndUses;
4659 }
4660
4661 ++NumAndsAdded;
4662 return true;
4663}
4664
Sanjay Patel69a50a12015-10-19 21:59:12 +00004665/// Check if V (an operand of a select instruction) is an expensive instruction
4666/// that is only used once.
4667static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4668 auto *I = dyn_cast<Instruction>(V);
4669 // If it's safe to speculatively execute, then it should not have side
4670 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004671 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4672 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004673}
4674
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004675/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004676static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004677 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004678 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004679 // If even a predictable select is cheap, then a branch can't be cheaper.
4680 if (!TLI->isPredictableSelectExpensive())
4681 return false;
4682
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004683 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004684 // whether a select is better represented as a branch.
4685
4686 // If metadata tells us that the select condition is obviously predictable,
4687 // then we want to replace the select with a branch.
4688 uint64_t TrueWeight, FalseWeight;
4689 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4690 uint64_t Max = std::max(TrueWeight, FalseWeight);
4691 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004692 if (Sum != 0) {
4693 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4694 if (Probability > TLI->getPredictableBranchThreshold())
4695 return true;
4696 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004697 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004698
4699 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4700
Sanjay Patel4e652762015-09-28 22:14:51 +00004701 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4702 // comparison condition. If the compare has more than one use, there's
4703 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004704 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004705 return false;
4706
Sanjay Patel69a50a12015-10-19 21:59:12 +00004707 // If either operand of the select is expensive and only needed on one side
4708 // of the select, we should form a branch.
4709 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4710 sinkSelectOperand(TTI, SI->getFalseValue()))
4711 return true;
4712
4713 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004714}
4715
Dehao Chen9bbb9412016-09-12 20:23:28 +00004716/// If \p isTrue is true, return the true value of \p SI, otherwise return
4717/// false value of \p SI. If the true/false value of \p SI is defined by any
4718/// select instructions in \p Selects, look through the defining select
4719/// instruction until the true/false value is not defined in \p Selects.
4720static Value *getTrueOrFalseValue(
4721 SelectInst *SI, bool isTrue,
4722 const SmallPtrSet<const Instruction *, 2> &Selects) {
4723 Value *V;
4724
4725 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4726 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004727 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004728 "The condition of DefSI does not match with SI");
4729 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4730 }
4731 return V;
4732}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004733
Nadav Rotem9d832022012-09-02 12:10:19 +00004734/// If we have a SelectInst that will likely profit from branch prediction,
4735/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004736bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004737 // Find all consecutive select instructions that share the same condition.
4738 SmallVector<SelectInst *, 2> ASI;
4739 ASI.push_back(SI);
4740 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4741 It != SI->getParent()->end(); ++It) {
4742 SelectInst *I = dyn_cast<SelectInst>(&*It);
4743 if (I && SI->getCondition() == I->getCondition()) {
4744 ASI.push_back(I);
4745 } else {
4746 break;
4747 }
4748 }
4749
4750 SelectInst *LastSI = ASI.back();
4751 // Increment the current iterator to skip all the rest of select instructions
4752 // because they will be either "not lowered" or "all lowered" to branch.
4753 CurInstIterator = std::next(LastSI->getIterator());
4754
Nadav Rotem9d832022012-09-02 12:10:19 +00004755 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4756
4757 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004758 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4759 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004760 return false;
4761
Nadav Rotem9d832022012-09-02 12:10:19 +00004762 TargetLowering::SelectSupportKind SelectKind;
4763 if (VectorCond)
4764 SelectKind = TargetLowering::VectorMaskSelect;
4765 else if (SI->getType()->isVectorTy())
4766 SelectKind = TargetLowering::ScalarCondVectorVal;
4767 else
4768 SelectKind = TargetLowering::ScalarValSelect;
4769
Sanjay Pateld66607b2016-04-26 17:11:17 +00004770 if (TLI->isSelectSupported(SelectKind) &&
4771 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4772 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004773
4774 ModifiedDT = true;
4775
Sanjay Patel69a50a12015-10-19 21:59:12 +00004776 // Transform a sequence like this:
4777 // start:
4778 // %cmp = cmp uge i32 %a, %b
4779 // %sel = select i1 %cmp, i32 %c, i32 %d
4780 //
4781 // Into:
4782 // start:
4783 // %cmp = cmp uge i32 %a, %b
4784 // br i1 %cmp, label %select.true, label %select.false
4785 // select.true:
4786 // br label %select.end
4787 // select.false:
4788 // br label %select.end
4789 // select.end:
4790 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4791 //
4792 // In addition, we may sink instructions that produce %c or %d from
4793 // the entry block into the destination(s) of the new branch.
4794 // If the true or false blocks do not contain a sunken instruction, that
4795 // block and its branch may be optimized away. In that case, one side of the
4796 // first branch will point directly to select.end, and the corresponding PHI
4797 // predecessor block will be the start block.
4798
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004799 // First, we split the block containing the select into 2 blocks.
4800 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004801 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004802 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004803
Sanjay Patel69a50a12015-10-19 21:59:12 +00004804 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004805 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004806
4807 // These are the new basic blocks for the conditional branch.
4808 // At least one will become an actual new basic block.
4809 BasicBlock *TrueBlock = nullptr;
4810 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004811 BranchInst *TrueBranch = nullptr;
4812 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004813
4814 // Sink expensive instructions into the conditional blocks to avoid executing
4815 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004816 for (SelectInst *SI : ASI) {
4817 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4818 if (TrueBlock == nullptr) {
4819 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4820 EndBlock->getParent(), EndBlock);
4821 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4822 }
4823 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4824 TrueInst->moveBefore(TrueBranch);
4825 }
4826 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4827 if (FalseBlock == nullptr) {
4828 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4829 EndBlock->getParent(), EndBlock);
4830 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4831 }
4832 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4833 FalseInst->moveBefore(FalseBranch);
4834 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004835 }
4836
4837 // If there was nothing to sink, then arbitrarily choose the 'false' side
4838 // for a new input value to the PHI.
4839 if (TrueBlock == FalseBlock) {
4840 assert(TrueBlock == nullptr &&
4841 "Unexpected basic block transform while optimizing select");
4842
4843 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4844 EndBlock->getParent(), EndBlock);
4845 BranchInst::Create(EndBlock, FalseBlock);
4846 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004847
4848 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004849 // If we did not create a new block for one of the 'true' or 'false' paths
4850 // of the condition, it means that side of the branch goes to the end block
4851 // directly and the path originates from the start block from the point of
4852 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004853 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004854 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004855 TT = EndBlock;
4856 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004857 TrueBlock = StartBlock;
4858 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004859 TT = TrueBlock;
4860 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004861 FalseBlock = StartBlock;
4862 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004863 TT = TrueBlock;
4864 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004865 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004866 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004867
Dehao Chen9bbb9412016-09-12 20:23:28 +00004868 SmallPtrSet<const Instruction *, 2> INS;
4869 INS.insert(ASI.begin(), ASI.end());
4870 // Use reverse iterator because later select may use the value of the
4871 // earlier select, and we need to propagate value through earlier select
4872 // to get the PHI operand.
4873 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4874 SelectInst *SI = *It;
4875 // The select itself is replaced with a PHI Node.
4876 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4877 PN->takeName(SI);
4878 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4879 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004880
Dehao Chen9bbb9412016-09-12 20:23:28 +00004881 SI->replaceAllUsesWith(PN);
4882 SI->eraseFromParent();
4883 INS.erase(SI);
4884 ++NumSelectsExpanded;
4885 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004886
4887 // Instruct OptimizeBlock to skip to the next block.
4888 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004889 return true;
4890}
4891
Benjamin Kramer573ff362014-03-01 17:24:40 +00004892static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004893 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4894 int SplatElem = -1;
4895 for (unsigned i = 0; i < Mask.size(); ++i) {
4896 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4897 return false;
4898 SplatElem = Mask[i];
4899 }
4900
4901 return true;
4902}
4903
4904/// Some targets have expensive vector shifts if the lanes aren't all the same
4905/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4906/// it's often worth sinking a shufflevector splat down to its use so that
4907/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004908bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004909 BasicBlock *DefBB = SVI->getParent();
4910
4911 // Only do this xform if variable vector shifts are particularly expensive.
4912 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4913 return false;
4914
4915 // We only expect better codegen by sinking a shuffle if we can recognise a
4916 // constant splat.
4917 if (!isBroadcastShuffle(SVI))
4918 return false;
4919
4920 // InsertedShuffles - Only insert a shuffle in each block once.
4921 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4922
4923 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004924 for (User *U : SVI->users()) {
4925 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004926
4927 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004928 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004929 if (UserBB == DefBB) continue;
4930
4931 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004932 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004933
4934 // Everything checks out, sink the shuffle if the user's block doesn't
4935 // already have a copy.
4936 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4937
4938 if (!InsertedShuffle) {
4939 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004940 assert(InsertPt != UserBB->end());
4941 InsertedShuffle =
4942 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4943 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004944 }
4945
Chandler Carruthcdf47882014-03-09 03:16:01 +00004946 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004947 MadeChange = true;
4948 }
4949
4950 // If we removed all uses, nuke the shuffle.
4951 if (SVI->use_empty()) {
4952 SVI->eraseFromParent();
4953 MadeChange = true;
4954 }
4955
4956 return MadeChange;
4957}
4958
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004959bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4960 if (!TLI || !DL)
4961 return false;
4962
4963 Value *Cond = SI->getCondition();
4964 Type *OldType = Cond->getType();
4965 LLVMContext &Context = Cond->getContext();
4966 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4967 unsigned RegWidth = RegType.getSizeInBits();
4968
4969 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4970 return false;
4971
4972 // If the register width is greater than the type width, expand the condition
4973 // of the switch instruction and each case constant to the width of the
4974 // register. By widening the type of the switch condition, subsequent
4975 // comparisons (for case comparisons) will not need to be extended to the
4976 // preferred register width, so we will potentially eliminate N-1 extends,
4977 // where N is the number of cases in the switch.
4978 auto *NewType = Type::getIntNTy(Context, RegWidth);
4979
4980 // Zero-extend the switch condition and case constants unless the switch
4981 // condition is a function argument that is already being sign-extended.
4982 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4983 // everything instead.
4984 Instruction::CastOps ExtType = Instruction::ZExt;
4985 if (auto *Arg = dyn_cast<Argument>(Cond))
4986 if (Arg->hasSExtAttr())
4987 ExtType = Instruction::SExt;
4988
4989 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4990 ExtInst->insertBefore(SI);
4991 SI->setCondition(ExtInst);
4992 for (SwitchInst::CaseIt Case : SI->cases()) {
4993 APInt NarrowConst = Case.getCaseValue()->getValue();
4994 APInt WideConst = (ExtType == Instruction::ZExt) ?
4995 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4996 Case.setValue(ConstantInt::get(Context, WideConst));
4997 }
4998
4999 return true;
5000}
5001
Quentin Colombetc32615d2014-10-31 17:52:53 +00005002namespace {
5003/// \brief Helper class to promote a scalar operation to a vector one.
5004/// This class is used to move downward extractelement transition.
5005/// E.g.,
5006/// a = vector_op <2 x i32>
5007/// b = extractelement <2 x i32> a, i32 0
5008/// c = scalar_op b
5009/// store c
5010///
5011/// =>
5012/// a = vector_op <2 x i32>
5013/// c = vector_op a (equivalent to scalar_op on the related lane)
5014/// * d = extractelement <2 x i32> c, i32 0
5015/// * store d
5016/// Assuming both extractelement and store can be combine, we get rid of the
5017/// transition.
5018class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005019 /// DataLayout associated with the current module.
5020 const DataLayout &DL;
5021
Quentin Colombetc32615d2014-10-31 17:52:53 +00005022 /// Used to perform some checks on the legality of vector operations.
5023 const TargetLowering &TLI;
5024
5025 /// Used to estimated the cost of the promoted chain.
5026 const TargetTransformInfo &TTI;
5027
5028 /// The transition being moved downwards.
5029 Instruction *Transition;
5030 /// The sequence of instructions to be promoted.
5031 SmallVector<Instruction *, 4> InstsToBePromoted;
5032 /// Cost of combining a store and an extract.
5033 unsigned StoreExtractCombineCost;
5034 /// Instruction that will be combined with the transition.
5035 Instruction *CombineInst;
5036
5037 /// \brief The instruction that represents the current end of the transition.
5038 /// Since we are faking the promotion until we reach the end of the chain
5039 /// of computation, we need a way to get the current end of the transition.
5040 Instruction *getEndOfTransition() const {
5041 if (InstsToBePromoted.empty())
5042 return Transition;
5043 return InstsToBePromoted.back();
5044 }
5045
5046 /// \brief Return the index of the original value in the transition.
5047 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5048 /// c, is at index 0.
5049 unsigned getTransitionOriginalValueIdx() const {
5050 assert(isa<ExtractElementInst>(Transition) &&
5051 "Other kind of transitions are not supported yet");
5052 return 0;
5053 }
5054
5055 /// \brief Return the index of the index in the transition.
5056 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5057 /// is at index 1.
5058 unsigned getTransitionIdx() const {
5059 assert(isa<ExtractElementInst>(Transition) &&
5060 "Other kind of transitions are not supported yet");
5061 return 1;
5062 }
5063
5064 /// \brief Get the type of the transition.
5065 /// This is the type of the original value.
5066 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5067 /// transition is <2 x i32>.
5068 Type *getTransitionType() const {
5069 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5070 }
5071
5072 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5073 /// I.e., we have the following sequence:
5074 /// Def = Transition <ty1> a to <ty2>
5075 /// b = ToBePromoted <ty2> Def, ...
5076 /// =>
5077 /// b = ToBePromoted <ty1> a, ...
5078 /// Def = Transition <ty1> ToBePromoted to <ty2>
5079 void promoteImpl(Instruction *ToBePromoted);
5080
5081 /// \brief Check whether or not it is profitable to promote all the
5082 /// instructions enqueued to be promoted.
5083 bool isProfitableToPromote() {
5084 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5085 unsigned Index = isa<ConstantInt>(ValIdx)
5086 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5087 : -1;
5088 Type *PromotedType = getTransitionType();
5089
5090 StoreInst *ST = cast<StoreInst>(CombineInst);
5091 unsigned AS = ST->getPointerAddressSpace();
5092 unsigned Align = ST->getAlignment();
5093 // Check if this store is supported.
5094 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005095 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5096 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005097 // If this is not supported, there is no way we can combine
5098 // the extract with the store.
5099 return false;
5100 }
5101
5102 // The scalar chain of computation has to pay for the transition
5103 // scalar to vector.
5104 // The vector chain has to account for the combining cost.
5105 uint64_t ScalarCost =
5106 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5107 uint64_t VectorCost = StoreExtractCombineCost;
5108 for (const auto &Inst : InstsToBePromoted) {
5109 // Compute the cost.
5110 // By construction, all instructions being promoted are arithmetic ones.
5111 // Moreover, one argument is a constant that can be viewed as a splat
5112 // constant.
5113 Value *Arg0 = Inst->getOperand(0);
5114 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5115 isa<ConstantFP>(Arg0);
5116 TargetTransformInfo::OperandValueKind Arg0OVK =
5117 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5118 : TargetTransformInfo::OK_AnyValue;
5119 TargetTransformInfo::OperandValueKind Arg1OVK =
5120 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5121 : TargetTransformInfo::OK_AnyValue;
5122 ScalarCost += TTI.getArithmeticInstrCost(
5123 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5124 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5125 Arg0OVK, Arg1OVK);
5126 }
5127 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5128 << ScalarCost << "\nVector: " << VectorCost << '\n');
5129 return ScalarCost > VectorCost;
5130 }
5131
5132 /// \brief Generate a constant vector with \p Val with the same
5133 /// number of elements as the transition.
5134 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005135 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005136 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5137 /// otherwise we generate a vector with as many undef as possible:
5138 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5139 /// used at the index of the extract.
5140 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5141 unsigned ExtractIdx = UINT_MAX;
5142 if (!UseSplat) {
5143 // If we cannot determine where the constant must be, we have to
5144 // use a splat constant.
5145 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5146 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5147 ExtractIdx = CstVal->getSExtValue();
5148 else
5149 UseSplat = true;
5150 }
5151
5152 unsigned End = getTransitionType()->getVectorNumElements();
5153 if (UseSplat)
5154 return ConstantVector::getSplat(End, Val);
5155
5156 SmallVector<Constant *, 4> ConstVec;
5157 UndefValue *UndefVal = UndefValue::get(Val->getType());
5158 for (unsigned Idx = 0; Idx != End; ++Idx) {
5159 if (Idx == ExtractIdx)
5160 ConstVec.push_back(Val);
5161 else
5162 ConstVec.push_back(UndefVal);
5163 }
5164 return ConstantVector::get(ConstVec);
5165 }
5166
5167 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5168 /// in \p Use can trigger undefined behavior.
5169 static bool canCauseUndefinedBehavior(const Instruction *Use,
5170 unsigned OperandIdx) {
5171 // This is not safe to introduce undef when the operand is on
5172 // the right hand side of a division-like instruction.
5173 if (OperandIdx != 1)
5174 return false;
5175 switch (Use->getOpcode()) {
5176 default:
5177 return false;
5178 case Instruction::SDiv:
5179 case Instruction::UDiv:
5180 case Instruction::SRem:
5181 case Instruction::URem:
5182 return true;
5183 case Instruction::FDiv:
5184 case Instruction::FRem:
5185 return !Use->hasNoNaNs();
5186 }
5187 llvm_unreachable(nullptr);
5188 }
5189
5190public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005191 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5192 const TargetTransformInfo &TTI, Instruction *Transition,
5193 unsigned CombineCost)
5194 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005195 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5196 assert(Transition && "Do not know how to promote null");
5197 }
5198
5199 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5200 bool canPromote(const Instruction *ToBePromoted) const {
5201 // We could support CastInst too.
5202 return isa<BinaryOperator>(ToBePromoted);
5203 }
5204
5205 /// \brief Check if it is profitable to promote \p ToBePromoted
5206 /// by moving downward the transition through.
5207 bool shouldPromote(const Instruction *ToBePromoted) const {
5208 // Promote only if all the operands can be statically expanded.
5209 // Indeed, we do not want to introduce any new kind of transitions.
5210 for (const Use &U : ToBePromoted->operands()) {
5211 const Value *Val = U.get();
5212 if (Val == getEndOfTransition()) {
5213 // If the use is a division and the transition is on the rhs,
5214 // we cannot promote the operation, otherwise we may create a
5215 // division by zero.
5216 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5217 return false;
5218 continue;
5219 }
5220 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5221 !isa<ConstantFP>(Val))
5222 return false;
5223 }
5224 // Check that the resulting operation is legal.
5225 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5226 if (!ISDOpcode)
5227 return false;
5228 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005229 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005230 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005231 }
5232
5233 /// \brief Check whether or not \p Use can be combined
5234 /// with the transition.
5235 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5236 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5237
5238 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5239 void enqueueForPromotion(Instruction *ToBePromoted) {
5240 InstsToBePromoted.push_back(ToBePromoted);
5241 }
5242
5243 /// \brief Set the instruction that will be combined with the transition.
5244 void recordCombineInstruction(Instruction *ToBeCombined) {
5245 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5246 CombineInst = ToBeCombined;
5247 }
5248
5249 /// \brief Promote all the instructions enqueued for promotion if it is
5250 /// is profitable.
5251 /// \return True if the promotion happened, false otherwise.
5252 bool promote() {
5253 // Check if there is something to promote.
5254 // Right now, if we do not have anything to combine with,
5255 // we assume the promotion is not profitable.
5256 if (InstsToBePromoted.empty() || !CombineInst)
5257 return false;
5258
5259 // Check cost.
5260 if (!StressStoreExtract && !isProfitableToPromote())
5261 return false;
5262
5263 // Promote.
5264 for (auto &ToBePromoted : InstsToBePromoted)
5265 promoteImpl(ToBePromoted);
5266 InstsToBePromoted.clear();
5267 return true;
5268 }
5269};
5270} // End of anonymous namespace.
5271
5272void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5273 // At this point, we know that all the operands of ToBePromoted but Def
5274 // can be statically promoted.
5275 // For Def, we need to use its parameter in ToBePromoted:
5276 // b = ToBePromoted ty1 a
5277 // Def = Transition ty1 b to ty2
5278 // Move the transition down.
5279 // 1. Replace all uses of the promoted operation by the transition.
5280 // = ... b => = ... Def.
5281 assert(ToBePromoted->getType() == Transition->getType() &&
5282 "The type of the result of the transition does not match "
5283 "the final type");
5284 ToBePromoted->replaceAllUsesWith(Transition);
5285 // 2. Update the type of the uses.
5286 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5287 Type *TransitionTy = getTransitionType();
5288 ToBePromoted->mutateType(TransitionTy);
5289 // 3. Update all the operands of the promoted operation with promoted
5290 // operands.
5291 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5292 for (Use &U : ToBePromoted->operands()) {
5293 Value *Val = U.get();
5294 Value *NewVal = nullptr;
5295 if (Val == Transition)
5296 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5297 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5298 isa<ConstantFP>(Val)) {
5299 // Use a splat constant if it is not safe to use undef.
5300 NewVal = getConstantVector(
5301 cast<Constant>(Val),
5302 isa<UndefValue>(Val) ||
5303 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5304 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005305 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5306 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005307 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5308 }
5309 Transition->removeFromParent();
5310 Transition->insertAfter(ToBePromoted);
5311 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5312}
5313
5314/// Some targets can do store(extractelement) with one instruction.
5315/// Try to push the extractelement towards the stores when the target
5316/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005317bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005318 unsigned CombineCost = UINT_MAX;
5319 if (DisableStoreExtract || !TLI ||
5320 (!StressStoreExtract &&
5321 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5322 Inst->getOperand(1), CombineCost)))
5323 return false;
5324
5325 // At this point we know that Inst is a vector to scalar transition.
5326 // Try to move it down the def-use chain, until:
5327 // - We can combine the transition with its single use
5328 // => we got rid of the transition.
5329 // - We escape the current basic block
5330 // => we would need to check that we are moving it at a cheaper place and
5331 // we do not do that for now.
5332 BasicBlock *Parent = Inst->getParent();
5333 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005334 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005335 // If the transition has more than one use, assume this is not going to be
5336 // beneficial.
5337 while (Inst->hasOneUse()) {
5338 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5339 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5340
5341 if (ToBePromoted->getParent() != Parent) {
5342 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5343 << ToBePromoted->getParent()->getName()
5344 << ") than the transition (" << Parent->getName() << ").\n");
5345 return false;
5346 }
5347
5348 if (VPH.canCombine(ToBePromoted)) {
5349 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5350 << "will be combined with: " << *ToBePromoted << '\n');
5351 VPH.recordCombineInstruction(ToBePromoted);
5352 bool Changed = VPH.promote();
5353 NumStoreExtractExposed += Changed;
5354 return Changed;
5355 }
5356
5357 DEBUG(dbgs() << "Try promoting.\n");
5358 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5359 return false;
5360
5361 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5362
5363 VPH.enqueueForPromotion(ToBePromoted);
5364 Inst = ToBePromoted;
5365 }
5366 return false;
5367}
5368
Sanjay Patelfc580a62015-09-21 23:03:16 +00005369bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005370 // Bail out if we inserted the instruction to prevent optimizations from
5371 // stepping on each other's toes.
5372 if (InsertedInsts.count(I))
5373 return false;
5374
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005375 if (PHINode *P = dyn_cast<PHINode>(I)) {
5376 // It is possible for very late stage optimizations (such as SimplifyCFG)
5377 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5378 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005379 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005380 P->replaceAllUsesWith(V);
5381 P->eraseFromParent();
5382 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005383 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005384 }
Chris Lattneree588de2011-01-15 07:29:01 +00005385 return false;
5386 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005387
Chris Lattneree588de2011-01-15 07:29:01 +00005388 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005389 // If the source of the cast is a constant, then this should have
5390 // already been constant folded. The only reason NOT to constant fold
5391 // it is if something (e.g. LSR) was careful to place the constant
5392 // evaluation in a block other than then one that uses it (e.g. to hoist
5393 // the address of globals out of a loop). If this is the case, we don't
5394 // want to forward-subst the cast.
5395 if (isa<Constant>(CI->getOperand(0)))
5396 return false;
5397
Mehdi Amini44ede332015-07-09 02:09:04 +00005398 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005399 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005400
Chris Lattneree588de2011-01-15 07:29:01 +00005401 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005402 /// Sink a zext or sext into its user blocks if the target type doesn't
5403 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005404 if (TLI &&
5405 TLI->getTypeAction(CI->getContext(),
5406 TLI->getValueType(*DL, CI->getType())) ==
5407 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005408 return SinkCast(CI);
5409 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005410 bool MadeChange = moveExtToFormExtLoad(I);
5411 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005412 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005413 }
Chris Lattneree588de2011-01-15 07:29:01 +00005414 return false;
5415 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005416
Chris Lattneree588de2011-01-15 07:29:01 +00005417 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005418 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005419 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005420
Chris Lattneree588de2011-01-15 07:29:01 +00005421 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005422 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005423 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005424 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005425 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005426 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5427 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005428 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005429 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005430 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005431
Chris Lattneree588de2011-01-15 07:29:01 +00005432 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005433 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005434 if (TLI) {
5435 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005436 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005437 SI->getOperand(0)->getType(), AS);
5438 }
Chris Lattneree588de2011-01-15 07:29:01 +00005439 return false;
5440 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005441
Yi Jiangd069f632014-04-21 19:34:27 +00005442 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5443
5444 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5445 BinOp->getOpcode() == Instruction::LShr)) {
5446 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5447 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005448 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005449
5450 return false;
5451 }
5452
Chris Lattneree588de2011-01-15 07:29:01 +00005453 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005454 if (GEPI->hasAllZeroIndices()) {
5455 /// The GEP operand must be a pointer, so must its result -> BitCast
5456 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5457 GEPI->getName(), GEPI);
5458 GEPI->replaceAllUsesWith(NC);
5459 GEPI->eraseFromParent();
5460 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005461 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005462 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005463 }
Chris Lattneree588de2011-01-15 07:29:01 +00005464 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005465 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005466
Chris Lattneree588de2011-01-15 07:29:01 +00005467 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005468 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005469
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005470 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005471 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005472
Tim Northoveraeb8e062014-02-19 10:02:43 +00005473 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005474 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005475
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005476 if (auto *Switch = dyn_cast<SwitchInst>(I))
5477 return optimizeSwitchInst(Switch);
5478
Quentin Colombetc32615d2014-10-31 17:52:53 +00005479 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005480 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005481
Chris Lattneree588de2011-01-15 07:29:01 +00005482 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005483}
5484
James Molloyf01488e2016-01-15 09:20:19 +00005485/// Given an OR instruction, check to see if this is a bitreverse
5486/// idiom. If so, insert the new intrinsic and return true.
5487static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5488 const TargetLowering &TLI) {
5489 if (!I.getType()->isIntegerTy() ||
5490 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5491 TLI.getValueType(DL, I.getType(), true)))
5492 return false;
5493
5494 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005495 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005496 return false;
5497 Instruction *LastInst = Insts.back();
5498 I.replaceAllUsesWith(LastInst);
5499 RecursivelyDeleteTriviallyDeadInstructions(&I);
5500 return true;
5501}
5502
Chris Lattnerf2836d12007-03-31 04:06:36 +00005503// In this pass we look for GEP and cast instructions that are used
5504// across basic blocks and rewrite them to improve basic-block-at-a-time
5505// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005506bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005507 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005508 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005509
Chris Lattner7a277142011-01-15 07:14:54 +00005510 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005511 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005512 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005513 if (ModifiedDT)
5514 return true;
5515 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005516
James Molloyf01488e2016-01-15 09:20:19 +00005517 bool MadeBitReverse = true;
5518 while (TLI && MadeBitReverse) {
5519 MadeBitReverse = false;
5520 for (auto &I : reverse(BB)) {
5521 if (makeBitReverse(I, *DL, *TLI)) {
5522 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005523 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005524 break;
5525 }
5526 }
5527 }
James Molloy3ef84c42016-01-15 10:36:01 +00005528 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005529
Chris Lattnerf2836d12007-03-31 04:06:36 +00005530 return MadeChange;
5531}
Devang Patel53771ba2011-08-18 00:50:51 +00005532
5533// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005534// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005535// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005536bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005537 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005538 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005539 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005540 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005541 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005542 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005543 // Leave dbg.values that refer to an alloca alone. These
5544 // instrinsics describe the address of a variable (= the alloca)
5545 // being taken. They should not be moved next to the alloca
5546 // (and to the beginning of the scope), but rather stay close to
5547 // where said address is used.
5548 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005549 PrevNonDbgInst = Insn;
5550 continue;
5551 }
5552
5553 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5554 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005555 // If VI is a phi in a block with an EHPad terminator, we can't insert
5556 // after it.
5557 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5558 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005559 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5560 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005561 if (isa<PHINode>(VI))
5562 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5563 else
5564 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005565 MadeChange = true;
5566 ++NumDbgValueMoved;
5567 }
5568 }
5569 }
5570 return MadeChange;
5571}
Tim Northovercea0abb2014-03-29 08:22:29 +00005572
5573// If there is a sequence that branches based on comparing a single bit
5574// against zero that can be combined into a single instruction, and the
5575// target supports folding these into a single instruction, sink the
5576// mask and compare into the branch uses. Do this before OptimizeBlock ->
5577// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5578// searched for.
5579bool CodeGenPrepare::sinkAndCmp(Function &F) {
5580 if (!EnableAndCmpSinking)
5581 return false;
5582 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5583 return false;
5584 bool MadeChange = false;
Sanjay Patel892f1672016-04-11 20:13:44 +00005585 for (BasicBlock &BB : F) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005586 // Does this BB end with the following?
5587 // %andVal = and %val, #single-bit-set
5588 // %icmpVal = icmp %andResult, 0
5589 // br i1 %cmpVal label %dest1, label %dest2"
Sanjay Patel892f1672016-04-11 20:13:44 +00005590 BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
Tim Northovercea0abb2014-03-29 08:22:29 +00005591 if (!Brcc || !Brcc->isConditional())
5592 continue;
5593 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005594 if (!Cmp || Cmp->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005595 continue;
5596 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5597 if (!Zero || !Zero->isZero())
5598 continue;
5599 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005600 if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005601 continue;
5602 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5603 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5604 continue;
Sanjay Patel892f1672016-04-11 20:13:44 +00005605 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
Tim Northovercea0abb2014-03-29 08:22:29 +00005606
5607 // Push the "and; icmp" for any users that are conditional branches.
5608 // Since there can only be one branch use per BB, we don't need to keep
5609 // track of which BBs we insert into.
Sanjay Patel892f1672016-04-11 20:13:44 +00005610 for (Use &TheUse : Cmp->uses()) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005611 // Find brcc use.
Sanjay Patel892f1672016-04-11 20:13:44 +00005612 BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
Tim Northovercea0abb2014-03-29 08:22:29 +00005613 if (!BrccUser || !BrccUser->isConditional())
5614 continue;
5615 BasicBlock *UserBB = BrccUser->getParent();
Sanjay Patel892f1672016-04-11 20:13:44 +00005616 if (UserBB == &BB) continue;
Tim Northovercea0abb2014-03-29 08:22:29 +00005617 DEBUG(dbgs() << "found Brcc use\n");
5618
5619 // Sink the "and; icmp" to use.
5620 MadeChange = true;
5621 BinaryOperator *NewAnd =
5622 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5623 BrccUser);
5624 CmpInst *NewCmp =
5625 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5626 "", BrccUser);
5627 TheUse = NewCmp;
5628 ++NumAndCmpsMoved;
5629 DEBUG(BrccUser->getParent()->dump());
5630 }
5631 }
5632 return MadeChange;
5633}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005634
5635/// \brief Scale down both weights to fit into uint32_t.
5636static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5637 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5638 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5639 NewTrue = NewTrue / Scale;
5640 NewFalse = NewFalse / Scale;
5641}
5642
5643/// \brief Some targets prefer to split a conditional branch like:
5644/// \code
5645/// %0 = icmp ne i32 %a, 0
5646/// %1 = icmp ne i32 %b, 0
5647/// %or.cond = or i1 %0, %1
5648/// br i1 %or.cond, label %TrueBB, label %FalseBB
5649/// \endcode
5650/// into multiple branch instructions like:
5651/// \code
5652/// bb1:
5653/// %0 = icmp ne i32 %a, 0
5654/// br i1 %0, label %TrueBB, label %bb2
5655/// bb2:
5656/// %1 = icmp ne i32 %b, 0
5657/// br i1 %1, label %TrueBB, label %FalseBB
5658/// \endcode
5659/// This usually allows instruction selection to do even further optimizations
5660/// and combine the compare with the branch instruction. Currently this is
5661/// applied for targets which have "cheap" jump instructions.
5662///
5663/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5664///
5665bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005666 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005667 return false;
5668
5669 bool MadeChange = false;
5670 for (auto &BB : F) {
5671 // Does this BB end with the following?
5672 // %cond1 = icmp|fcmp|binary instruction ...
5673 // %cond2 = icmp|fcmp|binary instruction ...
5674 // %cond.or = or|and i1 %cond1, cond2
5675 // br i1 %cond.or label %dest1, label %dest2"
5676 BinaryOperator *LogicOp;
5677 BasicBlock *TBB, *FBB;
5678 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5679 continue;
5680
Sanjay Patel42574202015-09-02 19:23:23 +00005681 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5682 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5683 continue;
5684
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005685 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005686 Value *Cond1, *Cond2;
5687 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5688 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005689 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005690 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5691 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005692 Opc = Instruction::Or;
5693 else
5694 continue;
5695
5696 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5697 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5698 continue;
5699
5700 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5701
5702 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005703 auto TmpBB =
5704 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5705 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005706
5707 // Update original basic block by using the first condition directly by the
5708 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005709 Br1->setCondition(Cond1);
5710 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005711
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005712 // Depending on the conditon we have to either replace the true or the false
5713 // successor of the original branch instruction.
5714 if (Opc == Instruction::And)
5715 Br1->setSuccessor(0, TmpBB);
5716 else
5717 Br1->setSuccessor(1, TmpBB);
5718
5719 // Fill in the new basic block.
5720 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005721 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5722 I->removeFromParent();
5723 I->insertBefore(Br2);
5724 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005725
5726 // Update PHI nodes in both successors. The original BB needs to be
5727 // replaced in one succesor's PHI nodes, because the branch comes now from
5728 // the newly generated BB (NewBB). In the other successor we need to add one
5729 // incoming edge to the PHI nodes, because both branch instructions target
5730 // now the same successor. Depending on the original branch condition
5731 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00005732 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005733 // This doesn't change the successor order of the just created branch
5734 // instruction (or any other instruction).
5735 if (Opc == Instruction::Or)
5736 std::swap(TBB, FBB);
5737
5738 // Replace the old BB with the new BB.
5739 for (auto &I : *TBB) {
5740 PHINode *PN = dyn_cast<PHINode>(&I);
5741 if (!PN)
5742 break;
5743 int i;
5744 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5745 PN->setIncomingBlock(i, TmpBB);
5746 }
5747
5748 // Add another incoming edge form the new BB.
5749 for (auto &I : *FBB) {
5750 PHINode *PN = dyn_cast<PHINode>(&I);
5751 if (!PN)
5752 break;
5753 auto *Val = PN->getIncomingValueForBlock(&BB);
5754 PN->addIncoming(Val, TmpBB);
5755 }
5756
5757 // Update the branch weights (from SelectionDAGBuilder::
5758 // FindMergedConditions).
5759 if (Opc == Instruction::Or) {
5760 // Codegen X | Y as:
5761 // BB1:
5762 // jmp_if_X TBB
5763 // jmp TmpBB
5764 // TmpBB:
5765 // jmp_if_Y TBB
5766 // jmp FBB
5767 //
5768
5769 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5770 // The requirement is that
5771 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5772 // = TrueProb for orignal BB.
5773 // Assuming the orignal weights are A and B, one choice is to set BB1's
5774 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5775 // assumes that
5776 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5777 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5778 // TmpBB, but the math is more complicated.
5779 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005780 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005781 uint64_t NewTrueWeight = TrueWeight;
5782 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5783 scaleWeights(NewTrueWeight, NewFalseWeight);
5784 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5785 .createBranchWeights(TrueWeight, FalseWeight));
5786
5787 NewTrueWeight = TrueWeight;
5788 NewFalseWeight = 2 * FalseWeight;
5789 scaleWeights(NewTrueWeight, NewFalseWeight);
5790 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5791 .createBranchWeights(TrueWeight, FalseWeight));
5792 }
5793 } else {
5794 // Codegen X & Y as:
5795 // BB1:
5796 // jmp_if_X TmpBB
5797 // jmp FBB
5798 // TmpBB:
5799 // jmp_if_Y TBB
5800 // jmp FBB
5801 //
5802 // This requires creation of TmpBB after CurBB.
5803
5804 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5805 // The requirement is that
5806 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5807 // = FalseProb for orignal BB.
5808 // Assuming the orignal weights are A and B, one choice is to set BB1's
5809 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5810 // assumes that
5811 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5812 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005813 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005814 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5815 uint64_t NewFalseWeight = FalseWeight;
5816 scaleWeights(NewTrueWeight, NewFalseWeight);
5817 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5818 .createBranchWeights(TrueWeight, FalseWeight));
5819
5820 NewTrueWeight = 2 * TrueWeight;
5821 NewFalseWeight = FalseWeight;
5822 scaleWeights(NewTrueWeight, NewFalseWeight);
5823 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5824 .createBranchWeights(TrueWeight, FalseWeight));
5825 }
5826 }
5827
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005828 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005829 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005830 ModifiedDT = true;
5831
5832 MadeChange = true;
5833
5834 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5835 TmpBB->dump());
5836 }
5837 return MadeChange;
5838}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005839
5840void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005841 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005842 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5843}