blob: 1e5d682a3313942565c25c45e24d82aac1eca855 [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 Lim90b6b502016-12-16 20:38:39 +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 Lim90b6b502016-12-16 20:38:39 +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 Lim90b6b502016-12-16 20:38:39 +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 Lim90b6b502016-12-16 20:38:39 +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 Lim90b6b502016-12-16 20:38:39 +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);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000221 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000222}
Devang Patel09f162c2007-05-01 21:15:47 +0000223
Devang Patel8c78a0b2007-05-03 01:11:54 +0000224char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000225INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
226 "Optimize for code generation", false, false)
227INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
228INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
229 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000230
Bill Wendling7a639ea2013-06-19 21:07:11 +0000231FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
232 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000233}
234
Chris Lattnerf2836d12007-03-31 04:06:36 +0000235bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000236 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000237 return false;
238
Mehdi Amini4fe37982015-07-07 18:45:17 +0000239 DL = &F.getParent()->getDataLayout();
240
Chris Lattnerf2836d12007-03-31 04:06:36 +0000241 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000242 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000243 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000244 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000245 BFI.reset();
246 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000247
Devang Patel8f606d72011-03-24 15:35:25 +0000248 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000249 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000250 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000251 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000252 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000253 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000254 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000255
Dehao Chen302b69c2016-10-18 20:42:47 +0000256 if (ProfileGuidedSectionPrefix) {
257 ProfileSummaryInfo *PSI =
258 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
259 if (PSI->isFunctionEntryHot(&F))
260 F.setSectionPrefix(".hot");
261 else if (PSI->isFunctionEntryCold(&F))
262 F.setSectionPrefix(".cold");
263 }
264
Preston Gurdcdf540d2012-09-04 18:22:17 +0000265 /// This optimization identifies DIV instructions that can be
266 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000267 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000268 const DenseMap<unsigned int, unsigned int> &BypassWidths =
269 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000270 BasicBlock* BB = &*F.begin();
271 while (BB != nullptr) {
272 // bypassSlowDivision may create new BBs, but we don't want to reapply the
273 // optimization to those blocks.
274 BasicBlock* Next = BB->getNextNode();
275 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
276 BB = Next;
277 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000278 }
279
280 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000281 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000282 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000283
Devang Patel53771ba2011-08-18 00:50:51 +0000284 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000285 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000286 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000287 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000288
Tim Northovercea0abb2014-03-29 08:22:29 +0000289 // If there is a mask, compare against zero, and branch that can be combined
290 // into a single target instruction, push the mask and compare into branch
291 // users. Do this before OptimizeBlock -> OptimizeInst ->
292 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000293 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000294 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000295 EverMadeChange |= splitBranchCondition(F);
296 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000297
Chris Lattnerc3748562007-04-02 01:35:34 +0000298 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000299 while (MadeChange) {
300 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000301 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000302 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000303 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000304 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000305
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000306 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000307 if (ModifiedDTOnIteration)
308 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000309 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000310 EverMadeChange |= MadeChange;
311 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000312
313 SunkAddrs.clear();
314
Cameron Zwarich338d3622011-03-11 21:52:04 +0000315 if (!DisableBranchOpts) {
316 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000317 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000318 for (BasicBlock &BB : F) {
319 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
320 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000321 if (!MadeChange) continue;
322
323 for (SmallVectorImpl<BasicBlock*>::iterator
324 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
325 if (pred_begin(*II) == pred_end(*II))
326 WorkList.insert(*II);
327 }
328
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000329 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000330 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000331 while (!WorkList.empty()) {
332 BasicBlock *BB = *WorkList.begin();
333 WorkList.erase(BB);
334 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
335
336 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000337
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000338 for (SmallVectorImpl<BasicBlock*>::iterator
339 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
340 if (pred_begin(*II) == pred_end(*II))
341 WorkList.insert(*II);
342 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000343
Nadav Rotem70409992012-08-14 05:19:07 +0000344 // Merge pairs of basic blocks with unconditional branches, connected by
345 // a single edge.
346 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000347 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000348
Cameron Zwarich338d3622011-03-11 21:52:04 +0000349 EverMadeChange |= MadeChange;
350 }
351
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000352 if (!DisableGCOpts) {
353 SmallVector<Instruction *, 2> Statepoints;
354 for (BasicBlock &BB : F)
355 for (Instruction &I : BB)
356 if (isStatepoint(I))
357 Statepoints.push_back(&I);
358 for (auto &I : Statepoints)
359 EverMadeChange |= simplifyOffsetableRelocate(*I);
360 }
361
Chris Lattnerf2836d12007-03-31 04:06:36 +0000362 return EverMadeChange;
363}
364
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000365/// Merge basic blocks which are connected by a single edge, where one of the
366/// basic blocks has a single successor pointing to the other basic block,
367/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000368bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000369 bool Changed = false;
370 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000371 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000372 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000373 // If the destination block has a single pred, then this is a trivial
374 // edge, just collapse it.
375 BasicBlock *SinglePred = BB->getSinglePredecessor();
376
Evan Cheng64a223a2012-09-28 23:58:57 +0000377 // Don't merge if BB's address is taken.
378 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000379
380 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
381 if (Term && !Term->isConditional()) {
382 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000383 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000384 // Remember if SinglePred was the entry block of the function.
385 // If so, we will need to move BB back to the entry position.
386 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000387 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000388
389 if (isEntry && BB != &BB->getParent()->getEntryBlock())
390 BB->moveBefore(&BB->getParent()->getEntryBlock());
391
392 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000393 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000394 }
395 }
396 return Changed;
397}
398
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000399/// Find a destination block from BB if BB is mergeable empty block.
400BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
401 // If this block doesn't end with an uncond branch, ignore it.
402 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
403 if (!BI || !BI->isUnconditional())
404 return nullptr;
405
406 // If the instruction before the branch (skipping debug info) isn't a phi
407 // node, then other stuff is happening here.
408 BasicBlock::iterator BBI = BI->getIterator();
409 if (BBI != BB->begin()) {
410 --BBI;
411 while (isa<DbgInfoIntrinsic>(BBI)) {
412 if (BBI == BB->begin())
413 break;
414 --BBI;
415 }
416 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
417 return nullptr;
418 }
419
420 // Do not break infinite loops.
421 BasicBlock *DestBB = BI->getSuccessor(0);
422 if (DestBB == BB)
423 return nullptr;
424
425 if (!canMergeBlocks(BB, DestBB))
426 DestBB = nullptr;
427
428 return DestBB;
429}
430
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000431/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
432/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
433/// edges in ways that are non-optimal for isel. Start by eliminating these
434/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000435bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000436 SmallPtrSet<BasicBlock *, 16> Preheaders;
437 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
438 while (!LoopList.empty()) {
439 Loop *L = LoopList.pop_back_val();
440 LoopList.insert(LoopList.end(), L->begin(), L->end());
441 if (BasicBlock *Preheader = L->getLoopPreheader())
442 Preheaders.insert(Preheader);
443 }
444
Chris Lattnerc3748562007-04-02 01:35:34 +0000445 bool MadeChange = false;
446 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000447 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000448 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000449 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
450 if (!DestBB ||
451 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000452 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000453
Sanjay Patelfc580a62015-09-21 23:03:16 +0000454 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000455 MadeChange = true;
456 }
457 return MadeChange;
458}
459
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000460bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
461 BasicBlock *DestBB,
462 bool isPreheader) {
463 // Do not delete loop preheaders if doing so would create a critical edge.
464 // Loop preheaders can be good locations to spill registers. If the
465 // preheader is deleted and we create a critical edge, registers may be
466 // spilled in the loop body instead.
467 if (!DisablePreheaderProtect && isPreheader &&
468 !(BB->getSinglePredecessor() &&
469 BB->getSinglePredecessor()->getSingleSuccessor()))
470 return false;
471
472 // Try to skip merging if the unique predecessor of BB is terminated by a
473 // switch or indirect branch instruction, and BB is used as an incoming block
474 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
475 // add COPY instructions in the predecessor of BB instead of BB (if it is not
476 // merged). Note that the critical edge created by merging such blocks wont be
477 // split in MachineSink because the jump table is not analyzable. By keeping
478 // such empty block (BB), ISel will place COPY instructions in BB, not in the
479 // predecessor of BB.
480 BasicBlock *Pred = BB->getUniquePredecessor();
481 if (!Pred ||
482 !(isa<SwitchInst>(Pred->getTerminator()) ||
483 isa<IndirectBrInst>(Pred->getTerminator())))
484 return true;
485
486 if (BB->getTerminator() != BB->getFirstNonPHI())
487 return true;
488
489 // We use a simple cost heuristic which determine skipping merging is
490 // profitable if the cost of skipping merging is less than the cost of
491 // merging : Cost(skipping merging) < Cost(merging BB), where the
492 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
493 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
494 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
495 // Freq(Pred) / Freq(BB) > 2.
496 // Note that if there are multiple empty blocks sharing the same incoming
497 // value for the PHIs in the DestBB, we consider them together. In such
498 // case, Cost(merging BB) will be the sum of their frequencies.
499
500 if (!isa<PHINode>(DestBB->begin()))
501 return true;
502
503 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
504
505 // Find all other incoming blocks from which incoming values of all PHIs in
506 // DestBB are the same as the ones from BB.
507 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
508 ++PI) {
509 BasicBlock *DestBBPred = *PI;
510 if (DestBBPred == BB)
511 continue;
512
513 bool HasAllSameValue = true;
514 BasicBlock::const_iterator DestBBI = DestBB->begin();
515 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
516 if (DestPN->getIncomingValueForBlock(BB) !=
517 DestPN->getIncomingValueForBlock(DestBBPred)) {
518 HasAllSameValue = false;
519 break;
520 }
521 }
522 if (HasAllSameValue)
523 SameIncomingValueBBs.insert(DestBBPred);
524 }
525
526 // See if all BB's incoming values are same as the value from Pred. In this
527 // case, no reason to skip merging because COPYs are expected to be place in
528 // Pred already.
529 if (SameIncomingValueBBs.count(Pred))
530 return true;
531
532 if (!BFI) {
533 Function &F = *BB->getParent();
534 LoopInfo LI{DominatorTree(F)};
535 BPI.reset(new BranchProbabilityInfo(F, LI));
536 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
537 }
538
539 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
540 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
541
542 for (auto SameValueBB : SameIncomingValueBBs)
543 if (SameValueBB->getUniquePredecessor() == Pred &&
544 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
545 BBFreq += BFI->getBlockFreq(SameValueBB);
546
547 return PredFreq.getFrequency() <=
548 BBFreq.getFrequency() * FreqRatioToSkipMerge;
549}
550
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000551/// Return true if we can merge BB into DestBB if there is a single
552/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000553/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000554bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000555 const BasicBlock *DestBB) const {
556 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
557 // the successor. If there are more complex condition (e.g. preheaders),
558 // don't mess around with them.
559 BasicBlock::const_iterator BBI = BB->begin();
560 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000561 for (const User *U : PN->users()) {
562 const Instruction *UI = cast<Instruction>(U);
563 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000564 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000565 // If User is inside DestBB block and it is a PHINode then check
566 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000567 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000568 if (UI->getParent() == DestBB) {
569 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000570 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
571 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
572 if (Insn && Insn->getParent() == BB &&
573 Insn->getParent() != UPN->getIncomingBlock(I))
574 return false;
575 }
576 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000577 }
578 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000579
Chris Lattnerc3748562007-04-02 01:35:34 +0000580 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
581 // and DestBB may have conflicting incoming values for the block. If so, we
582 // can't merge the block.
583 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
584 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000585
Chris Lattnerc3748562007-04-02 01:35:34 +0000586 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000587 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000588 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
589 // It is faster to get preds from a PHI than with pred_iterator.
590 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
591 BBPreds.insert(BBPN->getIncomingBlock(i));
592 } else {
593 BBPreds.insert(pred_begin(BB), pred_end(BB));
594 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000595
Chris Lattnerc3748562007-04-02 01:35:34 +0000596 // Walk the preds of DestBB.
597 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
598 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
599 if (BBPreds.count(Pred)) { // Common predecessor?
600 BBI = DestBB->begin();
601 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
602 const Value *V1 = PN->getIncomingValueForBlock(Pred);
603 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000604
Chris Lattnerc3748562007-04-02 01:35:34 +0000605 // If V2 is a phi node in BB, look up what the mapped value will be.
606 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
607 if (V2PN->getParent() == BB)
608 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000609
Chris Lattnerc3748562007-04-02 01:35:34 +0000610 // If there is a conflict, bail out.
611 if (V1 != V2) return false;
612 }
613 }
614 }
615
616 return true;
617}
618
619
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000620/// Eliminate a basic block that has only phi's and an unconditional branch in
621/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000622void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000623 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
624 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000625
David Greene74e2d492010-01-05 01:27:11 +0000626 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000627
Chris Lattnerc3748562007-04-02 01:35:34 +0000628 // If the destination block has a single pred, then this is a trivial edge,
629 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000630 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000631 if (SinglePred != DestBB) {
632 // Remember if SinglePred was the entry block of the function. If so, we
633 // will need to move BB back to the entry position.
634 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000635 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000636
Chris Lattner8a172da2008-11-28 19:54:49 +0000637 if (isEntry && BB != &BB->getParent()->getEntryBlock())
638 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000639
David Greene74e2d492010-01-05 01:27:11 +0000640 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000641 return;
642 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000643 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000644
Chris Lattnerc3748562007-04-02 01:35:34 +0000645 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
646 // to handle the new incoming edges it is about to have.
647 PHINode *PN;
648 for (BasicBlock::iterator BBI = DestBB->begin();
649 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
650 // Remove the incoming value for BB, and remember it.
651 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000652
Chris Lattnerc3748562007-04-02 01:35:34 +0000653 // Two options: either the InVal is a phi node defined in BB or it is some
654 // value that dominates BB.
655 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
656 if (InValPhi && InValPhi->getParent() == BB) {
657 // Add all of the input values of the input PHI as inputs of this phi.
658 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
659 PN->addIncoming(InValPhi->getIncomingValue(i),
660 InValPhi->getIncomingBlock(i));
661 } else {
662 // Otherwise, add one instance of the dominating value for each edge that
663 // we will be adding.
664 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
665 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
666 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
667 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000668 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
669 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000670 }
671 }
672 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000673
Chris Lattnerc3748562007-04-02 01:35:34 +0000674 // The PHIs are now updated, change everything that refers to BB to use
675 // DestBB and remove BB.
676 BB->replaceAllUsesWith(DestBB);
677 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000678 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000679
David Greene74e2d492010-01-05 01:27:11 +0000680 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000681}
682
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000683// Computes a map of base pointer relocation instructions to corresponding
684// derived pointer relocation instructions given a vector of all relocate calls
685static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000686 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
687 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
688 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000689 // Collect information in two maps: one primarily for locating the base object
690 // while filling the second map; the second map is the final structure holding
691 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000692 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
693 for (auto *ThisRelocate : AllRelocateCalls) {
694 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
695 ThisRelocate->getDerivedPtrIndex());
696 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000697 }
698 for (auto &Item : RelocateIdxMap) {
699 std::pair<unsigned, unsigned> Key = Item.first;
700 if (Key.first == Key.second)
701 // Base relocation: nothing to insert
702 continue;
703
Manuel Jacob83eefa62016-01-05 04:03:00 +0000704 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000705 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000706
707 // We're iterating over RelocateIdxMap so we cannot modify it.
708 auto MaybeBase = RelocateIdxMap.find(BaseKey);
709 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000710 // TODO: We might want to insert a new base object relocate and gep off
711 // that, if there are enough derived object relocates.
712 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000713
714 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000715 }
716}
717
718// Accepts a GEP and extracts the operands into a vector provided they're all
719// small integer constants
720static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
721 SmallVectorImpl<Value *> &OffsetV) {
722 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
723 // Only accept small constant integer operands
724 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
725 if (!Op || Op->getZExtValue() > 20)
726 return false;
727 }
728
729 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
730 OffsetV.push_back(GEP->getOperand(i));
731 return true;
732}
733
734// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
735// replace, computes a replacement, and affects it.
736static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000737simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
738 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000739 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000740 for (GCRelocateInst *ToReplace : Targets) {
741 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000742 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000743 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000744 // A duplicate relocate call. TODO: coalesce duplicates.
745 continue;
746 }
747
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000748 if (RelocatedBase->getParent() != ToReplace->getParent()) {
749 // Base and derived relocates are in different basic blocks.
750 // In this case transform is only valid when base dominates derived
751 // relocate. However it would be too expensive to check dominance
752 // for each such relocate, so we skip the whole transformation.
753 continue;
754 }
755
Manuel Jacob83eefa62016-01-05 04:03:00 +0000756 Value *Base = ToReplace->getBasePtr();
757 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000758 if (!Derived || Derived->getPointerOperand() != Base)
759 continue;
760
761 SmallVector<Value *, 2> OffsetV;
762 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
763 continue;
764
765 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000766 assert(RelocatedBase->getNextNode() &&
767 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000768
769 // Insert after RelocatedBase
770 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000771 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000772
773 // If gc_relocate does not match the actual type, cast it to the right type.
774 // In theory, there must be a bitcast after gc_relocate if the type does not
775 // match, and we should reuse it to get the derived pointer. But it could be
776 // cases like this:
777 // bb1:
778 // ...
779 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
780 // br label %merge
781 //
782 // bb2:
783 // ...
784 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
785 // br label %merge
786 //
787 // merge:
788 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
789 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
790 //
791 // In this case, we can not find the bitcast any more. So we insert a new bitcast
792 // no matter there is already one or not. In this way, we can handle all cases, and
793 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000794 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000795 if (RelocatedBase->getType() != Base->getType()) {
796 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000797 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000798 }
David Blaikie68d535c2015-03-24 22:38:16 +0000799 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000800 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000801 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000802 // If the newly generated derived pointer's type does not match the original derived
803 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000804 Value *ActualReplacement = Replacement;
805 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000806 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000807 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000808 }
809 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000810 ToReplace->eraseFromParent();
811
812 MadeChange = true;
813 }
814 return MadeChange;
815}
816
817// Turns this:
818//
819// %base = ...
820// %ptr = gep %base + 15
821// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
822// %base' = relocate(%tok, i32 4, i32 4)
823// %ptr' = relocate(%tok, i32 4, i32 5)
824// %val = load %ptr'
825//
826// into this:
827//
828// %base = ...
829// %ptr = gep %base + 15
830// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
831// %base' = gc.relocate(%tok, i32 4, i32 4)
832// %ptr' = gep %base' + 15
833// %val = load %ptr'
834bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
835 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000836 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000837
838 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000839 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000840 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000841 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000842
843 // We need atleast one base pointer relocation + one derived pointer
844 // relocation to mangle
845 if (AllRelocateCalls.size() < 2)
846 return false;
847
848 // RelocateInstMap is a mapping from the base relocate instruction to the
849 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000850 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000851 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
852 if (RelocateInstMap.empty())
853 return false;
854
855 for (auto &Item : RelocateInstMap)
856 // Item.first is the RelocatedBase to offset against
857 // Item.second is the vector of Targets to replace
858 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
859 return MadeChange;
860}
861
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000862/// SinkCast - Sink the specified cast instruction into its user blocks
863static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000864 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000865
Chris Lattnerf2836d12007-03-31 04:06:36 +0000866 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000867 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000868
Chris Lattnerf2836d12007-03-31 04:06:36 +0000869 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000870 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000871 UI != E; ) {
872 Use &TheUse = UI.getUse();
873 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000874
Chris Lattnerf2836d12007-03-31 04:06:36 +0000875 // Figure out which BB this cast is used in. For PHI's this is the
876 // appropriate predecessor block.
877 BasicBlock *UserBB = User->getParent();
878 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000879 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000880 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000881
Chris Lattnerf2836d12007-03-31 04:06:36 +0000882 // Preincrement use iterator so we don't invalidate it.
883 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000884
David Majnemer0c80e2e2016-04-27 19:36:38 +0000885 // The first insertion point of a block containing an EH pad is after the
886 // pad. If the pad is the user, we cannot sink the cast past the pad.
887 if (User->isEHPad())
888 continue;
889
Andrew Kaylord0430e82015-11-23 19:16:15 +0000890 // If the block selected to receive the cast is an EH pad that does not
891 // allow non-PHI instructions before the terminator, we can't sink the
892 // cast.
893 if (UserBB->getTerminator()->isEHPad())
894 continue;
895
Chris Lattnerf2836d12007-03-31 04:06:36 +0000896 // If this user is in the same block as the cast, don't change the cast.
897 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000898
Chris Lattnerf2836d12007-03-31 04:06:36 +0000899 // If we have already inserted a cast into this block, use it.
900 CastInst *&InsertedCast = InsertedCasts[UserBB];
901
902 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000903 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000904 assert(InsertPt != UserBB->end());
905 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
906 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000907 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000908
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000909 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000910 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000911 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000912 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000913 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000914
Chris Lattnerf2836d12007-03-31 04:06:36 +0000915 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000916 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000917 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000918 MadeChange = true;
919 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000920
Chris Lattnerf2836d12007-03-31 04:06:36 +0000921 return MadeChange;
922}
923
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000924/// If the specified cast instruction is a noop copy (e.g. it's casting from
925/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
926/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000927///
928/// Return true if any changes are made.
929///
Mehdi Amini44ede332015-07-09 02:09:04 +0000930static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
931 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +0000932 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
933 // than sinking only nop casts, but is helpful on some platforms.
934 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
935 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
936 ASC->getDestAddressSpace()))
937 return false;
938 }
939
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000940 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000941 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
942 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000943
944 // This is an fp<->int conversion?
945 if (SrcVT.isInteger() != DstVT.isInteger())
946 return false;
947
948 // If this is an extension, it will be a zero or sign extension, which
949 // isn't a noop.
950 if (SrcVT.bitsLT(DstVT)) return false;
951
952 // If these values will be promoted, find out what they will be promoted
953 // to. This helps us consider truncates on PPC as noop copies when they
954 // are.
955 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
956 TargetLowering::TypePromoteInteger)
957 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
958 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
959 TargetLowering::TypePromoteInteger)
960 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
961
962 // If, after promotion, these are the same types, this is a noop copy.
963 if (SrcVT != DstVT)
964 return false;
965
966 return SinkCast(CI);
967}
968
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000969/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
970/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000971///
972/// Return true if any changes were made.
973static bool CombineUAddWithOverflow(CmpInst *CI) {
974 Value *A, *B;
975 Instruction *AddI;
976 if (!match(CI,
977 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
978 return false;
979
980 Type *Ty = AddI->getType();
981 if (!isa<IntegerType>(Ty))
982 return false;
983
984 // We don't want to move around uses of condition values this late, so we we
985 // check if it is legal to create the call to the intrinsic in the basic
986 // block containing the icmp:
987
988 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
989 return false;
990
991#ifndef NDEBUG
992 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
993 // for now:
994 if (AddI->hasOneUse())
995 assert(*AddI->user_begin() == CI && "expected!");
996#endif
997
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000998 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000999 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1000
1001 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1002
1003 auto *UAddWithOverflow =
1004 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1005 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1006 auto *Overflow =
1007 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1008
1009 CI->replaceAllUsesWith(Overflow);
1010 AddI->replaceAllUsesWith(UAdd);
1011 CI->eraseFromParent();
1012 AddI->eraseFromParent();
1013 return true;
1014}
1015
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001016/// Sink the given CmpInst into user blocks to reduce the number of virtual
1017/// registers that must be created and coalesced. This is a clear win except on
1018/// targets with multiple condition code registers (PowerPC), where it might
1019/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001020///
1021/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001022static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001023 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001024
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001025 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001026 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001027 return false;
1028
1029 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001030 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001031
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001032 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001033 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001034 UI != E; ) {
1035 Use &TheUse = UI.getUse();
1036 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001037
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001038 // Preincrement use iterator so we don't invalidate it.
1039 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001040
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001041 // Don't bother for PHI nodes.
1042 if (isa<PHINode>(User))
1043 continue;
1044
1045 // Figure out which BB this cmp is used in.
1046 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001047
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001048 // If this user is in the same block as the cmp, don't change the cmp.
1049 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001050
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001051 // If we have already inserted a cmp into this block, use it.
1052 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1053
1054 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001055 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001056 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001057 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001058 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1059 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001060 // Propagate the debug info.
1061 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001062 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001063
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001064 // Replace a use of the cmp with a use of the new cmp.
1065 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001066 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001067 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001068 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001069
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001070 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001071 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001072 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001073 MadeChange = true;
1074 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001075
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001076 return MadeChange;
1077}
1078
Peter Zotovf87e5502016-04-03 17:11:53 +00001079static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001080 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001081 return true;
1082
1083 if (CombineUAddWithOverflow(CI))
1084 return true;
1085
1086 return false;
1087}
1088
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001089/// Check if the candidates could be combined with a shift instruction, which
1090/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001091/// 1. Truncate instruction
1092/// 2. And instruction and the imm is a mask of the low bits:
1093/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001094static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001095 if (!isa<TruncInst>(User)) {
1096 if (User->getOpcode() != Instruction::And ||
1097 !isa<ConstantInt>(User->getOperand(1)))
1098 return false;
1099
Quentin Colombetd4f44692014-04-22 01:20:34 +00001100 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001101
Quentin Colombetd4f44692014-04-22 01:20:34 +00001102 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001103 return false;
1104 }
1105 return true;
1106}
1107
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001108/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001109static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001110SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1111 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001112 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001113 BasicBlock *UserBB = User->getParent();
1114 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1115 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1116 bool MadeChange = false;
1117
1118 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1119 TruncE = TruncI->user_end();
1120 TruncUI != TruncE;) {
1121
1122 Use &TruncTheUse = TruncUI.getUse();
1123 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1124 // Preincrement use iterator so we don't invalidate it.
1125
1126 ++TruncUI;
1127
1128 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1129 if (!ISDOpcode)
1130 continue;
1131
Tim Northovere2239ff2014-07-29 10:20:22 +00001132 // If the use is actually a legal node, there will not be an
1133 // implicit truncate.
1134 // FIXME: always querying the result type is just an
1135 // approximation; some nodes' legality is determined by the
1136 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001137 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001138 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001139 continue;
1140
1141 // Don't bother for PHI nodes.
1142 if (isa<PHINode>(TruncUser))
1143 continue;
1144
1145 BasicBlock *TruncUserBB = TruncUser->getParent();
1146
1147 if (UserBB == TruncUserBB)
1148 continue;
1149
1150 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1151 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1152
1153 if (!InsertedShift && !InsertedTrunc) {
1154 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001155 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001156 // Sink the shift
1157 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001158 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1159 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001160 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001161 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1162 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001163
1164 // Sink the trunc
1165 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1166 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001167 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001168
1169 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001170 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001171
1172 MadeChange = true;
1173
1174 TruncTheUse = InsertedTrunc;
1175 }
1176 }
1177 return MadeChange;
1178}
1179
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001180/// Sink the shift *right* instruction into user blocks if the uses could
1181/// potentially be combined with this shift instruction and generate BitExtract
1182/// instruction. It will only be applied if the architecture supports BitExtract
1183/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001184/// BB1:
1185/// %x.extract.shift = lshr i64 %arg1, 32
1186/// BB2:
1187/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1188/// ==>
1189///
1190/// BB2:
1191/// %x.extract.shift.1 = lshr i64 %arg1, 32
1192/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1193///
1194/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1195/// instruction.
1196/// Return true if any changes are made.
1197static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001198 const TargetLowering &TLI,
1199 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001200 BasicBlock *DefBB = ShiftI->getParent();
1201
1202 /// Only insert instructions in each block once.
1203 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1204
Mehdi Amini44ede332015-07-09 02:09:04 +00001205 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001206
1207 bool MadeChange = false;
1208 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1209 UI != E;) {
1210 Use &TheUse = UI.getUse();
1211 Instruction *User = cast<Instruction>(*UI);
1212 // Preincrement use iterator so we don't invalidate it.
1213 ++UI;
1214
1215 // Don't bother for PHI nodes.
1216 if (isa<PHINode>(User))
1217 continue;
1218
1219 if (!isExtractBitsCandidateUse(User))
1220 continue;
1221
1222 BasicBlock *UserBB = User->getParent();
1223
1224 if (UserBB == DefBB) {
1225 // If the shift and truncate instruction are in the same BB. The use of
1226 // the truncate(TruncUse) may still introduce another truncate if not
1227 // legal. In this case, we would like to sink both shift and truncate
1228 // instruction to the BB of TruncUse.
1229 // for example:
1230 // BB1:
1231 // i64 shift.result = lshr i64 opnd, imm
1232 // trunc.result = trunc shift.result to i16
1233 //
1234 // BB2:
1235 // ----> We will have an implicit truncate here if the architecture does
1236 // not have i16 compare.
1237 // cmp i16 trunc.result, opnd2
1238 //
1239 if (isa<TruncInst>(User) && shiftIsLegal
1240 // If the type of the truncate is legal, no trucate will be
1241 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001242 &&
1243 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001244 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001245 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001246
1247 continue;
1248 }
1249 // If we have already inserted a shift into this block, use it.
1250 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1251
1252 if (!InsertedShift) {
1253 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001254 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001255
1256 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001257 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1258 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001259 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001260 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1261 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001262
1263 MadeChange = true;
1264 }
1265
1266 // Replace a use of the shift with a use of the new shift.
1267 TheUse = InsertedShift;
1268 }
1269
1270 // If we removed all uses, nuke the shift.
1271 if (ShiftI->use_empty())
1272 ShiftI->eraseFromParent();
1273
1274 return MadeChange;
1275}
1276
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001277// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001278// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1279// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001280// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001281// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001282//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001283// %1 = bitcast i8* %addr to i32*
1284// %2 = extractelement <16 x i1> %mask, i32 0
1285// %3 = icmp eq i1 %2, true
1286// br i1 %3, label %cond.load, label %else
1287//
1288//cond.load: ; preds = %0
1289// %4 = getelementptr i32* %1, i32 0
1290// %5 = load i32* %4
1291// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1292// br label %else
1293//
1294//else: ; preds = %0, %cond.load
1295// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1296// %7 = extractelement <16 x i1> %mask, i32 1
1297// %8 = icmp eq i1 %7, true
1298// br i1 %8, label %cond.load1, label %else2
1299//
1300//cond.load1: ; preds = %else
1301// %9 = getelementptr i32* %1, i32 1
1302// %10 = load i32* %9
1303// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1304// br label %else2
1305//
1306//else2: ; preds = %else, %cond.load1
1307// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1308// %12 = extractelement <16 x i1> %mask, i32 2
1309// %13 = icmp eq i1 %12, true
1310// br i1 %13, label %cond.load4, label %else5
1311//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001312static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001313 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001314 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001315 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001316 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001317
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001318 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1319 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001320 assert(VecType && "Unexpected return type of masked load intrinsic");
1321
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001322 Type *EltTy = CI->getType()->getVectorElementType();
1323
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001324 IRBuilder<> Builder(CI->getContext());
1325 Instruction *InsertPt = CI;
1326 BasicBlock *IfBlock = CI->getParent();
1327 BasicBlock *CondBlock = nullptr;
1328 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001329
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001330 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001331 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1332
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001333 // Short-cut if the mask is all-true.
1334 bool IsAllOnesMask = isa<Constant>(Mask) &&
1335 cast<Constant>(Mask)->isAllOnesValue();
1336
1337 if (IsAllOnesMask) {
1338 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1339 CI->replaceAllUsesWith(NewI);
1340 CI->eraseFromParent();
1341 return;
1342 }
1343
1344 // Adjust alignment for the scalar instruction.
1345 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001346 // Bitcast %addr fron i8* to EltTy*
1347 Type *NewPtrType =
1348 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1349 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001350 unsigned VectorWidth = VecType->getNumElements();
1351
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001352 Value *UndefVal = UndefValue::get(VecType);
1353
1354 // The result vector
1355 Value *VResult = UndefVal;
1356
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001357 if (isa<ConstantVector>(Mask)) {
1358 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1359 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1360 continue;
1361 Value *Gep =
1362 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1363 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1364 VResult = Builder.CreateInsertElement(VResult, Load,
1365 Builder.getInt32(Idx));
1366 }
1367 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1368 CI->replaceAllUsesWith(NewI);
1369 CI->eraseFromParent();
1370 return;
1371 }
1372
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001373 PHINode *Phi = nullptr;
1374 Value *PrevPhi = UndefVal;
1375
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001376 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1377
1378 // Fill the "else" block, created in the previous iteration
1379 //
1380 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1381 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1382 // %to_load = icmp eq i1 %mask_1, true
1383 // br i1 %to_load, label %cond.load, label %else
1384 //
1385 if (Idx > 0) {
1386 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1387 Phi->addIncoming(VResult, CondBlock);
1388 Phi->addIncoming(PrevPhi, PrevIfBlock);
1389 PrevPhi = Phi;
1390 VResult = Phi;
1391 }
1392
1393 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1394 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1395 ConstantInt::get(Predicate->getType(), 1));
1396
1397 // Create "cond" block
1398 //
1399 // %EltAddr = getelementptr i32* %1, i32 0
1400 // %Elt = load i32* %EltAddr
1401 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1402 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001403 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001404 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001405
1406 Value *Gep =
1407 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001408 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001409 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1410
1411 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001412 BasicBlock *NewIfBlock =
1413 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001414 Builder.SetInsertPoint(InsertPt);
1415 Instruction *OldBr = IfBlock->getTerminator();
1416 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1417 OldBr->eraseFromParent();
1418 PrevIfBlock = IfBlock;
1419 IfBlock = NewIfBlock;
1420 }
1421
1422 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1423 Phi->addIncoming(VResult, CondBlock);
1424 Phi->addIncoming(PrevPhi, PrevIfBlock);
1425 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1426 CI->replaceAllUsesWith(NewI);
1427 CI->eraseFromParent();
1428}
1429
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001430// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001431// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1432// <16 x i1> %mask)
1433// to a chain of basic blocks, that stores element one-by-one if
1434// the appropriate mask bit is set
1435//
1436// %1 = bitcast i8* %addr to i32*
1437// %2 = extractelement <16 x i1> %mask, i32 0
1438// %3 = icmp eq i1 %2, true
1439// br i1 %3, label %cond.store, label %else
1440//
1441// cond.store: ; preds = %0
1442// %4 = extractelement <16 x i32> %val, i32 0
1443// %5 = getelementptr i32* %1, i32 0
1444// store i32 %4, i32* %5
1445// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001446//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001447// else: ; preds = %0, %cond.store
1448// %6 = extractelement <16 x i1> %mask, i32 1
1449// %7 = icmp eq i1 %6, true
1450// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001451//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001452// cond.store1: ; preds = %else
1453// %8 = extractelement <16 x i32> %val, i32 1
1454// %9 = getelementptr i32* %1, i32 1
1455// store i32 %8, i32* %9
1456// br label %else2
1457// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001458static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001459 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001460 Value *Ptr = CI->getArgOperand(1);
1461 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001462 Value *Mask = CI->getArgOperand(3);
1463
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001464 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001465 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001466 assert(VecType && "Unexpected data type in masked store intrinsic");
1467
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001468 Type *EltTy = VecType->getElementType();
1469
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001470 IRBuilder<> Builder(CI->getContext());
1471 Instruction *InsertPt = CI;
1472 BasicBlock *IfBlock = CI->getParent();
1473 Builder.SetInsertPoint(InsertPt);
1474 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1475
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001476 // Short-cut if the mask is all-true.
1477 bool IsAllOnesMask = isa<Constant>(Mask) &&
1478 cast<Constant>(Mask)->isAllOnesValue();
1479
1480 if (IsAllOnesMask) {
1481 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1482 CI->eraseFromParent();
1483 return;
1484 }
1485
1486 // Adjust alignment for the scalar instruction.
1487 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001488 // Bitcast %addr fron i8* to EltTy*
1489 Type *NewPtrType =
1490 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1491 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001492 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001493
1494 if (isa<ConstantVector>(Mask)) {
1495 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1496 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1497 continue;
1498 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1499 Value *Gep =
1500 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1501 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1502 }
1503 CI->eraseFromParent();
1504 return;
1505 }
1506
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001507 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1508
1509 // Fill the "else" block, created in the previous iteration
1510 //
1511 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1512 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001513 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001514 //
1515 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1516 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1517 ConstantInt::get(Predicate->getType(), 1));
1518
1519 // Create "cond" block
1520 //
1521 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1522 // %EltAddr = getelementptr i32* %1, i32 0
1523 // %store i32 %OneElt, i32* %EltAddr
1524 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001525 BasicBlock *CondBlock =
1526 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001527 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001528
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001529 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001530 Value *Gep =
1531 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001532 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001533
1534 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001535 BasicBlock *NewIfBlock =
1536 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001537 Builder.SetInsertPoint(InsertPt);
1538 Instruction *OldBr = IfBlock->getTerminator();
1539 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1540 OldBr->eraseFromParent();
1541 IfBlock = NewIfBlock;
1542 }
1543 CI->eraseFromParent();
1544}
1545
Elena Demikhovsky09285852015-10-25 15:37:55 +00001546// Translate a masked gather intrinsic like
1547// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1548// <16 x i1> %Mask, <16 x i32> %Src)
1549// to a chain of basic blocks, with loading element one-by-one if
1550// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001551//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001552// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1553// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1554// % ToLoad0 = icmp eq i1 % Mask0, true
1555// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001556//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001557// cond.load:
1558// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1559// % Load0 = load i32, i32* % Ptr0, align 4
1560// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1561// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001562//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001563// else:
1564// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1565// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1566// % ToLoad1 = icmp eq i1 % Mask1, true
1567// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001568//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001569// cond.load1:
1570// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1571// % Load1 = load i32, i32* % Ptr1, align 4
1572// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1573// br label %else2
1574// . . .
1575// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1576// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001577static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001578 Value *Ptrs = CI->getArgOperand(0);
1579 Value *Alignment = CI->getArgOperand(1);
1580 Value *Mask = CI->getArgOperand(2);
1581 Value *Src0 = CI->getArgOperand(3);
1582
1583 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1584
1585 assert(VecType && "Unexpected return type of masked load intrinsic");
1586
1587 IRBuilder<> Builder(CI->getContext());
1588 Instruction *InsertPt = CI;
1589 BasicBlock *IfBlock = CI->getParent();
1590 BasicBlock *CondBlock = nullptr;
1591 BasicBlock *PrevIfBlock = CI->getParent();
1592 Builder.SetInsertPoint(InsertPt);
1593 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1594
1595 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1596
1597 Value *UndefVal = UndefValue::get(VecType);
1598
1599 // The result vector
1600 Value *VResult = UndefVal;
1601 unsigned VectorWidth = VecType->getNumElements();
1602
1603 // Shorten the way if the mask is a vector of constants.
1604 bool IsConstMask = isa<ConstantVector>(Mask);
1605
1606 if (IsConstMask) {
1607 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1608 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1609 continue;
1610 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1611 "Ptr" + Twine(Idx));
1612 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1613 "Load" + Twine(Idx));
1614 VResult = Builder.CreateInsertElement(VResult, Load,
1615 Builder.getInt32(Idx),
1616 "Res" + Twine(Idx));
1617 }
1618 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1619 CI->replaceAllUsesWith(NewI);
1620 CI->eraseFromParent();
1621 return;
1622 }
1623
1624 PHINode *Phi = nullptr;
1625 Value *PrevPhi = UndefVal;
1626
1627 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1628
1629 // Fill the "else" block, created in the previous iteration
1630 //
1631 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1632 // %ToLoad1 = icmp eq i1 %Mask1, true
1633 // br i1 %ToLoad1, label %cond.load, label %else
1634 //
1635 if (Idx > 0) {
1636 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1637 Phi->addIncoming(VResult, CondBlock);
1638 Phi->addIncoming(PrevPhi, PrevIfBlock);
1639 PrevPhi = Phi;
1640 VResult = Phi;
1641 }
1642
1643 Value *Predicate = Builder.CreateExtractElement(Mask,
1644 Builder.getInt32(Idx),
1645 "Mask" + Twine(Idx));
1646 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1647 ConstantInt::get(Predicate->getType(), 1),
1648 "ToLoad" + Twine(Idx));
1649
1650 // Create "cond" block
1651 //
1652 // %EltAddr = getelementptr i32* %1, i32 0
1653 // %Elt = load i32* %EltAddr
1654 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1655 //
1656 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1657 Builder.SetInsertPoint(InsertPt);
1658
1659 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1660 "Ptr" + Twine(Idx));
1661 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1662 "Load" + Twine(Idx));
1663 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1664 "Res" + Twine(Idx));
1665
1666 // Create "else" block, fill it in the next iteration
1667 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1668 Builder.SetInsertPoint(InsertPt);
1669 Instruction *OldBr = IfBlock->getTerminator();
1670 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1671 OldBr->eraseFromParent();
1672 PrevIfBlock = IfBlock;
1673 IfBlock = NewIfBlock;
1674 }
1675
1676 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1677 Phi->addIncoming(VResult, CondBlock);
1678 Phi->addIncoming(PrevPhi, PrevIfBlock);
1679 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1680 CI->replaceAllUsesWith(NewI);
1681 CI->eraseFromParent();
1682}
1683
1684// Translate a masked scatter intrinsic, like
1685// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1686// <16 x i1> %Mask)
1687// to a chain of basic blocks, that stores element one-by-one if
1688// the appropriate mask bit is set.
1689//
1690// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1691// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1692// % ToStore0 = icmp eq i1 % Mask0, true
1693// br i1 %ToStore0, label %cond.store, label %else
1694//
1695// cond.store:
1696// % Elt0 = extractelement <16 x i32> %Src, i32 0
1697// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1698// store i32 %Elt0, i32* % Ptr0, align 4
1699// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001700//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001701// else:
1702// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1703// % ToStore1 = icmp eq i1 % Mask1, true
1704// br i1 % ToStore1, label %cond.store1, label %else2
1705//
1706// cond.store1:
1707// % Elt1 = extractelement <16 x i32> %Src, i32 1
1708// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1709// store i32 % Elt1, i32* % Ptr1, align 4
1710// br label %else2
1711// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001712static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001713 Value *Src = CI->getArgOperand(0);
1714 Value *Ptrs = CI->getArgOperand(1);
1715 Value *Alignment = CI->getArgOperand(2);
1716 Value *Mask = CI->getArgOperand(3);
1717
1718 assert(isa<VectorType>(Src->getType()) &&
1719 "Unexpected data type in masked scatter intrinsic");
1720 assert(isa<VectorType>(Ptrs->getType()) &&
1721 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1722 "Vector of pointers is expected in masked scatter intrinsic");
1723
1724 IRBuilder<> Builder(CI->getContext());
1725 Instruction *InsertPt = CI;
1726 BasicBlock *IfBlock = CI->getParent();
1727 Builder.SetInsertPoint(InsertPt);
1728 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1729
1730 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1731 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1732
1733 // Shorten the way if the mask is a vector of constants.
1734 bool IsConstMask = isa<ConstantVector>(Mask);
1735
1736 if (IsConstMask) {
1737 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1738 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1739 continue;
1740 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1741 "Elt" + Twine(Idx));
1742 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1743 "Ptr" + Twine(Idx));
1744 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1745 }
1746 CI->eraseFromParent();
1747 return;
1748 }
1749 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1750 // Fill the "else" block, created in the previous iteration
1751 //
1752 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1753 // % ToStore = icmp eq i1 % Mask1, true
1754 // br i1 % ToStore, label %cond.store, label %else
1755 //
1756 Value *Predicate = Builder.CreateExtractElement(Mask,
1757 Builder.getInt32(Idx),
1758 "Mask" + Twine(Idx));
1759 Value *Cmp =
1760 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1761 ConstantInt::get(Predicate->getType(), 1),
1762 "ToStore" + Twine(Idx));
1763
1764 // Create "cond" block
1765 //
1766 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1767 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1768 // %store i32 % Elt1, i32* % Ptr1
1769 //
1770 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1771 Builder.SetInsertPoint(InsertPt);
1772
1773 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1774 "Elt" + Twine(Idx));
1775 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1776 "Ptr" + Twine(Idx));
1777 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1778
1779 // Create "else" block, fill it in the next iteration
1780 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1781 Builder.SetInsertPoint(InsertPt);
1782 Instruction *OldBr = IfBlock->getTerminator();
1783 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1784 OldBr->eraseFromParent();
1785 IfBlock = NewIfBlock;
1786 }
1787 CI->eraseFromParent();
1788}
1789
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001790/// If counting leading or trailing zeros is an expensive operation and a zero
1791/// input is defined, add a check for zero to avoid calling the intrinsic.
1792///
1793/// We want to transform:
1794/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1795///
1796/// into:
1797/// entry:
1798/// %cmpz = icmp eq i64 %A, 0
1799/// br i1 %cmpz, label %cond.end, label %cond.false
1800/// cond.false:
1801/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1802/// br label %cond.end
1803/// cond.end:
1804/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1805///
1806/// If the transform is performed, return true and set ModifiedDT to true.
1807static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1808 const TargetLowering *TLI,
1809 const DataLayout *DL,
1810 bool &ModifiedDT) {
1811 if (!TLI || !DL)
1812 return false;
1813
1814 // If a zero input is undefined, it doesn't make sense to despeculate that.
1815 if (match(CountZeros->getOperand(1), m_One()))
1816 return false;
1817
1818 // If it's cheap to speculate, there's nothing to do.
1819 auto IntrinsicID = CountZeros->getIntrinsicID();
1820 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1821 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1822 return false;
1823
1824 // Only handle legal scalar cases. Anything else requires too much work.
1825 Type *Ty = CountZeros->getType();
1826 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001827 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001828 return false;
1829
1830 // The intrinsic will be sunk behind a compare against zero and branch.
1831 BasicBlock *StartBlock = CountZeros->getParent();
1832 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1833
1834 // Create another block after the count zero intrinsic. A PHI will be added
1835 // in this block to select the result of the intrinsic or the bit-width
1836 // constant if the input to the intrinsic is zero.
1837 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1838 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1839
1840 // Set up a builder to create a compare, conditional branch, and PHI.
1841 IRBuilder<> Builder(CountZeros->getContext());
1842 Builder.SetInsertPoint(StartBlock->getTerminator());
1843 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1844
1845 // Replace the unconditional branch that was created by the first split with
1846 // a compare against zero and a conditional branch.
1847 Value *Zero = Constant::getNullValue(Ty);
1848 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1849 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1850 StartBlock->getTerminator()->eraseFromParent();
1851
1852 // Create a PHI in the end block to select either the output of the intrinsic
1853 // or the bit width of the operand.
1854 Builder.SetInsertPoint(&EndBlock->front());
1855 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1856 CountZeros->replaceAllUsesWith(PN);
1857 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1858 PN->addIncoming(BitWidth, StartBlock);
1859 PN->addIncoming(CountZeros, CallBlock);
1860
1861 // We are explicitly handling the zero case, so we can set the intrinsic's
1862 // undefined zero argument to 'true'. This will also prevent reprocessing the
1863 // intrinsic; we only despeculate when a zero input is defined.
1864 CountZeros->setArgOperand(1, Builder.getTrue());
1865 ModifiedDT = true;
1866 return true;
1867}
1868
Sanjay Patelfc580a62015-09-21 23:03:16 +00001869bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001870 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001871
Chris Lattner7a277142011-01-15 07:14:54 +00001872 // Lower inline assembly if we can.
1873 // If we found an inline asm expession, and if the target knows how to
1874 // lower it to normal LLVM code, do so now.
1875 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1876 if (TLI->ExpandInlineAsm(CI)) {
1877 // Avoid invalidating the iterator.
1878 CurInstIterator = BB->begin();
1879 // Avoid processing instructions out of order, which could cause
1880 // reuse before a value is defined.
1881 SunkAddrs.clear();
1882 return true;
1883 }
1884 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001885 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001886 return true;
1887 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001888
John Brawn0dbcd652015-03-18 12:01:59 +00001889 // Align the pointer arguments to this call if the target thinks it's a good
1890 // idea
1891 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001892 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001893 for (auto &Arg : CI->arg_operands()) {
1894 // We want to align both objects whose address is used directly and
1895 // objects whose address is used in casts and GEPs, though it only makes
1896 // sense for GEPs if the offset is a multiple of the desired alignment and
1897 // if size - offset meets the size threshold.
1898 if (!Arg->getType()->isPointerTy())
1899 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001900 APInt Offset(DL->getPointerSizeInBits(
1901 cast<PointerType>(Arg->getType())->getAddressSpace()),
1902 0);
1903 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001904 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001905 if ((Offset2 & (PrefAlign-1)) != 0)
1906 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001907 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001908 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1909 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001910 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001911 // Global variables can only be aligned if they are defined in this
1912 // object (i.e. they are uniquely initialized in this object), and
1913 // over-aligning global variables that have an explicit section is
1914 // forbidden.
1915 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001916 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001917 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001918 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001919 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001920 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001921 }
1922 // If this is a memcpy (or similar) then we may be able to improve the
1923 // alignment
1924 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001925 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001926 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001927 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001928 if (Align > MI->getAlignment())
1929 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001930 }
1931 }
1932
Philip Reamesac115ed2016-03-09 23:13:12 +00001933 // If we have a cold call site, try to sink addressing computation into the
1934 // cold block. This interacts with our handling for loads and stores to
1935 // ensure that we can fold all uses of a potential addressing computation
1936 // into their uses. TODO: generalize this to work over profiling data
1937 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1938 for (auto &Arg : CI->arg_operands()) {
1939 if (!Arg->getType()->isPointerTy())
1940 continue;
1941 unsigned AS = Arg->getType()->getPointerAddressSpace();
1942 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1943 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001944
Eric Christopher4b7948e2010-03-11 02:41:03 +00001945 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001946 if (II) {
1947 switch (II->getIntrinsicID()) {
1948 default: break;
1949 case Intrinsic::objectsize: {
1950 // Lower all uses of llvm.objectsize.*
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001951 uint64_t Size;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001952 Type *ReturnTy = CI->getType();
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001953 Constant *RetVal = nullptr;
1954 ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1));
1955 ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min;
1956 if (getObjectSize(II->getArgOperand(0),
1957 Size, *DL, TLInfo, false, Mode)) {
1958 RetVal = ConstantInt::get(ReturnTy, Size);
1959 } else {
1960 RetVal = ConstantInt::get(ReturnTy,
1961 Mode == ObjSizeMode::Min ? 0 : -1ULL);
1962 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001963 // Substituting this can cause recursive simplifications, which can
1964 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1965 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001966 Value *CurValue = &*CurInstIterator;
1967 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001968
Sanjay Patel545a4562016-01-20 18:59:16 +00001969 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001970
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001971 // If the iterator instruction was recursively deleted, start over at the
1972 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001973 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001974 CurInstIterator = BB->begin();
1975 SunkAddrs.clear();
1976 }
1977 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001978 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001979 case Intrinsic::masked_load: {
1980 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001981 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001982 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001983 ModifiedDT = true;
1984 return true;
1985 }
1986 return false;
1987 }
1988 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001989 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001990 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001991 ModifiedDT = true;
1992 return true;
1993 }
1994 return false;
1995 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001996 case Intrinsic::masked_gather: {
1997 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001998 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001999 ModifiedDT = true;
2000 return true;
2001 }
2002 return false;
2003 }
2004 case Intrinsic::masked_scatter: {
2005 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002006 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002007 ModifiedDT = true;
2008 return true;
2009 }
2010 return false;
2011 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002012 case Intrinsic::aarch64_stlxr:
2013 case Intrinsic::aarch64_stxr: {
2014 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2015 if (!ExtVal || !ExtVal->hasOneUse() ||
2016 ExtVal->getParent() == CI->getParent())
2017 return false;
2018 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2019 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002020 // Mark this instruction as "inserted by CGP", so that other
2021 // optimizations don't touch it.
2022 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002023 return true;
2024 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002025 case Intrinsic::invariant_group_barrier:
2026 II->replaceAllUsesWith(II->getArgOperand(0));
2027 II->eraseFromParent();
2028 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002029
2030 case Intrinsic::cttz:
2031 case Intrinsic::ctlz:
2032 // If counting zeros is expensive, try to avoid it.
2033 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002034 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002035
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002036 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002037 // Unknown address space.
2038 // TODO: Target hook to pick which address space the intrinsic cares
2039 // about?
2040 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002041 SmallVector<Value*, 2> PtrOps;
2042 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002043 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002044 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00002045 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002046 return true;
2047 }
Pete Cooper615fd892012-03-13 20:59:56 +00002048 }
2049
Eric Christopher4b7948e2010-03-11 02:41:03 +00002050 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002051 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002052
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002053 // Lower all default uses of _chk calls. This is very similar
2054 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002055 // to fortified library functions (e.g. __memcpy_chk) that have the default
2056 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002057 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002058 if (Value *V = Simplifier.optimizeCall(CI)) {
2059 CI->replaceAllUsesWith(V);
2060 CI->eraseFromParent();
2061 return true;
2062 }
2063 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002064}
Chris Lattner1b93be52011-01-15 07:25:29 +00002065
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002066/// Look for opportunities to duplicate return instructions to the predecessor
2067/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002068/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002069/// bb0:
2070/// %tmp0 = tail call i32 @f0()
2071/// br label %return
2072/// bb1:
2073/// %tmp1 = tail call i32 @f1()
2074/// br label %return
2075/// bb2:
2076/// %tmp2 = tail call i32 @f2()
2077/// br label %return
2078/// return:
2079/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2080/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002081/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002082///
2083/// =>
2084///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002085/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002086/// bb0:
2087/// %tmp0 = tail call i32 @f0()
2088/// ret i32 %tmp0
2089/// bb1:
2090/// %tmp1 = tail call i32 @f1()
2091/// ret i32 %tmp1
2092/// bb2:
2093/// %tmp2 = tail call i32 @f2()
2094/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002095/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002096bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002097 if (!TLI)
2098 return false;
2099
Michael Kuperstein71321562016-09-07 20:29:49 +00002100 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2101 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002102 return false;
2103
Craig Topperc0196b12014-04-14 00:51:57 +00002104 PHINode *PN = nullptr;
2105 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002106 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002107 if (V) {
2108 BCI = dyn_cast<BitCastInst>(V);
2109 if (BCI)
2110 V = BCI->getOperand(0);
2111
2112 PN = dyn_cast<PHINode>(V);
2113 if (!PN)
2114 return false;
2115 }
Evan Cheng0663f232011-03-21 01:19:09 +00002116
Cameron Zwarich4649f172011-03-24 04:52:10 +00002117 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002118 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002119
Cameron Zwarich4649f172011-03-24 04:52:10 +00002120 // Make sure there are no instructions between the PHI and return, or that the
2121 // return is the first instruction in the block.
2122 if (PN) {
2123 BasicBlock::iterator BI = BB->begin();
2124 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002125 if (&*BI == BCI)
2126 // Also skip over the bitcast.
2127 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002128 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002129 return false;
2130 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002131 BasicBlock::iterator BI = BB->begin();
2132 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002133 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002134 return false;
2135 }
Evan Cheng0663f232011-03-21 01:19:09 +00002136
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002137 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2138 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002139 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002140 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002141 if (PN) {
2142 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2143 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2144 // Make sure the phi value is indeed produced by the tail call.
2145 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002146 TLI->mayBeEmittedAsTailCall(CI) &&
2147 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002148 TailCalls.push_back(CI);
2149 }
2150 } else {
2151 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002152 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002153 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002154 continue;
2155
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002156 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002157 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2158 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002159 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2160 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002161 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002162
Cameron Zwarich4649f172011-03-24 04:52:10 +00002163 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002164 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2165 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002166 TailCalls.push_back(CI);
2167 }
Evan Cheng0663f232011-03-21 01:19:09 +00002168 }
2169
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002170 bool Changed = false;
2171 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2172 CallInst *CI = TailCalls[i];
2173 CallSite CS(CI);
2174
2175 // Conservatively require the attributes of the call to match those of the
2176 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002177 AttributeSet CalleeAttrs = CS.getAttributes();
2178 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002179 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002180 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002181 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002182 continue;
2183
2184 // Make sure the call instruction is followed by an unconditional branch to
2185 // the return block.
2186 BasicBlock *CallBB = CI->getParent();
2187 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2188 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2189 continue;
2190
2191 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002192 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002193 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002194 ++NumRetsDup;
2195 }
2196
2197 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002198 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002199 BB->eraseFromParent();
2200
2201 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002202}
2203
Chris Lattner728f9022008-11-25 07:09:13 +00002204//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002205// Memory Optimization
2206//===----------------------------------------------------------------------===//
2207
Chandler Carruthc8925912013-01-05 02:09:22 +00002208namespace {
2209
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002210/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002211/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002212struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002213 Value *BaseReg;
2214 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002215 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002216 void print(raw_ostream &OS) const;
2217 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002218
Chandler Carruthc8925912013-01-05 02:09:22 +00002219 bool operator==(const ExtAddrMode& O) const {
2220 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2221 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2222 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2223 }
2224};
2225
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002226#ifndef NDEBUG
2227static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2228 AM.print(OS);
2229 return OS;
2230}
2231#endif
2232
Chandler Carruthc8925912013-01-05 02:09:22 +00002233void ExtAddrMode::print(raw_ostream &OS) const {
2234 bool NeedPlus = false;
2235 OS << "[";
2236 if (BaseGV) {
2237 OS << (NeedPlus ? " + " : "")
2238 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002239 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002240 NeedPlus = true;
2241 }
2242
Richard Trieuc0f91212014-05-30 03:15:17 +00002243 if (BaseOffs) {
2244 OS << (NeedPlus ? " + " : "")
2245 << BaseOffs;
2246 NeedPlus = true;
2247 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002248
2249 if (BaseReg) {
2250 OS << (NeedPlus ? " + " : "")
2251 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002252 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002253 NeedPlus = true;
2254 }
2255 if (Scale) {
2256 OS << (NeedPlus ? " + " : "")
2257 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002258 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002259 }
2260
2261 OS << ']';
2262}
2263
2264#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002265LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002266 print(dbgs());
2267 dbgs() << '\n';
2268}
2269#endif
2270
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002271/// \brief This class provides transaction based operation on the IR.
2272/// Every change made through this class is recorded in the internal state and
2273/// can be undone (rollback) until commit is called.
2274class TypePromotionTransaction {
2275
2276 /// \brief This represents the common interface of the individual transaction.
2277 /// Each class implements the logic for doing one specific modification on
2278 /// the IR via the TypePromotionTransaction.
2279 class TypePromotionAction {
2280 protected:
2281 /// The Instruction modified.
2282 Instruction *Inst;
2283
2284 public:
2285 /// \brief Constructor of the action.
2286 /// The constructor performs the related action on the IR.
2287 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2288
2289 virtual ~TypePromotionAction() {}
2290
2291 /// \brief Undo the modification done by this action.
2292 /// When this method is called, the IR must be in the same state as it was
2293 /// before this action was applied.
2294 /// \pre Undoing the action works if and only if the IR is in the exact same
2295 /// state as it was directly after this action was applied.
2296 virtual void undo() = 0;
2297
2298 /// \brief Advocate every change made by this action.
2299 /// When the results on the IR of the action are to be kept, it is important
2300 /// to call this function, otherwise hidden information may be kept forever.
2301 virtual void commit() {
2302 // Nothing to be done, this action is not doing anything.
2303 }
2304 };
2305
2306 /// \brief Utility to remember the position of an instruction.
2307 class InsertionHandler {
2308 /// Position of an instruction.
2309 /// Either an instruction:
2310 /// - Is the first in a basic block: BB is used.
2311 /// - Has a previous instructon: PrevInst is used.
2312 union {
2313 Instruction *PrevInst;
2314 BasicBlock *BB;
2315 } Point;
2316 /// Remember whether or not the instruction had a previous instruction.
2317 bool HasPrevInstruction;
2318
2319 public:
2320 /// \brief Record the position of \p Inst.
2321 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002322 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002323 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2324 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002325 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002326 else
2327 Point.BB = Inst->getParent();
2328 }
2329
2330 /// \brief Insert \p Inst at the recorded position.
2331 void insert(Instruction *Inst) {
2332 if (HasPrevInstruction) {
2333 if (Inst->getParent())
2334 Inst->removeFromParent();
2335 Inst->insertAfter(Point.PrevInst);
2336 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002337 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002338 if (Inst->getParent())
2339 Inst->moveBefore(Position);
2340 else
2341 Inst->insertBefore(Position);
2342 }
2343 }
2344 };
2345
2346 /// \brief Move an instruction before another.
2347 class InstructionMoveBefore : public TypePromotionAction {
2348 /// Original position of the instruction.
2349 InsertionHandler Position;
2350
2351 public:
2352 /// \brief Move \p Inst before \p Before.
2353 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2354 : TypePromotionAction(Inst), Position(Inst) {
2355 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2356 Inst->moveBefore(Before);
2357 }
2358
2359 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002360 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002361 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2362 Position.insert(Inst);
2363 }
2364 };
2365
2366 /// \brief Set the operand of an instruction with a new value.
2367 class OperandSetter : public TypePromotionAction {
2368 /// Original operand of the instruction.
2369 Value *Origin;
2370 /// Index of the modified instruction.
2371 unsigned Idx;
2372
2373 public:
2374 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2375 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2376 : TypePromotionAction(Inst), Idx(Idx) {
2377 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2378 << "for:" << *Inst << "\n"
2379 << "with:" << *NewVal << "\n");
2380 Origin = Inst->getOperand(Idx);
2381 Inst->setOperand(Idx, NewVal);
2382 }
2383
2384 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002385 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002386 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2387 << "for: " << *Inst << "\n"
2388 << "with: " << *Origin << "\n");
2389 Inst->setOperand(Idx, Origin);
2390 }
2391 };
2392
2393 /// \brief Hide the operands of an instruction.
2394 /// Do as if this instruction was not using any of its operands.
2395 class OperandsHider : public TypePromotionAction {
2396 /// The list of original operands.
2397 SmallVector<Value *, 4> OriginalValues;
2398
2399 public:
2400 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2401 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2402 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2403 unsigned NumOpnds = Inst->getNumOperands();
2404 OriginalValues.reserve(NumOpnds);
2405 for (unsigned It = 0; It < NumOpnds; ++It) {
2406 // Save the current operand.
2407 Value *Val = Inst->getOperand(It);
2408 OriginalValues.push_back(Val);
2409 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002410 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002411 // that we are not willing to pay.
2412 Inst->setOperand(It, UndefValue::get(Val->getType()));
2413 }
2414 }
2415
2416 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002417 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002418 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2419 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2420 Inst->setOperand(It, OriginalValues[It]);
2421 }
2422 };
2423
2424 /// \brief Build a truncate instruction.
2425 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002426 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002427 public:
2428 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2429 /// result.
2430 /// trunc Opnd to Ty.
2431 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2432 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002433 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2434 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002435 }
2436
Quentin Colombetac55b152014-09-16 22:36:07 +00002437 /// \brief Get the built value.
2438 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439
2440 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002441 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002442 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2443 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2444 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 }
2446 };
2447
2448 /// \brief Build a sign extension instruction.
2449 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002450 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002451 public:
2452 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2453 /// result.
2454 /// sext Opnd to Ty.
2455 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002456 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002457 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002458 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2459 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002460 }
2461
Quentin Colombetac55b152014-09-16 22:36:07 +00002462 /// \brief Get the built value.
2463 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464
2465 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002466 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002467 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2468 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2469 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002470 }
2471 };
2472
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002473 /// \brief Build a zero extension instruction.
2474 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002475 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002476 public:
2477 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2478 /// result.
2479 /// zext Opnd to Ty.
2480 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002481 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002482 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002483 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2484 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002485 }
2486
Quentin Colombetac55b152014-09-16 22:36:07 +00002487 /// \brief Get the built value.
2488 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002489
2490 /// \brief Remove the built instruction.
2491 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002492 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2493 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2494 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002495 }
2496 };
2497
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002498 /// \brief Mutate an instruction to another type.
2499 class TypeMutator : public TypePromotionAction {
2500 /// Record the original type.
2501 Type *OrigTy;
2502
2503 public:
2504 /// \brief Mutate the type of \p Inst into \p NewTy.
2505 TypeMutator(Instruction *Inst, Type *NewTy)
2506 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2507 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2508 << "\n");
2509 Inst->mutateType(NewTy);
2510 }
2511
2512 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002513 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002514 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2515 << "\n");
2516 Inst->mutateType(OrigTy);
2517 }
2518 };
2519
2520 /// \brief Replace the uses of an instruction by another instruction.
2521 class UsesReplacer : public TypePromotionAction {
2522 /// Helper structure to keep track of the replaced uses.
2523 struct InstructionAndIdx {
2524 /// The instruction using the instruction.
2525 Instruction *Inst;
2526 /// The index where this instruction is used for Inst.
2527 unsigned Idx;
2528 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2529 : Inst(Inst), Idx(Idx) {}
2530 };
2531
2532 /// Keep track of the original uses (pair Instruction, Index).
2533 SmallVector<InstructionAndIdx, 4> OriginalUses;
2534 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2535
2536 public:
2537 /// \brief Replace all the use of \p Inst by \p New.
2538 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2539 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2540 << "\n");
2541 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002542 for (Use &U : Inst->uses()) {
2543 Instruction *UserI = cast<Instruction>(U.getUser());
2544 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002545 }
2546 // Now, we can replace the uses.
2547 Inst->replaceAllUsesWith(New);
2548 }
2549
2550 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002551 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002552 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2553 for (use_iterator UseIt = OriginalUses.begin(),
2554 EndIt = OriginalUses.end();
2555 UseIt != EndIt; ++UseIt) {
2556 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2557 }
2558 }
2559 };
2560
2561 /// \brief Remove an instruction from the IR.
2562 class InstructionRemover : public TypePromotionAction {
2563 /// Original position of the instruction.
2564 InsertionHandler Inserter;
2565 /// Helper structure to hide all the link to the instruction. In other
2566 /// words, this helps to do as if the instruction was removed.
2567 OperandsHider Hider;
2568 /// Keep track of the uses replaced, if any.
2569 UsesReplacer *Replacer;
2570
2571 public:
2572 /// \brief Remove all reference of \p Inst and optinally replace all its
2573 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002574 /// \pre If !Inst->use_empty(), then New != nullptr
2575 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002576 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002577 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002578 if (New)
2579 Replacer = new UsesReplacer(Inst, New);
2580 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2581 Inst->removeFromParent();
2582 }
2583
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002584 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002585
2586 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002587 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002588
2589 /// \brief Resurrect the instruction and reassign it to the proper uses if
2590 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002591 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002592 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2593 Inserter.insert(Inst);
2594 if (Replacer)
2595 Replacer->undo();
2596 Hider.undo();
2597 }
2598 };
2599
2600public:
2601 /// Restoration point.
2602 /// The restoration point is a pointer to an action instead of an iterator
2603 /// because the iterator may be invalidated but not the pointer.
2604 typedef const TypePromotionAction *ConstRestorationPt;
2605 /// Advocate every changes made in that transaction.
2606 void commit();
2607 /// Undo all the changes made after the given point.
2608 void rollback(ConstRestorationPt Point);
2609 /// Get the current restoration point.
2610 ConstRestorationPt getRestorationPoint() const;
2611
2612 /// \name API for IR modification with state keeping to support rollback.
2613 /// @{
2614 /// Same as Instruction::setOperand.
2615 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2616 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002617 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002618 /// Same as Value::replaceAllUsesWith.
2619 void replaceAllUsesWith(Instruction *Inst, Value *New);
2620 /// Same as Value::mutateType.
2621 void mutateType(Instruction *Inst, Type *NewTy);
2622 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002623 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002624 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002625 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002626 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002627 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002628 /// Same as Instruction::moveBefore.
2629 void moveBefore(Instruction *Inst, Instruction *Before);
2630 /// @}
2631
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002632private:
2633 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002634 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2635 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002636};
2637
2638void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2639 Value *NewVal) {
2640 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002641 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002642}
2643
2644void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2645 Value *NewVal) {
2646 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002647 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002648}
2649
2650void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2651 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002652 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002653}
2654
2655void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002656 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002657}
2658
Quentin Colombetac55b152014-09-16 22:36:07 +00002659Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2660 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002661 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002662 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002663 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002664 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002665}
2666
Quentin Colombetac55b152014-09-16 22:36:07 +00002667Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2668 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002669 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002670 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002671 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002672 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002673}
2674
Quentin Colombetac55b152014-09-16 22:36:07 +00002675Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2676 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002677 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002678 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002679 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002680 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002681}
2682
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002683void TypePromotionTransaction::moveBefore(Instruction *Inst,
2684 Instruction *Before) {
2685 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002686 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002687}
2688
2689TypePromotionTransaction::ConstRestorationPt
2690TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002691 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002692}
2693
2694void TypePromotionTransaction::commit() {
2695 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002696 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002697 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002698 Actions.clear();
2699}
2700
2701void TypePromotionTransaction::rollback(
2702 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002703 while (!Actions.empty() && Point != Actions.back().get()) {
2704 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002705 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002706 }
2707}
2708
Chandler Carruthc8925912013-01-05 02:09:22 +00002709/// \brief A helper class for matching addressing modes.
2710///
2711/// This encapsulates the logic for matching the target-legal addressing modes.
2712class AddressingModeMatcher {
2713 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002714 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002715 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002716 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002717
2718 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2719 /// the memory instruction that we're computing this address for.
2720 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002721 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002722 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002723
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002724 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002725 /// part of the return value of this addressing mode matching stuff.
2726 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002727
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002728 /// The instructions inserted by other CodeGenPrepare optimizations.
2729 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002730 /// A map from the instructions to their type before promotion.
2731 InstrToOrigTy &PromotedInsts;
2732 /// The ongoing transaction where every action should be registered.
2733 TypePromotionTransaction &TPT;
2734
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002735 /// This is set to true when we should not do profitability checks.
2736 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002737 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002738
Eric Christopherd75c00c2015-02-26 22:38:34 +00002739 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002740 const TargetMachine &TM, Type *AT, unsigned AS,
2741 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002742 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002743 InstrToOrigTy &PromotedInsts,
2744 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002745 : AddrModeInsts(AMI), TM(TM),
2746 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2747 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002748 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2749 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2750 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002751 IgnoreProfitability = false;
2752 }
2753public:
Stephen Lin837bba12013-07-15 17:55:02 +00002754
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002755 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002756 /// give an access type of AccessTy. This returns a list of involved
2757 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002758 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002759 /// optimizations.
2760 /// \p PromotedInsts maps the instructions to their type before promotion.
2761 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002762 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002763 Instruction *MemoryInst,
2764 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002765 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002766 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002767 InstrToOrigTy &PromotedInsts,
2768 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002769 ExtAddrMode Result;
2770
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002771 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002772 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002773 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002774 (void)Success; assert(Success && "Couldn't select *anything*?");
2775 return Result;
2776 }
2777private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002778 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2779 bool matchAddr(Value *V, unsigned Depth);
2780 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002781 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002782 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002783 ExtAddrMode &AMBefore,
2784 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002785 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2786 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002787 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002788};
2789
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002790/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002791/// Return true and update AddrMode if this addr mode is legal for the target,
2792/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002793bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002794 unsigned Depth) {
2795 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2796 // mode. Just process that directly.
2797 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002798 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002799
Chandler Carruthc8925912013-01-05 02:09:22 +00002800 // If the scale is 0, it takes nothing to add this.
2801 if (Scale == 0)
2802 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002803
Chandler Carruthc8925912013-01-05 02:09:22 +00002804 // If we already have a scale of this value, we can add to it, otherwise, we
2805 // need an available scale field.
2806 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2807 return false;
2808
2809 ExtAddrMode TestAddrMode = AddrMode;
2810
2811 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2812 // [A+B + A*7] -> [B+A*8].
2813 TestAddrMode.Scale += Scale;
2814 TestAddrMode.ScaledReg = ScaleReg;
2815
2816 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002817 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002818 return false;
2819
2820 // It was legal, so commit it.
2821 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002822
Chandler Carruthc8925912013-01-05 02:09:22 +00002823 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2824 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2825 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002826 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002827 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2828 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2829 TestAddrMode.ScaledReg = AddLHS;
2830 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002831
Chandler Carruthc8925912013-01-05 02:09:22 +00002832 // If this addressing mode is legal, commit it and remember that we folded
2833 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002834 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002835 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2836 AddrMode = TestAddrMode;
2837 return true;
2838 }
2839 }
2840
2841 // Otherwise, not (x+c)*scale, just return what we have.
2842 return true;
2843}
2844
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002845/// This is a little filter, which returns true if an addressing computation
2846/// involving I might be folded into a load/store accessing it.
2847/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002848/// the set of instructions that MatchOperationAddr can.
2849static bool MightBeFoldableInst(Instruction *I) {
2850 switch (I->getOpcode()) {
2851 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002852 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002853 // Don't touch identity bitcasts.
2854 if (I->getType() == I->getOperand(0)->getType())
2855 return false;
2856 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2857 case Instruction::PtrToInt:
2858 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2859 return true;
2860 case Instruction::IntToPtr:
2861 // We know the input is intptr_t, so this is foldable.
2862 return true;
2863 case Instruction::Add:
2864 return true;
2865 case Instruction::Mul:
2866 case Instruction::Shl:
2867 // Can only handle X*C and X << C.
2868 return isa<ConstantInt>(I->getOperand(1));
2869 case Instruction::GetElementPtr:
2870 return true;
2871 default:
2872 return false;
2873 }
2874}
2875
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002876/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2877/// \note \p Val is assumed to be the product of some type promotion.
2878/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2879/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002880static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2881 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002882 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2883 if (!PromotedInst)
2884 return false;
2885 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2886 // If the ISDOpcode is undefined, it was undefined before the promotion.
2887 if (!ISDOpcode)
2888 return true;
2889 // Otherwise, check if the promoted instruction is legal or not.
2890 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002891 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002892}
2893
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002894/// \brief Hepler class to perform type promotion.
2895class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002896 /// \brief Utility function to check whether or not a sign or zero extension
2897 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2898 /// either using the operands of \p Inst or promoting \p Inst.
2899 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002900 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002901 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002902 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002903 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002904 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002905 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002906 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002907 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2908 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002909
2910 /// \brief Utility function to determine if \p OpIdx should be promoted when
2911 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002912 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002913 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002914 }
2915
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002916 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002917 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002918 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002919 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002920 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002921 /// Newly added extensions are inserted in \p Exts.
2922 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002923 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002924 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002925 static Value *promoteOperandForTruncAndAnyExt(
2926 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002927 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002928 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002929 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002930
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002931 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002932 /// operand is promotable and is not a supported trunc or sext.
2933 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002934 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002935 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002936 /// Newly added extensions are inserted in \p Exts.
2937 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002938 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002939 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002940 static Value *promoteOperandForOther(Instruction *Ext,
2941 TypePromotionTransaction &TPT,
2942 InstrToOrigTy &PromotedInsts,
2943 unsigned &CreatedInstsCost,
2944 SmallVectorImpl<Instruction *> *Exts,
2945 SmallVectorImpl<Instruction *> *Truncs,
2946 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002947
2948 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002949 static Value *signExtendOperandForOther(
2950 Instruction *Ext, TypePromotionTransaction &TPT,
2951 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2952 SmallVectorImpl<Instruction *> *Exts,
2953 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2954 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2955 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002956 }
2957
2958 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002959 static Value *zeroExtendOperandForOther(
2960 Instruction *Ext, TypePromotionTransaction &TPT,
2961 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2962 SmallVectorImpl<Instruction *> *Exts,
2963 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2964 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2965 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002966 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002967
2968public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002969 /// Type for the utility function that promotes the operand of Ext.
2970 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002971 InstrToOrigTy &PromotedInsts,
2972 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002973 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002974 SmallVectorImpl<Instruction *> *Truncs,
2975 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002976 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2977 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002978 /// \return NULL if no promotable action is possible with the current
2979 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002980 /// \p InsertedInsts keeps track of all the instructions inserted by the
2981 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002982 /// because we do not want to promote these instructions as CodeGenPrepare
2983 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2984 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002985 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002986 const TargetLowering &TLI,
2987 const InstrToOrigTy &PromotedInsts);
2988};
2989
2990bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002991 Type *ConsideredExtType,
2992 const InstrToOrigTy &PromotedInsts,
2993 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002994 // The promotion helper does not know how to deal with vector types yet.
2995 // To be able to fix that, we would need to fix the places where we
2996 // statically extend, e.g., constants and such.
2997 if (Inst->getType()->isVectorTy())
2998 return false;
2999
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003000 // We can always get through zext.
3001 if (isa<ZExtInst>(Inst))
3002 return true;
3003
3004 // sext(sext) is ok too.
3005 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003006 return true;
3007
3008 // We can get through binary operator, if it is legal. In other words, the
3009 // binary operator must have a nuw or nsw flag.
3010 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3011 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003012 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3013 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003014 return true;
3015
3016 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003017 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003018 if (!isa<TruncInst>(Inst))
3019 return false;
3020
3021 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003022 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003023 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003024 if (!OpndVal->getType()->isIntegerTy() ||
3025 OpndVal->getType()->getIntegerBitWidth() >
3026 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003027 return false;
3028
3029 // If the operand of the truncate is not an instruction, we will not have
3030 // any information on the dropped bits.
3031 // (Actually we could for constant but it is not worth the extra logic).
3032 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3033 if (!Opnd)
3034 return false;
3035
3036 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003037 // I.e., check that trunc just drops extended bits of the same kind of
3038 // the extension.
3039 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003040 const Type *OpndType;
3041 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003042 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3043 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003044 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3045 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003046 else
3047 return false;
3048
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003049 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003050 return Inst->getType()->getIntegerBitWidth() >=
3051 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003052}
3053
3054TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003055 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003056 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003057 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3058 "Unexpected instruction type");
3059 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3060 Type *ExtTy = Ext->getType();
3061 bool IsSExt = isa<SExtInst>(Ext);
3062 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003063 // get through.
3064 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003065 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003066 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003067
3068 // Do not promote if the operand has been added by codegenprepare.
3069 // Otherwise, it means we are undoing an optimization that is likely to be
3070 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003071 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003072 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003073
3074 // SExt or Trunc instructions.
3075 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003076 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3077 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003078 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003079
3080 // Regular instruction.
3081 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003082 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003083 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003084 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003085}
3086
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003087Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003088 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003089 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003090 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003091 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003092 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3093 // get through it and this method should not be called.
3094 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003095 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003096 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003097 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003098 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003099 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003100 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003101 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003102 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3103 TPT.replaceAllUsesWith(SExt, ZExt);
3104 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003105 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003106 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003107 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3108 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003109 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3110 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003111 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003112
3113 // Remove dead code.
3114 if (SExtOpnd->use_empty())
3115 TPT.eraseInstruction(SExtOpnd);
3116
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003117 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003118 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003119 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003120 if (ExtInst) {
3121 if (Exts)
3122 Exts->push_back(ExtInst);
3123 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3124 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003125 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003126 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003127
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003128 // At this point we have: ext ty opnd to ty.
3129 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3130 Value *NextVal = ExtInst->getOperand(0);
3131 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003132 return NextVal;
3133}
3134
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003135Value *TypePromotionHelper::promoteOperandForOther(
3136 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003137 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003138 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003139 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3140 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003141 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003142 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003143 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003144 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003145 if (!ExtOpnd->hasOneUse()) {
3146 // ExtOpnd will be promoted.
3147 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003148 // promoted version.
3149 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003150 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003151 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3152 ITrunc->removeFromParent();
3153 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003154 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003155 if (Truncs)
3156 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003157 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003158
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003159 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003160 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003161 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003162 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003163 }
3164
3165 // Get through the Instruction:
3166 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003167 // 2. Replace the uses of Ext by Inst.
3168 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003169
3170 // Remember the original type of the instruction before promotion.
3171 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003172 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3173 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003174 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003175 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003176 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003177 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003178 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003179 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003180
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003181 DEBUG(dbgs() << "Propagate Ext to operands\n");
3182 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003183 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003184 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3185 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3186 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003187 DEBUG(dbgs() << "No need to propagate\n");
3188 continue;
3189 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003190 // Check if we can statically extend the operand.
3191 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003192 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003193 DEBUG(dbgs() << "Statically extend\n");
3194 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3195 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3196 : Cst->getValue().zext(BitWidth);
3197 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003198 continue;
3199 }
3200 // UndefValue are typed, so we have to statically sign extend them.
3201 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003202 DEBUG(dbgs() << "Statically extend\n");
3203 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003204 continue;
3205 }
3206
3207 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003208 // Check if Ext was reused to extend an operand.
3209 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003210 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003211 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003212 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3213 : TPT.createZExt(Ext, Opnd, Ext->getType());
3214 if (!isa<Instruction>(ValForExtOpnd)) {
3215 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3216 continue;
3217 }
3218 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003219 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003220 if (Exts)
3221 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003222 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003223
3224 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003225 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3226 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003227 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003228 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003229 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003230 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003231 if (ExtForOpnd == Ext) {
3232 DEBUG(dbgs() << "Extension is useless now\n");
3233 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003234 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003235 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003236}
3237
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003238/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003239/// \p NewCost gives the cost of extension instructions created by the
3240/// promotion.
3241/// \p OldCost gives the cost of extension instructions before the promotion
3242/// plus the number of instructions that have been
3243/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003244/// \p PromotedOperand is the value that has been promoted.
3245/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003246bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003247 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3248 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3249 // The cost of the new extensions is greater than the cost of the
3250 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003251 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003252 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003253 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003254 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003255 return true;
3256 // The promotion is neutral but it may help folding the sign extension in
3257 // loads for instance.
3258 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003259 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003260}
3261
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003262/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003263/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003264/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003265/// If \p MovedAway is not NULL, it contains the information of whether or
3266/// not AddrInst has to be folded into the addressing mode on success.
3267/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3268/// because it has been moved away.
3269/// Thus AddrInst must not be added in the matched instructions.
3270/// This state can happen when AddrInst is a sext, since it may be moved away.
3271/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3272/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003273bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003274 unsigned Depth,
3275 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003276 // Avoid exponential behavior on extremely deep expression trees.
3277 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003278
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003279 // By default, all matched instructions stay in place.
3280 if (MovedAway)
3281 *MovedAway = false;
3282
Chandler Carruthc8925912013-01-05 02:09:22 +00003283 switch (Opcode) {
3284 case Instruction::PtrToInt:
3285 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003286 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003287 case Instruction::IntToPtr: {
3288 auto AS = AddrInst->getType()->getPointerAddressSpace();
3289 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003290 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003291 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003292 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003293 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003294 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003295 case Instruction::BitCast:
3296 // BitCast is always a noop, and we can handle it as long as it is
3297 // int->int or pointer->pointer (we don't want int<->fp or something).
3298 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3299 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3300 // Don't touch identity bitcasts. These were probably put here by LSR,
3301 // and we don't want to mess around with them. Assume it knows what it
3302 // is doing.
3303 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003304 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003305 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003306 case Instruction::AddrSpaceCast: {
3307 unsigned SrcAS
3308 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3309 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3310 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003311 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003312 return false;
3313 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003314 case Instruction::Add: {
3315 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3316 ExtAddrMode BackupAddrMode = AddrMode;
3317 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003318 // Start a transaction at this point.
3319 // The LHS may match but not the RHS.
3320 // Therefore, we need a higher level restoration point to undo partially
3321 // matched operation.
3322 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3323 TPT.getRestorationPoint();
3324
Sanjay Patelfc580a62015-09-21 23:03:16 +00003325 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3326 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003327 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003328
Chandler Carruthc8925912013-01-05 02:09:22 +00003329 // Restore the old addr mode info.
3330 AddrMode = BackupAddrMode;
3331 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003332 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003333
Chandler Carruthc8925912013-01-05 02:09:22 +00003334 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003335 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3336 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003337 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003338
Chandler Carruthc8925912013-01-05 02:09:22 +00003339 // Otherwise we definitely can't merge the ADD in.
3340 AddrMode = BackupAddrMode;
3341 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003342 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003343 break;
3344 }
3345 //case Instruction::Or:
3346 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3347 //break;
3348 case Instruction::Mul:
3349 case Instruction::Shl: {
3350 // Can only handle X*C and X << C.
3351 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003352 if (!RHS)
3353 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003354 int64_t Scale = RHS->getSExtValue();
3355 if (Opcode == Instruction::Shl)
3356 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003357
Sanjay Patelfc580a62015-09-21 23:03:16 +00003358 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003359 }
3360 case Instruction::GetElementPtr: {
3361 // Scan the GEP. We check it if it contains constant offsets and at most
3362 // one variable offset.
3363 int VariableOperand = -1;
3364 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003365
Chandler Carruthc8925912013-01-05 02:09:22 +00003366 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003367 gep_type_iterator GTI = gep_type_begin(AddrInst);
3368 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003369 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003370 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003371 unsigned Idx =
3372 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3373 ConstantOffset += SL->getElementOffset(Idx);
3374 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003375 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003376 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3377 ConstantOffset += CI->getSExtValue()*TypeSize;
3378 } else if (TypeSize) { // Scales of zero don't do anything.
3379 // We only allow one variable index at the moment.
3380 if (VariableOperand != -1)
3381 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003382
Chandler Carruthc8925912013-01-05 02:09:22 +00003383 // Remember the variable index.
3384 VariableOperand = i;
3385 VariableScale = TypeSize;
3386 }
3387 }
3388 }
Stephen Lin837bba12013-07-15 17:55:02 +00003389
Chandler Carruthc8925912013-01-05 02:09:22 +00003390 // A common case is for the GEP to only do a constant offset. In this case,
3391 // just add it to the disp field and check validity.
3392 if (VariableOperand == -1) {
3393 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003394 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003395 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003396 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003397 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003398 return true;
3399 }
3400 AddrMode.BaseOffs -= ConstantOffset;
3401 return false;
3402 }
3403
3404 // Save the valid addressing mode in case we can't match.
3405 ExtAddrMode BackupAddrMode = AddrMode;
3406 unsigned OldSize = AddrModeInsts.size();
3407
3408 // See if the scale and offset amount is valid for this target.
3409 AddrMode.BaseOffs += ConstantOffset;
3410
3411 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003412 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003413 // If it couldn't be matched, just stuff the value in a register.
3414 if (AddrMode.HasBaseReg) {
3415 AddrMode = BackupAddrMode;
3416 AddrModeInsts.resize(OldSize);
3417 return false;
3418 }
3419 AddrMode.HasBaseReg = true;
3420 AddrMode.BaseReg = AddrInst->getOperand(0);
3421 }
3422
3423 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003424 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003425 Depth)) {
3426 // If it couldn't be matched, try stuffing the base into a register
3427 // instead of matching it, and retrying the match of the scale.
3428 AddrMode = BackupAddrMode;
3429 AddrModeInsts.resize(OldSize);
3430 if (AddrMode.HasBaseReg)
3431 return false;
3432 AddrMode.HasBaseReg = true;
3433 AddrMode.BaseReg = AddrInst->getOperand(0);
3434 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003435 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003436 VariableScale, Depth)) {
3437 // If even that didn't work, bail.
3438 AddrMode = BackupAddrMode;
3439 AddrModeInsts.resize(OldSize);
3440 return false;
3441 }
3442 }
3443
3444 return true;
3445 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003446 case Instruction::SExt:
3447 case Instruction::ZExt: {
3448 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3449 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003450 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003451
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003452 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003453 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003454 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003455 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003456 if (!TPH)
3457 return false;
3458
3459 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3460 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003461 unsigned CreatedInstsCost = 0;
3462 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003463 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003464 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003465 // SExt has been moved away.
3466 // Thus either it will be rematched later in the recursive calls or it is
3467 // gone. Anyway, we must not fold it into the addressing mode at this point.
3468 // E.g.,
3469 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003470 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003471 // addr = gep base, idx
3472 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003473 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003474 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3475 // addr = gep base, op <- match
3476 if (MovedAway)
3477 *MovedAway = true;
3478
3479 assert(PromotedOperand &&
3480 "TypePromotionHelper should have filtered out those cases");
3481
3482 ExtAddrMode BackupAddrMode = AddrMode;
3483 unsigned OldSize = AddrModeInsts.size();
3484
Sanjay Patelfc580a62015-09-21 23:03:16 +00003485 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003486 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003487 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003488 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003489 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003490 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003491 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003492 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003493 AddrMode = BackupAddrMode;
3494 AddrModeInsts.resize(OldSize);
3495 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3496 TPT.rollback(LastKnownGood);
3497 return false;
3498 }
3499 return true;
3500 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003501 }
3502 return false;
3503}
3504
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003505/// If we can, try to add the value of 'Addr' into the current addressing mode.
3506/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3507/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3508/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003509///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003510bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003511 // Start a transaction at this point that we will rollback if the matching
3512 // fails.
3513 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3514 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003515 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3516 // Fold in immediates if legal for the target.
3517 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003518 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003519 return true;
3520 AddrMode.BaseOffs -= CI->getSExtValue();
3521 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3522 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003523 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003524 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003525 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003526 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003527 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003528 }
3529 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3530 ExtAddrMode BackupAddrMode = AddrMode;
3531 unsigned OldSize = AddrModeInsts.size();
3532
3533 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003534 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003535 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003536 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003537 // to check here.
3538 if (MovedAway)
3539 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003540 // Okay, it's possible to fold this. Check to see if it is actually
3541 // *profitable* to do so. We use a simple cost model to avoid increasing
3542 // register pressure too much.
3543 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003544 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003545 AddrModeInsts.push_back(I);
3546 return true;
3547 }
Stephen Lin837bba12013-07-15 17:55:02 +00003548
Chandler Carruthc8925912013-01-05 02:09:22 +00003549 // It isn't profitable to do this, roll back.
3550 //cerr << "NOT FOLDING: " << *I;
3551 AddrMode = BackupAddrMode;
3552 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003553 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003554 }
3555 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003556 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003557 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003558 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003559 } else if (isa<ConstantPointerNull>(Addr)) {
3560 // Null pointer gets folded without affecting the addressing mode.
3561 return true;
3562 }
3563
3564 // Worse case, the target should support [reg] addressing modes. :)
3565 if (!AddrMode.HasBaseReg) {
3566 AddrMode.HasBaseReg = true;
3567 AddrMode.BaseReg = Addr;
3568 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003569 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003570 return true;
3571 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003572 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003573 }
3574
3575 // If the base register is already taken, see if we can do [r+r].
3576 if (AddrMode.Scale == 0) {
3577 AddrMode.Scale = 1;
3578 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003579 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003580 return true;
3581 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003582 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003583 }
3584 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003585 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003586 return false;
3587}
3588
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003589/// Check to see if all uses of OpVal by the specified inline asm call are due
3590/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003591static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003592 const TargetMachine &TM) {
3593 const Function *F = CI->getParent()->getParent();
3594 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3595 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003596 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003597 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3598 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003599 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3600 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003601
Chandler Carruthc8925912013-01-05 02:09:22 +00003602 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003603 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003604
3605 // If this asm operand is our Value*, and if it isn't an indirect memory
3606 // operand, we can't fold it!
3607 if (OpInfo.CallOperandVal == OpVal &&
3608 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3609 !OpInfo.isIndirect))
3610 return false;
3611 }
3612
3613 return true;
3614}
3615
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003616/// Recursively walk all the uses of I until we find a memory use.
3617/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003618/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003619static bool FindAllMemoryUses(
3620 Instruction *I,
3621 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3622 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003623 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003624 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003625 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003626
Chandler Carruthc8925912013-01-05 02:09:22 +00003627 // If this is an obviously unfoldable instruction, bail out.
3628 if (!MightBeFoldableInst(I))
3629 return true;
3630
Philip Reamesac115ed2016-03-09 23:13:12 +00003631 const bool OptSize = I->getFunction()->optForSize();
3632
Chandler Carruthc8925912013-01-05 02:09:22 +00003633 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003634 for (Use &U : I->uses()) {
3635 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003636
Chandler Carruthcdf47882014-03-09 03:16:01 +00003637 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3638 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003639 continue;
3640 }
Stephen Lin837bba12013-07-15 17:55:02 +00003641
Chandler Carruthcdf47882014-03-09 03:16:01 +00003642 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3643 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003644 if (opNo == 0) return true; // Storing addr, not into addr.
3645 MemoryUses.push_back(std::make_pair(SI, opNo));
3646 continue;
3647 }
Stephen Lin837bba12013-07-15 17:55:02 +00003648
Chandler Carruthcdf47882014-03-09 03:16:01 +00003649 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003650 // If this is a cold call, we can sink the addressing calculation into
3651 // the cold path. See optimizeCallInst
3652 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3653 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003654
Chandler Carruthc8925912013-01-05 02:09:22 +00003655 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3656 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003657
Chandler Carruthc8925912013-01-05 02:09:22 +00003658 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003659 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003660 return true;
3661 continue;
3662 }
Stephen Lin837bba12013-07-15 17:55:02 +00003663
Eric Christopher11e4df72015-02-26 22:38:43 +00003664 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003665 return true;
3666 }
3667
3668 return false;
3669}
3670
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003671/// Return true if Val is already known to be live at the use site that we're
3672/// folding it into. If so, there is no cost to include it in the addressing
3673/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3674/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003675bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003676 Value *KnownLive2) {
3677 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003678 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003679 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003680
Chandler Carruthc8925912013-01-05 02:09:22 +00003681 // All values other than instructions and arguments (e.g. constants) are live.
3682 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003683
Chandler Carruthc8925912013-01-05 02:09:22 +00003684 // If Val is a constant sized alloca in the entry block, it is live, this is
3685 // true because it is just a reference to the stack/frame pointer, which is
3686 // live for the whole function.
3687 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3688 if (AI->isStaticAlloca())
3689 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003690
Chandler Carruthc8925912013-01-05 02:09:22 +00003691 // Check to see if this value is already used in the memory instruction's
3692 // block. If so, it's already live into the block at the very least, so we
3693 // can reasonably fold it.
3694 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3695}
3696
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003697/// It is possible for the addressing mode of the machine to fold the specified
3698/// instruction into a load or store that ultimately uses it.
3699/// However, the specified instruction has multiple uses.
3700/// Given this, it may actually increase register pressure to fold it
3701/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003702///
3703/// X = ...
3704/// Y = X+1
3705/// use(Y) -> nonload/store
3706/// Z = Y+1
3707/// load Z
3708///
3709/// In this case, Y has multiple uses, and can be folded into the load of Z
3710/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3711/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3712/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3713/// number of computations either.
3714///
3715/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3716/// X was live across 'load Z' for other reasons, we actually *would* want to
3717/// fold the addressing mode in the Z case. This would make Y die earlier.
3718bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003719isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003720 ExtAddrMode &AMAfter) {
3721 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003722
Chandler Carruthc8925912013-01-05 02:09:22 +00003723 // AMBefore is the addressing mode before this instruction was folded into it,
3724 // and AMAfter is the addressing mode after the instruction was folded. Get
3725 // the set of registers referenced by AMAfter and subtract out those
3726 // referenced by AMBefore: this is the set of values which folding in this
3727 // address extends the lifetime of.
3728 //
3729 // Note that there are only two potential values being referenced here,
3730 // BaseReg and ScaleReg (global addresses are always available, as are any
3731 // folded immediates).
3732 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003733
Chandler Carruthc8925912013-01-05 02:09:22 +00003734 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3735 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003736 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003737 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003738 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003739 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003740
3741 // If folding this instruction (and it's subexprs) didn't extend any live
3742 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003743 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003744 return true;
3745
Philip Reamesac115ed2016-03-09 23:13:12 +00003746 // If all uses of this instruction can have the address mode sunk into them,
3747 // we can remove the addressing mode and effectively trade one live register
3748 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003749 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003750 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3751 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003752 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003753 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003754
Chandler Carruthc8925912013-01-05 02:09:22 +00003755 // Now that we know that all uses of this instruction are part of a chain of
3756 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003757 // into a memory use, loop over each of these memory operation uses and see
3758 // if they could *actually* fold the instruction. The assumption is that
3759 // addressing modes are cheap and that duplicating the computation involved
3760 // many times is worthwhile, even on a fastpath. For sinking candidates
3761 // (i.e. cold call sites), this serves as a way to prevent excessive code
3762 // growth since most architectures have some reasonable small and fast way to
3763 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003764 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3765 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3766 Instruction *User = MemoryUses[i].first;
3767 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003768
Chandler Carruthc8925912013-01-05 02:09:22 +00003769 // Get the access type of this use. If the use isn't a pointer, we don't
3770 // know what it accesses.
3771 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003772 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3773 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003774 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003775 Type *AddressAccessTy = AddrTy->getElementType();
3776 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003777
Chandler Carruthc8925912013-01-05 02:09:22 +00003778 // Do a match against the root of this address, ignoring profitability. This
3779 // will tell us if the addressing mode for the memory operation will
3780 // *actually* cover the shared instruction.
3781 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003782 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3783 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003784 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003785 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003786 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003787 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003788 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003789 (void)Success; assert(Success && "Couldn't select *anything*?");
3790
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003791 // The match was to check the profitability, the changes made are not
3792 // part of the original matcher. Therefore, they should be dropped
3793 // otherwise the original matcher will not present the right state.
3794 TPT.rollback(LastKnownGood);
3795
Chandler Carruthc8925912013-01-05 02:09:22 +00003796 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003797 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003798 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003799
Chandler Carruthc8925912013-01-05 02:09:22 +00003800 MatchedAddrModeInsts.clear();
3801 }
Stephen Lin837bba12013-07-15 17:55:02 +00003802
Chandler Carruthc8925912013-01-05 02:09:22 +00003803 return true;
3804}
3805
3806} // end anonymous namespace
3807
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003808/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003809/// different basic block than BB.
3810static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3811 if (Instruction *I = dyn_cast<Instruction>(V))
3812 return I->getParent() != BB;
3813 return false;
3814}
3815
Philip Reamesac115ed2016-03-09 23:13:12 +00003816/// Sink addressing mode computation immediate before MemoryInst if doing so
3817/// can be done without increasing register pressure. The need for the
3818/// register pressure constraint means this can end up being an all or nothing
3819/// decision for all uses of the same addressing computation.
3820///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003821/// Load and Store Instructions often have addressing modes that can do
3822/// significant amounts of computation. As such, instruction selection will try
3823/// to get the load or store to do as much computation as possible for the
3824/// program. The problem is that isel can only see within a single block. As
3825/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003826///
3827/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003828/// operands. It's also used to sink addressing computations feeding into cold
3829/// call sites into their (cold) basic block.
3830///
3831/// The motivation for handling sinking into cold blocks is that doing so can
3832/// both enable other address mode sinking (by satisfying the register pressure
3833/// constraint above), and reduce register pressure globally (by removing the
3834/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003835bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003836 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003837 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003838
3839 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003840 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003841 SmallVector<Value*, 8> worklist;
3842 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003843 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003844
Owen Anderson8ba5f392010-11-27 08:15:55 +00003845 // Use a worklist to iteratively look through PHI nodes, and ensure that
3846 // the addressing mode obtained from the non-PHI roots of the graph
3847 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003848 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003849 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003850 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003851 SmallVector<Instruction*, 16> AddrModeInsts;
3852 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003853 TypePromotionTransaction TPT;
3854 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3855 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003856 while (!worklist.empty()) {
3857 Value *V = worklist.back();
3858 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003859
Owen Anderson8ba5f392010-11-27 08:15:55 +00003860 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003861 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003862 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003863 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003864 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003865
Owen Anderson8ba5f392010-11-27 08:15:55 +00003866 // For a PHI node, push all of its incoming values.
3867 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003868 for (Value *IncValue : P->incoming_values())
3869 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003870 continue;
3871 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003872
Philip Reamesac115ed2016-03-09 23:13:12 +00003873 // For non-PHIs, determine the addressing mode being computed. Note that
3874 // the result may differ depending on what other uses our candidate
3875 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003876 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003877 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003878 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003879 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003880
3881 // This check is broken into two cases with very similar code to avoid using
3882 // getNumUses() as much as possible. Some values have a lot of uses, so
3883 // calling getNumUses() unconditionally caused a significant compile-time
3884 // regression.
3885 if (!Consensus) {
3886 Consensus = V;
3887 AddrMode = NewAddrMode;
3888 AddrModeInsts = NewAddrModeInsts;
3889 continue;
3890 } else if (NewAddrMode == AddrMode) {
3891 if (!IsNumUsesConsensusValid) {
3892 NumUsesConsensus = Consensus->getNumUses();
3893 IsNumUsesConsensusValid = true;
3894 }
3895
3896 // Ensure that the obtained addressing mode is equivalent to that obtained
3897 // for all other roots of the PHI traversal. Also, when choosing one
3898 // such root as representative, select the one with the most uses in order
3899 // to keep the cost modeling heuristics in AddressingModeMatcher
3900 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003901 unsigned NumUses = V->getNumUses();
3902 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003903 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003904 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003905 AddrModeInsts = NewAddrModeInsts;
3906 }
3907 continue;
3908 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003909
Craig Topperc0196b12014-04-14 00:51:57 +00003910 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003911 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003912 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003913
Owen Anderson8ba5f392010-11-27 08:15:55 +00003914 // If the addressing mode couldn't be determined, or if multiple different
3915 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003916 if (!Consensus) {
3917 TPT.rollback(LastKnownGood);
3918 return false;
3919 }
3920 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003921
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003922 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00003923 if (none_of(AddrModeInsts, [&](Value *V) {
3924 return IsNonLocalValue(V, MemoryInst->getParent());
3925 })) {
David Greene74e2d492010-01-05 01:27:11 +00003926 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003927 return false;
3928 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003929
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003930 // Insert this computation right after this user. Since our caller is
3931 // scanning from the top of the BB to the bottom, reuse of the expr are
3932 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003933 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003934
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003935 // Now that we determined the addressing expression we want to use and know
3936 // that we have to sink it into this block. Check to see if we have already
3937 // done this for some other load/store instr in this block. If so, reuse the
3938 // computation.
3939 Value *&SunkAddr = SunkAddrs[Addr];
3940 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003941 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003942 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003943 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003944 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003945 } else if (AddrSinkUsingGEPs ||
3946 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003947 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3948 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003949 // By default, we use the GEP-based method when AA is used later. This
3950 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3951 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003952 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003953 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003954 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003955
3956 // First, find the pointer.
3957 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3958 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003959 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003960 }
3961
3962 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3963 // We can't add more than one pointer together, nor can we scale a
3964 // pointer (both of which seem meaningless).
3965 if (ResultPtr || AddrMode.Scale != 1)
3966 return false;
3967
3968 ResultPtr = AddrMode.ScaledReg;
3969 AddrMode.Scale = 0;
3970 }
3971
3972 if (AddrMode.BaseGV) {
3973 if (ResultPtr)
3974 return false;
3975
3976 ResultPtr = AddrMode.BaseGV;
3977 }
3978
3979 // If the real base value actually came from an inttoptr, then the matcher
3980 // will look through it and provide only the integer value. In that case,
3981 // use it here.
3982 if (!ResultPtr && AddrMode.BaseReg) {
3983 ResultPtr =
3984 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003985 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003986 } else if (!ResultPtr && AddrMode.Scale == 1) {
3987 ResultPtr =
3988 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3989 AddrMode.Scale = 0;
3990 }
3991
3992 if (!ResultPtr &&
3993 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3994 SunkAddr = Constant::getNullValue(Addr->getType());
3995 } else if (!ResultPtr) {
3996 return false;
3997 } else {
3998 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003999 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
4000 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00004001
4002 // Start with the base register. Do this first so that subsequent address
4003 // matching finds it last, which will prevent it from trying to match it
4004 // as the scaled value in case it happens to be a mul. That would be
4005 // problematic if we've sunk a different mul for the scale, because then
4006 // we'd end up sinking both muls.
4007 if (AddrMode.BaseReg) {
4008 Value *V = AddrMode.BaseReg;
4009 if (V->getType() != IntPtrTy)
4010 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4011
4012 ResultIndex = V;
4013 }
4014
4015 // Add the scale value.
4016 if (AddrMode.Scale) {
4017 Value *V = AddrMode.ScaledReg;
4018 if (V->getType() == IntPtrTy) {
4019 // done.
4020 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4021 cast<IntegerType>(V->getType())->getBitWidth()) {
4022 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4023 } else {
4024 // It is only safe to sign extend the BaseReg if we know that the math
4025 // required to create it did not overflow before we extend it. Since
4026 // the original IR value was tossed in favor of a constant back when
4027 // the AddrMode was created we need to bail out gracefully if widths
4028 // do not match instead of extending it.
4029 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4030 if (I && (ResultIndex != AddrMode.BaseReg))
4031 I->eraseFromParent();
4032 return false;
4033 }
4034
4035 if (AddrMode.Scale != 1)
4036 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4037 "sunkaddr");
4038 if (ResultIndex)
4039 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4040 else
4041 ResultIndex = V;
4042 }
4043
4044 // Add in the Base Offset if present.
4045 if (AddrMode.BaseOffs) {
4046 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4047 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004048 // We need to add this separately from the scale above to help with
4049 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004050 if (ResultPtr->getType() != I8PtrTy)
4051 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004052 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004053 }
4054
4055 ResultIndex = V;
4056 }
4057
4058 if (!ResultIndex) {
4059 SunkAddr = ResultPtr;
4060 } else {
4061 if (ResultPtr->getType() != I8PtrTy)
4062 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004063 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004064 }
4065
4066 if (SunkAddr->getType() != Addr->getType())
4067 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4068 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004069 } else {
David Greene74e2d492010-01-05 01:27:11 +00004070 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004071 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004072 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004073 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004074
4075 // Start with the base register. Do this first so that subsequent address
4076 // matching finds it last, which will prevent it from trying to match it
4077 // as the scaled value in case it happens to be a mul. That would be
4078 // problematic if we've sunk a different mul for the scale, because then
4079 // we'd end up sinking both muls.
4080 if (AddrMode.BaseReg) {
4081 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004082 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004083 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004084 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004085 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004086 Result = V;
4087 }
4088
4089 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004090 if (AddrMode.Scale) {
4091 Value *V = AddrMode.ScaledReg;
4092 if (V->getType() == IntPtrTy) {
4093 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004094 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004095 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004096 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4097 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004098 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004099 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004100 // It is only safe to sign extend the BaseReg if we know that the math
4101 // required to create it did not overflow before we extend it. Since
4102 // the original IR value was tossed in favor of a constant back when
4103 // the AddrMode was created we need to bail out gracefully if widths
4104 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004105 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004106 if (I && (Result != AddrMode.BaseReg))
4107 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004108 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004109 }
4110 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004111 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4112 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004113 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004114 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004115 else
4116 Result = V;
4117 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004118
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004119 // Add in the BaseGV if present.
4120 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004121 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004122 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004123 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004124 else
4125 Result = V;
4126 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004127
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004128 // Add in the Base Offset if present.
4129 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004130 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004131 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004132 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004133 else
4134 Result = V;
4135 }
4136
Craig Topperc0196b12014-04-14 00:51:57 +00004137 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004138 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004139 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004140 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004141 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004142
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004143 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004144
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004145 // If we have no uses, recursively delete the value and all dead instructions
4146 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004147 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004148 // This can cause recursive deletion, which can invalidate our iterator.
4149 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004150 Value *CurValue = &*CurInstIterator;
4151 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004152 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004153
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004154 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004155
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004156 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004157 // If the iterator instruction was recursively deleted, start over at the
4158 // start of the block.
4159 CurInstIterator = BB->begin();
4160 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004161 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004162 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004163 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004164 return true;
4165}
4166
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004167/// If there are any memory operands, use OptimizeMemoryInst to sink their
4168/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004169bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004170 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004171
Eric Christopher11e4df72015-02-26 22:38:43 +00004172 const TargetRegisterInfo *TRI =
4173 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004174 TargetLowering::AsmOperandInfoVector TargetConstraints =
4175 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004176 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004177 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4178 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004179
Evan Cheng1da25002008-02-26 02:42:37 +00004180 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004181 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004182
Eli Friedman666bbe32008-02-26 18:37:49 +00004183 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4184 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004185 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004186 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004187 } else if (OpInfo.Type == InlineAsm::isInput)
4188 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004189 }
4190
4191 return MadeChange;
4192}
4193
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004194/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4195/// sign extensions.
4196static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4197 assert(!Inst->use_empty() && "Input must have at least one use");
4198 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4199 bool IsSExt = isa<SExtInst>(FirstUser);
4200 Type *ExtTy = FirstUser->getType();
4201 for (const User *U : Inst->users()) {
4202 const Instruction *UI = cast<Instruction>(U);
4203 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4204 return false;
4205 Type *CurTy = UI->getType();
4206 // Same input and output types: Same instruction after CSE.
4207 if (CurTy == ExtTy)
4208 continue;
4209
4210 // If IsSExt is true, we are in this situation:
4211 // a = Inst
4212 // b = sext ty1 a to ty2
4213 // c = sext ty1 a to ty3
4214 // Assuming ty2 is shorter than ty3, this could be turned into:
4215 // a = Inst
4216 // b = sext ty1 a to ty2
4217 // c = sext ty2 b to ty3
4218 // However, the last sext is not free.
4219 if (IsSExt)
4220 return false;
4221
4222 // This is a ZExt, maybe this is free to extend from one type to another.
4223 // In that case, we would not account for a different use.
4224 Type *NarrowTy;
4225 Type *LargeTy;
4226 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4227 CurTy->getScalarType()->getIntegerBitWidth()) {
4228 NarrowTy = CurTy;
4229 LargeTy = ExtTy;
4230 } else {
4231 NarrowTy = ExtTy;
4232 LargeTy = CurTy;
4233 }
4234
4235 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4236 return false;
4237 }
4238 // All uses are the same or can be derived from one another for free.
4239 return true;
4240}
4241
4242/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4243/// load instruction.
4244/// If an ext(load) can be formed, it is returned via \p LI for the load
4245/// and \p Inst for the extension.
4246/// Otherwise LI == nullptr and Inst == nullptr.
4247/// When some promotion happened, \p TPT contains the proper state to
4248/// revert them.
4249///
4250/// \return true when promoting was necessary to expose the ext(load)
4251/// opportunity, false otherwise.
4252///
4253/// Example:
4254/// \code
4255/// %ld = load i32* %addr
4256/// %add = add nuw i32 %ld, 4
4257/// %zext = zext i32 %add to i64
4258/// \endcode
4259/// =>
4260/// \code
4261/// %ld = load i32* %addr
4262/// %zext = zext i32 %ld to i64
4263/// %add = add nuw i64 %zext, 4
4264/// \encode
4265/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004266bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004267 LoadInst *&LI, Instruction *&Inst,
4268 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004269 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004270 // Iterate over all the extensions to see if one form an ext(load).
4271 for (auto I : Exts) {
4272 // Check if we directly have ext(load).
4273 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4274 Inst = I;
4275 // No promotion happened here.
4276 return false;
4277 }
4278 // Check whether or not we want to do any promotion.
4279 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4280 continue;
4281 // Get the action to perform the promotion.
4282 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004283 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004284 // Check if we can promote.
4285 if (!TPH)
4286 continue;
4287 // Save the current state.
4288 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4289 TPT.getRestorationPoint();
4290 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004291 unsigned NewCreatedInstsCost = 0;
4292 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004293 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004294 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4295 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004296 assert(PromotedVal &&
4297 "TypePromotionHelper should have filtered out those cases");
4298
4299 // We would be able to merge only one extension in a load.
4300 // Therefore, if we have more than 1 new extension we heuristically
4301 // cut this search path, because it means we degrade the code quality.
4302 // With exactly 2, the transformation is neutral, because we will merge
4303 // one extension but leave one. However, we optimistically keep going,
4304 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004305 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4306 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004307 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004308 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004309 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004310 // The promotion is not profitable, rollback to the previous state.
4311 TPT.rollback(LastKnownGood);
4312 continue;
4313 }
4314 // The promotion is profitable.
4315 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004316 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004317 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004318 // If we have created a new extension, i.e., now we have two
4319 // extensions. We must make sure one of them is merged with
4320 // the load, otherwise we may degrade the code quality.
4321 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4322 // Promotion happened.
4323 return true;
4324 // If this does not help to expose an ext(load) then, rollback.
4325 TPT.rollback(LastKnownGood);
4326 }
4327 // None of the extension can form an ext(load).
4328 LI = nullptr;
4329 Inst = nullptr;
4330 return false;
4331}
4332
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004333/// Move a zext or sext fed by a load into the same basic block as the load,
4334/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4335/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004336/// \p I[in/out] the extension may be modified during the process if some
4337/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004338///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004339bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004340 // ExtLoad formation infrastructure requires TLI to be effective.
4341 if (!TLI)
4342 return false;
4343
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004344 // Try to promote a chain of computation if it allows to form
4345 // an extended load.
4346 TypePromotionTransaction TPT;
4347 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4348 TPT.getRestorationPoint();
4349 SmallVector<Instruction *, 1> Exts;
4350 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004351 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004352 LoadInst *LI = nullptr;
4353 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004354 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004355 if (!LI || !I) {
4356 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4357 "the code must remain the same");
4358 I = OldExt;
4359 return false;
4360 }
Dan Gohman99429a02009-10-16 20:59:35 +00004361
4362 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004363 // Make the cheap checks first if we did not promote.
4364 // If we promoted, we need to check if it is indeed profitable.
4365 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004366 return false;
4367
Mehdi Amini44ede332015-07-09 02:09:04 +00004368 EVT VT = TLI->getValueType(*DL, I->getType());
4369 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004370
Dan Gohman99429a02009-10-16 20:59:35 +00004371 // If the load has other users and the truncate is not free, this probably
4372 // isn't worthwhile.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004373 if (!LI->hasOneUse() &&
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004374 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004375 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4376 I = OldExt;
4377 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004378 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004379 }
Dan Gohman99429a02009-10-16 20:59:35 +00004380
4381 // Check whether the target supports casts folded into loads.
4382 unsigned LType;
4383 if (isa<ZExtInst>(I))
4384 LType = ISD::ZEXTLOAD;
4385 else {
4386 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4387 LType = ISD::SEXTLOAD;
4388 }
Chandler Carruth0f139b42016-11-04 06:54:00 +00004389 if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004390 I = OldExt;
4391 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004392 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004393 }
Dan Gohman99429a02009-10-16 20:59:35 +00004394
4395 // Move the extend into the same block as the load, so that SelectionDAG
4396 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004397 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004398 I->removeFromParent();
4399 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004400 // CGP does not check if the zext would be speculatively executed when moved
4401 // to the same basic block as the load. Preserving its original location would
4402 // pessimize the debugging experience, as well as negatively impact the
4403 // quality of sample pgo. We don't want to use "line 0" as that has a
4404 // size cost in the line-table section and logically the zext can be seen as
4405 // part of the load. Therefore we conservatively reuse the same debug location
4406 // for the load and the zext.
4407 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004408 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004409 return true;
4410}
4411
Sanjay Patelfc580a62015-09-21 23:03:16 +00004412bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004413 BasicBlock *DefBB = I->getParent();
4414
Bob Wilsonff714f92010-09-21 21:44:14 +00004415 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004416 // other uses of the source with result of extension.
4417 Value *Src = I->getOperand(0);
4418 if (Src->hasOneUse())
4419 return false;
4420
Evan Cheng2011df42007-12-13 07:50:36 +00004421 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004422 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004423 return false;
4424
Evan Cheng7bc89422007-12-12 00:51:06 +00004425 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004426 // this block.
4427 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004428 return false;
4429
Evan Chengd3d80172007-12-05 23:58:20 +00004430 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004431 for (User *U : I->users()) {
4432 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004433
4434 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004435 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004436 if (UserBB == DefBB) continue;
4437 DefIsLiveOut = true;
4438 break;
4439 }
4440 if (!DefIsLiveOut)
4441 return false;
4442
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004443 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004444 for (User *U : Src->users()) {
4445 Instruction *UI = cast<Instruction>(U);
4446 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004447 if (UserBB == DefBB) continue;
4448 // Be conservative. We don't want this xform to end up introducing
4449 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004450 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004451 return false;
4452 }
4453
Evan Chengd3d80172007-12-05 23:58:20 +00004454 // InsertedTruncs - Only insert one trunc in each block once.
4455 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4456
4457 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004458 for (Use &U : Src->uses()) {
4459 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004460
4461 // Figure out which BB this ext is used in.
4462 BasicBlock *UserBB = User->getParent();
4463 if (UserBB == DefBB) continue;
4464
4465 // Both src and def are live in this block. Rewrite the use.
4466 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4467
4468 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004469 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004470 assert(InsertPt != UserBB->end());
4471 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004472 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004473 }
4474
4475 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004476 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004477 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004478 MadeChange = true;
4479 }
4480
4481 return MadeChange;
4482}
4483
Geoff Berry5256fca2015-11-20 22:34:39 +00004484// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4485// just after the load if the target can fold this into one extload instruction,
4486// with the hope of eliminating some of the other later "and" instructions using
4487// the loaded value. "and"s that are made trivially redundant by the insertion
4488// of the new "and" are removed by this function, while others (e.g. those whose
4489// path from the load goes through a phi) are left for isel to potentially
4490// remove.
4491//
4492// For example:
4493//
4494// b0:
4495// x = load i32
4496// ...
4497// b1:
4498// y = and x, 0xff
4499// z = use y
4500//
4501// becomes:
4502//
4503// b0:
4504// x = load i32
4505// x' = and x, 0xff
4506// ...
4507// b1:
4508// z = use x'
4509//
4510// whereas:
4511//
4512// b0:
4513// x1 = load i32
4514// ...
4515// b1:
4516// x2 = load i32
4517// ...
4518// b2:
4519// x = phi x1, x2
4520// y = and x, 0xff
4521//
4522// becomes (after a call to optimizeLoadExt for each load):
4523//
4524// b0:
4525// x1 = load i32
4526// x1' = and x1, 0xff
4527// ...
4528// b1:
4529// x2 = load i32
4530// x2' = and x2, 0xff
4531// ...
4532// b2:
4533// x = phi x1', x2'
4534// y = and x, 0xff
4535//
4536
4537bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4538
4539 if (!Load->isSimple() ||
4540 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4541 return false;
4542
4543 // Skip loads we've already transformed or have no reason to transform.
4544 if (Load->hasOneUse()) {
4545 User *LoadUser = *Load->user_begin();
4546 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4547 !dyn_cast<PHINode>(LoadUser))
4548 return false;
4549 }
4550
4551 // Look at all uses of Load, looking through phis, to determine how many bits
4552 // of the loaded value are needed.
4553 SmallVector<Instruction *, 8> WorkList;
4554 SmallPtrSet<Instruction *, 16> Visited;
4555 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4556 for (auto *U : Load->users())
4557 WorkList.push_back(cast<Instruction>(U));
4558
4559 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4560 unsigned BitWidth = LoadResultVT.getSizeInBits();
4561 APInt DemandBits(BitWidth, 0);
4562 APInt WidestAndBits(BitWidth, 0);
4563
4564 while (!WorkList.empty()) {
4565 Instruction *I = WorkList.back();
4566 WorkList.pop_back();
4567
4568 // Break use-def graph loops.
4569 if (!Visited.insert(I).second)
4570 continue;
4571
4572 // For a PHI node, push all of its users.
4573 if (auto *Phi = dyn_cast<PHINode>(I)) {
4574 for (auto *U : Phi->users())
4575 WorkList.push_back(cast<Instruction>(U));
4576 continue;
4577 }
4578
4579 switch (I->getOpcode()) {
4580 case llvm::Instruction::And: {
4581 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4582 if (!AndC)
4583 return false;
4584 APInt AndBits = AndC->getValue();
4585 DemandBits |= AndBits;
4586 // Keep track of the widest and mask we see.
4587 if (AndBits.ugt(WidestAndBits))
4588 WidestAndBits = AndBits;
4589 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4590 AndsToMaybeRemove.push_back(I);
4591 break;
4592 }
4593
4594 case llvm::Instruction::Shl: {
4595 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4596 if (!ShlC)
4597 return false;
4598 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4599 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4600 DemandBits |= ShlDemandBits;
4601 break;
4602 }
4603
4604 case llvm::Instruction::Trunc: {
4605 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4606 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4607 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4608 DemandBits |= TruncBits;
4609 break;
4610 }
4611
4612 default:
4613 return false;
4614 }
4615 }
4616
4617 uint32_t ActiveBits = DemandBits.getActiveBits();
4618 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4619 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4620 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4621 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4622 // followed by an AND.
4623 // TODO: Look into removing this restriction by fixing backends to either
4624 // return false for isLoadExtLegal for i1 or have them select this pattern to
4625 // a single instruction.
4626 //
4627 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4628 // mask, since these are the only ands that will be removed by isel.
4629 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4630 WidestAndBits != DemandBits)
4631 return false;
4632
4633 LLVMContext &Ctx = Load->getType()->getContext();
4634 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4635 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4636
4637 // Reject cases that won't be matched as extloads.
4638 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4639 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4640 return false;
4641
4642 IRBuilder<> Builder(Load->getNextNode());
4643 auto *NewAnd = dyn_cast<Instruction>(
4644 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4645
4646 // Replace all uses of load with new and (except for the use of load in the
4647 // new and itself).
4648 Load->replaceAllUsesWith(NewAnd);
4649 NewAnd->setOperand(0, Load);
4650
4651 // Remove any and instructions that are now redundant.
4652 for (auto *And : AndsToMaybeRemove)
4653 // Check that the and mask is the same as the one we decided to put on the
4654 // new and.
4655 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4656 And->replaceAllUsesWith(NewAnd);
4657 if (&*CurInstIterator == And)
4658 CurInstIterator = std::next(And->getIterator());
4659 And->eraseFromParent();
4660 ++NumAndUses;
4661 }
4662
4663 ++NumAndsAdded;
4664 return true;
4665}
4666
Sanjay Patel69a50a12015-10-19 21:59:12 +00004667/// Check if V (an operand of a select instruction) is an expensive instruction
4668/// that is only used once.
4669static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4670 auto *I = dyn_cast<Instruction>(V);
4671 // If it's safe to speculatively execute, then it should not have side
4672 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004673 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4674 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004675}
4676
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004677/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004678static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004679 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004680 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004681 // If even a predictable select is cheap, then a branch can't be cheaper.
4682 if (!TLI->isPredictableSelectExpensive())
4683 return false;
4684
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004685 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004686 // whether a select is better represented as a branch.
4687
4688 // If metadata tells us that the select condition is obviously predictable,
4689 // then we want to replace the select with a branch.
4690 uint64_t TrueWeight, FalseWeight;
4691 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4692 uint64_t Max = std::max(TrueWeight, FalseWeight);
4693 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004694 if (Sum != 0) {
4695 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4696 if (Probability > TLI->getPredictableBranchThreshold())
4697 return true;
4698 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004699 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004700
4701 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4702
Sanjay Patel4e652762015-09-28 22:14:51 +00004703 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4704 // comparison condition. If the compare has more than one use, there's
4705 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004706 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004707 return false;
4708
Sanjay Patel69a50a12015-10-19 21:59:12 +00004709 // If either operand of the select is expensive and only needed on one side
4710 // of the select, we should form a branch.
4711 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4712 sinkSelectOperand(TTI, SI->getFalseValue()))
4713 return true;
4714
4715 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004716}
4717
Dehao Chen9bbb9412016-09-12 20:23:28 +00004718/// If \p isTrue is true, return the true value of \p SI, otherwise return
4719/// false value of \p SI. If the true/false value of \p SI is defined by any
4720/// select instructions in \p Selects, look through the defining select
4721/// instruction until the true/false value is not defined in \p Selects.
4722static Value *getTrueOrFalseValue(
4723 SelectInst *SI, bool isTrue,
4724 const SmallPtrSet<const Instruction *, 2> &Selects) {
4725 Value *V;
4726
4727 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4728 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004729 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004730 "The condition of DefSI does not match with SI");
4731 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4732 }
4733 return V;
4734}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004735
Nadav Rotem9d832022012-09-02 12:10:19 +00004736/// If we have a SelectInst that will likely profit from branch prediction,
4737/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004738bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004739 // Find all consecutive select instructions that share the same condition.
4740 SmallVector<SelectInst *, 2> ASI;
4741 ASI.push_back(SI);
4742 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4743 It != SI->getParent()->end(); ++It) {
4744 SelectInst *I = dyn_cast<SelectInst>(&*It);
4745 if (I && SI->getCondition() == I->getCondition()) {
4746 ASI.push_back(I);
4747 } else {
4748 break;
4749 }
4750 }
4751
4752 SelectInst *LastSI = ASI.back();
4753 // Increment the current iterator to skip all the rest of select instructions
4754 // because they will be either "not lowered" or "all lowered" to branch.
4755 CurInstIterator = std::next(LastSI->getIterator());
4756
Nadav Rotem9d832022012-09-02 12:10:19 +00004757 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4758
4759 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004760 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4761 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004762 return false;
4763
Nadav Rotem9d832022012-09-02 12:10:19 +00004764 TargetLowering::SelectSupportKind SelectKind;
4765 if (VectorCond)
4766 SelectKind = TargetLowering::VectorMaskSelect;
4767 else if (SI->getType()->isVectorTy())
4768 SelectKind = TargetLowering::ScalarCondVectorVal;
4769 else
4770 SelectKind = TargetLowering::ScalarValSelect;
4771
Sanjay Pateld66607b2016-04-26 17:11:17 +00004772 if (TLI->isSelectSupported(SelectKind) &&
4773 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4774 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004775
4776 ModifiedDT = true;
4777
Sanjay Patel69a50a12015-10-19 21:59:12 +00004778 // Transform a sequence like this:
4779 // start:
4780 // %cmp = cmp uge i32 %a, %b
4781 // %sel = select i1 %cmp, i32 %c, i32 %d
4782 //
4783 // Into:
4784 // start:
4785 // %cmp = cmp uge i32 %a, %b
4786 // br i1 %cmp, label %select.true, label %select.false
4787 // select.true:
4788 // br label %select.end
4789 // select.false:
4790 // br label %select.end
4791 // select.end:
4792 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4793 //
4794 // In addition, we may sink instructions that produce %c or %d from
4795 // the entry block into the destination(s) of the new branch.
4796 // If the true or false blocks do not contain a sunken instruction, that
4797 // block and its branch may be optimized away. In that case, one side of the
4798 // first branch will point directly to select.end, and the corresponding PHI
4799 // predecessor block will be the start block.
4800
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004801 // First, we split the block containing the select into 2 blocks.
4802 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004803 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004804 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004805
Sanjay Patel69a50a12015-10-19 21:59:12 +00004806 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004807 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004808
4809 // These are the new basic blocks for the conditional branch.
4810 // At least one will become an actual new basic block.
4811 BasicBlock *TrueBlock = nullptr;
4812 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004813 BranchInst *TrueBranch = nullptr;
4814 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004815
4816 // Sink expensive instructions into the conditional blocks to avoid executing
4817 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004818 for (SelectInst *SI : ASI) {
4819 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4820 if (TrueBlock == nullptr) {
4821 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4822 EndBlock->getParent(), EndBlock);
4823 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4824 }
4825 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4826 TrueInst->moveBefore(TrueBranch);
4827 }
4828 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4829 if (FalseBlock == nullptr) {
4830 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4831 EndBlock->getParent(), EndBlock);
4832 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4833 }
4834 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4835 FalseInst->moveBefore(FalseBranch);
4836 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004837 }
4838
4839 // If there was nothing to sink, then arbitrarily choose the 'false' side
4840 // for a new input value to the PHI.
4841 if (TrueBlock == FalseBlock) {
4842 assert(TrueBlock == nullptr &&
4843 "Unexpected basic block transform while optimizing select");
4844
4845 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4846 EndBlock->getParent(), EndBlock);
4847 BranchInst::Create(EndBlock, FalseBlock);
4848 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004849
4850 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004851 // If we did not create a new block for one of the 'true' or 'false' paths
4852 // of the condition, it means that side of the branch goes to the end block
4853 // directly and the path originates from the start block from the point of
4854 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004855 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004856 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004857 TT = EndBlock;
4858 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004859 TrueBlock = StartBlock;
4860 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004861 TT = TrueBlock;
4862 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004863 FalseBlock = StartBlock;
4864 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004865 TT = TrueBlock;
4866 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004867 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004868 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004869
Dehao Chen9bbb9412016-09-12 20:23:28 +00004870 SmallPtrSet<const Instruction *, 2> INS;
4871 INS.insert(ASI.begin(), ASI.end());
4872 // Use reverse iterator because later select may use the value of the
4873 // earlier select, and we need to propagate value through earlier select
4874 // to get the PHI operand.
4875 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4876 SelectInst *SI = *It;
4877 // The select itself is replaced with a PHI Node.
4878 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4879 PN->takeName(SI);
4880 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4881 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004882
Dehao Chen9bbb9412016-09-12 20:23:28 +00004883 SI->replaceAllUsesWith(PN);
4884 SI->eraseFromParent();
4885 INS.erase(SI);
4886 ++NumSelectsExpanded;
4887 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004888
4889 // Instruct OptimizeBlock to skip to the next block.
4890 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004891 return true;
4892}
4893
Benjamin Kramer573ff362014-03-01 17:24:40 +00004894static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004895 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4896 int SplatElem = -1;
4897 for (unsigned i = 0; i < Mask.size(); ++i) {
4898 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4899 return false;
4900 SplatElem = Mask[i];
4901 }
4902
4903 return true;
4904}
4905
4906/// Some targets have expensive vector shifts if the lanes aren't all the same
4907/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4908/// it's often worth sinking a shufflevector splat down to its use so that
4909/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004910bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004911 BasicBlock *DefBB = SVI->getParent();
4912
4913 // Only do this xform if variable vector shifts are particularly expensive.
4914 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4915 return false;
4916
4917 // We only expect better codegen by sinking a shuffle if we can recognise a
4918 // constant splat.
4919 if (!isBroadcastShuffle(SVI))
4920 return false;
4921
4922 // InsertedShuffles - Only insert a shuffle in each block once.
4923 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4924
4925 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004926 for (User *U : SVI->users()) {
4927 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004928
4929 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004930 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004931 if (UserBB == DefBB) continue;
4932
4933 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004934 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004935
4936 // Everything checks out, sink the shuffle if the user's block doesn't
4937 // already have a copy.
4938 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4939
4940 if (!InsertedShuffle) {
4941 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004942 assert(InsertPt != UserBB->end());
4943 InsertedShuffle =
4944 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4945 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004946 }
4947
Chandler Carruthcdf47882014-03-09 03:16:01 +00004948 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004949 MadeChange = true;
4950 }
4951
4952 // If we removed all uses, nuke the shuffle.
4953 if (SVI->use_empty()) {
4954 SVI->eraseFromParent();
4955 MadeChange = true;
4956 }
4957
4958 return MadeChange;
4959}
4960
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004961bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4962 if (!TLI || !DL)
4963 return false;
4964
4965 Value *Cond = SI->getCondition();
4966 Type *OldType = Cond->getType();
4967 LLVMContext &Context = Cond->getContext();
4968 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4969 unsigned RegWidth = RegType.getSizeInBits();
4970
4971 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4972 return false;
4973
4974 // If the register width is greater than the type width, expand the condition
4975 // of the switch instruction and each case constant to the width of the
4976 // register. By widening the type of the switch condition, subsequent
4977 // comparisons (for case comparisons) will not need to be extended to the
4978 // preferred register width, so we will potentially eliminate N-1 extends,
4979 // where N is the number of cases in the switch.
4980 auto *NewType = Type::getIntNTy(Context, RegWidth);
4981
4982 // Zero-extend the switch condition and case constants unless the switch
4983 // condition is a function argument that is already being sign-extended.
4984 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4985 // everything instead.
4986 Instruction::CastOps ExtType = Instruction::ZExt;
4987 if (auto *Arg = dyn_cast<Argument>(Cond))
4988 if (Arg->hasSExtAttr())
4989 ExtType = Instruction::SExt;
4990
4991 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4992 ExtInst->insertBefore(SI);
4993 SI->setCondition(ExtInst);
4994 for (SwitchInst::CaseIt Case : SI->cases()) {
4995 APInt NarrowConst = Case.getCaseValue()->getValue();
4996 APInt WideConst = (ExtType == Instruction::ZExt) ?
4997 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4998 Case.setValue(ConstantInt::get(Context, WideConst));
4999 }
5000
5001 return true;
5002}
5003
Quentin Colombetc32615d2014-10-31 17:52:53 +00005004namespace {
5005/// \brief Helper class to promote a scalar operation to a vector one.
5006/// This class is used to move downward extractelement transition.
5007/// E.g.,
5008/// a = vector_op <2 x i32>
5009/// b = extractelement <2 x i32> a, i32 0
5010/// c = scalar_op b
5011/// store c
5012///
5013/// =>
5014/// a = vector_op <2 x i32>
5015/// c = vector_op a (equivalent to scalar_op on the related lane)
5016/// * d = extractelement <2 x i32> c, i32 0
5017/// * store d
5018/// Assuming both extractelement and store can be combine, we get rid of the
5019/// transition.
5020class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005021 /// DataLayout associated with the current module.
5022 const DataLayout &DL;
5023
Quentin Colombetc32615d2014-10-31 17:52:53 +00005024 /// Used to perform some checks on the legality of vector operations.
5025 const TargetLowering &TLI;
5026
5027 /// Used to estimated the cost of the promoted chain.
5028 const TargetTransformInfo &TTI;
5029
5030 /// The transition being moved downwards.
5031 Instruction *Transition;
5032 /// The sequence of instructions to be promoted.
5033 SmallVector<Instruction *, 4> InstsToBePromoted;
5034 /// Cost of combining a store and an extract.
5035 unsigned StoreExtractCombineCost;
5036 /// Instruction that will be combined with the transition.
5037 Instruction *CombineInst;
5038
5039 /// \brief The instruction that represents the current end of the transition.
5040 /// Since we are faking the promotion until we reach the end of the chain
5041 /// of computation, we need a way to get the current end of the transition.
5042 Instruction *getEndOfTransition() const {
5043 if (InstsToBePromoted.empty())
5044 return Transition;
5045 return InstsToBePromoted.back();
5046 }
5047
5048 /// \brief Return the index of the original value in the transition.
5049 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5050 /// c, is at index 0.
5051 unsigned getTransitionOriginalValueIdx() const {
5052 assert(isa<ExtractElementInst>(Transition) &&
5053 "Other kind of transitions are not supported yet");
5054 return 0;
5055 }
5056
5057 /// \brief Return the index of the index in the transition.
5058 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5059 /// is at index 1.
5060 unsigned getTransitionIdx() const {
5061 assert(isa<ExtractElementInst>(Transition) &&
5062 "Other kind of transitions are not supported yet");
5063 return 1;
5064 }
5065
5066 /// \brief Get the type of the transition.
5067 /// This is the type of the original value.
5068 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5069 /// transition is <2 x i32>.
5070 Type *getTransitionType() const {
5071 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5072 }
5073
5074 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5075 /// I.e., we have the following sequence:
5076 /// Def = Transition <ty1> a to <ty2>
5077 /// b = ToBePromoted <ty2> Def, ...
5078 /// =>
5079 /// b = ToBePromoted <ty1> a, ...
5080 /// Def = Transition <ty1> ToBePromoted to <ty2>
5081 void promoteImpl(Instruction *ToBePromoted);
5082
5083 /// \brief Check whether or not it is profitable to promote all the
5084 /// instructions enqueued to be promoted.
5085 bool isProfitableToPromote() {
5086 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5087 unsigned Index = isa<ConstantInt>(ValIdx)
5088 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5089 : -1;
5090 Type *PromotedType = getTransitionType();
5091
5092 StoreInst *ST = cast<StoreInst>(CombineInst);
5093 unsigned AS = ST->getPointerAddressSpace();
5094 unsigned Align = ST->getAlignment();
5095 // Check if this store is supported.
5096 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005097 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5098 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005099 // If this is not supported, there is no way we can combine
5100 // the extract with the store.
5101 return false;
5102 }
5103
5104 // The scalar chain of computation has to pay for the transition
5105 // scalar to vector.
5106 // The vector chain has to account for the combining cost.
5107 uint64_t ScalarCost =
5108 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5109 uint64_t VectorCost = StoreExtractCombineCost;
5110 for (const auto &Inst : InstsToBePromoted) {
5111 // Compute the cost.
5112 // By construction, all instructions being promoted are arithmetic ones.
5113 // Moreover, one argument is a constant that can be viewed as a splat
5114 // constant.
5115 Value *Arg0 = Inst->getOperand(0);
5116 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5117 isa<ConstantFP>(Arg0);
5118 TargetTransformInfo::OperandValueKind Arg0OVK =
5119 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5120 : TargetTransformInfo::OK_AnyValue;
5121 TargetTransformInfo::OperandValueKind Arg1OVK =
5122 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5123 : TargetTransformInfo::OK_AnyValue;
5124 ScalarCost += TTI.getArithmeticInstrCost(
5125 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5126 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5127 Arg0OVK, Arg1OVK);
5128 }
5129 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5130 << ScalarCost << "\nVector: " << VectorCost << '\n');
5131 return ScalarCost > VectorCost;
5132 }
5133
5134 /// \brief Generate a constant vector with \p Val with the same
5135 /// number of elements as the transition.
5136 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005137 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005138 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5139 /// otherwise we generate a vector with as many undef as possible:
5140 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5141 /// used at the index of the extract.
5142 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5143 unsigned ExtractIdx = UINT_MAX;
5144 if (!UseSplat) {
5145 // If we cannot determine where the constant must be, we have to
5146 // use a splat constant.
5147 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5148 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5149 ExtractIdx = CstVal->getSExtValue();
5150 else
5151 UseSplat = true;
5152 }
5153
5154 unsigned End = getTransitionType()->getVectorNumElements();
5155 if (UseSplat)
5156 return ConstantVector::getSplat(End, Val);
5157
5158 SmallVector<Constant *, 4> ConstVec;
5159 UndefValue *UndefVal = UndefValue::get(Val->getType());
5160 for (unsigned Idx = 0; Idx != End; ++Idx) {
5161 if (Idx == ExtractIdx)
5162 ConstVec.push_back(Val);
5163 else
5164 ConstVec.push_back(UndefVal);
5165 }
5166 return ConstantVector::get(ConstVec);
5167 }
5168
5169 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5170 /// in \p Use can trigger undefined behavior.
5171 static bool canCauseUndefinedBehavior(const Instruction *Use,
5172 unsigned OperandIdx) {
5173 // This is not safe to introduce undef when the operand is on
5174 // the right hand side of a division-like instruction.
5175 if (OperandIdx != 1)
5176 return false;
5177 switch (Use->getOpcode()) {
5178 default:
5179 return false;
5180 case Instruction::SDiv:
5181 case Instruction::UDiv:
5182 case Instruction::SRem:
5183 case Instruction::URem:
5184 return true;
5185 case Instruction::FDiv:
5186 case Instruction::FRem:
5187 return !Use->hasNoNaNs();
5188 }
5189 llvm_unreachable(nullptr);
5190 }
5191
5192public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005193 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5194 const TargetTransformInfo &TTI, Instruction *Transition,
5195 unsigned CombineCost)
5196 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005197 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5198 assert(Transition && "Do not know how to promote null");
5199 }
5200
5201 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5202 bool canPromote(const Instruction *ToBePromoted) const {
5203 // We could support CastInst too.
5204 return isa<BinaryOperator>(ToBePromoted);
5205 }
5206
5207 /// \brief Check if it is profitable to promote \p ToBePromoted
5208 /// by moving downward the transition through.
5209 bool shouldPromote(const Instruction *ToBePromoted) const {
5210 // Promote only if all the operands can be statically expanded.
5211 // Indeed, we do not want to introduce any new kind of transitions.
5212 for (const Use &U : ToBePromoted->operands()) {
5213 const Value *Val = U.get();
5214 if (Val == getEndOfTransition()) {
5215 // If the use is a division and the transition is on the rhs,
5216 // we cannot promote the operation, otherwise we may create a
5217 // division by zero.
5218 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5219 return false;
5220 continue;
5221 }
5222 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5223 !isa<ConstantFP>(Val))
5224 return false;
5225 }
5226 // Check that the resulting operation is legal.
5227 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5228 if (!ISDOpcode)
5229 return false;
5230 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005231 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005232 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005233 }
5234
5235 /// \brief Check whether or not \p Use can be combined
5236 /// with the transition.
5237 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5238 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5239
5240 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5241 void enqueueForPromotion(Instruction *ToBePromoted) {
5242 InstsToBePromoted.push_back(ToBePromoted);
5243 }
5244
5245 /// \brief Set the instruction that will be combined with the transition.
5246 void recordCombineInstruction(Instruction *ToBeCombined) {
5247 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5248 CombineInst = ToBeCombined;
5249 }
5250
5251 /// \brief Promote all the instructions enqueued for promotion if it is
5252 /// is profitable.
5253 /// \return True if the promotion happened, false otherwise.
5254 bool promote() {
5255 // Check if there is something to promote.
5256 // Right now, if we do not have anything to combine with,
5257 // we assume the promotion is not profitable.
5258 if (InstsToBePromoted.empty() || !CombineInst)
5259 return false;
5260
5261 // Check cost.
5262 if (!StressStoreExtract && !isProfitableToPromote())
5263 return false;
5264
5265 // Promote.
5266 for (auto &ToBePromoted : InstsToBePromoted)
5267 promoteImpl(ToBePromoted);
5268 InstsToBePromoted.clear();
5269 return true;
5270 }
5271};
5272} // End of anonymous namespace.
5273
5274void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5275 // At this point, we know that all the operands of ToBePromoted but Def
5276 // can be statically promoted.
5277 // For Def, we need to use its parameter in ToBePromoted:
5278 // b = ToBePromoted ty1 a
5279 // Def = Transition ty1 b to ty2
5280 // Move the transition down.
5281 // 1. Replace all uses of the promoted operation by the transition.
5282 // = ... b => = ... Def.
5283 assert(ToBePromoted->getType() == Transition->getType() &&
5284 "The type of the result of the transition does not match "
5285 "the final type");
5286 ToBePromoted->replaceAllUsesWith(Transition);
5287 // 2. Update the type of the uses.
5288 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5289 Type *TransitionTy = getTransitionType();
5290 ToBePromoted->mutateType(TransitionTy);
5291 // 3. Update all the operands of the promoted operation with promoted
5292 // operands.
5293 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5294 for (Use &U : ToBePromoted->operands()) {
5295 Value *Val = U.get();
5296 Value *NewVal = nullptr;
5297 if (Val == Transition)
5298 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5299 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5300 isa<ConstantFP>(Val)) {
5301 // Use a splat constant if it is not safe to use undef.
5302 NewVal = getConstantVector(
5303 cast<Constant>(Val),
5304 isa<UndefValue>(Val) ||
5305 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5306 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005307 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5308 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005309 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5310 }
5311 Transition->removeFromParent();
5312 Transition->insertAfter(ToBePromoted);
5313 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5314}
5315
5316/// Some targets can do store(extractelement) with one instruction.
5317/// Try to push the extractelement towards the stores when the target
5318/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005319bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005320 unsigned CombineCost = UINT_MAX;
5321 if (DisableStoreExtract || !TLI ||
5322 (!StressStoreExtract &&
5323 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5324 Inst->getOperand(1), CombineCost)))
5325 return false;
5326
5327 // At this point we know that Inst is a vector to scalar transition.
5328 // Try to move it down the def-use chain, until:
5329 // - We can combine the transition with its single use
5330 // => we got rid of the transition.
5331 // - We escape the current basic block
5332 // => we would need to check that we are moving it at a cheaper place and
5333 // we do not do that for now.
5334 BasicBlock *Parent = Inst->getParent();
5335 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005336 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005337 // If the transition has more than one use, assume this is not going to be
5338 // beneficial.
5339 while (Inst->hasOneUse()) {
5340 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5341 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5342
5343 if (ToBePromoted->getParent() != Parent) {
5344 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5345 << ToBePromoted->getParent()->getName()
5346 << ") than the transition (" << Parent->getName() << ").\n");
5347 return false;
5348 }
5349
5350 if (VPH.canCombine(ToBePromoted)) {
5351 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5352 << "will be combined with: " << *ToBePromoted << '\n');
5353 VPH.recordCombineInstruction(ToBePromoted);
5354 bool Changed = VPH.promote();
5355 NumStoreExtractExposed += Changed;
5356 return Changed;
5357 }
5358
5359 DEBUG(dbgs() << "Try promoting.\n");
5360 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5361 return false;
5362
5363 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5364
5365 VPH.enqueueForPromotion(ToBePromoted);
5366 Inst = ToBePromoted;
5367 }
5368 return false;
5369}
5370
Sanjay Patelfc580a62015-09-21 23:03:16 +00005371bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005372 // Bail out if we inserted the instruction to prevent optimizations from
5373 // stepping on each other's toes.
5374 if (InsertedInsts.count(I))
5375 return false;
5376
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005377 if (PHINode *P = dyn_cast<PHINode>(I)) {
5378 // It is possible for very late stage optimizations (such as SimplifyCFG)
5379 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5380 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005381 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005382 P->replaceAllUsesWith(V);
5383 P->eraseFromParent();
5384 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005385 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005386 }
Chris Lattneree588de2011-01-15 07:29:01 +00005387 return false;
5388 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005389
Chris Lattneree588de2011-01-15 07:29:01 +00005390 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005391 // If the source of the cast is a constant, then this should have
5392 // already been constant folded. The only reason NOT to constant fold
5393 // it is if something (e.g. LSR) was careful to place the constant
5394 // evaluation in a block other than then one that uses it (e.g. to hoist
5395 // the address of globals out of a loop). If this is the case, we don't
5396 // want to forward-subst the cast.
5397 if (isa<Constant>(CI->getOperand(0)))
5398 return false;
5399
Mehdi Amini44ede332015-07-09 02:09:04 +00005400 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005401 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005402
Chris Lattneree588de2011-01-15 07:29:01 +00005403 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005404 /// Sink a zext or sext into its user blocks if the target type doesn't
5405 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005406 if (TLI &&
5407 TLI->getTypeAction(CI->getContext(),
5408 TLI->getValueType(*DL, CI->getType())) ==
5409 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005410 return SinkCast(CI);
5411 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005412 bool MadeChange = moveExtToFormExtLoad(I);
5413 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005414 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005415 }
Chris Lattneree588de2011-01-15 07:29:01 +00005416 return false;
5417 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005418
Chris Lattneree588de2011-01-15 07:29:01 +00005419 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005420 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005421 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005422
Chris Lattneree588de2011-01-15 07:29:01 +00005423 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00005424 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005425 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005426 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005427 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005428 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5429 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005430 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005431 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005432 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005433
Chris Lattneree588de2011-01-15 07:29:01 +00005434 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00005435 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005436 if (TLI) {
5437 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005438 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005439 SI->getOperand(0)->getType(), AS);
5440 }
Chris Lattneree588de2011-01-15 07:29:01 +00005441 return false;
5442 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005443
Yi Jiangd069f632014-04-21 19:34:27 +00005444 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5445
5446 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5447 BinOp->getOpcode() == Instruction::LShr)) {
5448 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5449 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005450 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005451
5452 return false;
5453 }
5454
Chris Lattneree588de2011-01-15 07:29:01 +00005455 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005456 if (GEPI->hasAllZeroIndices()) {
5457 /// The GEP operand must be a pointer, so must its result -> BitCast
5458 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5459 GEPI->getName(), GEPI);
5460 GEPI->replaceAllUsesWith(NC);
5461 GEPI->eraseFromParent();
5462 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005463 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005464 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005465 }
Chris Lattneree588de2011-01-15 07:29:01 +00005466 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005467 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005468
Chris Lattneree588de2011-01-15 07:29:01 +00005469 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005470 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005471
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005472 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005473 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005474
Tim Northoveraeb8e062014-02-19 10:02:43 +00005475 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005476 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005477
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005478 if (auto *Switch = dyn_cast<SwitchInst>(I))
5479 return optimizeSwitchInst(Switch);
5480
Quentin Colombetc32615d2014-10-31 17:52:53 +00005481 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005482 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005483
Chris Lattneree588de2011-01-15 07:29:01 +00005484 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005485}
5486
James Molloyf01488e2016-01-15 09:20:19 +00005487/// Given an OR instruction, check to see if this is a bitreverse
5488/// idiom. If so, insert the new intrinsic and return true.
5489static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5490 const TargetLowering &TLI) {
5491 if (!I.getType()->isIntegerTy() ||
5492 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5493 TLI.getValueType(DL, I.getType(), true)))
5494 return false;
5495
5496 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005497 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005498 return false;
5499 Instruction *LastInst = Insts.back();
5500 I.replaceAllUsesWith(LastInst);
5501 RecursivelyDeleteTriviallyDeadInstructions(&I);
5502 return true;
5503}
5504
Chris Lattnerf2836d12007-03-31 04:06:36 +00005505// In this pass we look for GEP and cast instructions that are used
5506// across basic blocks and rewrite them to improve basic-block-at-a-time
5507// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005508bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005509 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005510 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005511
Chris Lattner7a277142011-01-15 07:14:54 +00005512 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005513 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005514 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005515 if (ModifiedDT)
5516 return true;
5517 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005518
James Molloyf01488e2016-01-15 09:20:19 +00005519 bool MadeBitReverse = true;
5520 while (TLI && MadeBitReverse) {
5521 MadeBitReverse = false;
5522 for (auto &I : reverse(BB)) {
5523 if (makeBitReverse(I, *DL, *TLI)) {
5524 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005525 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005526 break;
5527 }
5528 }
5529 }
James Molloy3ef84c42016-01-15 10:36:01 +00005530 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005531
Chris Lattnerf2836d12007-03-31 04:06:36 +00005532 return MadeChange;
5533}
Devang Patel53771ba2011-08-18 00:50:51 +00005534
5535// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005536// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005537// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005538bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005539 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005540 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005541 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005542 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005543 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005544 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005545 // Leave dbg.values that refer to an alloca alone. These
5546 // instrinsics describe the address of a variable (= the alloca)
5547 // being taken. They should not be moved next to the alloca
5548 // (and to the beginning of the scope), but rather stay close to
5549 // where said address is used.
5550 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005551 PrevNonDbgInst = Insn;
5552 continue;
5553 }
5554
5555 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5556 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005557 // If VI is a phi in a block with an EHPad terminator, we can't insert
5558 // after it.
5559 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5560 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005561 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5562 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005563 if (isa<PHINode>(VI))
5564 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5565 else
5566 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005567 MadeChange = true;
5568 ++NumDbgValueMoved;
5569 }
5570 }
5571 }
5572 return MadeChange;
5573}
Tim Northovercea0abb2014-03-29 08:22:29 +00005574
5575// If there is a sequence that branches based on comparing a single bit
5576// against zero that can be combined into a single instruction, and the
5577// target supports folding these into a single instruction, sink the
5578// mask and compare into the branch uses. Do this before OptimizeBlock ->
5579// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5580// searched for.
5581bool CodeGenPrepare::sinkAndCmp(Function &F) {
5582 if (!EnableAndCmpSinking)
5583 return false;
5584 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5585 return false;
5586 bool MadeChange = false;
Sanjay Patel892f1672016-04-11 20:13:44 +00005587 for (BasicBlock &BB : F) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005588 // Does this BB end with the following?
5589 // %andVal = and %val, #single-bit-set
5590 // %icmpVal = icmp %andResult, 0
5591 // br i1 %cmpVal label %dest1, label %dest2"
Sanjay Patel892f1672016-04-11 20:13:44 +00005592 BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
Tim Northovercea0abb2014-03-29 08:22:29 +00005593 if (!Brcc || !Brcc->isConditional())
5594 continue;
5595 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005596 if (!Cmp || Cmp->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005597 continue;
5598 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5599 if (!Zero || !Zero->isZero())
5600 continue;
5601 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005602 if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005603 continue;
5604 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5605 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5606 continue;
Sanjay Patel892f1672016-04-11 20:13:44 +00005607 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
Tim Northovercea0abb2014-03-29 08:22:29 +00005608
5609 // Push the "and; icmp" for any users that are conditional branches.
5610 // Since there can only be one branch use per BB, we don't need to keep
5611 // track of which BBs we insert into.
Sanjay Patel892f1672016-04-11 20:13:44 +00005612 for (Use &TheUse : Cmp->uses()) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005613 // Find brcc use.
Sanjay Patel892f1672016-04-11 20:13:44 +00005614 BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
Tim Northovercea0abb2014-03-29 08:22:29 +00005615 if (!BrccUser || !BrccUser->isConditional())
5616 continue;
5617 BasicBlock *UserBB = BrccUser->getParent();
Sanjay Patel892f1672016-04-11 20:13:44 +00005618 if (UserBB == &BB) continue;
Tim Northovercea0abb2014-03-29 08:22:29 +00005619 DEBUG(dbgs() << "found Brcc use\n");
5620
5621 // Sink the "and; icmp" to use.
5622 MadeChange = true;
5623 BinaryOperator *NewAnd =
5624 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5625 BrccUser);
5626 CmpInst *NewCmp =
5627 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5628 "", BrccUser);
5629 TheUse = NewCmp;
5630 ++NumAndCmpsMoved;
5631 DEBUG(BrccUser->getParent()->dump());
5632 }
5633 }
5634 return MadeChange;
5635}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005636
5637/// \brief Scale down both weights to fit into uint32_t.
5638static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5639 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5640 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5641 NewTrue = NewTrue / Scale;
5642 NewFalse = NewFalse / Scale;
5643}
5644
5645/// \brief Some targets prefer to split a conditional branch like:
5646/// \code
5647/// %0 = icmp ne i32 %a, 0
5648/// %1 = icmp ne i32 %b, 0
5649/// %or.cond = or i1 %0, %1
5650/// br i1 %or.cond, label %TrueBB, label %FalseBB
5651/// \endcode
5652/// into multiple branch instructions like:
5653/// \code
5654/// bb1:
5655/// %0 = icmp ne i32 %a, 0
5656/// br i1 %0, label %TrueBB, label %bb2
5657/// bb2:
5658/// %1 = icmp ne i32 %b, 0
5659/// br i1 %1, label %TrueBB, label %FalseBB
5660/// \endcode
5661/// This usually allows instruction selection to do even further optimizations
5662/// and combine the compare with the branch instruction. Currently this is
5663/// applied for targets which have "cheap" jump instructions.
5664///
5665/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5666///
5667bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005668 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005669 return false;
5670
5671 bool MadeChange = false;
5672 for (auto &BB : F) {
5673 // Does this BB end with the following?
5674 // %cond1 = icmp|fcmp|binary instruction ...
5675 // %cond2 = icmp|fcmp|binary instruction ...
5676 // %cond.or = or|and i1 %cond1, cond2
5677 // br i1 %cond.or label %dest1, label %dest2"
5678 BinaryOperator *LogicOp;
5679 BasicBlock *TBB, *FBB;
5680 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5681 continue;
5682
Sanjay Patel42574202015-09-02 19:23:23 +00005683 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5684 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5685 continue;
5686
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005687 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005688 Value *Cond1, *Cond2;
5689 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5690 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005691 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005692 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5693 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005694 Opc = Instruction::Or;
5695 else
5696 continue;
5697
5698 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5699 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5700 continue;
5701
5702 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5703
5704 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005705 auto TmpBB =
5706 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5707 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005708
5709 // Update original basic block by using the first condition directly by the
5710 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005711 Br1->setCondition(Cond1);
5712 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005713
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005714 // Depending on the conditon we have to either replace the true or the false
5715 // successor of the original branch instruction.
5716 if (Opc == Instruction::And)
5717 Br1->setSuccessor(0, TmpBB);
5718 else
5719 Br1->setSuccessor(1, TmpBB);
5720
5721 // Fill in the new basic block.
5722 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005723 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5724 I->removeFromParent();
5725 I->insertBefore(Br2);
5726 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005727
5728 // Update PHI nodes in both successors. The original BB needs to be
5729 // replaced in one succesor's PHI nodes, because the branch comes now from
5730 // the newly generated BB (NewBB). In the other successor we need to add one
5731 // incoming edge to the PHI nodes, because both branch instructions target
5732 // now the same successor. Depending on the original branch condition
5733 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00005734 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005735 // This doesn't change the successor order of the just created branch
5736 // instruction (or any other instruction).
5737 if (Opc == Instruction::Or)
5738 std::swap(TBB, FBB);
5739
5740 // Replace the old BB with the new BB.
5741 for (auto &I : *TBB) {
5742 PHINode *PN = dyn_cast<PHINode>(&I);
5743 if (!PN)
5744 break;
5745 int i;
5746 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5747 PN->setIncomingBlock(i, TmpBB);
5748 }
5749
5750 // Add another incoming edge form the new BB.
5751 for (auto &I : *FBB) {
5752 PHINode *PN = dyn_cast<PHINode>(&I);
5753 if (!PN)
5754 break;
5755 auto *Val = PN->getIncomingValueForBlock(&BB);
5756 PN->addIncoming(Val, TmpBB);
5757 }
5758
5759 // Update the branch weights (from SelectionDAGBuilder::
5760 // FindMergedConditions).
5761 if (Opc == Instruction::Or) {
5762 // Codegen X | Y as:
5763 // BB1:
5764 // jmp_if_X TBB
5765 // jmp TmpBB
5766 // TmpBB:
5767 // jmp_if_Y TBB
5768 // jmp FBB
5769 //
5770
5771 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5772 // The requirement is that
5773 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5774 // = TrueProb for orignal BB.
5775 // Assuming the orignal weights are A and B, one choice is to set BB1's
5776 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5777 // assumes that
5778 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5779 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5780 // TmpBB, but the math is more complicated.
5781 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005782 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005783 uint64_t NewTrueWeight = TrueWeight;
5784 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5785 scaleWeights(NewTrueWeight, NewFalseWeight);
5786 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5787 .createBranchWeights(TrueWeight, FalseWeight));
5788
5789 NewTrueWeight = TrueWeight;
5790 NewFalseWeight = 2 * FalseWeight;
5791 scaleWeights(NewTrueWeight, NewFalseWeight);
5792 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5793 .createBranchWeights(TrueWeight, FalseWeight));
5794 }
5795 } else {
5796 // Codegen X & Y as:
5797 // BB1:
5798 // jmp_if_X TmpBB
5799 // jmp FBB
5800 // TmpBB:
5801 // jmp_if_Y TBB
5802 // jmp FBB
5803 //
5804 // This requires creation of TmpBB after CurBB.
5805
5806 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5807 // The requirement is that
5808 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5809 // = FalseProb for orignal BB.
5810 // Assuming the orignal weights are A and B, one choice is to set BB1's
5811 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5812 // assumes that
5813 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5814 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005815 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005816 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5817 uint64_t NewFalseWeight = FalseWeight;
5818 scaleWeights(NewTrueWeight, NewFalseWeight);
5819 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5820 .createBranchWeights(TrueWeight, FalseWeight));
5821
5822 NewTrueWeight = 2 * TrueWeight;
5823 NewFalseWeight = FalseWeight;
5824 scaleWeights(NewTrueWeight, NewFalseWeight);
5825 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5826 .createBranchWeights(TrueWeight, FalseWeight));
5827 }
5828 }
5829
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005830 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005831 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005832 ModifiedDT = true;
5833
5834 MadeChange = true;
5835
5836 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5837 TmpBB->dump());
5838 }
5839 return MadeChange;
5840}