blob: 3029cb10a78edceb20e6022877a60347cd5fc3a1 [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
Wei Mia2f0b592016-12-22 19:44:45 +0000134static cl::opt<bool> ForceSplitStore(
135 "force-split-store", cl::Hidden, cl::init(false),
136 cl::desc("Force store splitting no matter what the target query says."));
137
Eric Christopherc1ea1492008-09-24 05:32:41 +0000138namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000139typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000140typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000141typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000142class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000143
Chris Lattner2dd09db2009-09-02 06:11:42 +0000144 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000145 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000146 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000147 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000148 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000149 const LoopInfo *LI;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000150 std::unique_ptr<BlockFrequencyInfo> BFI;
151 std::unique_ptr<BranchProbabilityInfo> BPI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000152
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000153 /// As we scan instructions optimizing them, this is the next instruction
154 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000155 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000156
Evan Cheng0663f232011-03-21 01:19:09 +0000157 /// Keeps track of non-local addresses that have been sunk into a block.
158 /// This allows us to avoid inserting duplicate code for blocks with
159 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000160 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000161
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000162 /// Keeps track of all instructions inserted for the current function.
163 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000164 /// Keeps track of the type of the related instruction before their
165 /// promotion for the current function.
166 InstrToOrigTy PromotedInsts;
167
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000168 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000169 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000170
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000171 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000172 bool OptSize;
173
Mehdi Amini4fe37982015-07-07 18:45:17 +0000174 /// DataLayout for the Function being processed.
175 const DataLayout *DL;
176
Chris Lattnerf2836d12007-03-31 04:06:36 +0000177 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000178 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000179 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000180 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000181 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
182 }
Craig Topper4584cd52014-03-07 09:26:03 +0000183 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000184
Mehdi Amini117296c2016-10-01 02:56:57 +0000185 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000186
Craig Topper4584cd52014-03-07 09:26:03 +0000187 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000188 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000189 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000190 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000191 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000192 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000193 }
194
Chris Lattnerf2836d12007-03-31 04:06:36 +0000195 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000196 bool eliminateFallThrough(Function &F);
197 bool eliminateMostlyEmptyBlocks(Function &F);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000198 BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000199 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
200 void eliminateMostlyEmptyBlock(BasicBlock *BB);
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000201 bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
202 bool isPreheader);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000203 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
204 bool optimizeInst(Instruction *I, bool& ModifiedDT);
205 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000206 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000207 bool optimizeInlineAsmInst(CallInst *CS);
208 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
209 bool moveExtToFormExtLoad(Instruction *&I);
210 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000211 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000212 bool optimizeSelectInst(SelectInst *SI);
213 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000214 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000215 bool optimizeExtractElementInst(Instruction *Inst);
216 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
217 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000218 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000219 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000220 Instruction *&Inst,
221 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000222 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000223 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000224 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000225 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000226}
Devang Patel09f162c2007-05-01 21:15:47 +0000227
Devang Patel8c78a0b2007-05-03 01:11:54 +0000228char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000229INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
230 "Optimize for code generation", false, false)
231INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
232INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
233 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000234
Bill Wendling7a639ea2013-06-19 21:07:11 +0000235FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
236 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000237}
238
Chris Lattnerf2836d12007-03-31 04:06:36 +0000239bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000240 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000241 return false;
242
Mehdi Amini4fe37982015-07-07 18:45:17 +0000243 DL = &F.getParent()->getDataLayout();
244
Chris Lattnerf2836d12007-03-31 04:06:36 +0000245 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000246 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000247 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000248 PromotedInsts.clear();
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000249 BFI.reset();
250 BPI.reset();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000251
Devang Patel8f606d72011-03-24 15:35:25 +0000252 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000253 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000254 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000255 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000256 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000257 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000258 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000259
Dehao Chen302b69c2016-10-18 20:42:47 +0000260 if (ProfileGuidedSectionPrefix) {
261 ProfileSummaryInfo *PSI =
262 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
263 if (PSI->isFunctionEntryHot(&F))
264 F.setSectionPrefix(".hot");
265 else if (PSI->isFunctionEntryCold(&F))
266 F.setSectionPrefix(".cold");
267 }
268
Preston Gurdcdf540d2012-09-04 18:22:17 +0000269 /// This optimization identifies DIV instructions that can be
270 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000271 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000272 const DenseMap<unsigned int, unsigned int> &BypassWidths =
273 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000274 BasicBlock* BB = &*F.begin();
275 while (BB != nullptr) {
276 // bypassSlowDivision may create new BBs, but we don't want to reapply the
277 // optimization to those blocks.
278 BasicBlock* Next = BB->getNextNode();
279 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
280 BB = Next;
281 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000282 }
283
284 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000285 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000286 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000287
Devang Patel53771ba2011-08-18 00:50:51 +0000288 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000289 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000290 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000291 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000292
Tim Northovercea0abb2014-03-29 08:22:29 +0000293 // If there is a mask, compare against zero, and branch that can be combined
294 // into a single target instruction, push the mask and compare into branch
295 // users. Do this before OptimizeBlock -> OptimizeInst ->
296 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000297 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000298 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000299 EverMadeChange |= splitBranchCondition(F);
300 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000301
Chris Lattnerc3748562007-04-02 01:35:34 +0000302 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000303 while (MadeChange) {
304 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000305 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000306 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000307 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000308 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000309
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000310 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000311 if (ModifiedDTOnIteration)
312 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000313 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000314 EverMadeChange |= MadeChange;
315 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000316
317 SunkAddrs.clear();
318
Cameron Zwarich338d3622011-03-11 21:52:04 +0000319 if (!DisableBranchOpts) {
320 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000321 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000322 for (BasicBlock &BB : F) {
323 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
324 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000325 if (!MadeChange) continue;
326
327 for (SmallVectorImpl<BasicBlock*>::iterator
328 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
329 if (pred_begin(*II) == pred_end(*II))
330 WorkList.insert(*II);
331 }
332
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000333 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000334 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000335 while (!WorkList.empty()) {
336 BasicBlock *BB = *WorkList.begin();
337 WorkList.erase(BB);
338 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
339
340 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000341
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000342 for (SmallVectorImpl<BasicBlock*>::iterator
343 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
344 if (pred_begin(*II) == pred_end(*II))
345 WorkList.insert(*II);
346 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000347
Nadav Rotem70409992012-08-14 05:19:07 +0000348 // Merge pairs of basic blocks with unconditional branches, connected by
349 // a single edge.
350 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000351 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000352
Cameron Zwarich338d3622011-03-11 21:52:04 +0000353 EverMadeChange |= MadeChange;
354 }
355
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000356 if (!DisableGCOpts) {
357 SmallVector<Instruction *, 2> Statepoints;
358 for (BasicBlock &BB : F)
359 for (Instruction &I : BB)
360 if (isStatepoint(I))
361 Statepoints.push_back(&I);
362 for (auto &I : Statepoints)
363 EverMadeChange |= simplifyOffsetableRelocate(*I);
364 }
365
Chris Lattnerf2836d12007-03-31 04:06:36 +0000366 return EverMadeChange;
367}
368
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000369/// Merge basic blocks which are connected by a single edge, where one of the
370/// basic blocks has a single successor pointing to the other basic block,
371/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000372bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000373 bool Changed = false;
374 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000375 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000376 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000377 // If the destination block has a single pred, then this is a trivial
378 // edge, just collapse it.
379 BasicBlock *SinglePred = BB->getSinglePredecessor();
380
Evan Cheng64a223a2012-09-28 23:58:57 +0000381 // Don't merge if BB's address is taken.
382 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000383
384 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
385 if (Term && !Term->isConditional()) {
386 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000387 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000388 // Remember if SinglePred was the entry block of the function.
389 // If so, we will need to move BB back to the entry position.
390 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000391 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000392
393 if (isEntry && BB != &BB->getParent()->getEntryBlock())
394 BB->moveBefore(&BB->getParent()->getEntryBlock());
395
396 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000397 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000398 }
399 }
400 return Changed;
401}
402
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000403/// Find a destination block from BB if BB is mergeable empty block.
404BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
405 // If this block doesn't end with an uncond branch, ignore it.
406 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
407 if (!BI || !BI->isUnconditional())
408 return nullptr;
409
410 // If the instruction before the branch (skipping debug info) isn't a phi
411 // node, then other stuff is happening here.
412 BasicBlock::iterator BBI = BI->getIterator();
413 if (BBI != BB->begin()) {
414 --BBI;
415 while (isa<DbgInfoIntrinsic>(BBI)) {
416 if (BBI == BB->begin())
417 break;
418 --BBI;
419 }
420 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
421 return nullptr;
422 }
423
424 // Do not break infinite loops.
425 BasicBlock *DestBB = BI->getSuccessor(0);
426 if (DestBB == BB)
427 return nullptr;
428
429 if (!canMergeBlocks(BB, DestBB))
430 DestBB = nullptr;
431
432 return DestBB;
433}
434
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000435/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
436/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
437/// edges in ways that are non-optimal for isel. Start by eliminating these
438/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000439bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000440 SmallPtrSet<BasicBlock *, 16> Preheaders;
441 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
442 while (!LoopList.empty()) {
443 Loop *L = LoopList.pop_back_val();
444 LoopList.insert(LoopList.end(), L->begin(), L->end());
445 if (BasicBlock *Preheader = L->getLoopPreheader())
446 Preheaders.insert(Preheader);
447 }
448
Chris Lattnerc3748562007-04-02 01:35:34 +0000449 bool MadeChange = false;
450 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000451 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000452 BasicBlock *BB = &*I++;
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000453 BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
454 if (!DestBB ||
455 !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
Chris Lattnerc3748562007-04-02 01:35:34 +0000456 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000457
Sanjay Patelfc580a62015-09-21 23:03:16 +0000458 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000459 MadeChange = true;
460 }
461 return MadeChange;
462}
463
Jun Bum Lim90b6b502016-12-16 20:38:39 +0000464bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
465 BasicBlock *DestBB,
466 bool isPreheader) {
467 // Do not delete loop preheaders if doing so would create a critical edge.
468 // Loop preheaders can be good locations to spill registers. If the
469 // preheader is deleted and we create a critical edge, registers may be
470 // spilled in the loop body instead.
471 if (!DisablePreheaderProtect && isPreheader &&
472 !(BB->getSinglePredecessor() &&
473 BB->getSinglePredecessor()->getSingleSuccessor()))
474 return false;
475
476 // Try to skip merging if the unique predecessor of BB is terminated by a
477 // switch or indirect branch instruction, and BB is used as an incoming block
478 // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
479 // add COPY instructions in the predecessor of BB instead of BB (if it is not
480 // merged). Note that the critical edge created by merging such blocks wont be
481 // split in MachineSink because the jump table is not analyzable. By keeping
482 // such empty block (BB), ISel will place COPY instructions in BB, not in the
483 // predecessor of BB.
484 BasicBlock *Pred = BB->getUniquePredecessor();
485 if (!Pred ||
486 !(isa<SwitchInst>(Pred->getTerminator()) ||
487 isa<IndirectBrInst>(Pred->getTerminator())))
488 return true;
489
490 if (BB->getTerminator() != BB->getFirstNonPHI())
491 return true;
492
493 // We use a simple cost heuristic which determine skipping merging is
494 // profitable if the cost of skipping merging is less than the cost of
495 // merging : Cost(skipping merging) < Cost(merging BB), where the
496 // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
497 // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
498 // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
499 // Freq(Pred) / Freq(BB) > 2.
500 // Note that if there are multiple empty blocks sharing the same incoming
501 // value for the PHIs in the DestBB, we consider them together. In such
502 // case, Cost(merging BB) will be the sum of their frequencies.
503
504 if (!isa<PHINode>(DestBB->begin()))
505 return true;
506
507 SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
508
509 // Find all other incoming blocks from which incoming values of all PHIs in
510 // DestBB are the same as the ones from BB.
511 for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
512 ++PI) {
513 BasicBlock *DestBBPred = *PI;
514 if (DestBBPred == BB)
515 continue;
516
517 bool HasAllSameValue = true;
518 BasicBlock::const_iterator DestBBI = DestBB->begin();
519 while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
520 if (DestPN->getIncomingValueForBlock(BB) !=
521 DestPN->getIncomingValueForBlock(DestBBPred)) {
522 HasAllSameValue = false;
523 break;
524 }
525 }
526 if (HasAllSameValue)
527 SameIncomingValueBBs.insert(DestBBPred);
528 }
529
530 // See if all BB's incoming values are same as the value from Pred. In this
531 // case, no reason to skip merging because COPYs are expected to be place in
532 // Pred already.
533 if (SameIncomingValueBBs.count(Pred))
534 return true;
535
536 if (!BFI) {
537 Function &F = *BB->getParent();
538 LoopInfo LI{DominatorTree(F)};
539 BPI.reset(new BranchProbabilityInfo(F, LI));
540 BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
541 }
542
543 BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
544 BlockFrequency BBFreq = BFI->getBlockFreq(BB);
545
546 for (auto SameValueBB : SameIncomingValueBBs)
547 if (SameValueBB->getUniquePredecessor() == Pred &&
548 DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
549 BBFreq += BFI->getBlockFreq(SameValueBB);
550
551 return PredFreq.getFrequency() <=
552 BBFreq.getFrequency() * FreqRatioToSkipMerge;
553}
554
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000555/// Return true if we can merge BB into DestBB if there is a single
556/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000557/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000558bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000559 const BasicBlock *DestBB) const {
560 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
561 // the successor. If there are more complex condition (e.g. preheaders),
562 // don't mess around with them.
563 BasicBlock::const_iterator BBI = BB->begin();
564 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000565 for (const User *U : PN->users()) {
566 const Instruction *UI = cast<Instruction>(U);
567 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000568 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000569 // If User is inside DestBB block and it is a PHINode then check
570 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000571 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000572 if (UI->getParent() == DestBB) {
573 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000574 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
575 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
576 if (Insn && Insn->getParent() == BB &&
577 Insn->getParent() != UPN->getIncomingBlock(I))
578 return false;
579 }
580 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000581 }
582 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000583
Chris Lattnerc3748562007-04-02 01:35:34 +0000584 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
585 // and DestBB may have conflicting incoming values for the block. If so, we
586 // can't merge the block.
587 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
588 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000589
Chris Lattnerc3748562007-04-02 01:35:34 +0000590 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000591 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000592 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
593 // It is faster to get preds from a PHI than with pred_iterator.
594 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
595 BBPreds.insert(BBPN->getIncomingBlock(i));
596 } else {
597 BBPreds.insert(pred_begin(BB), pred_end(BB));
598 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000599
Chris Lattnerc3748562007-04-02 01:35:34 +0000600 // Walk the preds of DestBB.
601 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
602 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
603 if (BBPreds.count(Pred)) { // Common predecessor?
604 BBI = DestBB->begin();
605 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
606 const Value *V1 = PN->getIncomingValueForBlock(Pred);
607 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000608
Chris Lattnerc3748562007-04-02 01:35:34 +0000609 // If V2 is a phi node in BB, look up what the mapped value will be.
610 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
611 if (V2PN->getParent() == BB)
612 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000613
Chris Lattnerc3748562007-04-02 01:35:34 +0000614 // If there is a conflict, bail out.
615 if (V1 != V2) return false;
616 }
617 }
618 }
619
620 return true;
621}
622
623
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000624/// Eliminate a basic block that has only phi's and an unconditional branch in
625/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000626void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000627 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
628 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000629
David Greene74e2d492010-01-05 01:27:11 +0000630 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000631
Chris Lattnerc3748562007-04-02 01:35:34 +0000632 // If the destination block has a single pred, then this is a trivial edge,
633 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000634 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000635 if (SinglePred != DestBB) {
636 // Remember if SinglePred was the entry block of the function. If so, we
637 // will need to move BB back to the entry position.
638 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000639 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000640
Chris Lattner8a172da2008-11-28 19:54:49 +0000641 if (isEntry && BB != &BB->getParent()->getEntryBlock())
642 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000643
David Greene74e2d492010-01-05 01:27:11 +0000644 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000645 return;
646 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000647 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000648
Chris Lattnerc3748562007-04-02 01:35:34 +0000649 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
650 // to handle the new incoming edges it is about to have.
651 PHINode *PN;
652 for (BasicBlock::iterator BBI = DestBB->begin();
653 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
654 // Remove the incoming value for BB, and remember it.
655 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000656
Chris Lattnerc3748562007-04-02 01:35:34 +0000657 // Two options: either the InVal is a phi node defined in BB or it is some
658 // value that dominates BB.
659 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
660 if (InValPhi && InValPhi->getParent() == BB) {
661 // Add all of the input values of the input PHI as inputs of this phi.
662 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
663 PN->addIncoming(InValPhi->getIncomingValue(i),
664 InValPhi->getIncomingBlock(i));
665 } else {
666 // Otherwise, add one instance of the dominating value for each edge that
667 // we will be adding.
668 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
669 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
670 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
671 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000672 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
673 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000674 }
675 }
676 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000677
Chris Lattnerc3748562007-04-02 01:35:34 +0000678 // The PHIs are now updated, change everything that refers to BB to use
679 // DestBB and remove BB.
680 BB->replaceAllUsesWith(DestBB);
681 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000682 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000683
David Greene74e2d492010-01-05 01:27:11 +0000684 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000685}
686
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000687// Computes a map of base pointer relocation instructions to corresponding
688// derived pointer relocation instructions given a vector of all relocate calls
689static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000690 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
691 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
692 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000693 // Collect information in two maps: one primarily for locating the base object
694 // while filling the second map; the second map is the final structure holding
695 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000696 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
697 for (auto *ThisRelocate : AllRelocateCalls) {
698 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
699 ThisRelocate->getDerivedPtrIndex());
700 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000701 }
702 for (auto &Item : RelocateIdxMap) {
703 std::pair<unsigned, unsigned> Key = Item.first;
704 if (Key.first == Key.second)
705 // Base relocation: nothing to insert
706 continue;
707
Manuel Jacob83eefa62016-01-05 04:03:00 +0000708 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000709 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000710
711 // We're iterating over RelocateIdxMap so we cannot modify it.
712 auto MaybeBase = RelocateIdxMap.find(BaseKey);
713 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000714 // TODO: We might want to insert a new base object relocate and gep off
715 // that, if there are enough derived object relocates.
716 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000717
718 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000719 }
720}
721
722// Accepts a GEP and extracts the operands into a vector provided they're all
723// small integer constants
724static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
725 SmallVectorImpl<Value *> &OffsetV) {
726 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
727 // Only accept small constant integer operands
728 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
729 if (!Op || Op->getZExtValue() > 20)
730 return false;
731 }
732
733 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
734 OffsetV.push_back(GEP->getOperand(i));
735 return true;
736}
737
738// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
739// replace, computes a replacement, and affects it.
740static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000741simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
742 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000743 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000744 for (GCRelocateInst *ToReplace : Targets) {
745 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000746 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000747 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000748 // A duplicate relocate call. TODO: coalesce duplicates.
749 continue;
750 }
751
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000752 if (RelocatedBase->getParent() != ToReplace->getParent()) {
753 // Base and derived relocates are in different basic blocks.
754 // In this case transform is only valid when base dominates derived
755 // relocate. However it would be too expensive to check dominance
756 // for each such relocate, so we skip the whole transformation.
757 continue;
758 }
759
Manuel Jacob83eefa62016-01-05 04:03:00 +0000760 Value *Base = ToReplace->getBasePtr();
761 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000762 if (!Derived || Derived->getPointerOperand() != Base)
763 continue;
764
765 SmallVector<Value *, 2> OffsetV;
766 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
767 continue;
768
769 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000770 assert(RelocatedBase->getNextNode() &&
771 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000772
773 // Insert after RelocatedBase
774 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000775 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000776
777 // If gc_relocate does not match the actual type, cast it to the right type.
778 // In theory, there must be a bitcast after gc_relocate if the type does not
779 // match, and we should reuse it to get the derived pointer. But it could be
780 // cases like this:
781 // bb1:
782 // ...
783 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
784 // br label %merge
785 //
786 // bb2:
787 // ...
788 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
789 // br label %merge
790 //
791 // merge:
792 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
793 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
794 //
795 // In this case, we can not find the bitcast any more. So we insert a new bitcast
796 // no matter there is already one or not. In this way, we can handle all cases, and
797 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000798 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000799 if (RelocatedBase->getType() != Base->getType()) {
800 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000801 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000802 }
David Blaikie68d535c2015-03-24 22:38:16 +0000803 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000804 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000805 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000806 // If the newly generated derived pointer's type does not match the original derived
807 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000808 Value *ActualReplacement = Replacement;
809 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000810 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000811 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000812 }
813 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000814 ToReplace->eraseFromParent();
815
816 MadeChange = true;
817 }
818 return MadeChange;
819}
820
821// Turns this:
822//
823// %base = ...
824// %ptr = gep %base + 15
825// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
826// %base' = relocate(%tok, i32 4, i32 4)
827// %ptr' = relocate(%tok, i32 4, i32 5)
828// %val = load %ptr'
829//
830// into this:
831//
832// %base = ...
833// %ptr = gep %base + 15
834// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
835// %base' = gc.relocate(%tok, i32 4, i32 4)
836// %ptr' = gep %base' + 15
837// %val = load %ptr'
838bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
839 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000840 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000841
842 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000843 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000844 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000845 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000846
847 // We need atleast one base pointer relocation + one derived pointer
848 // relocation to mangle
849 if (AllRelocateCalls.size() < 2)
850 return false;
851
852 // RelocateInstMap is a mapping from the base relocate instruction to the
853 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000854 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000855 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
856 if (RelocateInstMap.empty())
857 return false;
858
859 for (auto &Item : RelocateInstMap)
860 // Item.first is the RelocatedBase to offset against
861 // Item.second is the vector of Targets to replace
862 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
863 return MadeChange;
864}
865
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000866/// SinkCast - Sink the specified cast instruction into its user blocks
867static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000868 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000869
Chris Lattnerf2836d12007-03-31 04:06:36 +0000870 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000871 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000872
Chris Lattnerf2836d12007-03-31 04:06:36 +0000873 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000874 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000875 UI != E; ) {
876 Use &TheUse = UI.getUse();
877 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000878
Chris Lattnerf2836d12007-03-31 04:06:36 +0000879 // Figure out which BB this cast is used in. For PHI's this is the
880 // appropriate predecessor block.
881 BasicBlock *UserBB = User->getParent();
882 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000883 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000884 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000885
Chris Lattnerf2836d12007-03-31 04:06:36 +0000886 // Preincrement use iterator so we don't invalidate it.
887 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000888
David Majnemer0c80e2e2016-04-27 19:36:38 +0000889 // The first insertion point of a block containing an EH pad is after the
890 // pad. If the pad is the user, we cannot sink the cast past the pad.
891 if (User->isEHPad())
892 continue;
893
Andrew Kaylord0430e82015-11-23 19:16:15 +0000894 // If the block selected to receive the cast is an EH pad that does not
895 // allow non-PHI instructions before the terminator, we can't sink the
896 // cast.
897 if (UserBB->getTerminator()->isEHPad())
898 continue;
899
Chris Lattnerf2836d12007-03-31 04:06:36 +0000900 // If this user is in the same block as the cast, don't change the cast.
901 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000902
Chris Lattnerf2836d12007-03-31 04:06:36 +0000903 // If we have already inserted a cast into this block, use it.
904 CastInst *&InsertedCast = InsertedCasts[UserBB];
905
906 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000907 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000908 assert(InsertPt != UserBB->end());
909 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
910 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000911 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000912
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000913 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000914 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000915 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000916 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000917 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000918
Chris Lattnerf2836d12007-03-31 04:06:36 +0000919 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000920 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000921 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000922 MadeChange = true;
923 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000924
Chris Lattnerf2836d12007-03-31 04:06:36 +0000925 return MadeChange;
926}
927
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000928/// If the specified cast instruction is a noop copy (e.g. it's casting from
929/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
930/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000931///
932/// Return true if any changes are made.
933///
Mehdi Amini44ede332015-07-09 02:09:04 +0000934static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
935 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +0000936 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
937 // than sinking only nop casts, but is helpful on some platforms.
938 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
939 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
940 ASC->getDestAddressSpace()))
941 return false;
942 }
943
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000944 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000945 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
946 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000947
948 // This is an fp<->int conversion?
949 if (SrcVT.isInteger() != DstVT.isInteger())
950 return false;
951
952 // If this is an extension, it will be a zero or sign extension, which
953 // isn't a noop.
954 if (SrcVT.bitsLT(DstVT)) return false;
955
956 // If these values will be promoted, find out what they will be promoted
957 // to. This helps us consider truncates on PPC as noop copies when they
958 // are.
959 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
960 TargetLowering::TypePromoteInteger)
961 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
962 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
963 TargetLowering::TypePromoteInteger)
964 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
965
966 // If, after promotion, these are the same types, this is a noop copy.
967 if (SrcVT != DstVT)
968 return false;
969
970 return SinkCast(CI);
971}
972
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000973/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
974/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000975///
976/// Return true if any changes were made.
977static bool CombineUAddWithOverflow(CmpInst *CI) {
978 Value *A, *B;
979 Instruction *AddI;
980 if (!match(CI,
981 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
982 return false;
983
984 Type *Ty = AddI->getType();
985 if (!isa<IntegerType>(Ty))
986 return false;
987
988 // We don't want to move around uses of condition values this late, so we we
989 // check if it is legal to create the call to the intrinsic in the basic
990 // block containing the icmp:
991
992 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
993 return false;
994
995#ifndef NDEBUG
996 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
997 // for now:
998 if (AddI->hasOneUse())
999 assert(*AddI->user_begin() == CI && "expected!");
1000#endif
1001
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001002 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001003 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
1004
1005 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
1006
1007 auto *UAddWithOverflow =
1008 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
1009 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
1010 auto *Overflow =
1011 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
1012
1013 CI->replaceAllUsesWith(Overflow);
1014 AddI->replaceAllUsesWith(UAdd);
1015 CI->eraseFromParent();
1016 AddI->eraseFromParent();
1017 return true;
1018}
1019
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001020/// Sink the given CmpInst into user blocks to reduce the number of virtual
1021/// registers that must be created and coalesced. This is a clear win except on
1022/// targets with multiple condition code registers (PowerPC), where it might
1023/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001024///
1025/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001026static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001027 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001028
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001029 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +00001030 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +00001031 return false;
1032
1033 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001034 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001035
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001036 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001037 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001038 UI != E; ) {
1039 Use &TheUse = UI.getUse();
1040 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +00001041
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001042 // Preincrement use iterator so we don't invalidate it.
1043 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001044
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001045 // Don't bother for PHI nodes.
1046 if (isa<PHINode>(User))
1047 continue;
1048
1049 // Figure out which BB this cmp is used in.
1050 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +00001051
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001052 // If this user is in the same block as the cmp, don't change the cmp.
1053 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +00001054
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001055 // If we have already inserted a cmp into this block, use it.
1056 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
1057
1058 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00001059 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001060 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +00001061 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001062 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1063 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +00001064 // Propagate the debug info.
1065 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001066 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001067
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001068 // Replace a use of the cmp with a use of the new cmp.
1069 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001070 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +00001071 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001072 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001073
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001074 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001075 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001076 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +00001077 MadeChange = true;
1078 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00001079
Dale Johannesenedfec0b2007-06-12 16:50:17 +00001080 return MadeChange;
1081}
1082
Peter Zotovf87e5502016-04-03 17:11:53 +00001083static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +00001084 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +00001085 return true;
1086
1087 if (CombineUAddWithOverflow(CI))
1088 return true;
1089
1090 return false;
1091}
1092
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001093/// Check if the candidates could be combined with a shift instruction, which
1094/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +00001095/// 1. Truncate instruction
1096/// 2. And instruction and the imm is a mask of the low bits:
1097/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +00001098static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +00001099 if (!isa<TruncInst>(User)) {
1100 if (User->getOpcode() != Instruction::And ||
1101 !isa<ConstantInt>(User->getOperand(1)))
1102 return false;
1103
Quentin Colombetd4f44692014-04-22 01:20:34 +00001104 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +00001105
Quentin Colombetd4f44692014-04-22 01:20:34 +00001106 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +00001107 return false;
1108 }
1109 return true;
1110}
1111
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001112/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001113static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001114SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1115 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001116 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001117 BasicBlock *UserBB = User->getParent();
1118 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1119 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1120 bool MadeChange = false;
1121
1122 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1123 TruncE = TruncI->user_end();
1124 TruncUI != TruncE;) {
1125
1126 Use &TruncTheUse = TruncUI.getUse();
1127 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1128 // Preincrement use iterator so we don't invalidate it.
1129
1130 ++TruncUI;
1131
1132 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1133 if (!ISDOpcode)
1134 continue;
1135
Tim Northovere2239ff2014-07-29 10:20:22 +00001136 // If the use is actually a legal node, there will not be an
1137 // implicit truncate.
1138 // FIXME: always querying the result type is just an
1139 // approximation; some nodes' legality is determined by the
1140 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001141 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001142 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001143 continue;
1144
1145 // Don't bother for PHI nodes.
1146 if (isa<PHINode>(TruncUser))
1147 continue;
1148
1149 BasicBlock *TruncUserBB = TruncUser->getParent();
1150
1151 if (UserBB == TruncUserBB)
1152 continue;
1153
1154 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1155 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1156
1157 if (!InsertedShift && !InsertedTrunc) {
1158 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001159 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001160 // Sink the shift
1161 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001162 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1163 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001164 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001165 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1166 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001167
1168 // Sink the trunc
1169 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1170 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001171 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001172
1173 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001174 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001175
1176 MadeChange = true;
1177
1178 TruncTheUse = InsertedTrunc;
1179 }
1180 }
1181 return MadeChange;
1182}
1183
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001184/// Sink the shift *right* instruction into user blocks if the uses could
1185/// potentially be combined with this shift instruction and generate BitExtract
1186/// instruction. It will only be applied if the architecture supports BitExtract
1187/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001188/// BB1:
1189/// %x.extract.shift = lshr i64 %arg1, 32
1190/// BB2:
1191/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1192/// ==>
1193///
1194/// BB2:
1195/// %x.extract.shift.1 = lshr i64 %arg1, 32
1196/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1197///
1198/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1199/// instruction.
1200/// Return true if any changes are made.
1201static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001202 const TargetLowering &TLI,
1203 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001204 BasicBlock *DefBB = ShiftI->getParent();
1205
1206 /// Only insert instructions in each block once.
1207 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1208
Mehdi Amini44ede332015-07-09 02:09:04 +00001209 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001210
1211 bool MadeChange = false;
1212 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1213 UI != E;) {
1214 Use &TheUse = UI.getUse();
1215 Instruction *User = cast<Instruction>(*UI);
1216 // Preincrement use iterator so we don't invalidate it.
1217 ++UI;
1218
1219 // Don't bother for PHI nodes.
1220 if (isa<PHINode>(User))
1221 continue;
1222
1223 if (!isExtractBitsCandidateUse(User))
1224 continue;
1225
1226 BasicBlock *UserBB = User->getParent();
1227
1228 if (UserBB == DefBB) {
1229 // If the shift and truncate instruction are in the same BB. The use of
1230 // the truncate(TruncUse) may still introduce another truncate if not
1231 // legal. In this case, we would like to sink both shift and truncate
1232 // instruction to the BB of TruncUse.
1233 // for example:
1234 // BB1:
1235 // i64 shift.result = lshr i64 opnd, imm
1236 // trunc.result = trunc shift.result to i16
1237 //
1238 // BB2:
1239 // ----> We will have an implicit truncate here if the architecture does
1240 // not have i16 compare.
1241 // cmp i16 trunc.result, opnd2
1242 //
1243 if (isa<TruncInst>(User) && shiftIsLegal
1244 // If the type of the truncate is legal, no trucate will be
1245 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001246 &&
1247 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001248 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001249 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001250
1251 continue;
1252 }
1253 // If we have already inserted a shift into this block, use it.
1254 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1255
1256 if (!InsertedShift) {
1257 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001258 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001259
1260 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001261 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1262 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001263 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001264 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1265 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001266
1267 MadeChange = true;
1268 }
1269
1270 // Replace a use of the shift with a use of the new shift.
1271 TheUse = InsertedShift;
1272 }
1273
1274 // If we removed all uses, nuke the shift.
1275 if (ShiftI->use_empty())
1276 ShiftI->eraseFromParent();
1277
1278 return MadeChange;
1279}
1280
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001281// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001282// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1283// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001284// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001285// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001286//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001287// %1 = bitcast i8* %addr to i32*
1288// %2 = extractelement <16 x i1> %mask, i32 0
1289// %3 = icmp eq i1 %2, true
1290// br i1 %3, label %cond.load, label %else
1291//
1292//cond.load: ; preds = %0
1293// %4 = getelementptr i32* %1, i32 0
1294// %5 = load i32* %4
1295// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1296// br label %else
1297//
1298//else: ; preds = %0, %cond.load
1299// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1300// %7 = extractelement <16 x i1> %mask, i32 1
1301// %8 = icmp eq i1 %7, true
1302// br i1 %8, label %cond.load1, label %else2
1303//
1304//cond.load1: ; preds = %else
1305// %9 = getelementptr i32* %1, i32 1
1306// %10 = load i32* %9
1307// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1308// br label %else2
1309//
1310//else2: ; preds = %else, %cond.load1
1311// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1312// %12 = extractelement <16 x i1> %mask, i32 2
1313// %13 = icmp eq i1 %12, true
1314// br i1 %13, label %cond.load4, label %else5
1315//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001316static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001317 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001318 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001319 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001320 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001321
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001322 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1323 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001324 assert(VecType && "Unexpected return type of masked load intrinsic");
1325
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001326 Type *EltTy = CI->getType()->getVectorElementType();
1327
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001328 IRBuilder<> Builder(CI->getContext());
1329 Instruction *InsertPt = CI;
1330 BasicBlock *IfBlock = CI->getParent();
1331 BasicBlock *CondBlock = nullptr;
1332 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001333
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001334 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001335 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1336
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001337 // Short-cut if the mask is all-true.
1338 bool IsAllOnesMask = isa<Constant>(Mask) &&
1339 cast<Constant>(Mask)->isAllOnesValue();
1340
1341 if (IsAllOnesMask) {
1342 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1343 CI->replaceAllUsesWith(NewI);
1344 CI->eraseFromParent();
1345 return;
1346 }
1347
1348 // Adjust alignment for the scalar instruction.
1349 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001350 // Bitcast %addr fron i8* to EltTy*
1351 Type *NewPtrType =
1352 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1353 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001354 unsigned VectorWidth = VecType->getNumElements();
1355
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001356 Value *UndefVal = UndefValue::get(VecType);
1357
1358 // The result vector
1359 Value *VResult = UndefVal;
1360
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001361 if (isa<ConstantVector>(Mask)) {
1362 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1363 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1364 continue;
1365 Value *Gep =
1366 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1367 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1368 VResult = Builder.CreateInsertElement(VResult, Load,
1369 Builder.getInt32(Idx));
1370 }
1371 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1372 CI->replaceAllUsesWith(NewI);
1373 CI->eraseFromParent();
1374 return;
1375 }
1376
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001377 PHINode *Phi = nullptr;
1378 Value *PrevPhi = UndefVal;
1379
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001380 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1381
1382 // Fill the "else" block, created in the previous iteration
1383 //
1384 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1385 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1386 // %to_load = icmp eq i1 %mask_1, true
1387 // br i1 %to_load, label %cond.load, label %else
1388 //
1389 if (Idx > 0) {
1390 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1391 Phi->addIncoming(VResult, CondBlock);
1392 Phi->addIncoming(PrevPhi, PrevIfBlock);
1393 PrevPhi = Phi;
1394 VResult = Phi;
1395 }
1396
1397 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1398 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1399 ConstantInt::get(Predicate->getType(), 1));
1400
1401 // Create "cond" block
1402 //
1403 // %EltAddr = getelementptr i32* %1, i32 0
1404 // %Elt = load i32* %EltAddr
1405 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1406 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001407 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001408 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001409
1410 Value *Gep =
1411 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001412 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001413 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1414
1415 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001416 BasicBlock *NewIfBlock =
1417 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001418 Builder.SetInsertPoint(InsertPt);
1419 Instruction *OldBr = IfBlock->getTerminator();
1420 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1421 OldBr->eraseFromParent();
1422 PrevIfBlock = IfBlock;
1423 IfBlock = NewIfBlock;
1424 }
1425
1426 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1427 Phi->addIncoming(VResult, CondBlock);
1428 Phi->addIncoming(PrevPhi, PrevIfBlock);
1429 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1430 CI->replaceAllUsesWith(NewI);
1431 CI->eraseFromParent();
1432}
1433
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001434// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001435// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1436// <16 x i1> %mask)
1437// to a chain of basic blocks, that stores element one-by-one if
1438// the appropriate mask bit is set
1439//
1440// %1 = bitcast i8* %addr to i32*
1441// %2 = extractelement <16 x i1> %mask, i32 0
1442// %3 = icmp eq i1 %2, true
1443// br i1 %3, label %cond.store, label %else
1444//
1445// cond.store: ; preds = %0
1446// %4 = extractelement <16 x i32> %val, i32 0
1447// %5 = getelementptr i32* %1, i32 0
1448// store i32 %4, i32* %5
1449// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001450//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001451// else: ; preds = %0, %cond.store
1452// %6 = extractelement <16 x i1> %mask, i32 1
1453// %7 = icmp eq i1 %6, true
1454// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001455//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001456// cond.store1: ; preds = %else
1457// %8 = extractelement <16 x i32> %val, i32 1
1458// %9 = getelementptr i32* %1, i32 1
1459// store i32 %8, i32* %9
1460// br label %else2
1461// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001462static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001463 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001464 Value *Ptr = CI->getArgOperand(1);
1465 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001466 Value *Mask = CI->getArgOperand(3);
1467
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001468 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001469 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001470 assert(VecType && "Unexpected data type in masked store intrinsic");
1471
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001472 Type *EltTy = VecType->getElementType();
1473
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001474 IRBuilder<> Builder(CI->getContext());
1475 Instruction *InsertPt = CI;
1476 BasicBlock *IfBlock = CI->getParent();
1477 Builder.SetInsertPoint(InsertPt);
1478 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1479
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001480 // Short-cut if the mask is all-true.
1481 bool IsAllOnesMask = isa<Constant>(Mask) &&
1482 cast<Constant>(Mask)->isAllOnesValue();
1483
1484 if (IsAllOnesMask) {
1485 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1486 CI->eraseFromParent();
1487 return;
1488 }
1489
1490 // Adjust alignment for the scalar instruction.
1491 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001492 // Bitcast %addr fron i8* to EltTy*
1493 Type *NewPtrType =
1494 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1495 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001496 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001497
1498 if (isa<ConstantVector>(Mask)) {
1499 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1500 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1501 continue;
1502 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1503 Value *Gep =
1504 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1505 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1506 }
1507 CI->eraseFromParent();
1508 return;
1509 }
1510
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001511 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1512
1513 // Fill the "else" block, created in the previous iteration
1514 //
1515 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1516 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001517 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001518 //
1519 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1520 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1521 ConstantInt::get(Predicate->getType(), 1));
1522
1523 // Create "cond" block
1524 //
1525 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1526 // %EltAddr = getelementptr i32* %1, i32 0
1527 // %store i32 %OneElt, i32* %EltAddr
1528 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001529 BasicBlock *CondBlock =
1530 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001531 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001532
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001533 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001534 Value *Gep =
1535 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001536 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001537
1538 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001539 BasicBlock *NewIfBlock =
1540 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001541 Builder.SetInsertPoint(InsertPt);
1542 Instruction *OldBr = IfBlock->getTerminator();
1543 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1544 OldBr->eraseFromParent();
1545 IfBlock = NewIfBlock;
1546 }
1547 CI->eraseFromParent();
1548}
1549
Elena Demikhovsky09285852015-10-25 15:37:55 +00001550// Translate a masked gather intrinsic like
1551// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1552// <16 x i1> %Mask, <16 x i32> %Src)
1553// to a chain of basic blocks, with loading element one-by-one if
1554// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001555//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001556// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1557// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1558// % ToLoad0 = icmp eq i1 % Mask0, true
1559// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001560//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001561// cond.load:
1562// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1563// % Load0 = load i32, i32* % Ptr0, align 4
1564// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1565// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001566//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001567// else:
1568// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1569// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1570// % ToLoad1 = icmp eq i1 % Mask1, true
1571// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001572//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001573// cond.load1:
1574// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1575// % Load1 = load i32, i32* % Ptr1, align 4
1576// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1577// br label %else2
1578// . . .
1579// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1580// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001581static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001582 Value *Ptrs = CI->getArgOperand(0);
1583 Value *Alignment = CI->getArgOperand(1);
1584 Value *Mask = CI->getArgOperand(2);
1585 Value *Src0 = CI->getArgOperand(3);
1586
1587 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1588
1589 assert(VecType && "Unexpected return type of masked load intrinsic");
1590
1591 IRBuilder<> Builder(CI->getContext());
1592 Instruction *InsertPt = CI;
1593 BasicBlock *IfBlock = CI->getParent();
1594 BasicBlock *CondBlock = nullptr;
1595 BasicBlock *PrevIfBlock = CI->getParent();
1596 Builder.SetInsertPoint(InsertPt);
1597 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1598
1599 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1600
1601 Value *UndefVal = UndefValue::get(VecType);
1602
1603 // The result vector
1604 Value *VResult = UndefVal;
1605 unsigned VectorWidth = VecType->getNumElements();
1606
1607 // Shorten the way if the mask is a vector of constants.
1608 bool IsConstMask = isa<ConstantVector>(Mask);
1609
1610 if (IsConstMask) {
1611 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1612 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1613 continue;
1614 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1615 "Ptr" + Twine(Idx));
1616 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1617 "Load" + Twine(Idx));
1618 VResult = Builder.CreateInsertElement(VResult, Load,
1619 Builder.getInt32(Idx),
1620 "Res" + Twine(Idx));
1621 }
1622 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1623 CI->replaceAllUsesWith(NewI);
1624 CI->eraseFromParent();
1625 return;
1626 }
1627
1628 PHINode *Phi = nullptr;
1629 Value *PrevPhi = UndefVal;
1630
1631 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1632
1633 // Fill the "else" block, created in the previous iteration
1634 //
1635 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1636 // %ToLoad1 = icmp eq i1 %Mask1, true
1637 // br i1 %ToLoad1, label %cond.load, label %else
1638 //
1639 if (Idx > 0) {
1640 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1641 Phi->addIncoming(VResult, CondBlock);
1642 Phi->addIncoming(PrevPhi, PrevIfBlock);
1643 PrevPhi = Phi;
1644 VResult = Phi;
1645 }
1646
1647 Value *Predicate = Builder.CreateExtractElement(Mask,
1648 Builder.getInt32(Idx),
1649 "Mask" + Twine(Idx));
1650 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1651 ConstantInt::get(Predicate->getType(), 1),
1652 "ToLoad" + Twine(Idx));
1653
1654 // Create "cond" block
1655 //
1656 // %EltAddr = getelementptr i32* %1, i32 0
1657 // %Elt = load i32* %EltAddr
1658 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1659 //
1660 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1661 Builder.SetInsertPoint(InsertPt);
1662
1663 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1664 "Ptr" + Twine(Idx));
1665 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1666 "Load" + Twine(Idx));
1667 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1668 "Res" + Twine(Idx));
1669
1670 // Create "else" block, fill it in the next iteration
1671 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1672 Builder.SetInsertPoint(InsertPt);
1673 Instruction *OldBr = IfBlock->getTerminator();
1674 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1675 OldBr->eraseFromParent();
1676 PrevIfBlock = IfBlock;
1677 IfBlock = NewIfBlock;
1678 }
1679
1680 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1681 Phi->addIncoming(VResult, CondBlock);
1682 Phi->addIncoming(PrevPhi, PrevIfBlock);
1683 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1684 CI->replaceAllUsesWith(NewI);
1685 CI->eraseFromParent();
1686}
1687
1688// Translate a masked scatter intrinsic, like
1689// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1690// <16 x i1> %Mask)
1691// to a chain of basic blocks, that stores element one-by-one if
1692// the appropriate mask bit is set.
1693//
1694// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1695// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1696// % ToStore0 = icmp eq i1 % Mask0, true
1697// br i1 %ToStore0, label %cond.store, label %else
1698//
1699// cond.store:
1700// % Elt0 = extractelement <16 x i32> %Src, i32 0
1701// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1702// store i32 %Elt0, i32* % Ptr0, align 4
1703// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001704//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001705// else:
1706// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1707// % ToStore1 = icmp eq i1 % Mask1, true
1708// br i1 % ToStore1, label %cond.store1, label %else2
1709//
1710// cond.store1:
1711// % Elt1 = extractelement <16 x i32> %Src, i32 1
1712// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1713// store i32 % Elt1, i32* % Ptr1, align 4
1714// br label %else2
1715// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001716static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001717 Value *Src = CI->getArgOperand(0);
1718 Value *Ptrs = CI->getArgOperand(1);
1719 Value *Alignment = CI->getArgOperand(2);
1720 Value *Mask = CI->getArgOperand(3);
1721
1722 assert(isa<VectorType>(Src->getType()) &&
1723 "Unexpected data type in masked scatter intrinsic");
1724 assert(isa<VectorType>(Ptrs->getType()) &&
1725 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1726 "Vector of pointers is expected in masked scatter intrinsic");
1727
1728 IRBuilder<> Builder(CI->getContext());
1729 Instruction *InsertPt = CI;
1730 BasicBlock *IfBlock = CI->getParent();
1731 Builder.SetInsertPoint(InsertPt);
1732 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1733
1734 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1735 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1736
1737 // Shorten the way if the mask is a vector of constants.
1738 bool IsConstMask = isa<ConstantVector>(Mask);
1739
1740 if (IsConstMask) {
1741 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1742 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1743 continue;
1744 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1745 "Elt" + Twine(Idx));
1746 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1747 "Ptr" + Twine(Idx));
1748 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1749 }
1750 CI->eraseFromParent();
1751 return;
1752 }
1753 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1754 // Fill the "else" block, created in the previous iteration
1755 //
1756 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1757 // % ToStore = icmp eq i1 % Mask1, true
1758 // br i1 % ToStore, label %cond.store, label %else
1759 //
1760 Value *Predicate = Builder.CreateExtractElement(Mask,
1761 Builder.getInt32(Idx),
1762 "Mask" + Twine(Idx));
1763 Value *Cmp =
1764 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1765 ConstantInt::get(Predicate->getType(), 1),
1766 "ToStore" + Twine(Idx));
1767
1768 // Create "cond" block
1769 //
1770 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1771 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1772 // %store i32 % Elt1, i32* % Ptr1
1773 //
1774 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1775 Builder.SetInsertPoint(InsertPt);
1776
1777 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1778 "Elt" + Twine(Idx));
1779 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1780 "Ptr" + Twine(Idx));
1781 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1782
1783 // Create "else" block, fill it in the next iteration
1784 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1785 Builder.SetInsertPoint(InsertPt);
1786 Instruction *OldBr = IfBlock->getTerminator();
1787 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1788 OldBr->eraseFromParent();
1789 IfBlock = NewIfBlock;
1790 }
1791 CI->eraseFromParent();
1792}
1793
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001794/// If counting leading or trailing zeros is an expensive operation and a zero
1795/// input is defined, add a check for zero to avoid calling the intrinsic.
1796///
1797/// We want to transform:
1798/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1799///
1800/// into:
1801/// entry:
1802/// %cmpz = icmp eq i64 %A, 0
1803/// br i1 %cmpz, label %cond.end, label %cond.false
1804/// cond.false:
1805/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1806/// br label %cond.end
1807/// cond.end:
1808/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1809///
1810/// If the transform is performed, return true and set ModifiedDT to true.
1811static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1812 const TargetLowering *TLI,
1813 const DataLayout *DL,
1814 bool &ModifiedDT) {
1815 if (!TLI || !DL)
1816 return false;
1817
1818 // If a zero input is undefined, it doesn't make sense to despeculate that.
1819 if (match(CountZeros->getOperand(1), m_One()))
1820 return false;
1821
1822 // If it's cheap to speculate, there's nothing to do.
1823 auto IntrinsicID = CountZeros->getIntrinsicID();
1824 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1825 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1826 return false;
1827
1828 // Only handle legal scalar cases. Anything else requires too much work.
1829 Type *Ty = CountZeros->getType();
1830 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001831 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001832 return false;
1833
1834 // The intrinsic will be sunk behind a compare against zero and branch.
1835 BasicBlock *StartBlock = CountZeros->getParent();
1836 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1837
1838 // Create another block after the count zero intrinsic. A PHI will be added
1839 // in this block to select the result of the intrinsic or the bit-width
1840 // constant if the input to the intrinsic is zero.
1841 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1842 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1843
1844 // Set up a builder to create a compare, conditional branch, and PHI.
1845 IRBuilder<> Builder(CountZeros->getContext());
1846 Builder.SetInsertPoint(StartBlock->getTerminator());
1847 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1848
1849 // Replace the unconditional branch that was created by the first split with
1850 // a compare against zero and a conditional branch.
1851 Value *Zero = Constant::getNullValue(Ty);
1852 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1853 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1854 StartBlock->getTerminator()->eraseFromParent();
1855
1856 // Create a PHI in the end block to select either the output of the intrinsic
1857 // or the bit width of the operand.
1858 Builder.SetInsertPoint(&EndBlock->front());
1859 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1860 CountZeros->replaceAllUsesWith(PN);
1861 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1862 PN->addIncoming(BitWidth, StartBlock);
1863 PN->addIncoming(CountZeros, CallBlock);
1864
1865 // We are explicitly handling the zero case, so we can set the intrinsic's
1866 // undefined zero argument to 'true'. This will also prevent reprocessing the
1867 // intrinsic; we only despeculate when a zero input is defined.
1868 CountZeros->setArgOperand(1, Builder.getTrue());
1869 ModifiedDT = true;
1870 return true;
1871}
1872
Sanjay Patelfc580a62015-09-21 23:03:16 +00001873bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001874 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001875
Chris Lattner7a277142011-01-15 07:14:54 +00001876 // Lower inline assembly if we can.
1877 // If we found an inline asm expession, and if the target knows how to
1878 // lower it to normal LLVM code, do so now.
1879 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1880 if (TLI->ExpandInlineAsm(CI)) {
1881 // Avoid invalidating the iterator.
1882 CurInstIterator = BB->begin();
1883 // Avoid processing instructions out of order, which could cause
1884 // reuse before a value is defined.
1885 SunkAddrs.clear();
1886 return true;
1887 }
1888 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001889 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001890 return true;
1891 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001892
John Brawn0dbcd652015-03-18 12:01:59 +00001893 // Align the pointer arguments to this call if the target thinks it's a good
1894 // idea
1895 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001896 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001897 for (auto &Arg : CI->arg_operands()) {
1898 // We want to align both objects whose address is used directly and
1899 // objects whose address is used in casts and GEPs, though it only makes
1900 // sense for GEPs if the offset is a multiple of the desired alignment and
1901 // if size - offset meets the size threshold.
1902 if (!Arg->getType()->isPointerTy())
1903 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001904 APInt Offset(DL->getPointerSizeInBits(
1905 cast<PointerType>(Arg->getType())->getAddressSpace()),
1906 0);
1907 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001908 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001909 if ((Offset2 & (PrefAlign-1)) != 0)
1910 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001911 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001912 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1913 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001914 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001915 // Global variables can only be aligned if they are defined in this
1916 // object (i.e. they are uniquely initialized in this object), and
1917 // over-aligning global variables that have an explicit section is
1918 // forbidden.
1919 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001920 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001921 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001922 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001923 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001924 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001925 }
1926 // If this is a memcpy (or similar) then we may be able to improve the
1927 // alignment
1928 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001929 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001930 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001931 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001932 if (Align > MI->getAlignment())
1933 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001934 }
1935 }
1936
Philip Reamesac115ed2016-03-09 23:13:12 +00001937 // If we have a cold call site, try to sink addressing computation into the
1938 // cold block. This interacts with our handling for loads and stores to
1939 // ensure that we can fold all uses of a potential addressing computation
1940 // into their uses. TODO: generalize this to work over profiling data
1941 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1942 for (auto &Arg : CI->arg_operands()) {
1943 if (!Arg->getType()->isPointerTy())
1944 continue;
1945 unsigned AS = Arg->getType()->getPointerAddressSpace();
1946 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1947 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001948
Eric Christopher4b7948e2010-03-11 02:41:03 +00001949 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001950 if (II) {
1951 switch (II->getIntrinsicID()) {
1952 default: break;
1953 case Intrinsic::objectsize: {
1954 // Lower all uses of llvm.objectsize.*
George Burgess IV3f089142016-12-20 23:46:36 +00001955 ConstantInt *RetVal =
1956 lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001957 // Substituting this can cause recursive simplifications, which can
1958 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1959 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001960 Value *CurValue = &*CurInstIterator;
1961 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001962
Sanjay Patel545a4562016-01-20 18:59:16 +00001963 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001964
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001965 // If the iterator instruction was recursively deleted, start over at the
1966 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001967 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001968 CurInstIterator = BB->begin();
1969 SunkAddrs.clear();
1970 }
1971 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001972 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001973 case Intrinsic::masked_load: {
1974 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001975 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001976 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001977 ModifiedDT = true;
1978 return true;
1979 }
1980 return false;
1981 }
1982 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001983 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001984 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001985 ModifiedDT = true;
1986 return true;
1987 }
1988 return false;
1989 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001990 case Intrinsic::masked_gather: {
1991 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001992 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001993 ModifiedDT = true;
1994 return true;
1995 }
1996 return false;
1997 }
1998 case Intrinsic::masked_scatter: {
1999 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00002000 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00002001 ModifiedDT = true;
2002 return true;
2003 }
2004 return false;
2005 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002006 case Intrinsic::aarch64_stlxr:
2007 case Intrinsic::aarch64_stxr: {
2008 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
2009 if (!ExtVal || !ExtVal->hasOneUse() ||
2010 ExtVal->getParent() == CI->getParent())
2011 return false;
2012 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
2013 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002014 // Mark this instruction as "inserted by CGP", so that other
2015 // optimizations don't touch it.
2016 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00002017 return true;
2018 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00002019 case Intrinsic::invariant_group_barrier:
2020 II->replaceAllUsesWith(II->getArgOperand(0));
2021 II->eraseFromParent();
2022 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00002023
2024 case Intrinsic::cttz:
2025 case Intrinsic::ctlz:
2026 // If counting zeros is expensive, try to avoid it.
2027 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002028 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00002029
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002030 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002031 // Unknown address space.
2032 // TODO: Target hook to pick which address space the intrinsic cares
2033 // about?
2034 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002035 SmallVector<Value*, 2> PtrOps;
2036 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002037 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002038 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00002039 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00002040 return true;
2041 }
Pete Cooper615fd892012-03-13 20:59:56 +00002042 }
2043
Eric Christopher4b7948e2010-03-11 02:41:03 +00002044 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00002045 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00002046
Benjamin Kramer7b88a492010-03-12 09:27:41 +00002047 // Lower all default uses of _chk calls. This is very similar
2048 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002049 // to fortified library functions (e.g. __memcpy_chk) that have the default
2050 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002051 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00002052 if (Value *V = Simplifier.optimizeCall(CI)) {
2053 CI->replaceAllUsesWith(V);
2054 CI->eraseFromParent();
2055 return true;
2056 }
2057 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00002058}
Chris Lattner1b93be52011-01-15 07:25:29 +00002059
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002060/// Look for opportunities to duplicate return instructions to the predecessor
2061/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002062/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002063/// bb0:
2064/// %tmp0 = tail call i32 @f0()
2065/// br label %return
2066/// bb1:
2067/// %tmp1 = tail call i32 @f1()
2068/// br label %return
2069/// bb2:
2070/// %tmp2 = tail call i32 @f2()
2071/// br label %return
2072/// return:
2073/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
2074/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002075/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00002076///
2077/// =>
2078///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002079/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00002080/// bb0:
2081/// %tmp0 = tail call i32 @f0()
2082/// ret i32 %tmp0
2083/// bb1:
2084/// %tmp1 = tail call i32 @f1()
2085/// ret i32 %tmp1
2086/// bb2:
2087/// %tmp2 = tail call i32 @f2()
2088/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00002089/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00002090bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00002091 if (!TLI)
2092 return false;
2093
Michael Kuperstein71321562016-09-07 20:29:49 +00002094 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
2095 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00002096 return false;
2097
Craig Topperc0196b12014-04-14 00:51:57 +00002098 PHINode *PN = nullptr;
2099 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002100 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002101 if (V) {
2102 BCI = dyn_cast<BitCastInst>(V);
2103 if (BCI)
2104 V = BCI->getOperand(0);
2105
2106 PN = dyn_cast<PHINode>(V);
2107 if (!PN)
2108 return false;
2109 }
Evan Cheng0663f232011-03-21 01:19:09 +00002110
Cameron Zwarich4649f172011-03-24 04:52:10 +00002111 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002112 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002113
Cameron Zwarich4649f172011-03-24 04:52:10 +00002114 // Make sure there are no instructions between the PHI and return, or that the
2115 // return is the first instruction in the block.
2116 if (PN) {
2117 BasicBlock::iterator BI = BB->begin();
2118 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002119 if (&*BI == BCI)
2120 // Also skip over the bitcast.
2121 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002122 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002123 return false;
2124 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002125 BasicBlock::iterator BI = BB->begin();
2126 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002127 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002128 return false;
2129 }
Evan Cheng0663f232011-03-21 01:19:09 +00002130
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002131 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2132 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002133 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002134 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002135 if (PN) {
2136 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2137 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2138 // Make sure the phi value is indeed produced by the tail call.
2139 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002140 TLI->mayBeEmittedAsTailCall(CI) &&
2141 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002142 TailCalls.push_back(CI);
2143 }
2144 } else {
2145 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002146 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002147 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002148 continue;
2149
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002150 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002151 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2152 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002153 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2154 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002155 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002156
Cameron Zwarich4649f172011-03-24 04:52:10 +00002157 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002158 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2159 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002160 TailCalls.push_back(CI);
2161 }
Evan Cheng0663f232011-03-21 01:19:09 +00002162 }
2163
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002164 bool Changed = false;
2165 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2166 CallInst *CI = TailCalls[i];
2167 CallSite CS(CI);
2168
2169 // Conservatively require the attributes of the call to match those of the
2170 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002171 AttributeSet CalleeAttrs = CS.getAttributes();
2172 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002173 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002174 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002175 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002176 continue;
2177
2178 // Make sure the call instruction is followed by an unconditional branch to
2179 // the return block.
2180 BasicBlock *CallBB = CI->getParent();
2181 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2182 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2183 continue;
2184
2185 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002186 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002187 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002188 ++NumRetsDup;
2189 }
2190
2191 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002192 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002193 BB->eraseFromParent();
2194
2195 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002196}
2197
Chris Lattner728f9022008-11-25 07:09:13 +00002198//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002199// Memory Optimization
2200//===----------------------------------------------------------------------===//
2201
Chandler Carruthc8925912013-01-05 02:09:22 +00002202namespace {
2203
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002204/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002205/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002206struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002207 Value *BaseReg;
2208 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002209 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002210 void print(raw_ostream &OS) const;
2211 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002212
Chandler Carruthc8925912013-01-05 02:09:22 +00002213 bool operator==(const ExtAddrMode& O) const {
2214 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2215 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2216 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2217 }
2218};
2219
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002220#ifndef NDEBUG
2221static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2222 AM.print(OS);
2223 return OS;
2224}
2225#endif
2226
Chandler Carruthc8925912013-01-05 02:09:22 +00002227void ExtAddrMode::print(raw_ostream &OS) const {
2228 bool NeedPlus = false;
2229 OS << "[";
2230 if (BaseGV) {
2231 OS << (NeedPlus ? " + " : "")
2232 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002233 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002234 NeedPlus = true;
2235 }
2236
Richard Trieuc0f91212014-05-30 03:15:17 +00002237 if (BaseOffs) {
2238 OS << (NeedPlus ? " + " : "")
2239 << BaseOffs;
2240 NeedPlus = true;
2241 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002242
2243 if (BaseReg) {
2244 OS << (NeedPlus ? " + " : "")
2245 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002246 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002247 NeedPlus = true;
2248 }
2249 if (Scale) {
2250 OS << (NeedPlus ? " + " : "")
2251 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002252 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002253 }
2254
2255 OS << ']';
2256}
2257
2258#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002259LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002260 print(dbgs());
2261 dbgs() << '\n';
2262}
2263#endif
2264
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002265/// \brief This class provides transaction based operation on the IR.
2266/// Every change made through this class is recorded in the internal state and
2267/// can be undone (rollback) until commit is called.
2268class TypePromotionTransaction {
2269
2270 /// \brief This represents the common interface of the individual transaction.
2271 /// Each class implements the logic for doing one specific modification on
2272 /// the IR via the TypePromotionTransaction.
2273 class TypePromotionAction {
2274 protected:
2275 /// The Instruction modified.
2276 Instruction *Inst;
2277
2278 public:
2279 /// \brief Constructor of the action.
2280 /// The constructor performs the related action on the IR.
2281 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2282
2283 virtual ~TypePromotionAction() {}
2284
2285 /// \brief Undo the modification done by this action.
2286 /// When this method is called, the IR must be in the same state as it was
2287 /// before this action was applied.
2288 /// \pre Undoing the action works if and only if the IR is in the exact same
2289 /// state as it was directly after this action was applied.
2290 virtual void undo() = 0;
2291
2292 /// \brief Advocate every change made by this action.
2293 /// When the results on the IR of the action are to be kept, it is important
2294 /// to call this function, otherwise hidden information may be kept forever.
2295 virtual void commit() {
2296 // Nothing to be done, this action is not doing anything.
2297 }
2298 };
2299
2300 /// \brief Utility to remember the position of an instruction.
2301 class InsertionHandler {
2302 /// Position of an instruction.
2303 /// Either an instruction:
2304 /// - Is the first in a basic block: BB is used.
2305 /// - Has a previous instructon: PrevInst is used.
2306 union {
2307 Instruction *PrevInst;
2308 BasicBlock *BB;
2309 } Point;
2310 /// Remember whether or not the instruction had a previous instruction.
2311 bool HasPrevInstruction;
2312
2313 public:
2314 /// \brief Record the position of \p Inst.
2315 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002316 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002317 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2318 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002319 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002320 else
2321 Point.BB = Inst->getParent();
2322 }
2323
2324 /// \brief Insert \p Inst at the recorded position.
2325 void insert(Instruction *Inst) {
2326 if (HasPrevInstruction) {
2327 if (Inst->getParent())
2328 Inst->removeFromParent();
2329 Inst->insertAfter(Point.PrevInst);
2330 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002331 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002332 if (Inst->getParent())
2333 Inst->moveBefore(Position);
2334 else
2335 Inst->insertBefore(Position);
2336 }
2337 }
2338 };
2339
2340 /// \brief Move an instruction before another.
2341 class InstructionMoveBefore : public TypePromotionAction {
2342 /// Original position of the instruction.
2343 InsertionHandler Position;
2344
2345 public:
2346 /// \brief Move \p Inst before \p Before.
2347 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2348 : TypePromotionAction(Inst), Position(Inst) {
2349 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2350 Inst->moveBefore(Before);
2351 }
2352
2353 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002354 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002355 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2356 Position.insert(Inst);
2357 }
2358 };
2359
2360 /// \brief Set the operand of an instruction with a new value.
2361 class OperandSetter : public TypePromotionAction {
2362 /// Original operand of the instruction.
2363 Value *Origin;
2364 /// Index of the modified instruction.
2365 unsigned Idx;
2366
2367 public:
2368 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2369 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2370 : TypePromotionAction(Inst), Idx(Idx) {
2371 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2372 << "for:" << *Inst << "\n"
2373 << "with:" << *NewVal << "\n");
2374 Origin = Inst->getOperand(Idx);
2375 Inst->setOperand(Idx, NewVal);
2376 }
2377
2378 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002379 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002380 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2381 << "for: " << *Inst << "\n"
2382 << "with: " << *Origin << "\n");
2383 Inst->setOperand(Idx, Origin);
2384 }
2385 };
2386
2387 /// \brief Hide the operands of an instruction.
2388 /// Do as if this instruction was not using any of its operands.
2389 class OperandsHider : public TypePromotionAction {
2390 /// The list of original operands.
2391 SmallVector<Value *, 4> OriginalValues;
2392
2393 public:
2394 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2395 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2396 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2397 unsigned NumOpnds = Inst->getNumOperands();
2398 OriginalValues.reserve(NumOpnds);
2399 for (unsigned It = 0; It < NumOpnds; ++It) {
2400 // Save the current operand.
2401 Value *Val = Inst->getOperand(It);
2402 OriginalValues.push_back(Val);
2403 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002404 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002405 // that we are not willing to pay.
2406 Inst->setOperand(It, UndefValue::get(Val->getType()));
2407 }
2408 }
2409
2410 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002411 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002412 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2413 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2414 Inst->setOperand(It, OriginalValues[It]);
2415 }
2416 };
2417
2418 /// \brief Build a truncate instruction.
2419 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002420 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002421 public:
2422 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2423 /// result.
2424 /// trunc Opnd to Ty.
2425 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2426 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002427 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2428 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002429 }
2430
Quentin Colombetac55b152014-09-16 22:36:07 +00002431 /// \brief Get the built value.
2432 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433
2434 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002435 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002436 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2437 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2438 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 }
2440 };
2441
2442 /// \brief Build a sign extension instruction.
2443 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002444 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 public:
2446 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2447 /// result.
2448 /// sext Opnd to Ty.
2449 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002450 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002451 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002452 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2453 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002454 }
2455
Quentin Colombetac55b152014-09-16 22:36:07 +00002456 /// \brief Get the built value.
2457 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002458
2459 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002460 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002461 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2462 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2463 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002464 }
2465 };
2466
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002467 /// \brief Build a zero extension instruction.
2468 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002469 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002470 public:
2471 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2472 /// result.
2473 /// zext Opnd to Ty.
2474 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002475 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002476 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002477 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2478 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002479 }
2480
Quentin Colombetac55b152014-09-16 22:36:07 +00002481 /// \brief Get the built value.
2482 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002483
2484 /// \brief Remove the built instruction.
2485 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002486 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2487 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2488 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002489 }
2490 };
2491
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002492 /// \brief Mutate an instruction to another type.
2493 class TypeMutator : public TypePromotionAction {
2494 /// Record the original type.
2495 Type *OrigTy;
2496
2497 public:
2498 /// \brief Mutate the type of \p Inst into \p NewTy.
2499 TypeMutator(Instruction *Inst, Type *NewTy)
2500 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2501 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2502 << "\n");
2503 Inst->mutateType(NewTy);
2504 }
2505
2506 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002507 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002508 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2509 << "\n");
2510 Inst->mutateType(OrigTy);
2511 }
2512 };
2513
2514 /// \brief Replace the uses of an instruction by another instruction.
2515 class UsesReplacer : public TypePromotionAction {
2516 /// Helper structure to keep track of the replaced uses.
2517 struct InstructionAndIdx {
2518 /// The instruction using the instruction.
2519 Instruction *Inst;
2520 /// The index where this instruction is used for Inst.
2521 unsigned Idx;
2522 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2523 : Inst(Inst), Idx(Idx) {}
2524 };
2525
2526 /// Keep track of the original uses (pair Instruction, Index).
2527 SmallVector<InstructionAndIdx, 4> OriginalUses;
2528 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2529
2530 public:
2531 /// \brief Replace all the use of \p Inst by \p New.
2532 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2533 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2534 << "\n");
2535 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002536 for (Use &U : Inst->uses()) {
2537 Instruction *UserI = cast<Instruction>(U.getUser());
2538 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002539 }
2540 // Now, we can replace the uses.
2541 Inst->replaceAllUsesWith(New);
2542 }
2543
2544 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002545 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002546 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2547 for (use_iterator UseIt = OriginalUses.begin(),
2548 EndIt = OriginalUses.end();
2549 UseIt != EndIt; ++UseIt) {
2550 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2551 }
2552 }
2553 };
2554
2555 /// \brief Remove an instruction from the IR.
2556 class InstructionRemover : public TypePromotionAction {
2557 /// Original position of the instruction.
2558 InsertionHandler Inserter;
2559 /// Helper structure to hide all the link to the instruction. In other
2560 /// words, this helps to do as if the instruction was removed.
2561 OperandsHider Hider;
2562 /// Keep track of the uses replaced, if any.
2563 UsesReplacer *Replacer;
2564
2565 public:
2566 /// \brief Remove all reference of \p Inst and optinally replace all its
2567 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002568 /// \pre If !Inst->use_empty(), then New != nullptr
2569 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002570 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002571 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002572 if (New)
2573 Replacer = new UsesReplacer(Inst, New);
2574 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2575 Inst->removeFromParent();
2576 }
2577
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002578 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002579
2580 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002581 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582
2583 /// \brief Resurrect the instruction and reassign it to the proper uses if
2584 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002585 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002586 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2587 Inserter.insert(Inst);
2588 if (Replacer)
2589 Replacer->undo();
2590 Hider.undo();
2591 }
2592 };
2593
2594public:
2595 /// Restoration point.
2596 /// The restoration point is a pointer to an action instead of an iterator
2597 /// because the iterator may be invalidated but not the pointer.
2598 typedef const TypePromotionAction *ConstRestorationPt;
2599 /// Advocate every changes made in that transaction.
2600 void commit();
2601 /// Undo all the changes made after the given point.
2602 void rollback(ConstRestorationPt Point);
2603 /// Get the current restoration point.
2604 ConstRestorationPt getRestorationPoint() const;
2605
2606 /// \name API for IR modification with state keeping to support rollback.
2607 /// @{
2608 /// Same as Instruction::setOperand.
2609 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2610 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002611 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002612 /// Same as Value::replaceAllUsesWith.
2613 void replaceAllUsesWith(Instruction *Inst, Value *New);
2614 /// Same as Value::mutateType.
2615 void mutateType(Instruction *Inst, Type *NewTy);
2616 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002617 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002618 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002619 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002620 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002621 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002622 /// Same as Instruction::moveBefore.
2623 void moveBefore(Instruction *Inst, Instruction *Before);
2624 /// @}
2625
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002626private:
2627 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002628 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2629 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002630};
2631
2632void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2633 Value *NewVal) {
2634 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002635 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002636}
2637
2638void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2639 Value *NewVal) {
2640 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002641 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002642}
2643
2644void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2645 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002646 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002647}
2648
2649void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002650 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002651}
2652
Quentin Colombetac55b152014-09-16 22:36:07 +00002653Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2654 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002655 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002656 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002657 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002658 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002659}
2660
Quentin Colombetac55b152014-09-16 22:36:07 +00002661Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2662 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002663 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002664 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002665 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002666 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002667}
2668
Quentin Colombetac55b152014-09-16 22:36:07 +00002669Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2670 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002671 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002672 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002673 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002674 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002675}
2676
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002677void TypePromotionTransaction::moveBefore(Instruction *Inst,
2678 Instruction *Before) {
2679 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002680 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002681}
2682
2683TypePromotionTransaction::ConstRestorationPt
2684TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002685 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002686}
2687
2688void TypePromotionTransaction::commit() {
2689 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002690 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002691 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002692 Actions.clear();
2693}
2694
2695void TypePromotionTransaction::rollback(
2696 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002697 while (!Actions.empty() && Point != Actions.back().get()) {
2698 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002699 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002700 }
2701}
2702
Chandler Carruthc8925912013-01-05 02:09:22 +00002703/// \brief A helper class for matching addressing modes.
2704///
2705/// This encapsulates the logic for matching the target-legal addressing modes.
2706class AddressingModeMatcher {
2707 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002708 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002709 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002710 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002711
2712 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2713 /// the memory instruction that we're computing this address for.
2714 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002715 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002716 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002717
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002718 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002719 /// part of the return value of this addressing mode matching stuff.
2720 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002721
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002722 /// The instructions inserted by other CodeGenPrepare optimizations.
2723 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002724 /// A map from the instructions to their type before promotion.
2725 InstrToOrigTy &PromotedInsts;
2726 /// The ongoing transaction where every action should be registered.
2727 TypePromotionTransaction &TPT;
2728
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002729 /// This is set to true when we should not do profitability checks.
2730 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002731 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002732
Eric Christopherd75c00c2015-02-26 22:38:34 +00002733 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002734 const TargetMachine &TM, Type *AT, unsigned AS,
2735 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002736 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002737 InstrToOrigTy &PromotedInsts,
2738 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002739 : AddrModeInsts(AMI), TM(TM),
2740 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2741 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002742 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2743 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2744 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002745 IgnoreProfitability = false;
2746 }
2747public:
Stephen Lin837bba12013-07-15 17:55:02 +00002748
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002749 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002750 /// give an access type of AccessTy. This returns a list of involved
2751 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002752 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002753 /// optimizations.
2754 /// \p PromotedInsts maps the instructions to their type before promotion.
2755 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002756 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002757 Instruction *MemoryInst,
2758 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002759 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002760 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002761 InstrToOrigTy &PromotedInsts,
2762 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002763 ExtAddrMode Result;
2764
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002765 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002766 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002767 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002768 (void)Success; assert(Success && "Couldn't select *anything*?");
2769 return Result;
2770 }
2771private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002772 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2773 bool matchAddr(Value *V, unsigned Depth);
2774 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002775 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002776 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002777 ExtAddrMode &AMBefore,
2778 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002779 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2780 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002781 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002782};
2783
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002784/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002785/// Return true and update AddrMode if this addr mode is legal for the target,
2786/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002787bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002788 unsigned Depth) {
2789 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2790 // mode. Just process that directly.
2791 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002792 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002793
Chandler Carruthc8925912013-01-05 02:09:22 +00002794 // If the scale is 0, it takes nothing to add this.
2795 if (Scale == 0)
2796 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002797
Chandler Carruthc8925912013-01-05 02:09:22 +00002798 // If we already have a scale of this value, we can add to it, otherwise, we
2799 // need an available scale field.
2800 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2801 return false;
2802
2803 ExtAddrMode TestAddrMode = AddrMode;
2804
2805 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2806 // [A+B + A*7] -> [B+A*8].
2807 TestAddrMode.Scale += Scale;
2808 TestAddrMode.ScaledReg = ScaleReg;
2809
2810 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002811 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002812 return false;
2813
2814 // It was legal, so commit it.
2815 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002816
Chandler Carruthc8925912013-01-05 02:09:22 +00002817 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2818 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2819 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002820 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002821 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2822 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2823 TestAddrMode.ScaledReg = AddLHS;
2824 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002825
Chandler Carruthc8925912013-01-05 02:09:22 +00002826 // If this addressing mode is legal, commit it and remember that we folded
2827 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002828 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002829 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2830 AddrMode = TestAddrMode;
2831 return true;
2832 }
2833 }
2834
2835 // Otherwise, not (x+c)*scale, just return what we have.
2836 return true;
2837}
2838
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002839/// This is a little filter, which returns true if an addressing computation
2840/// involving I might be folded into a load/store accessing it.
2841/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002842/// the set of instructions that MatchOperationAddr can.
2843static bool MightBeFoldableInst(Instruction *I) {
2844 switch (I->getOpcode()) {
2845 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002846 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002847 // Don't touch identity bitcasts.
2848 if (I->getType() == I->getOperand(0)->getType())
2849 return false;
2850 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2851 case Instruction::PtrToInt:
2852 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2853 return true;
2854 case Instruction::IntToPtr:
2855 // We know the input is intptr_t, so this is foldable.
2856 return true;
2857 case Instruction::Add:
2858 return true;
2859 case Instruction::Mul:
2860 case Instruction::Shl:
2861 // Can only handle X*C and X << C.
2862 return isa<ConstantInt>(I->getOperand(1));
2863 case Instruction::GetElementPtr:
2864 return true;
2865 default:
2866 return false;
2867 }
2868}
2869
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002870/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2871/// \note \p Val is assumed to be the product of some type promotion.
2872/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2873/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002874static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2875 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002876 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2877 if (!PromotedInst)
2878 return false;
2879 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2880 // If the ISDOpcode is undefined, it was undefined before the promotion.
2881 if (!ISDOpcode)
2882 return true;
2883 // Otherwise, check if the promoted instruction is legal or not.
2884 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002885 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002886}
2887
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002888/// \brief Hepler class to perform type promotion.
2889class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002890 /// \brief Utility function to check whether or not a sign or zero extension
2891 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2892 /// either using the operands of \p Inst or promoting \p Inst.
2893 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002894 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002895 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002896 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002897 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002898 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002899 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002900 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002901 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2902 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002903
2904 /// \brief Utility function to determine if \p OpIdx should be promoted when
2905 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002906 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002907 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002908 }
2909
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002910 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002911 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002912 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002913 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002914 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002915 /// Newly added extensions are inserted in \p Exts.
2916 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002917 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002918 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002919 static Value *promoteOperandForTruncAndAnyExt(
2920 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002921 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002922 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002923 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002924
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002925 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002926 /// operand is promotable and is not a supported trunc or sext.
2927 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002928 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002929 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002930 /// Newly added extensions are inserted in \p Exts.
2931 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002932 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002933 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002934 static Value *promoteOperandForOther(Instruction *Ext,
2935 TypePromotionTransaction &TPT,
2936 InstrToOrigTy &PromotedInsts,
2937 unsigned &CreatedInstsCost,
2938 SmallVectorImpl<Instruction *> *Exts,
2939 SmallVectorImpl<Instruction *> *Truncs,
2940 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002941
2942 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002943 static Value *signExtendOperandForOther(
2944 Instruction *Ext, TypePromotionTransaction &TPT,
2945 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2946 SmallVectorImpl<Instruction *> *Exts,
2947 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2948 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2949 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002950 }
2951
2952 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002953 static Value *zeroExtendOperandForOther(
2954 Instruction *Ext, TypePromotionTransaction &TPT,
2955 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2956 SmallVectorImpl<Instruction *> *Exts,
2957 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2958 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2959 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002960 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002961
2962public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002963 /// Type for the utility function that promotes the operand of Ext.
2964 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002965 InstrToOrigTy &PromotedInsts,
2966 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002967 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002968 SmallVectorImpl<Instruction *> *Truncs,
2969 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002970 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2971 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002972 /// \return NULL if no promotable action is possible with the current
2973 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002974 /// \p InsertedInsts keeps track of all the instructions inserted by the
2975 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002976 /// because we do not want to promote these instructions as CodeGenPrepare
2977 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2978 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002979 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002980 const TargetLowering &TLI,
2981 const InstrToOrigTy &PromotedInsts);
2982};
2983
2984bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002985 Type *ConsideredExtType,
2986 const InstrToOrigTy &PromotedInsts,
2987 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002988 // The promotion helper does not know how to deal with vector types yet.
2989 // To be able to fix that, we would need to fix the places where we
2990 // statically extend, e.g., constants and such.
2991 if (Inst->getType()->isVectorTy())
2992 return false;
2993
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002994 // We can always get through zext.
2995 if (isa<ZExtInst>(Inst))
2996 return true;
2997
2998 // sext(sext) is ok too.
2999 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003000 return true;
3001
3002 // We can get through binary operator, if it is legal. In other words, the
3003 // binary operator must have a nuw or nsw flag.
3004 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
3005 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003006 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
3007 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003008 return true;
3009
3010 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003011 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003012 if (!isa<TruncInst>(Inst))
3013 return false;
3014
3015 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003016 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003017 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003018 if (!OpndVal->getType()->isIntegerTy() ||
3019 OpndVal->getType()->getIntegerBitWidth() >
3020 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003021 return false;
3022
3023 // If the operand of the truncate is not an instruction, we will not have
3024 // any information on the dropped bits.
3025 // (Actually we could for constant but it is not worth the extra logic).
3026 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
3027 if (!Opnd)
3028 return false;
3029
3030 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003031 // I.e., check that trunc just drops extended bits of the same kind of
3032 // the extension.
3033 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003034 const Type *OpndType;
3035 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00003036 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
3037 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003038 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
3039 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003040 else
3041 return false;
3042
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003043 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00003044 return Inst->getType()->getIntegerBitWidth() >=
3045 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003046}
3047
3048TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003049 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003050 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003051 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3052 "Unexpected instruction type");
3053 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
3054 Type *ExtTy = Ext->getType();
3055 bool IsSExt = isa<SExtInst>(Ext);
3056 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003057 // get through.
3058 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003059 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00003060 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003061
3062 // Do not promote if the operand has been added by codegenprepare.
3063 // Otherwise, it means we are undoing an optimization that is likely to be
3064 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003065 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00003066 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003067
3068 // SExt or Trunc instructions.
3069 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003070 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
3071 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003072 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003073
3074 // Regular instruction.
3075 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003076 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00003077 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003078 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003079}
3080
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003081Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003082 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003083 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003084 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003085 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003086 // By construction, the operand of SExt is an instruction. Otherwise we cannot
3087 // get through it and this method should not be called.
3088 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00003089 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003090 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003091 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003092 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003093 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003094 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00003095 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003096 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
3097 TPT.replaceAllUsesWith(SExt, ZExt);
3098 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00003099 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003100 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003101 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3102 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003103 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3104 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003105 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003106
3107 // Remove dead code.
3108 if (SExtOpnd->use_empty())
3109 TPT.eraseInstruction(SExtOpnd);
3110
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003111 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003112 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003113 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003114 if (ExtInst) {
3115 if (Exts)
3116 Exts->push_back(ExtInst);
3117 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3118 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003119 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003120 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003121
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003122 // At this point we have: ext ty opnd to ty.
3123 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3124 Value *NextVal = ExtInst->getOperand(0);
3125 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003126 return NextVal;
3127}
3128
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003129Value *TypePromotionHelper::promoteOperandForOther(
3130 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003131 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003132 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003133 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3134 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003135 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003136 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003137 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003138 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003139 if (!ExtOpnd->hasOneUse()) {
3140 // ExtOpnd will be promoted.
3141 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003142 // promoted version.
3143 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003144 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003145 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3146 ITrunc->removeFromParent();
3147 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003148 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003149 if (Truncs)
3150 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003151 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003152
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003153 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003154 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003155 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003156 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003157 }
3158
3159 // Get through the Instruction:
3160 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003161 // 2. Replace the uses of Ext by Inst.
3162 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003163
3164 // Remember the original type of the instruction before promotion.
3165 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003166 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3167 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003168 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003169 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003170 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003171 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003172 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003173 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003174
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003175 DEBUG(dbgs() << "Propagate Ext to operands\n");
3176 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003177 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003178 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3179 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3180 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003181 DEBUG(dbgs() << "No need to propagate\n");
3182 continue;
3183 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003184 // Check if we can statically extend the operand.
3185 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003186 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003187 DEBUG(dbgs() << "Statically extend\n");
3188 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3189 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3190 : Cst->getValue().zext(BitWidth);
3191 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003192 continue;
3193 }
3194 // UndefValue are typed, so we have to statically sign extend them.
3195 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003196 DEBUG(dbgs() << "Statically extend\n");
3197 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003198 continue;
3199 }
3200
3201 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003202 // Check if Ext was reused to extend an operand.
3203 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003204 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003205 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003206 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3207 : TPT.createZExt(Ext, Opnd, Ext->getType());
3208 if (!isa<Instruction>(ValForExtOpnd)) {
3209 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3210 continue;
3211 }
3212 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003213 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003214 if (Exts)
3215 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003216 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003217
3218 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003219 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3220 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003221 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003222 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003223 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003224 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003225 if (ExtForOpnd == Ext) {
3226 DEBUG(dbgs() << "Extension is useless now\n");
3227 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003228 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003229 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003230}
3231
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003232/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003233/// \p NewCost gives the cost of extension instructions created by the
3234/// promotion.
3235/// \p OldCost gives the cost of extension instructions before the promotion
3236/// plus the number of instructions that have been
3237/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003238/// \p PromotedOperand is the value that has been promoted.
3239/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003240bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003241 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3242 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3243 // The cost of the new extensions is greater than the cost of the
3244 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003245 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003246 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003247 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003248 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003249 return true;
3250 // The promotion is neutral but it may help folding the sign extension in
3251 // loads for instance.
3252 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003253 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003254}
3255
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003256/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003257/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003258/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003259/// If \p MovedAway is not NULL, it contains the information of whether or
3260/// not AddrInst has to be folded into the addressing mode on success.
3261/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3262/// because it has been moved away.
3263/// Thus AddrInst must not be added in the matched instructions.
3264/// This state can happen when AddrInst is a sext, since it may be moved away.
3265/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3266/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003267bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003268 unsigned Depth,
3269 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003270 // Avoid exponential behavior on extremely deep expression trees.
3271 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003272
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003273 // By default, all matched instructions stay in place.
3274 if (MovedAway)
3275 *MovedAway = false;
3276
Chandler Carruthc8925912013-01-05 02:09:22 +00003277 switch (Opcode) {
3278 case Instruction::PtrToInt:
3279 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003280 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003281 case Instruction::IntToPtr: {
3282 auto AS = AddrInst->getType()->getPointerAddressSpace();
3283 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003284 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003285 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003286 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003287 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003288 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003289 case Instruction::BitCast:
3290 // BitCast is always a noop, and we can handle it as long as it is
3291 // int->int or pointer->pointer (we don't want int<->fp or something).
3292 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3293 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3294 // Don't touch identity bitcasts. These were probably put here by LSR,
3295 // and we don't want to mess around with them. Assume it knows what it
3296 // is doing.
3297 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003298 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003299 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003300 case Instruction::AddrSpaceCast: {
3301 unsigned SrcAS
3302 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3303 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3304 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003305 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003306 return false;
3307 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003308 case Instruction::Add: {
3309 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3310 ExtAddrMode BackupAddrMode = AddrMode;
3311 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003312 // Start a transaction at this point.
3313 // The LHS may match but not the RHS.
3314 // Therefore, we need a higher level restoration point to undo partially
3315 // matched operation.
3316 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3317 TPT.getRestorationPoint();
3318
Sanjay Patelfc580a62015-09-21 23:03:16 +00003319 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3320 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003321 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003322
Chandler Carruthc8925912013-01-05 02:09:22 +00003323 // Restore the old addr mode info.
3324 AddrMode = BackupAddrMode;
3325 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003326 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003327
Chandler Carruthc8925912013-01-05 02:09:22 +00003328 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003329 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3330 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003331 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003332
Chandler Carruthc8925912013-01-05 02:09:22 +00003333 // Otherwise we definitely can't merge the ADD in.
3334 AddrMode = BackupAddrMode;
3335 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003336 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003337 break;
3338 }
3339 //case Instruction::Or:
3340 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3341 //break;
3342 case Instruction::Mul:
3343 case Instruction::Shl: {
3344 // Can only handle X*C and X << C.
3345 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003346 if (!RHS)
3347 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003348 int64_t Scale = RHS->getSExtValue();
3349 if (Opcode == Instruction::Shl)
3350 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003351
Sanjay Patelfc580a62015-09-21 23:03:16 +00003352 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003353 }
3354 case Instruction::GetElementPtr: {
3355 // Scan the GEP. We check it if it contains constant offsets and at most
3356 // one variable offset.
3357 int VariableOperand = -1;
3358 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003359
Chandler Carruthc8925912013-01-05 02:09:22 +00003360 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003361 gep_type_iterator GTI = gep_type_begin(AddrInst);
3362 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003363 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003364 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003365 unsigned Idx =
3366 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3367 ConstantOffset += SL->getElementOffset(Idx);
3368 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003369 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003370 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3371 ConstantOffset += CI->getSExtValue()*TypeSize;
3372 } else if (TypeSize) { // Scales of zero don't do anything.
3373 // We only allow one variable index at the moment.
3374 if (VariableOperand != -1)
3375 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003376
Chandler Carruthc8925912013-01-05 02:09:22 +00003377 // Remember the variable index.
3378 VariableOperand = i;
3379 VariableScale = TypeSize;
3380 }
3381 }
3382 }
Stephen Lin837bba12013-07-15 17:55:02 +00003383
Chandler Carruthc8925912013-01-05 02:09:22 +00003384 // A common case is for the GEP to only do a constant offset. In this case,
3385 // just add it to the disp field and check validity.
3386 if (VariableOperand == -1) {
3387 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003388 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003389 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003390 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003391 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003392 return true;
3393 }
3394 AddrMode.BaseOffs -= ConstantOffset;
3395 return false;
3396 }
3397
3398 // Save the valid addressing mode in case we can't match.
3399 ExtAddrMode BackupAddrMode = AddrMode;
3400 unsigned OldSize = AddrModeInsts.size();
3401
3402 // See if the scale and offset amount is valid for this target.
3403 AddrMode.BaseOffs += ConstantOffset;
3404
3405 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003406 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003407 // If it couldn't be matched, just stuff the value in a register.
3408 if (AddrMode.HasBaseReg) {
3409 AddrMode = BackupAddrMode;
3410 AddrModeInsts.resize(OldSize);
3411 return false;
3412 }
3413 AddrMode.HasBaseReg = true;
3414 AddrMode.BaseReg = AddrInst->getOperand(0);
3415 }
3416
3417 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003418 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003419 Depth)) {
3420 // If it couldn't be matched, try stuffing the base into a register
3421 // instead of matching it, and retrying the match of the scale.
3422 AddrMode = BackupAddrMode;
3423 AddrModeInsts.resize(OldSize);
3424 if (AddrMode.HasBaseReg)
3425 return false;
3426 AddrMode.HasBaseReg = true;
3427 AddrMode.BaseReg = AddrInst->getOperand(0);
3428 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003429 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003430 VariableScale, Depth)) {
3431 // If even that didn't work, bail.
3432 AddrMode = BackupAddrMode;
3433 AddrModeInsts.resize(OldSize);
3434 return false;
3435 }
3436 }
3437
3438 return true;
3439 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003440 case Instruction::SExt:
3441 case Instruction::ZExt: {
3442 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3443 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003444 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003445
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003446 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003447 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003448 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003449 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003450 if (!TPH)
3451 return false;
3452
3453 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3454 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003455 unsigned CreatedInstsCost = 0;
3456 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003457 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003458 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003459 // SExt has been moved away.
3460 // Thus either it will be rematched later in the recursive calls or it is
3461 // gone. Anyway, we must not fold it into the addressing mode at this point.
3462 // E.g.,
3463 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003464 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003465 // addr = gep base, idx
3466 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003467 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003468 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3469 // addr = gep base, op <- match
3470 if (MovedAway)
3471 *MovedAway = true;
3472
3473 assert(PromotedOperand &&
3474 "TypePromotionHelper should have filtered out those cases");
3475
3476 ExtAddrMode BackupAddrMode = AddrMode;
3477 unsigned OldSize = AddrModeInsts.size();
3478
Sanjay Patelfc580a62015-09-21 23:03:16 +00003479 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003480 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003481 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003482 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003483 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003484 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003485 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003486 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003487 AddrMode = BackupAddrMode;
3488 AddrModeInsts.resize(OldSize);
3489 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3490 TPT.rollback(LastKnownGood);
3491 return false;
3492 }
3493 return true;
3494 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003495 }
3496 return false;
3497}
3498
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003499/// If we can, try to add the value of 'Addr' into the current addressing mode.
3500/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3501/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3502/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003503///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003504bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003505 // Start a transaction at this point that we will rollback if the matching
3506 // fails.
3507 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3508 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003509 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3510 // Fold in immediates if legal for the target.
3511 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003512 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003513 return true;
3514 AddrMode.BaseOffs -= CI->getSExtValue();
3515 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3516 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003517 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003518 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003519 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003520 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003521 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003522 }
3523 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3524 ExtAddrMode BackupAddrMode = AddrMode;
3525 unsigned OldSize = AddrModeInsts.size();
3526
3527 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003528 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003529 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003530 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003531 // to check here.
3532 if (MovedAway)
3533 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003534 // Okay, it's possible to fold this. Check to see if it is actually
3535 // *profitable* to do so. We use a simple cost model to avoid increasing
3536 // register pressure too much.
3537 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003538 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003539 AddrModeInsts.push_back(I);
3540 return true;
3541 }
Stephen Lin837bba12013-07-15 17:55:02 +00003542
Chandler Carruthc8925912013-01-05 02:09:22 +00003543 // It isn't profitable to do this, roll back.
3544 //cerr << "NOT FOLDING: " << *I;
3545 AddrMode = BackupAddrMode;
3546 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003547 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003548 }
3549 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003550 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003551 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003552 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003553 } else if (isa<ConstantPointerNull>(Addr)) {
3554 // Null pointer gets folded without affecting the addressing mode.
3555 return true;
3556 }
3557
3558 // Worse case, the target should support [reg] addressing modes. :)
3559 if (!AddrMode.HasBaseReg) {
3560 AddrMode.HasBaseReg = true;
3561 AddrMode.BaseReg = Addr;
3562 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003563 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003564 return true;
3565 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003566 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003567 }
3568
3569 // If the base register is already taken, see if we can do [r+r].
3570 if (AddrMode.Scale == 0) {
3571 AddrMode.Scale = 1;
3572 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003573 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003574 return true;
3575 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003576 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003577 }
3578 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003579 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003580 return false;
3581}
3582
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003583/// Check to see if all uses of OpVal by the specified inline asm call are due
3584/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003585static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003586 const TargetMachine &TM) {
3587 const Function *F = CI->getParent()->getParent();
3588 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3589 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003590 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003591 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3592 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003593 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3594 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003595
Chandler Carruthc8925912013-01-05 02:09:22 +00003596 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003597 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003598
3599 // If this asm operand is our Value*, and if it isn't an indirect memory
3600 // operand, we can't fold it!
3601 if (OpInfo.CallOperandVal == OpVal &&
3602 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3603 !OpInfo.isIndirect))
3604 return false;
3605 }
3606
3607 return true;
3608}
3609
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003610/// Recursively walk all the uses of I until we find a memory use.
3611/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003612/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003613static bool FindAllMemoryUses(
3614 Instruction *I,
3615 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3616 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003617 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003618 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003619 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003620
Chandler Carruthc8925912013-01-05 02:09:22 +00003621 // If this is an obviously unfoldable instruction, bail out.
3622 if (!MightBeFoldableInst(I))
3623 return true;
3624
Philip Reamesac115ed2016-03-09 23:13:12 +00003625 const bool OptSize = I->getFunction()->optForSize();
3626
Chandler Carruthc8925912013-01-05 02:09:22 +00003627 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003628 for (Use &U : I->uses()) {
3629 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003630
Chandler Carruthcdf47882014-03-09 03:16:01 +00003631 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3632 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003633 continue;
3634 }
Stephen Lin837bba12013-07-15 17:55:02 +00003635
Chandler Carruthcdf47882014-03-09 03:16:01 +00003636 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3637 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003638 if (opNo == 0) return true; // Storing addr, not into addr.
3639 MemoryUses.push_back(std::make_pair(SI, opNo));
3640 continue;
3641 }
Stephen Lin837bba12013-07-15 17:55:02 +00003642
Chandler Carruthcdf47882014-03-09 03:16:01 +00003643 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003644 // If this is a cold call, we can sink the addressing calculation into
3645 // the cold path. See optimizeCallInst
3646 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3647 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003648
Chandler Carruthc8925912013-01-05 02:09:22 +00003649 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3650 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003651
Chandler Carruthc8925912013-01-05 02:09:22 +00003652 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003653 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003654 return true;
3655 continue;
3656 }
Stephen Lin837bba12013-07-15 17:55:02 +00003657
Eric Christopher11e4df72015-02-26 22:38:43 +00003658 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003659 return true;
3660 }
3661
3662 return false;
3663}
3664
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003665/// Return true if Val is already known to be live at the use site that we're
3666/// folding it into. If so, there is no cost to include it in the addressing
3667/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3668/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003669bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003670 Value *KnownLive2) {
3671 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003672 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003673 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003674
Chandler Carruthc8925912013-01-05 02:09:22 +00003675 // All values other than instructions and arguments (e.g. constants) are live.
3676 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003677
Chandler Carruthc8925912013-01-05 02:09:22 +00003678 // If Val is a constant sized alloca in the entry block, it is live, this is
3679 // true because it is just a reference to the stack/frame pointer, which is
3680 // live for the whole function.
3681 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3682 if (AI->isStaticAlloca())
3683 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003684
Chandler Carruthc8925912013-01-05 02:09:22 +00003685 // Check to see if this value is already used in the memory instruction's
3686 // block. If so, it's already live into the block at the very least, so we
3687 // can reasonably fold it.
3688 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3689}
3690
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003691/// It is possible for the addressing mode of the machine to fold the specified
3692/// instruction into a load or store that ultimately uses it.
3693/// However, the specified instruction has multiple uses.
3694/// Given this, it may actually increase register pressure to fold it
3695/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003696///
3697/// X = ...
3698/// Y = X+1
3699/// use(Y) -> nonload/store
3700/// Z = Y+1
3701/// load Z
3702///
3703/// In this case, Y has multiple uses, and can be folded into the load of Z
3704/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3705/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3706/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3707/// number of computations either.
3708///
3709/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3710/// X was live across 'load Z' for other reasons, we actually *would* want to
3711/// fold the addressing mode in the Z case. This would make Y die earlier.
3712bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003713isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003714 ExtAddrMode &AMAfter) {
3715 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003716
Chandler Carruthc8925912013-01-05 02:09:22 +00003717 // AMBefore is the addressing mode before this instruction was folded into it,
3718 // and AMAfter is the addressing mode after the instruction was folded. Get
3719 // the set of registers referenced by AMAfter and subtract out those
3720 // referenced by AMBefore: this is the set of values which folding in this
3721 // address extends the lifetime of.
3722 //
3723 // Note that there are only two potential values being referenced here,
3724 // BaseReg and ScaleReg (global addresses are always available, as are any
3725 // folded immediates).
3726 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003727
Chandler Carruthc8925912013-01-05 02:09:22 +00003728 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3729 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003730 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003731 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003732 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003733 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003734
3735 // If folding this instruction (and it's subexprs) didn't extend any live
3736 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003737 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003738 return true;
3739
Philip Reamesac115ed2016-03-09 23:13:12 +00003740 // If all uses of this instruction can have the address mode sunk into them,
3741 // we can remove the addressing mode and effectively trade one live register
3742 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003743 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003744 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3745 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003746 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003747 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003748
Chandler Carruthc8925912013-01-05 02:09:22 +00003749 // Now that we know that all uses of this instruction are part of a chain of
3750 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003751 // into a memory use, loop over each of these memory operation uses and see
3752 // if they could *actually* fold the instruction. The assumption is that
3753 // addressing modes are cheap and that duplicating the computation involved
3754 // many times is worthwhile, even on a fastpath. For sinking candidates
3755 // (i.e. cold call sites), this serves as a way to prevent excessive code
3756 // growth since most architectures have some reasonable small and fast way to
3757 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003758 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3759 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3760 Instruction *User = MemoryUses[i].first;
3761 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003762
Chandler Carruthc8925912013-01-05 02:09:22 +00003763 // Get the access type of this use. If the use isn't a pointer, we don't
3764 // know what it accesses.
3765 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003766 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3767 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003768 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003769 Type *AddressAccessTy = AddrTy->getElementType();
3770 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003771
Chandler Carruthc8925912013-01-05 02:09:22 +00003772 // Do a match against the root of this address, ignoring profitability. This
3773 // will tell us if the addressing mode for the memory operation will
3774 // *actually* cover the shared instruction.
3775 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003776 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3777 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003778 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003779 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003780 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003781 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003782 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003783 (void)Success; assert(Success && "Couldn't select *anything*?");
3784
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003785 // The match was to check the profitability, the changes made are not
3786 // part of the original matcher. Therefore, they should be dropped
3787 // otherwise the original matcher will not present the right state.
3788 TPT.rollback(LastKnownGood);
3789
Chandler Carruthc8925912013-01-05 02:09:22 +00003790 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003791 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003792 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003793
Chandler Carruthc8925912013-01-05 02:09:22 +00003794 MatchedAddrModeInsts.clear();
3795 }
Stephen Lin837bba12013-07-15 17:55:02 +00003796
Chandler Carruthc8925912013-01-05 02:09:22 +00003797 return true;
3798}
3799
3800} // end anonymous namespace
3801
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003802/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003803/// different basic block than BB.
3804static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3805 if (Instruction *I = dyn_cast<Instruction>(V))
3806 return I->getParent() != BB;
3807 return false;
3808}
3809
Philip Reamesac115ed2016-03-09 23:13:12 +00003810/// Sink addressing mode computation immediate before MemoryInst if doing so
3811/// can be done without increasing register pressure. The need for the
3812/// register pressure constraint means this can end up being an all or nothing
3813/// decision for all uses of the same addressing computation.
3814///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003815/// Load and Store Instructions often have addressing modes that can do
3816/// significant amounts of computation. As such, instruction selection will try
3817/// to get the load or store to do as much computation as possible for the
3818/// program. The problem is that isel can only see within a single block. As
3819/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003820///
3821/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003822/// operands. It's also used to sink addressing computations feeding into cold
3823/// call sites into their (cold) basic block.
3824///
3825/// The motivation for handling sinking into cold blocks is that doing so can
3826/// both enable other address mode sinking (by satisfying the register pressure
3827/// constraint above), and reduce register pressure globally (by removing the
3828/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003829bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003830 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003831 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003832
3833 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003834 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003835 SmallVector<Value*, 8> worklist;
3836 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003837 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003838
Owen Anderson8ba5f392010-11-27 08:15:55 +00003839 // Use a worklist to iteratively look through PHI nodes, and ensure that
3840 // the addressing mode obtained from the non-PHI roots of the graph
3841 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003842 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003843 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003844 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003845 SmallVector<Instruction*, 16> AddrModeInsts;
3846 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003847 TypePromotionTransaction TPT;
3848 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3849 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003850 while (!worklist.empty()) {
3851 Value *V = worklist.back();
3852 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003853
Owen Anderson8ba5f392010-11-27 08:15:55 +00003854 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003855 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003856 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003857 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003858 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003859
Owen Anderson8ba5f392010-11-27 08:15:55 +00003860 // For a PHI node, push all of its incoming values.
3861 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003862 for (Value *IncValue : P->incoming_values())
3863 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003864 continue;
3865 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003866
Philip Reamesac115ed2016-03-09 23:13:12 +00003867 // For non-PHIs, determine the addressing mode being computed. Note that
3868 // the result may differ depending on what other uses our candidate
3869 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003870 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003871 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003872 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003873 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003874
3875 // This check is broken into two cases with very similar code to avoid using
3876 // getNumUses() as much as possible. Some values have a lot of uses, so
3877 // calling getNumUses() unconditionally caused a significant compile-time
3878 // regression.
3879 if (!Consensus) {
3880 Consensus = V;
3881 AddrMode = NewAddrMode;
3882 AddrModeInsts = NewAddrModeInsts;
3883 continue;
3884 } else if (NewAddrMode == AddrMode) {
3885 if (!IsNumUsesConsensusValid) {
3886 NumUsesConsensus = Consensus->getNumUses();
3887 IsNumUsesConsensusValid = true;
3888 }
3889
3890 // Ensure that the obtained addressing mode is equivalent to that obtained
3891 // for all other roots of the PHI traversal. Also, when choosing one
3892 // such root as representative, select the one with the most uses in order
3893 // to keep the cost modeling heuristics in AddressingModeMatcher
3894 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003895 unsigned NumUses = V->getNumUses();
3896 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003897 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003898 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003899 AddrModeInsts = NewAddrModeInsts;
3900 }
3901 continue;
3902 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003903
Craig Topperc0196b12014-04-14 00:51:57 +00003904 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003905 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003906 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003907
Owen Anderson8ba5f392010-11-27 08:15:55 +00003908 // If the addressing mode couldn't be determined, or if multiple different
3909 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003910 if (!Consensus) {
3911 TPT.rollback(LastKnownGood);
3912 return false;
3913 }
3914 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003915
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003916 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00003917 if (none_of(AddrModeInsts, [&](Value *V) {
3918 return IsNonLocalValue(V, MemoryInst->getParent());
3919 })) {
David Greene74e2d492010-01-05 01:27:11 +00003920 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003921 return false;
3922 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003923
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003924 // Insert this computation right after this user. Since our caller is
3925 // scanning from the top of the BB to the bottom, reuse of the expr are
3926 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003927 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003928
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003929 // Now that we determined the addressing expression we want to use and know
3930 // that we have to sink it into this block. Check to see if we have already
3931 // done this for some other load/store instr in this block. If so, reuse the
3932 // computation.
3933 Value *&SunkAddr = SunkAddrs[Addr];
3934 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003935 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003936 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003937 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003938 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003939 } else if (AddrSinkUsingGEPs ||
3940 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003941 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3942 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003943 // By default, we use the GEP-based method when AA is used later. This
3944 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3945 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003946 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003947 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003948 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003949
3950 // First, find the pointer.
3951 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3952 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003953 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003954 }
3955
3956 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3957 // We can't add more than one pointer together, nor can we scale a
3958 // pointer (both of which seem meaningless).
3959 if (ResultPtr || AddrMode.Scale != 1)
3960 return false;
3961
3962 ResultPtr = AddrMode.ScaledReg;
3963 AddrMode.Scale = 0;
3964 }
3965
3966 if (AddrMode.BaseGV) {
3967 if (ResultPtr)
3968 return false;
3969
3970 ResultPtr = AddrMode.BaseGV;
3971 }
3972
3973 // If the real base value actually came from an inttoptr, then the matcher
3974 // will look through it and provide only the integer value. In that case,
3975 // use it here.
3976 if (!ResultPtr && AddrMode.BaseReg) {
3977 ResultPtr =
3978 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003979 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003980 } else if (!ResultPtr && AddrMode.Scale == 1) {
3981 ResultPtr =
3982 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3983 AddrMode.Scale = 0;
3984 }
3985
3986 if (!ResultPtr &&
3987 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3988 SunkAddr = Constant::getNullValue(Addr->getType());
3989 } else if (!ResultPtr) {
3990 return false;
3991 } else {
3992 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003993 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3994 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003995
3996 // Start with the base register. Do this first so that subsequent address
3997 // matching finds it last, which will prevent it from trying to match it
3998 // as the scaled value in case it happens to be a mul. That would be
3999 // problematic if we've sunk a different mul for the scale, because then
4000 // we'd end up sinking both muls.
4001 if (AddrMode.BaseReg) {
4002 Value *V = AddrMode.BaseReg;
4003 if (V->getType() != IntPtrTy)
4004 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
4005
4006 ResultIndex = V;
4007 }
4008
4009 // Add the scale value.
4010 if (AddrMode.Scale) {
4011 Value *V = AddrMode.ScaledReg;
4012 if (V->getType() == IntPtrTy) {
4013 // done.
4014 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4015 cast<IntegerType>(V->getType())->getBitWidth()) {
4016 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
4017 } else {
4018 // It is only safe to sign extend the BaseReg if we know that the math
4019 // required to create it did not overflow before we extend it. Since
4020 // the original IR value was tossed in favor of a constant back when
4021 // the AddrMode was created we need to bail out gracefully if widths
4022 // do not match instead of extending it.
4023 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
4024 if (I && (ResultIndex != AddrMode.BaseReg))
4025 I->eraseFromParent();
4026 return false;
4027 }
4028
4029 if (AddrMode.Scale != 1)
4030 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4031 "sunkaddr");
4032 if (ResultIndex)
4033 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
4034 else
4035 ResultIndex = V;
4036 }
4037
4038 // Add in the Base Offset if present.
4039 if (AddrMode.BaseOffs) {
4040 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
4041 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00004042 // We need to add this separately from the scale above to help with
4043 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00004044 if (ResultPtr->getType() != I8PtrTy)
4045 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004046 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004047 }
4048
4049 ResultIndex = V;
4050 }
4051
4052 if (!ResultIndex) {
4053 SunkAddr = ResultPtr;
4054 } else {
4055 if (ResultPtr->getType() != I8PtrTy)
4056 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00004057 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00004058 }
4059
4060 if (SunkAddr->getType() != Addr->getType())
4061 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
4062 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004063 } else {
David Greene74e2d492010-01-05 01:27:11 +00004064 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00004065 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00004066 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00004067 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00004068
4069 // Start with the base register. Do this first so that subsequent address
4070 // matching finds it last, which will prevent it from trying to match it
4071 // as the scaled value in case it happens to be a mul. That would be
4072 // problematic if we've sunk a different mul for the scale, because then
4073 // we'd end up sinking both muls.
4074 if (AddrMode.BaseReg) {
4075 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00004076 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00004077 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004078 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00004079 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00004080 Result = V;
4081 }
4082
4083 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004084 if (AddrMode.Scale) {
4085 Value *V = AddrMode.ScaledReg;
4086 if (V->getType() == IntPtrTy) {
4087 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00004088 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004089 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004090 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
4091 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004092 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004093 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00004094 // It is only safe to sign extend the BaseReg if we know that the math
4095 // required to create it did not overflow before we extend it. Since
4096 // the original IR value was tossed in favor of a constant back when
4097 // the AddrMode was created we need to bail out gracefully if widths
4098 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00004099 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004100 if (I && (Result != AddrMode.BaseReg))
4101 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004102 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004103 }
4104 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004105 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4106 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004107 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004108 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004109 else
4110 Result = V;
4111 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004112
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004113 // Add in the BaseGV if present.
4114 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004115 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004116 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004117 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004118 else
4119 Result = V;
4120 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004121
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004122 // Add in the Base Offset if present.
4123 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004124 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004125 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004126 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004127 else
4128 Result = V;
4129 }
4130
Craig Topperc0196b12014-04-14 00:51:57 +00004131 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004132 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004133 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004134 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004135 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004136
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004137 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004138
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004139 // If we have no uses, recursively delete the value and all dead instructions
4140 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004141 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004142 // This can cause recursive deletion, which can invalidate our iterator.
4143 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004144 Value *CurValue = &*CurInstIterator;
4145 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004146 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004147
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004148 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004149
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004150 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004151 // If the iterator instruction was recursively deleted, start over at the
4152 // start of the block.
4153 CurInstIterator = BB->begin();
4154 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004155 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004156 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004157 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004158 return true;
4159}
4160
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004161/// If there are any memory operands, use OptimizeMemoryInst to sink their
4162/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004163bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004164 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004165
Eric Christopher11e4df72015-02-26 22:38:43 +00004166 const TargetRegisterInfo *TRI =
4167 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004168 TargetLowering::AsmOperandInfoVector TargetConstraints =
4169 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004170 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004171 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4172 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004173
Evan Cheng1da25002008-02-26 02:42:37 +00004174 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004175 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004176
Eli Friedman666bbe32008-02-26 18:37:49 +00004177 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4178 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004179 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004180 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004181 } else if (OpInfo.Type == InlineAsm::isInput)
4182 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004183 }
4184
4185 return MadeChange;
4186}
4187
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004188/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4189/// sign extensions.
4190static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4191 assert(!Inst->use_empty() && "Input must have at least one use");
4192 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4193 bool IsSExt = isa<SExtInst>(FirstUser);
4194 Type *ExtTy = FirstUser->getType();
4195 for (const User *U : Inst->users()) {
4196 const Instruction *UI = cast<Instruction>(U);
4197 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4198 return false;
4199 Type *CurTy = UI->getType();
4200 // Same input and output types: Same instruction after CSE.
4201 if (CurTy == ExtTy)
4202 continue;
4203
4204 // If IsSExt is true, we are in this situation:
4205 // a = Inst
4206 // b = sext ty1 a to ty2
4207 // c = sext ty1 a to ty3
4208 // Assuming ty2 is shorter than ty3, this could be turned into:
4209 // a = Inst
4210 // b = sext ty1 a to ty2
4211 // c = sext ty2 b to ty3
4212 // However, the last sext is not free.
4213 if (IsSExt)
4214 return false;
4215
4216 // This is a ZExt, maybe this is free to extend from one type to another.
4217 // In that case, we would not account for a different use.
4218 Type *NarrowTy;
4219 Type *LargeTy;
4220 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4221 CurTy->getScalarType()->getIntegerBitWidth()) {
4222 NarrowTy = CurTy;
4223 LargeTy = ExtTy;
4224 } else {
4225 NarrowTy = ExtTy;
4226 LargeTy = CurTy;
4227 }
4228
4229 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4230 return false;
4231 }
4232 // All uses are the same or can be derived from one another for free.
4233 return true;
4234}
4235
4236/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4237/// load instruction.
4238/// If an ext(load) can be formed, it is returned via \p LI for the load
4239/// and \p Inst for the extension.
4240/// Otherwise LI == nullptr and Inst == nullptr.
4241/// When some promotion happened, \p TPT contains the proper state to
4242/// revert them.
4243///
4244/// \return true when promoting was necessary to expose the ext(load)
4245/// opportunity, false otherwise.
4246///
4247/// Example:
4248/// \code
4249/// %ld = load i32* %addr
4250/// %add = add nuw i32 %ld, 4
4251/// %zext = zext i32 %add to i64
4252/// \endcode
4253/// =>
4254/// \code
4255/// %ld = load i32* %addr
4256/// %zext = zext i32 %ld to i64
4257/// %add = add nuw i64 %zext, 4
Haicheng Wu8ce2d142017-01-18 21:12:10 +00004258/// \endcode
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004259/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004260bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004261 LoadInst *&LI, Instruction *&Inst,
4262 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004263 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004264 // Iterate over all the extensions to see if one form an ext(load).
4265 for (auto I : Exts) {
4266 // Check if we directly have ext(load).
4267 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4268 Inst = I;
4269 // No promotion happened here.
4270 return false;
4271 }
4272 // Check whether or not we want to do any promotion.
4273 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4274 continue;
4275 // Get the action to perform the promotion.
4276 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004277 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004278 // Check if we can promote.
4279 if (!TPH)
4280 continue;
4281 // Save the current state.
4282 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4283 TPT.getRestorationPoint();
4284 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004285 unsigned NewCreatedInstsCost = 0;
4286 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004287 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004288 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4289 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004290 assert(PromotedVal &&
4291 "TypePromotionHelper should have filtered out those cases");
4292
4293 // We would be able to merge only one extension in a load.
4294 // Therefore, if we have more than 1 new extension we heuristically
4295 // cut this search path, because it means we degrade the code quality.
4296 // With exactly 2, the transformation is neutral, because we will merge
4297 // one extension but leave one. However, we optimistically keep going,
4298 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004299 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
Jun Bum Limb99a06b2017-01-27 17:16:37 +00004300 // FIXME: It would be possible to propagate a negative value instead of
4301 // conservatively ceiling it to 0.
4302 TotalCreatedInstsCost =
4303 std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004304 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004305 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004306 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004307 // The promotion is not profitable, rollback to the previous state.
4308 TPT.rollback(LastKnownGood);
4309 continue;
4310 }
4311 // The promotion is profitable.
4312 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004313 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004314 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004315 // If we have created a new extension, i.e., now we have two
4316 // extensions. We must make sure one of them is merged with
4317 // the load, otherwise we may degrade the code quality.
4318 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4319 // Promotion happened.
4320 return true;
4321 // If this does not help to expose an ext(load) then, rollback.
4322 TPT.rollback(LastKnownGood);
4323 }
4324 // None of the extension can form an ext(load).
4325 LI = nullptr;
4326 Inst = nullptr;
4327 return false;
4328}
4329
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004330/// Move a zext or sext fed by a load into the same basic block as the load,
4331/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4332/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004333/// \p I[in/out] the extension may be modified during the process if some
4334/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004335///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004336bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004337 // ExtLoad formation infrastructure requires TLI to be effective.
4338 if (!TLI)
4339 return false;
4340
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004341 // Try to promote a chain of computation if it allows to form
4342 // an extended load.
4343 TypePromotionTransaction TPT;
4344 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4345 TPT.getRestorationPoint();
4346 SmallVector<Instruction *, 1> Exts;
4347 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004348 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004349 LoadInst *LI = nullptr;
4350 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004351 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004352 if (!LI || !I) {
4353 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4354 "the code must remain the same");
4355 I = OldExt;
4356 return false;
4357 }
Dan Gohman99429a02009-10-16 20:59:35 +00004358
4359 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004360 // Make the cheap checks first if we did not promote.
4361 // If we promoted, we need to check if it is indeed profitable.
4362 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004363 return false;
4364
Mehdi Amini44ede332015-07-09 02:09:04 +00004365 EVT VT = TLI->getValueType(*DL, I->getType());
4366 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004367
Dan Gohman99429a02009-10-16 20:59:35 +00004368 // If the load has other users and the truncate is not free, this probably
4369 // isn't worthwhile.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004370 if (!LI->hasOneUse() &&
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004371 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004372 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4373 I = OldExt;
4374 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004375 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004376 }
Dan Gohman99429a02009-10-16 20:59:35 +00004377
4378 // Check whether the target supports casts folded into loads.
4379 unsigned LType;
4380 if (isa<ZExtInst>(I))
4381 LType = ISD::ZEXTLOAD;
4382 else {
4383 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4384 LType = ISD::SEXTLOAD;
4385 }
Chandler Carruth0f139b42016-11-04 06:54:00 +00004386 if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004387 I = OldExt;
4388 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004389 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004390 }
Dan Gohman99429a02009-10-16 20:59:35 +00004391
4392 // Move the extend into the same block as the load, so that SelectionDAG
4393 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004394 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004395 I->removeFromParent();
4396 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004397 // CGP does not check if the zext would be speculatively executed when moved
4398 // to the same basic block as the load. Preserving its original location would
4399 // pessimize the debugging experience, as well as negatively impact the
4400 // quality of sample pgo. We don't want to use "line 0" as that has a
4401 // size cost in the line-table section and logically the zext can be seen as
4402 // part of the load. Therefore we conservatively reuse the same debug location
4403 // for the load and the zext.
4404 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004405 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004406 return true;
4407}
4408
Sanjay Patelfc580a62015-09-21 23:03:16 +00004409bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004410 BasicBlock *DefBB = I->getParent();
4411
Bob Wilsonff714f92010-09-21 21:44:14 +00004412 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004413 // other uses of the source with result of extension.
4414 Value *Src = I->getOperand(0);
4415 if (Src->hasOneUse())
4416 return false;
4417
Evan Cheng2011df42007-12-13 07:50:36 +00004418 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004419 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004420 return false;
4421
Evan Cheng7bc89422007-12-12 00:51:06 +00004422 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004423 // this block.
4424 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004425 return false;
4426
Evan Chengd3d80172007-12-05 23:58:20 +00004427 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004428 for (User *U : I->users()) {
4429 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004430
4431 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004432 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004433 if (UserBB == DefBB) continue;
4434 DefIsLiveOut = true;
4435 break;
4436 }
4437 if (!DefIsLiveOut)
4438 return false;
4439
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004440 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004441 for (User *U : Src->users()) {
4442 Instruction *UI = cast<Instruction>(U);
4443 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004444 if (UserBB == DefBB) continue;
4445 // Be conservative. We don't want this xform to end up introducing
4446 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004447 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004448 return false;
4449 }
4450
Evan Chengd3d80172007-12-05 23:58:20 +00004451 // InsertedTruncs - Only insert one trunc in each block once.
4452 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4453
4454 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004455 for (Use &U : Src->uses()) {
4456 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004457
4458 // Figure out which BB this ext is used in.
4459 BasicBlock *UserBB = User->getParent();
4460 if (UserBB == DefBB) continue;
4461
4462 // Both src and def are live in this block. Rewrite the use.
4463 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4464
4465 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004466 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004467 assert(InsertPt != UserBB->end());
4468 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004469 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004470 }
4471
4472 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004473 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004474 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004475 MadeChange = true;
4476 }
4477
4478 return MadeChange;
4479}
4480
Geoff Berry5256fca2015-11-20 22:34:39 +00004481// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4482// just after the load if the target can fold this into one extload instruction,
4483// with the hope of eliminating some of the other later "and" instructions using
4484// the loaded value. "and"s that are made trivially redundant by the insertion
4485// of the new "and" are removed by this function, while others (e.g. those whose
4486// path from the load goes through a phi) are left for isel to potentially
4487// remove.
4488//
4489// For example:
4490//
4491// b0:
4492// x = load i32
4493// ...
4494// b1:
4495// y = and x, 0xff
4496// z = use y
4497//
4498// becomes:
4499//
4500// b0:
4501// x = load i32
4502// x' = and x, 0xff
4503// ...
4504// b1:
4505// z = use x'
4506//
4507// whereas:
4508//
4509// b0:
4510// x1 = load i32
4511// ...
4512// b1:
4513// x2 = load i32
4514// ...
4515// b2:
4516// x = phi x1, x2
4517// y = and x, 0xff
4518//
4519// becomes (after a call to optimizeLoadExt for each load):
4520//
4521// b0:
4522// x1 = load i32
4523// x1' = and x1, 0xff
4524// ...
4525// b1:
4526// x2 = load i32
4527// x2' = and x2, 0xff
4528// ...
4529// b2:
4530// x = phi x1', x2'
4531// y = and x, 0xff
4532//
4533
4534bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4535
4536 if (!Load->isSimple() ||
4537 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4538 return false;
4539
4540 // Skip loads we've already transformed or have no reason to transform.
4541 if (Load->hasOneUse()) {
4542 User *LoadUser = *Load->user_begin();
4543 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4544 !dyn_cast<PHINode>(LoadUser))
4545 return false;
4546 }
4547
4548 // Look at all uses of Load, looking through phis, to determine how many bits
4549 // of the loaded value are needed.
4550 SmallVector<Instruction *, 8> WorkList;
4551 SmallPtrSet<Instruction *, 16> Visited;
4552 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4553 for (auto *U : Load->users())
4554 WorkList.push_back(cast<Instruction>(U));
4555
4556 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4557 unsigned BitWidth = LoadResultVT.getSizeInBits();
4558 APInt DemandBits(BitWidth, 0);
4559 APInt WidestAndBits(BitWidth, 0);
4560
4561 while (!WorkList.empty()) {
4562 Instruction *I = WorkList.back();
4563 WorkList.pop_back();
4564
4565 // Break use-def graph loops.
4566 if (!Visited.insert(I).second)
4567 continue;
4568
4569 // For a PHI node, push all of its users.
4570 if (auto *Phi = dyn_cast<PHINode>(I)) {
4571 for (auto *U : Phi->users())
4572 WorkList.push_back(cast<Instruction>(U));
4573 continue;
4574 }
4575
4576 switch (I->getOpcode()) {
4577 case llvm::Instruction::And: {
4578 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4579 if (!AndC)
4580 return false;
4581 APInt AndBits = AndC->getValue();
4582 DemandBits |= AndBits;
4583 // Keep track of the widest and mask we see.
4584 if (AndBits.ugt(WidestAndBits))
4585 WidestAndBits = AndBits;
4586 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4587 AndsToMaybeRemove.push_back(I);
4588 break;
4589 }
4590
4591 case llvm::Instruction::Shl: {
4592 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4593 if (!ShlC)
4594 return false;
4595 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4596 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4597 DemandBits |= ShlDemandBits;
4598 break;
4599 }
4600
4601 case llvm::Instruction::Trunc: {
4602 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4603 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4604 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4605 DemandBits |= TruncBits;
4606 break;
4607 }
4608
4609 default:
4610 return false;
4611 }
4612 }
4613
4614 uint32_t ActiveBits = DemandBits.getActiveBits();
4615 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4616 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4617 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4618 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4619 // followed by an AND.
4620 // TODO: Look into removing this restriction by fixing backends to either
4621 // return false for isLoadExtLegal for i1 or have them select this pattern to
4622 // a single instruction.
4623 //
4624 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4625 // mask, since these are the only ands that will be removed by isel.
4626 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4627 WidestAndBits != DemandBits)
4628 return false;
4629
4630 LLVMContext &Ctx = Load->getType()->getContext();
4631 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4632 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4633
4634 // Reject cases that won't be matched as extloads.
4635 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4636 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4637 return false;
4638
4639 IRBuilder<> Builder(Load->getNextNode());
4640 auto *NewAnd = dyn_cast<Instruction>(
4641 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4642
4643 // Replace all uses of load with new and (except for the use of load in the
4644 // new and itself).
4645 Load->replaceAllUsesWith(NewAnd);
4646 NewAnd->setOperand(0, Load);
4647
4648 // Remove any and instructions that are now redundant.
4649 for (auto *And : AndsToMaybeRemove)
4650 // Check that the and mask is the same as the one we decided to put on the
4651 // new and.
4652 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4653 And->replaceAllUsesWith(NewAnd);
4654 if (&*CurInstIterator == And)
4655 CurInstIterator = std::next(And->getIterator());
4656 And->eraseFromParent();
4657 ++NumAndUses;
4658 }
4659
4660 ++NumAndsAdded;
4661 return true;
4662}
4663
Sanjay Patel69a50a12015-10-19 21:59:12 +00004664/// Check if V (an operand of a select instruction) is an expensive instruction
4665/// that is only used once.
4666static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4667 auto *I = dyn_cast<Instruction>(V);
4668 // If it's safe to speculatively execute, then it should not have side
4669 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004670 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4671 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004672}
4673
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004674/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004675static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004676 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004677 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004678 // If even a predictable select is cheap, then a branch can't be cheaper.
4679 if (!TLI->isPredictableSelectExpensive())
4680 return false;
4681
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004682 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004683 // whether a select is better represented as a branch.
4684
4685 // If metadata tells us that the select condition is obviously predictable,
4686 // then we want to replace the select with a branch.
4687 uint64_t TrueWeight, FalseWeight;
4688 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4689 uint64_t Max = std::max(TrueWeight, FalseWeight);
4690 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004691 if (Sum != 0) {
4692 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4693 if (Probability > TLI->getPredictableBranchThreshold())
4694 return true;
4695 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004696 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004697
4698 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4699
Sanjay Patel4e652762015-09-28 22:14:51 +00004700 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4701 // comparison condition. If the compare has more than one use, there's
4702 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004703 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004704 return false;
4705
Sanjay Patel69a50a12015-10-19 21:59:12 +00004706 // If either operand of the select is expensive and only needed on one side
4707 // of the select, we should form a branch.
4708 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4709 sinkSelectOperand(TTI, SI->getFalseValue()))
4710 return true;
4711
4712 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004713}
4714
Dehao Chen9bbb9412016-09-12 20:23:28 +00004715/// If \p isTrue is true, return the true value of \p SI, otherwise return
4716/// false value of \p SI. If the true/false value of \p SI is defined by any
4717/// select instructions in \p Selects, look through the defining select
4718/// instruction until the true/false value is not defined in \p Selects.
4719static Value *getTrueOrFalseValue(
4720 SelectInst *SI, bool isTrue,
4721 const SmallPtrSet<const Instruction *, 2> &Selects) {
4722 Value *V;
4723
4724 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4725 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004726 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004727 "The condition of DefSI does not match with SI");
4728 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4729 }
4730 return V;
4731}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004732
Nadav Rotem9d832022012-09-02 12:10:19 +00004733/// If we have a SelectInst that will likely profit from branch prediction,
4734/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004735bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004736 // Find all consecutive select instructions that share the same condition.
4737 SmallVector<SelectInst *, 2> ASI;
4738 ASI.push_back(SI);
4739 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4740 It != SI->getParent()->end(); ++It) {
4741 SelectInst *I = dyn_cast<SelectInst>(&*It);
4742 if (I && SI->getCondition() == I->getCondition()) {
4743 ASI.push_back(I);
4744 } else {
4745 break;
4746 }
4747 }
4748
4749 SelectInst *LastSI = ASI.back();
4750 // Increment the current iterator to skip all the rest of select instructions
4751 // because they will be either "not lowered" or "all lowered" to branch.
4752 CurInstIterator = std::next(LastSI->getIterator());
4753
Nadav Rotem9d832022012-09-02 12:10:19 +00004754 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4755
4756 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004757 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4758 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004759 return false;
4760
Nadav Rotem9d832022012-09-02 12:10:19 +00004761 TargetLowering::SelectSupportKind SelectKind;
4762 if (VectorCond)
4763 SelectKind = TargetLowering::VectorMaskSelect;
4764 else if (SI->getType()->isVectorTy())
4765 SelectKind = TargetLowering::ScalarCondVectorVal;
4766 else
4767 SelectKind = TargetLowering::ScalarValSelect;
4768
Sanjay Pateld66607b2016-04-26 17:11:17 +00004769 if (TLI->isSelectSupported(SelectKind) &&
4770 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4771 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004772
4773 ModifiedDT = true;
4774
Sanjay Patel69a50a12015-10-19 21:59:12 +00004775 // Transform a sequence like this:
4776 // start:
4777 // %cmp = cmp uge i32 %a, %b
4778 // %sel = select i1 %cmp, i32 %c, i32 %d
4779 //
4780 // Into:
4781 // start:
4782 // %cmp = cmp uge i32 %a, %b
4783 // br i1 %cmp, label %select.true, label %select.false
4784 // select.true:
4785 // br label %select.end
4786 // select.false:
4787 // br label %select.end
4788 // select.end:
4789 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4790 //
4791 // In addition, we may sink instructions that produce %c or %d from
4792 // the entry block into the destination(s) of the new branch.
4793 // If the true or false blocks do not contain a sunken instruction, that
4794 // block and its branch may be optimized away. In that case, one side of the
4795 // first branch will point directly to select.end, and the corresponding PHI
4796 // predecessor block will be the start block.
4797
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004798 // First, we split the block containing the select into 2 blocks.
4799 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004800 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004801 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004802
Sanjay Patel69a50a12015-10-19 21:59:12 +00004803 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004804 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004805
4806 // These are the new basic blocks for the conditional branch.
4807 // At least one will become an actual new basic block.
4808 BasicBlock *TrueBlock = nullptr;
4809 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004810 BranchInst *TrueBranch = nullptr;
4811 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004812
4813 // Sink expensive instructions into the conditional blocks to avoid executing
4814 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004815 for (SelectInst *SI : ASI) {
4816 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4817 if (TrueBlock == nullptr) {
4818 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4819 EndBlock->getParent(), EndBlock);
4820 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4821 }
4822 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4823 TrueInst->moveBefore(TrueBranch);
4824 }
4825 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4826 if (FalseBlock == nullptr) {
4827 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4828 EndBlock->getParent(), EndBlock);
4829 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4830 }
4831 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4832 FalseInst->moveBefore(FalseBranch);
4833 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004834 }
4835
4836 // If there was nothing to sink, then arbitrarily choose the 'false' side
4837 // for a new input value to the PHI.
4838 if (TrueBlock == FalseBlock) {
4839 assert(TrueBlock == nullptr &&
4840 "Unexpected basic block transform while optimizing select");
4841
4842 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4843 EndBlock->getParent(), EndBlock);
4844 BranchInst::Create(EndBlock, FalseBlock);
4845 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004846
4847 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004848 // If we did not create a new block for one of the 'true' or 'false' paths
4849 // of the condition, it means that side of the branch goes to the end block
4850 // directly and the path originates from the start block from the point of
4851 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004852 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004853 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004854 TT = EndBlock;
4855 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004856 TrueBlock = StartBlock;
4857 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004858 TT = TrueBlock;
4859 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004860 FalseBlock = StartBlock;
4861 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004862 TT = TrueBlock;
4863 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004864 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004865 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004866
Dehao Chen9bbb9412016-09-12 20:23:28 +00004867 SmallPtrSet<const Instruction *, 2> INS;
4868 INS.insert(ASI.begin(), ASI.end());
4869 // Use reverse iterator because later select may use the value of the
4870 // earlier select, and we need to propagate value through earlier select
4871 // to get the PHI operand.
4872 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4873 SelectInst *SI = *It;
4874 // The select itself is replaced with a PHI Node.
4875 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4876 PN->takeName(SI);
4877 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4878 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004879
Dehao Chen9bbb9412016-09-12 20:23:28 +00004880 SI->replaceAllUsesWith(PN);
4881 SI->eraseFromParent();
4882 INS.erase(SI);
4883 ++NumSelectsExpanded;
4884 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004885
4886 // Instruct OptimizeBlock to skip to the next block.
4887 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004888 return true;
4889}
4890
Benjamin Kramer573ff362014-03-01 17:24:40 +00004891static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004892 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4893 int SplatElem = -1;
4894 for (unsigned i = 0; i < Mask.size(); ++i) {
4895 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4896 return false;
4897 SplatElem = Mask[i];
4898 }
4899
4900 return true;
4901}
4902
4903/// Some targets have expensive vector shifts if the lanes aren't all the same
4904/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4905/// it's often worth sinking a shufflevector splat down to its use so that
4906/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004907bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004908 BasicBlock *DefBB = SVI->getParent();
4909
4910 // Only do this xform if variable vector shifts are particularly expensive.
4911 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4912 return false;
4913
4914 // We only expect better codegen by sinking a shuffle if we can recognise a
4915 // constant splat.
4916 if (!isBroadcastShuffle(SVI))
4917 return false;
4918
4919 // InsertedShuffles - Only insert a shuffle in each block once.
4920 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4921
4922 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004923 for (User *U : SVI->users()) {
4924 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004925
4926 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004927 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004928 if (UserBB == DefBB) continue;
4929
4930 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004931 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004932
4933 // Everything checks out, sink the shuffle if the user's block doesn't
4934 // already have a copy.
4935 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4936
4937 if (!InsertedShuffle) {
4938 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004939 assert(InsertPt != UserBB->end());
4940 InsertedShuffle =
4941 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4942 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004943 }
4944
Chandler Carruthcdf47882014-03-09 03:16:01 +00004945 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004946 MadeChange = true;
4947 }
4948
4949 // If we removed all uses, nuke the shuffle.
4950 if (SVI->use_empty()) {
4951 SVI->eraseFromParent();
4952 MadeChange = true;
4953 }
4954
4955 return MadeChange;
4956}
4957
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004958bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4959 if (!TLI || !DL)
4960 return false;
4961
4962 Value *Cond = SI->getCondition();
4963 Type *OldType = Cond->getType();
4964 LLVMContext &Context = Cond->getContext();
4965 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4966 unsigned RegWidth = RegType.getSizeInBits();
4967
4968 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4969 return false;
4970
4971 // If the register width is greater than the type width, expand the condition
4972 // of the switch instruction and each case constant to the width of the
4973 // register. By widening the type of the switch condition, subsequent
4974 // comparisons (for case comparisons) will not need to be extended to the
4975 // preferred register width, so we will potentially eliminate N-1 extends,
4976 // where N is the number of cases in the switch.
4977 auto *NewType = Type::getIntNTy(Context, RegWidth);
4978
4979 // Zero-extend the switch condition and case constants unless the switch
4980 // condition is a function argument that is already being sign-extended.
4981 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4982 // everything instead.
4983 Instruction::CastOps ExtType = Instruction::ZExt;
4984 if (auto *Arg = dyn_cast<Argument>(Cond))
4985 if (Arg->hasSExtAttr())
4986 ExtType = Instruction::SExt;
4987
4988 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4989 ExtInst->insertBefore(SI);
4990 SI->setCondition(ExtInst);
4991 for (SwitchInst::CaseIt Case : SI->cases()) {
4992 APInt NarrowConst = Case.getCaseValue()->getValue();
4993 APInt WideConst = (ExtType == Instruction::ZExt) ?
4994 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4995 Case.setValue(ConstantInt::get(Context, WideConst));
4996 }
4997
4998 return true;
4999}
5000
Quentin Colombetc32615d2014-10-31 17:52:53 +00005001namespace {
5002/// \brief Helper class to promote a scalar operation to a vector one.
5003/// This class is used to move downward extractelement transition.
5004/// E.g.,
5005/// a = vector_op <2 x i32>
5006/// b = extractelement <2 x i32> a, i32 0
5007/// c = scalar_op b
5008/// store c
5009///
5010/// =>
5011/// a = vector_op <2 x i32>
5012/// c = vector_op a (equivalent to scalar_op on the related lane)
5013/// * d = extractelement <2 x i32> c, i32 0
5014/// * store d
5015/// Assuming both extractelement and store can be combine, we get rid of the
5016/// transition.
5017class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00005018 /// DataLayout associated with the current module.
5019 const DataLayout &DL;
5020
Quentin Colombetc32615d2014-10-31 17:52:53 +00005021 /// Used to perform some checks on the legality of vector operations.
5022 const TargetLowering &TLI;
5023
5024 /// Used to estimated the cost of the promoted chain.
5025 const TargetTransformInfo &TTI;
5026
5027 /// The transition being moved downwards.
5028 Instruction *Transition;
5029 /// The sequence of instructions to be promoted.
5030 SmallVector<Instruction *, 4> InstsToBePromoted;
5031 /// Cost of combining a store and an extract.
5032 unsigned StoreExtractCombineCost;
5033 /// Instruction that will be combined with the transition.
5034 Instruction *CombineInst;
5035
5036 /// \brief The instruction that represents the current end of the transition.
5037 /// Since we are faking the promotion until we reach the end of the chain
5038 /// of computation, we need a way to get the current end of the transition.
5039 Instruction *getEndOfTransition() const {
5040 if (InstsToBePromoted.empty())
5041 return Transition;
5042 return InstsToBePromoted.back();
5043 }
5044
5045 /// \brief Return the index of the original value in the transition.
5046 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
5047 /// c, is at index 0.
5048 unsigned getTransitionOriginalValueIdx() const {
5049 assert(isa<ExtractElementInst>(Transition) &&
5050 "Other kind of transitions are not supported yet");
5051 return 0;
5052 }
5053
5054 /// \brief Return the index of the index in the transition.
5055 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
5056 /// is at index 1.
5057 unsigned getTransitionIdx() const {
5058 assert(isa<ExtractElementInst>(Transition) &&
5059 "Other kind of transitions are not supported yet");
5060 return 1;
5061 }
5062
5063 /// \brief Get the type of the transition.
5064 /// This is the type of the original value.
5065 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
5066 /// transition is <2 x i32>.
5067 Type *getTransitionType() const {
5068 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
5069 }
5070
5071 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
5072 /// I.e., we have the following sequence:
5073 /// Def = Transition <ty1> a to <ty2>
5074 /// b = ToBePromoted <ty2> Def, ...
5075 /// =>
5076 /// b = ToBePromoted <ty1> a, ...
5077 /// Def = Transition <ty1> ToBePromoted to <ty2>
5078 void promoteImpl(Instruction *ToBePromoted);
5079
5080 /// \brief Check whether or not it is profitable to promote all the
5081 /// instructions enqueued to be promoted.
5082 bool isProfitableToPromote() {
5083 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
5084 unsigned Index = isa<ConstantInt>(ValIdx)
5085 ? cast<ConstantInt>(ValIdx)->getZExtValue()
5086 : -1;
5087 Type *PromotedType = getTransitionType();
5088
5089 StoreInst *ST = cast<StoreInst>(CombineInst);
5090 unsigned AS = ST->getPointerAddressSpace();
5091 unsigned Align = ST->getAlignment();
5092 // Check if this store is supported.
5093 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00005094 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
5095 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005096 // If this is not supported, there is no way we can combine
5097 // the extract with the store.
5098 return false;
5099 }
5100
5101 // The scalar chain of computation has to pay for the transition
5102 // scalar to vector.
5103 // The vector chain has to account for the combining cost.
5104 uint64_t ScalarCost =
5105 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5106 uint64_t VectorCost = StoreExtractCombineCost;
5107 for (const auto &Inst : InstsToBePromoted) {
5108 // Compute the cost.
5109 // By construction, all instructions being promoted are arithmetic ones.
5110 // Moreover, one argument is a constant that can be viewed as a splat
5111 // constant.
5112 Value *Arg0 = Inst->getOperand(0);
5113 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5114 isa<ConstantFP>(Arg0);
5115 TargetTransformInfo::OperandValueKind Arg0OVK =
5116 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5117 : TargetTransformInfo::OK_AnyValue;
5118 TargetTransformInfo::OperandValueKind Arg1OVK =
5119 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5120 : TargetTransformInfo::OK_AnyValue;
5121 ScalarCost += TTI.getArithmeticInstrCost(
5122 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5123 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5124 Arg0OVK, Arg1OVK);
5125 }
5126 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5127 << ScalarCost << "\nVector: " << VectorCost << '\n');
5128 return ScalarCost > VectorCost;
5129 }
5130
5131 /// \brief Generate a constant vector with \p Val with the same
5132 /// number of elements as the transition.
5133 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005134 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005135 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5136 /// otherwise we generate a vector with as many undef as possible:
5137 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5138 /// used at the index of the extract.
5139 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5140 unsigned ExtractIdx = UINT_MAX;
5141 if (!UseSplat) {
5142 // If we cannot determine where the constant must be, we have to
5143 // use a splat constant.
5144 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5145 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5146 ExtractIdx = CstVal->getSExtValue();
5147 else
5148 UseSplat = true;
5149 }
5150
5151 unsigned End = getTransitionType()->getVectorNumElements();
5152 if (UseSplat)
5153 return ConstantVector::getSplat(End, Val);
5154
5155 SmallVector<Constant *, 4> ConstVec;
5156 UndefValue *UndefVal = UndefValue::get(Val->getType());
5157 for (unsigned Idx = 0; Idx != End; ++Idx) {
5158 if (Idx == ExtractIdx)
5159 ConstVec.push_back(Val);
5160 else
5161 ConstVec.push_back(UndefVal);
5162 }
5163 return ConstantVector::get(ConstVec);
5164 }
5165
5166 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5167 /// in \p Use can trigger undefined behavior.
5168 static bool canCauseUndefinedBehavior(const Instruction *Use,
5169 unsigned OperandIdx) {
5170 // This is not safe to introduce undef when the operand is on
5171 // the right hand side of a division-like instruction.
5172 if (OperandIdx != 1)
5173 return false;
5174 switch (Use->getOpcode()) {
5175 default:
5176 return false;
5177 case Instruction::SDiv:
5178 case Instruction::UDiv:
5179 case Instruction::SRem:
5180 case Instruction::URem:
5181 return true;
5182 case Instruction::FDiv:
5183 case Instruction::FRem:
5184 return !Use->hasNoNaNs();
5185 }
5186 llvm_unreachable(nullptr);
5187 }
5188
5189public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005190 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5191 const TargetTransformInfo &TTI, Instruction *Transition,
5192 unsigned CombineCost)
5193 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005194 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5195 assert(Transition && "Do not know how to promote null");
5196 }
5197
5198 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5199 bool canPromote(const Instruction *ToBePromoted) const {
5200 // We could support CastInst too.
5201 return isa<BinaryOperator>(ToBePromoted);
5202 }
5203
5204 /// \brief Check if it is profitable to promote \p ToBePromoted
5205 /// by moving downward the transition through.
5206 bool shouldPromote(const Instruction *ToBePromoted) const {
5207 // Promote only if all the operands can be statically expanded.
5208 // Indeed, we do not want to introduce any new kind of transitions.
5209 for (const Use &U : ToBePromoted->operands()) {
5210 const Value *Val = U.get();
5211 if (Val == getEndOfTransition()) {
5212 // If the use is a division and the transition is on the rhs,
5213 // we cannot promote the operation, otherwise we may create a
5214 // division by zero.
5215 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5216 return false;
5217 continue;
5218 }
5219 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5220 !isa<ConstantFP>(Val))
5221 return false;
5222 }
5223 // Check that the resulting operation is legal.
5224 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5225 if (!ISDOpcode)
5226 return false;
5227 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005228 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005229 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005230 }
5231
5232 /// \brief Check whether or not \p Use can be combined
5233 /// with the transition.
5234 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5235 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5236
5237 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5238 void enqueueForPromotion(Instruction *ToBePromoted) {
5239 InstsToBePromoted.push_back(ToBePromoted);
5240 }
5241
5242 /// \brief Set the instruction that will be combined with the transition.
5243 void recordCombineInstruction(Instruction *ToBeCombined) {
5244 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5245 CombineInst = ToBeCombined;
5246 }
5247
5248 /// \brief Promote all the instructions enqueued for promotion if it is
5249 /// is profitable.
5250 /// \return True if the promotion happened, false otherwise.
5251 bool promote() {
5252 // Check if there is something to promote.
5253 // Right now, if we do not have anything to combine with,
5254 // we assume the promotion is not profitable.
5255 if (InstsToBePromoted.empty() || !CombineInst)
5256 return false;
5257
5258 // Check cost.
5259 if (!StressStoreExtract && !isProfitableToPromote())
5260 return false;
5261
5262 // Promote.
5263 for (auto &ToBePromoted : InstsToBePromoted)
5264 promoteImpl(ToBePromoted);
5265 InstsToBePromoted.clear();
5266 return true;
5267 }
5268};
5269} // End of anonymous namespace.
5270
5271void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5272 // At this point, we know that all the operands of ToBePromoted but Def
5273 // can be statically promoted.
5274 // For Def, we need to use its parameter in ToBePromoted:
5275 // b = ToBePromoted ty1 a
5276 // Def = Transition ty1 b to ty2
5277 // Move the transition down.
5278 // 1. Replace all uses of the promoted operation by the transition.
5279 // = ... b => = ... Def.
5280 assert(ToBePromoted->getType() == Transition->getType() &&
5281 "The type of the result of the transition does not match "
5282 "the final type");
5283 ToBePromoted->replaceAllUsesWith(Transition);
5284 // 2. Update the type of the uses.
5285 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5286 Type *TransitionTy = getTransitionType();
5287 ToBePromoted->mutateType(TransitionTy);
5288 // 3. Update all the operands of the promoted operation with promoted
5289 // operands.
5290 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5291 for (Use &U : ToBePromoted->operands()) {
5292 Value *Val = U.get();
5293 Value *NewVal = nullptr;
5294 if (Val == Transition)
5295 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5296 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5297 isa<ConstantFP>(Val)) {
5298 // Use a splat constant if it is not safe to use undef.
5299 NewVal = getConstantVector(
5300 cast<Constant>(Val),
5301 isa<UndefValue>(Val) ||
5302 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5303 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005304 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5305 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005306 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5307 }
5308 Transition->removeFromParent();
5309 Transition->insertAfter(ToBePromoted);
5310 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5311}
5312
5313/// Some targets can do store(extractelement) with one instruction.
5314/// Try to push the extractelement towards the stores when the target
5315/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005316bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005317 unsigned CombineCost = UINT_MAX;
5318 if (DisableStoreExtract || !TLI ||
5319 (!StressStoreExtract &&
5320 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5321 Inst->getOperand(1), CombineCost)))
5322 return false;
5323
5324 // At this point we know that Inst is a vector to scalar transition.
5325 // Try to move it down the def-use chain, until:
5326 // - We can combine the transition with its single use
5327 // => we got rid of the transition.
5328 // - We escape the current basic block
5329 // => we would need to check that we are moving it at a cheaper place and
5330 // we do not do that for now.
5331 BasicBlock *Parent = Inst->getParent();
5332 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005333 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005334 // If the transition has more than one use, assume this is not going to be
5335 // beneficial.
5336 while (Inst->hasOneUse()) {
5337 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5338 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5339
5340 if (ToBePromoted->getParent() != Parent) {
5341 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5342 << ToBePromoted->getParent()->getName()
5343 << ") than the transition (" << Parent->getName() << ").\n");
5344 return false;
5345 }
5346
5347 if (VPH.canCombine(ToBePromoted)) {
5348 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5349 << "will be combined with: " << *ToBePromoted << '\n');
5350 VPH.recordCombineInstruction(ToBePromoted);
5351 bool Changed = VPH.promote();
5352 NumStoreExtractExposed += Changed;
5353 return Changed;
5354 }
5355
5356 DEBUG(dbgs() << "Try promoting.\n");
5357 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5358 return false;
5359
5360 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5361
5362 VPH.enqueueForPromotion(ToBePromoted);
5363 Inst = ToBePromoted;
5364 }
5365 return false;
5366}
5367
Wei Mia2f0b592016-12-22 19:44:45 +00005368/// For the instruction sequence of store below, F and I values
5369/// are bundled together as an i64 value before being stored into memory.
5370/// Sometimes it is more efficent to generate separate stores for F and I,
5371/// which can remove the bitwise instructions or sink them to colder places.
5372///
5373/// (store (or (zext (bitcast F to i32) to i64),
5374/// (shl (zext I to i64), 32)), addr) -->
5375/// (store F, addr) and (store I, addr+4)
5376///
5377/// Similarly, splitting for other merged store can also be beneficial, like:
5378/// For pair of {i32, i32}, i64 store --> two i32 stores.
5379/// For pair of {i32, i16}, i64 store --> two i32 stores.
5380/// For pair of {i16, i16}, i32 store --> two i16 stores.
5381/// For pair of {i16, i8}, i32 store --> two i16 stores.
5382/// For pair of {i8, i8}, i16 store --> two i8 stores.
5383///
5384/// We allow each target to determine specifically which kind of splitting is
5385/// supported.
5386///
5387/// The store patterns are commonly seen from the simple code snippet below
5388/// if only std::make_pair(...) is sroa transformed before inlined into hoo.
5389/// void goo(const std::pair<int, float> &);
5390/// hoo() {
5391/// ...
5392/// goo(std::make_pair(tmp, ftmp));
5393/// ...
5394/// }
5395///
5396/// Although we already have similar splitting in DAG Combine, we duplicate
5397/// it in CodeGenPrepare to catch the case in which pattern is across
5398/// multiple BBs. The logic in DAG Combine is kept to catch case generated
5399/// during code expansion.
5400static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
5401 const TargetLowering &TLI) {
5402 // Handle simple but common cases only.
5403 Type *StoreType = SI.getValueOperand()->getType();
5404 if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
5405 DL.getTypeSizeInBits(StoreType) == 0)
5406 return false;
5407
5408 unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
5409 Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
5410 if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
5411 DL.getTypeSizeInBits(SplitStoreType))
5412 return false;
5413
5414 // Match the following patterns:
5415 // (store (or (zext LValue to i64),
5416 // (shl (zext HValue to i64), 32)), HalfValBitSize)
5417 // or
5418 // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
5419 // (zext LValue to i64),
5420 // Expect both operands of OR and the first operand of SHL have only
5421 // one use.
5422 Value *LValue, *HValue;
5423 if (!match(SI.getValueOperand(),
5424 m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
5425 m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
5426 m_SpecificInt(HalfValBitSize))))))
5427 return false;
5428
5429 // Check LValue and HValue are int with size less or equal than 32.
5430 if (!LValue->getType()->isIntegerTy() ||
5431 DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
5432 !HValue->getType()->isIntegerTy() ||
5433 DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
5434 return false;
5435
5436 // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
5437 // as the input of target query.
5438 auto *LBC = dyn_cast<BitCastInst>(LValue);
5439 auto *HBC = dyn_cast<BitCastInst>(HValue);
5440 EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
5441 : EVT::getEVT(LValue->getType());
5442 EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
5443 : EVT::getEVT(HValue->getType());
5444 if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
5445 return false;
5446
5447 // Start to split store.
5448 IRBuilder<> Builder(SI.getContext());
5449 Builder.SetInsertPoint(&SI);
5450
5451 // If LValue/HValue is a bitcast in another BB, create a new one in current
5452 // BB so it may be merged with the splitted stores by dag combiner.
5453 if (LBC && LBC->getParent() != SI.getParent())
5454 LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
5455 if (HBC && HBC->getParent() != SI.getParent())
5456 HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
5457
5458 auto CreateSplitStore = [&](Value *V, bool Upper) {
5459 V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
5460 Value *Addr = Builder.CreateBitCast(
5461 SI.getOperand(1),
5462 SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
5463 if (Upper)
5464 Addr = Builder.CreateGEP(
5465 SplitStoreType, Addr,
5466 ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
5467 Builder.CreateAlignedStore(
5468 V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
5469 };
5470
5471 CreateSplitStore(LValue, false);
5472 CreateSplitStore(HValue, true);
5473
5474 // Delete the old store.
5475 SI.eraseFromParent();
5476 return true;
5477}
5478
Sanjay Patelfc580a62015-09-21 23:03:16 +00005479bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005480 // Bail out if we inserted the instruction to prevent optimizations from
5481 // stepping on each other's toes.
5482 if (InsertedInsts.count(I))
5483 return false;
5484
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005485 if (PHINode *P = dyn_cast<PHINode>(I)) {
5486 // It is possible for very late stage optimizations (such as SimplifyCFG)
5487 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5488 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005489 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005490 P->replaceAllUsesWith(V);
5491 P->eraseFromParent();
5492 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005493 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005494 }
Chris Lattneree588de2011-01-15 07:29:01 +00005495 return false;
5496 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005497
Chris Lattneree588de2011-01-15 07:29:01 +00005498 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005499 // If the source of the cast is a constant, then this should have
5500 // already been constant folded. The only reason NOT to constant fold
5501 // it is if something (e.g. LSR) was careful to place the constant
5502 // evaluation in a block other than then one that uses it (e.g. to hoist
5503 // the address of globals out of a loop). If this is the case, we don't
5504 // want to forward-subst the cast.
5505 if (isa<Constant>(CI->getOperand(0)))
5506 return false;
5507
Mehdi Amini44ede332015-07-09 02:09:04 +00005508 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005509 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005510
Chris Lattneree588de2011-01-15 07:29:01 +00005511 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005512 /// Sink a zext or sext into its user blocks if the target type doesn't
5513 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005514 if (TLI &&
5515 TLI->getTypeAction(CI->getContext(),
5516 TLI->getValueType(*DL, CI->getType())) ==
5517 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005518 return SinkCast(CI);
5519 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005520 bool MadeChange = moveExtToFormExtLoad(I);
5521 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005522 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005523 }
Chris Lattneree588de2011-01-15 07:29:01 +00005524 return false;
5525 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005526
Chris Lattneree588de2011-01-15 07:29:01 +00005527 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005528 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005529 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005530
Chris Lattneree588de2011-01-15 07:29:01 +00005531 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00005532 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005533 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005534 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005535 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005536 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5537 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005538 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005539 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005540 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005541
Chris Lattneree588de2011-01-15 07:29:01 +00005542 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Wei Mia2f0b592016-12-22 19:44:45 +00005543 if (TLI && splitMergedValStore(*SI, *DL, *TLI))
5544 return true;
Sanjoy Das00757272016-12-16 20:29:39 +00005545 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005546 if (TLI) {
5547 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005548 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005549 SI->getOperand(0)->getType(), AS);
5550 }
Chris Lattneree588de2011-01-15 07:29:01 +00005551 return false;
5552 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005553
Yi Jiangd069f632014-04-21 19:34:27 +00005554 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5555
5556 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5557 BinOp->getOpcode() == Instruction::LShr)) {
5558 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5559 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005560 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005561
5562 return false;
5563 }
5564
Chris Lattneree588de2011-01-15 07:29:01 +00005565 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005566 if (GEPI->hasAllZeroIndices()) {
5567 /// The GEP operand must be a pointer, so must its result -> BitCast
5568 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5569 GEPI->getName(), GEPI);
5570 GEPI->replaceAllUsesWith(NC);
5571 GEPI->eraseFromParent();
5572 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005573 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005574 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005575 }
Chris Lattneree588de2011-01-15 07:29:01 +00005576 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005577 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005578
Chris Lattneree588de2011-01-15 07:29:01 +00005579 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005580 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005581
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005582 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005583 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005584
Tim Northoveraeb8e062014-02-19 10:02:43 +00005585 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005586 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005587
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005588 if (auto *Switch = dyn_cast<SwitchInst>(I))
5589 return optimizeSwitchInst(Switch);
5590
Quentin Colombetc32615d2014-10-31 17:52:53 +00005591 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005592 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005593
Chris Lattneree588de2011-01-15 07:29:01 +00005594 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005595}
5596
James Molloyf01488e2016-01-15 09:20:19 +00005597/// Given an OR instruction, check to see if this is a bitreverse
5598/// idiom. If so, insert the new intrinsic and return true.
5599static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5600 const TargetLowering &TLI) {
5601 if (!I.getType()->isIntegerTy() ||
5602 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5603 TLI.getValueType(DL, I.getType(), true)))
5604 return false;
5605
5606 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005607 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005608 return false;
5609 Instruction *LastInst = Insts.back();
5610 I.replaceAllUsesWith(LastInst);
5611 RecursivelyDeleteTriviallyDeadInstructions(&I);
5612 return true;
5613}
5614
Chris Lattnerf2836d12007-03-31 04:06:36 +00005615// In this pass we look for GEP and cast instructions that are used
5616// across basic blocks and rewrite them to improve basic-block-at-a-time
5617// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005618bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005619 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005620 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005621
Chris Lattner7a277142011-01-15 07:14:54 +00005622 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005623 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005624 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005625 if (ModifiedDT)
5626 return true;
5627 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005628
James Molloyf01488e2016-01-15 09:20:19 +00005629 bool MadeBitReverse = true;
5630 while (TLI && MadeBitReverse) {
5631 MadeBitReverse = false;
5632 for (auto &I : reverse(BB)) {
5633 if (makeBitReverse(I, *DL, *TLI)) {
5634 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005635 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005636 break;
5637 }
5638 }
5639 }
James Molloy3ef84c42016-01-15 10:36:01 +00005640 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005641
Chris Lattnerf2836d12007-03-31 04:06:36 +00005642 return MadeChange;
5643}
Devang Patel53771ba2011-08-18 00:50:51 +00005644
5645// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005646// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005647// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005648bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005649 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005650 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005651 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005652 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005653 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005654 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005655 // Leave dbg.values that refer to an alloca alone. These
5656 // instrinsics describe the address of a variable (= the alloca)
5657 // being taken. They should not be moved next to the alloca
5658 // (and to the beginning of the scope), but rather stay close to
5659 // where said address is used.
5660 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005661 PrevNonDbgInst = Insn;
5662 continue;
5663 }
5664
5665 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5666 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005667 // If VI is a phi in a block with an EHPad terminator, we can't insert
5668 // after it.
5669 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5670 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005671 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5672 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005673 if (isa<PHINode>(VI))
5674 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5675 else
5676 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005677 MadeChange = true;
5678 ++NumDbgValueMoved;
5679 }
5680 }
5681 }
5682 return MadeChange;
5683}
Tim Northovercea0abb2014-03-29 08:22:29 +00005684
5685// If there is a sequence that branches based on comparing a single bit
5686// against zero that can be combined into a single instruction, and the
5687// target supports folding these into a single instruction, sink the
5688// mask and compare into the branch uses. Do this before OptimizeBlock ->
5689// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5690// searched for.
5691bool CodeGenPrepare::sinkAndCmp(Function &F) {
5692 if (!EnableAndCmpSinking)
5693 return false;
5694 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5695 return false;
5696 bool MadeChange = false;
Sanjay Patel892f1672016-04-11 20:13:44 +00005697 for (BasicBlock &BB : F) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005698 // Does this BB end with the following?
5699 // %andVal = and %val, #single-bit-set
5700 // %icmpVal = icmp %andResult, 0
5701 // br i1 %cmpVal label %dest1, label %dest2"
Sanjay Patel892f1672016-04-11 20:13:44 +00005702 BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
Tim Northovercea0abb2014-03-29 08:22:29 +00005703 if (!Brcc || !Brcc->isConditional())
5704 continue;
5705 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005706 if (!Cmp || Cmp->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005707 continue;
5708 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5709 if (!Zero || !Zero->isZero())
5710 continue;
5711 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005712 if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005713 continue;
5714 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5715 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5716 continue;
Sanjay Patel892f1672016-04-11 20:13:44 +00005717 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
Tim Northovercea0abb2014-03-29 08:22:29 +00005718
5719 // Push the "and; icmp" for any users that are conditional branches.
5720 // Since there can only be one branch use per BB, we don't need to keep
5721 // track of which BBs we insert into.
Sanjay Patel892f1672016-04-11 20:13:44 +00005722 for (Use &TheUse : Cmp->uses()) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005723 // Find brcc use.
Sanjay Patel892f1672016-04-11 20:13:44 +00005724 BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
Tim Northovercea0abb2014-03-29 08:22:29 +00005725 if (!BrccUser || !BrccUser->isConditional())
5726 continue;
5727 BasicBlock *UserBB = BrccUser->getParent();
Sanjay Patel892f1672016-04-11 20:13:44 +00005728 if (UserBB == &BB) continue;
Tim Northovercea0abb2014-03-29 08:22:29 +00005729 DEBUG(dbgs() << "found Brcc use\n");
5730
5731 // Sink the "and; icmp" to use.
5732 MadeChange = true;
5733 BinaryOperator *NewAnd =
5734 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5735 BrccUser);
5736 CmpInst *NewCmp =
5737 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5738 "", BrccUser);
5739 TheUse = NewCmp;
5740 ++NumAndCmpsMoved;
5741 DEBUG(BrccUser->getParent()->dump());
5742 }
5743 }
5744 return MadeChange;
5745}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005746
5747/// \brief Scale down both weights to fit into uint32_t.
5748static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5749 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5750 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5751 NewTrue = NewTrue / Scale;
5752 NewFalse = NewFalse / Scale;
5753}
5754
5755/// \brief Some targets prefer to split a conditional branch like:
5756/// \code
5757/// %0 = icmp ne i32 %a, 0
5758/// %1 = icmp ne i32 %b, 0
5759/// %or.cond = or i1 %0, %1
5760/// br i1 %or.cond, label %TrueBB, label %FalseBB
5761/// \endcode
5762/// into multiple branch instructions like:
5763/// \code
5764/// bb1:
5765/// %0 = icmp ne i32 %a, 0
5766/// br i1 %0, label %TrueBB, label %bb2
5767/// bb2:
5768/// %1 = icmp ne i32 %b, 0
5769/// br i1 %1, label %TrueBB, label %FalseBB
5770/// \endcode
5771/// This usually allows instruction selection to do even further optimizations
5772/// and combine the compare with the branch instruction. Currently this is
5773/// applied for targets which have "cheap" jump instructions.
5774///
5775/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5776///
5777bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005778 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005779 return false;
5780
5781 bool MadeChange = false;
5782 for (auto &BB : F) {
5783 // Does this BB end with the following?
5784 // %cond1 = icmp|fcmp|binary instruction ...
5785 // %cond2 = icmp|fcmp|binary instruction ...
5786 // %cond.or = or|and i1 %cond1, cond2
5787 // br i1 %cond.or label %dest1, label %dest2"
5788 BinaryOperator *LogicOp;
5789 BasicBlock *TBB, *FBB;
5790 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5791 continue;
5792
Sanjay Patel42574202015-09-02 19:23:23 +00005793 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5794 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5795 continue;
5796
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005797 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005798 Value *Cond1, *Cond2;
5799 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5800 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005801 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005802 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5803 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005804 Opc = Instruction::Or;
5805 else
5806 continue;
5807
5808 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5809 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5810 continue;
5811
5812 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5813
5814 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005815 auto TmpBB =
5816 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5817 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005818
5819 // Update original basic block by using the first condition directly by the
5820 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005821 Br1->setCondition(Cond1);
5822 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005823
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005824 // Depending on the conditon we have to either replace the true or the false
5825 // successor of the original branch instruction.
5826 if (Opc == Instruction::And)
5827 Br1->setSuccessor(0, TmpBB);
5828 else
5829 Br1->setSuccessor(1, TmpBB);
5830
5831 // Fill in the new basic block.
5832 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005833 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5834 I->removeFromParent();
5835 I->insertBefore(Br2);
5836 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005837
5838 // Update PHI nodes in both successors. The original BB needs to be
5839 // replaced in one succesor's PHI nodes, because the branch comes now from
5840 // the newly generated BB (NewBB). In the other successor we need to add one
5841 // incoming edge to the PHI nodes, because both branch instructions target
5842 // now the same successor. Depending on the original branch condition
5843 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00005844 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005845 // This doesn't change the successor order of the just created branch
5846 // instruction (or any other instruction).
5847 if (Opc == Instruction::Or)
5848 std::swap(TBB, FBB);
5849
5850 // Replace the old BB with the new BB.
5851 for (auto &I : *TBB) {
5852 PHINode *PN = dyn_cast<PHINode>(&I);
5853 if (!PN)
5854 break;
5855 int i;
5856 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5857 PN->setIncomingBlock(i, TmpBB);
5858 }
5859
5860 // Add another incoming edge form the new BB.
5861 for (auto &I : *FBB) {
5862 PHINode *PN = dyn_cast<PHINode>(&I);
5863 if (!PN)
5864 break;
5865 auto *Val = PN->getIncomingValueForBlock(&BB);
5866 PN->addIncoming(Val, TmpBB);
5867 }
5868
5869 // Update the branch weights (from SelectionDAGBuilder::
5870 // FindMergedConditions).
5871 if (Opc == Instruction::Or) {
5872 // Codegen X | Y as:
5873 // BB1:
5874 // jmp_if_X TBB
5875 // jmp TmpBB
5876 // TmpBB:
5877 // jmp_if_Y TBB
5878 // jmp FBB
5879 //
5880
5881 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5882 // The requirement is that
5883 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5884 // = TrueProb for orignal BB.
5885 // Assuming the orignal weights are A and B, one choice is to set BB1's
5886 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5887 // assumes that
5888 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5889 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5890 // TmpBB, but the math is more complicated.
5891 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005892 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005893 uint64_t NewTrueWeight = TrueWeight;
5894 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5895 scaleWeights(NewTrueWeight, NewFalseWeight);
5896 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5897 .createBranchWeights(TrueWeight, FalseWeight));
5898
5899 NewTrueWeight = TrueWeight;
5900 NewFalseWeight = 2 * FalseWeight;
5901 scaleWeights(NewTrueWeight, NewFalseWeight);
5902 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5903 .createBranchWeights(TrueWeight, FalseWeight));
5904 }
5905 } else {
5906 // Codegen X & Y as:
5907 // BB1:
5908 // jmp_if_X TmpBB
5909 // jmp FBB
5910 // TmpBB:
5911 // jmp_if_Y TBB
5912 // jmp FBB
5913 //
5914 // This requires creation of TmpBB after CurBB.
5915
5916 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5917 // The requirement is that
5918 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5919 // = FalseProb for orignal BB.
5920 // Assuming the orignal weights are A and B, one choice is to set BB1's
5921 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5922 // assumes that
5923 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5924 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005925 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005926 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5927 uint64_t NewFalseWeight = FalseWeight;
5928 scaleWeights(NewTrueWeight, NewFalseWeight);
5929 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5930 .createBranchWeights(TrueWeight, FalseWeight));
5931
5932 NewTrueWeight = 2 * TrueWeight;
5933 NewFalseWeight = FalseWeight;
5934 scaleWeights(NewTrueWeight, NewFalseWeight);
5935 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5936 .createBranchWeights(TrueWeight, FalseWeight));
5937 }
5938 }
5939
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005940 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005941 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005942 ModifiedDT = true;
5943
5944 MadeChange = true;
5945
5946 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5947 TmpBB->dump());
5948 }
5949 return MadeChange;
5950}