blob: 0ff09936496ea901c004a41bc5642a1c947f8ba6 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/Analysis/InstructionSimplify.h"
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +000021#include "llvm/Analysis/LoopInfo.h"
Dehao Chen302b69c2016-10-18 20:42:47 +000022#include "llvm/Analysis/ProfileSummaryInfo.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000023#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000024#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000025#include "llvm/Analysis/ValueTracking.h"
Petar Jovanovic644b8c12016-04-13 12:25:25 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Michael Kupersteinf79af6f2016-09-08 00:48:37 +000027#include "llvm/CodeGen/Analysis.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000028#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Constants.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000032#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000034#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/IRBuilder.h"
36#include "llvm/IR/InlineAsm.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000039#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000041#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000042#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000043#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000044#include "llvm/Pass.h"
Sanjay Pateld66607b2016-04-26 17:11:17 +000045#include "llvm/Support/BranchProbability.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000046#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000047#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000050#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000051#include "llvm/Transforms/Utils/BasicBlockUtils.h"
52#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000053#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000054#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000055#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000056using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000057using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000058
Chandler Carruth1b9dde02014-04-22 02:02:50 +000059#define DEBUG_TYPE "codegenprepare"
60
Cameron Zwarichced753f2011-01-05 17:27:27 +000061STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000062STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
63STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000064STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
65 "sunken Cmps");
66STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
67 "of sunken Casts");
68STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
69 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000070STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
71STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
Geoff Berry5256fca2015-11-20 22:34:39 +000072STATISTIC(NumAndsAdded,
73 "Number of and mask instructions added to form ext loads");
74STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000075STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000076STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000077STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000078STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000079STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000080
Cameron Zwarich338d3622011-03-11 21:52:04 +000081static cl::opt<bool> DisableBranchOpts(
82 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
83 cl::desc("Disable branch optimizations in CodeGenPrepare"));
84
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000085static cl::opt<bool>
86 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
87 cl::desc("Disable GC optimizations in CodeGenPrepare"));
88
Benjamin Kramer3d38c172012-05-06 14:25:16 +000089static cl::opt<bool> DisableSelectToBranch(
90 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
91 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000092
Hal Finkelc3998302014-04-12 00:59:48 +000093static cl::opt<bool> AddrSinkUsingGEPs(
94 "addr-sink-using-gep", cl::Hidden, cl::init(false),
95 cl::desc("Address sinking in CGP using GEPs."));
96
Tim Northovercea0abb2014-03-29 08:22:29 +000097static cl::opt<bool> EnableAndCmpSinking(
98 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
99 cl::desc("Enable sinkinig and/cmp into branches."));
100
Quentin Colombetc32615d2014-10-31 17:52:53 +0000101static cl::opt<bool> DisableStoreExtract(
102 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
103 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
104
105static cl::opt<bool> StressStoreExtract(
106 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
107 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
108
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000109static cl::opt<bool> DisableExtLdPromotion(
110 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
111 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
112 "CodeGenPrepare"));
113
114static cl::opt<bool> StressExtLdPromotion(
115 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
116 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
117 "optimization in CodeGenPrepare"));
118
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000119static cl::opt<bool> DisablePreheaderProtect(
120 "disable-preheader-prot", cl::Hidden, cl::init(false),
121 cl::desc("Disable protection against removing loop preheaders"));
122
Dehao Chen302b69c2016-10-18 20:42:47 +0000123static cl::opt<bool> ProfileGuidedSectionPrefix(
124 "profile-guided-section-prefix", cl::Hidden, cl::init(true),
125 cl::desc("Use profile info to add section prefix for hot/cold functions"));
126
Eric Christopherc1ea1492008-09-24 05:32:41 +0000127namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000128typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000129typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000130typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000131class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000132
Chris Lattner2dd09db2009-09-02 06:11:42 +0000133 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000134 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000135 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000136 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000137 const TargetLibraryInfo *TLInfo;
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000138 const LoopInfo *LI;
Nadav Rotem465834c2012-07-24 10:51:42 +0000139
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000140 /// As we scan instructions optimizing them, this is the next instruction
141 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000142 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000143
Evan Cheng0663f232011-03-21 01:19:09 +0000144 /// Keeps track of non-local addresses that have been sunk into a block.
145 /// This allows us to avoid inserting duplicate code for blocks with
146 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000147 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000148
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000149 /// Keeps track of all instructions inserted for the current function.
150 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000151 /// Keeps track of the type of the related instruction before their
152 /// promotion for the current function.
153 InstrToOrigTy PromotedInsts;
154
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000155 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000156 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000157
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000158 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000159 bool OptSize;
160
Mehdi Amini4fe37982015-07-07 18:45:17 +0000161 /// DataLayout for the Function being processed.
162 const DataLayout *DL;
163
Chris Lattnerf2836d12007-03-31 04:06:36 +0000164 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000165 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000166 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000167 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000168 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
169 }
Craig Topper4584cd52014-03-07 09:26:03 +0000170 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000171
Mehdi Amini117296c2016-10-01 02:56:57 +0000172 StringRef getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000173
Craig Topper4584cd52014-03-07 09:26:03 +0000174 void getAnalysisUsage(AnalysisUsage &AU) const override {
George Burgess IVd4febd12016-03-22 21:25:08 +0000175 // FIXME: When we can selectively preserve passes, preserve the domtree.
Dehao Chen302b69c2016-10-18 20:42:47 +0000176 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000177 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000178 AU.addRequired<TargetTransformInfoWrapperPass>();
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000179 AU.addRequired<LoopInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000180 }
181
Chris Lattnerf2836d12007-03-31 04:06:36 +0000182 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000183 bool eliminateFallThrough(Function &F);
184 bool eliminateMostlyEmptyBlocks(Function &F);
185 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
186 void eliminateMostlyEmptyBlock(BasicBlock *BB);
187 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
188 bool optimizeInst(Instruction *I, bool& ModifiedDT);
189 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000190 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000191 bool optimizeInlineAsmInst(CallInst *CS);
192 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
193 bool moveExtToFormExtLoad(Instruction *&I);
194 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000195 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000196 bool optimizeSelectInst(SelectInst *SI);
197 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000198 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000199 bool optimizeExtractElementInst(Instruction *Inst);
200 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
201 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000202 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000203 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000204 Instruction *&Inst,
205 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000206 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000207 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000208 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000209 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000210}
Devang Patel09f162c2007-05-01 21:15:47 +0000211
Devang Patel8c78a0b2007-05-03 01:11:54 +0000212char CodeGenPrepare::ID = 0;
Dehao Chen302b69c2016-10-18 20:42:47 +0000213INITIALIZE_TM_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
214 "Optimize for code generation", false, false)
215INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
216INITIALIZE_TM_PASS_END(CodeGenPrepare, "codegenprepare",
217 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000218
Bill Wendling7a639ea2013-06-19 21:07:11 +0000219FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
220 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000221}
222
Chris Lattnerf2836d12007-03-31 04:06:36 +0000223bool CodeGenPrepare::runOnFunction(Function &F) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000224 if (skipFunction(F))
Paul Robinson7c99ec52014-03-31 17:43:35 +0000225 return false;
226
Mehdi Amini4fe37982015-07-07 18:45:17 +0000227 DL = &F.getParent()->getDataLayout();
228
Chris Lattnerf2836d12007-03-31 04:06:36 +0000229 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000230 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000231 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000232 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000233
Devang Patel8f606d72011-03-24 15:35:25 +0000234 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000235 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000236 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000237 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000238 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000239 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000240 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000241
Dehao Chen302b69c2016-10-18 20:42:47 +0000242 if (ProfileGuidedSectionPrefix) {
243 ProfileSummaryInfo *PSI =
244 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
245 if (PSI->isFunctionEntryHot(&F))
246 F.setSectionPrefix(".hot");
247 else if (PSI->isFunctionEntryCold(&F))
248 F.setSectionPrefix(".cold");
249 }
250
Preston Gurdcdf540d2012-09-04 18:22:17 +0000251 /// This optimization identifies DIV instructions that can be
252 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000253 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000254 const DenseMap<unsigned int, unsigned int> &BypassWidths =
255 TLI->getBypassSlowDivWidths();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000256 BasicBlock* BB = &*F.begin();
257 while (BB != nullptr) {
258 // bypassSlowDivision may create new BBs, but we don't want to reapply the
259 // optimization to those blocks.
260 BasicBlock* Next = BB->getNextNode();
261 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
262 BB = Next;
263 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000264 }
265
266 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000267 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000268 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000269
Devang Patel53771ba2011-08-18 00:50:51 +0000270 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000271 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000272 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000273 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000274
Tim Northovercea0abb2014-03-29 08:22:29 +0000275 // If there is a mask, compare against zero, and branch that can be combined
276 // into a single target instruction, push the mask and compare into branch
277 // users. Do this before OptimizeBlock -> OptimizeInst ->
278 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000279 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000280 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000281 EverMadeChange |= splitBranchCondition(F);
282 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000283
Chris Lattnerc3748562007-04-02 01:35:34 +0000284 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000285 while (MadeChange) {
286 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000287 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000288 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000289 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000290 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000291
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000292 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000293 if (ModifiedDTOnIteration)
294 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000295 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000296 EverMadeChange |= MadeChange;
297 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000298
299 SunkAddrs.clear();
300
Cameron Zwarich338d3622011-03-11 21:52:04 +0000301 if (!DisableBranchOpts) {
302 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000303 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000304 for (BasicBlock &BB : F) {
305 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
306 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000307 if (!MadeChange) continue;
308
309 for (SmallVectorImpl<BasicBlock*>::iterator
310 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
311 if (pred_begin(*II) == pred_end(*II))
312 WorkList.insert(*II);
313 }
314
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000315 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000316 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000317 while (!WorkList.empty()) {
318 BasicBlock *BB = *WorkList.begin();
319 WorkList.erase(BB);
320 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
321
322 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000323
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000324 for (SmallVectorImpl<BasicBlock*>::iterator
325 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
326 if (pred_begin(*II) == pred_end(*II))
327 WorkList.insert(*II);
328 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000329
Nadav Rotem70409992012-08-14 05:19:07 +0000330 // Merge pairs of basic blocks with unconditional branches, connected by
331 // a single edge.
332 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000333 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000334
Cameron Zwarich338d3622011-03-11 21:52:04 +0000335 EverMadeChange |= MadeChange;
336 }
337
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000338 if (!DisableGCOpts) {
339 SmallVector<Instruction *, 2> Statepoints;
340 for (BasicBlock &BB : F)
341 for (Instruction &I : BB)
342 if (isStatepoint(I))
343 Statepoints.push_back(&I);
344 for (auto &I : Statepoints)
345 EverMadeChange |= simplifyOffsetableRelocate(*I);
346 }
347
Chris Lattnerf2836d12007-03-31 04:06:36 +0000348 return EverMadeChange;
349}
350
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000351/// Merge basic blocks which are connected by a single edge, where one of the
352/// basic blocks has a single successor pointing to the other basic block,
353/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000354bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000355 bool Changed = false;
356 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000357 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000358 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000359 // If the destination block has a single pred, then this is a trivial
360 // edge, just collapse it.
361 BasicBlock *SinglePred = BB->getSinglePredecessor();
362
Evan Cheng64a223a2012-09-28 23:58:57 +0000363 // Don't merge if BB's address is taken.
364 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000365
366 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
367 if (Term && !Term->isConditional()) {
368 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000369 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000370 // Remember if SinglePred was the entry block of the function.
371 // If so, we will need to move BB back to the entry position.
372 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000373 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000374
375 if (isEntry && BB != &BB->getParent()->getEntryBlock())
376 BB->moveBefore(&BB->getParent()->getEntryBlock());
377
378 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000379 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000380 }
381 }
382 return Changed;
383}
384
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000385/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
386/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
387/// edges in ways that are non-optimal for isel. Start by eliminating these
388/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000389bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chuang-Yu Chengd3fb38c2016-04-05 14:06:20 +0000390 SmallPtrSet<BasicBlock *, 16> Preheaders;
391 SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
392 while (!LoopList.empty()) {
393 Loop *L = LoopList.pop_back_val();
394 LoopList.insert(LoopList.end(), L->begin(), L->end());
395 if (BasicBlock *Preheader = L->getLoopPreheader())
396 Preheaders.insert(Preheader);
397 }
398
Chris Lattnerc3748562007-04-02 01:35:34 +0000399 bool MadeChange = false;
400 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000401 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000402 BasicBlock *BB = &*I++;
Jun Bum Limf9416af2016-12-16 17:06:14 +0000403
404 // If this block doesn't end with an uncond branch, ignore it.
405 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
406 if (!BI || !BI->isUnconditional())
Chris Lattnerc3748562007-04-02 01:35:34 +0000407 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000408
Jun Bum Limf9416af2016-12-16 17:06:14 +0000409 // If the instruction before the branch (skipping debug info) isn't a phi
410 // node, then other stuff is happening here.
411 BasicBlock::iterator BBI = BI->getIterator();
412 if (BBI != BB->begin()) {
413 --BBI;
414 while (isa<DbgInfoIntrinsic>(BBI)) {
415 if (BBI == BB->begin())
416 break;
417 --BBI;
418 }
419 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
420 continue;
421 }
422
423 // Do not break infinite loops.
424 BasicBlock *DestBB = BI->getSuccessor(0);
425 if (DestBB == BB)
426 continue;
427
428 if (!canMergeBlocks(BB, DestBB))
429 continue;
430
431 // Do not delete loop preheaders if doing so would create a critical edge.
432 // Loop preheaders can be good locations to spill registers. If the
433 // preheader is deleted and we create a critical edge, registers may be
434 // spilled in the loop body instead.
435 if (!DisablePreheaderProtect && Preheaders.count(BB) &&
436 !(BB->getSinglePredecessor() && BB->getSinglePredecessor()->getSingleSuccessor()))
437 continue;
438
Sanjay Patelfc580a62015-09-21 23:03:16 +0000439 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000440 MadeChange = true;
441 }
442 return MadeChange;
443}
444
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000445/// Return true if we can merge BB into DestBB if there is a single
446/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000447/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000448bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000449 const BasicBlock *DestBB) const {
450 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
451 // the successor. If there are more complex condition (e.g. preheaders),
452 // don't mess around with them.
453 BasicBlock::const_iterator BBI = BB->begin();
454 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000455 for (const User *U : PN->users()) {
456 const Instruction *UI = cast<Instruction>(U);
457 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000458 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000459 // If User is inside DestBB block and it is a PHINode then check
460 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000461 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000462 if (UI->getParent() == DestBB) {
463 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000464 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
465 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
466 if (Insn && Insn->getParent() == BB &&
467 Insn->getParent() != UPN->getIncomingBlock(I))
468 return false;
469 }
470 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000471 }
472 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000473
Chris Lattnerc3748562007-04-02 01:35:34 +0000474 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
475 // and DestBB may have conflicting incoming values for the block. If so, we
476 // can't merge the block.
477 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
478 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000479
Chris Lattnerc3748562007-04-02 01:35:34 +0000480 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000481 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000482 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
483 // It is faster to get preds from a PHI than with pred_iterator.
484 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
485 BBPreds.insert(BBPN->getIncomingBlock(i));
486 } else {
487 BBPreds.insert(pred_begin(BB), pred_end(BB));
488 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000489
Chris Lattnerc3748562007-04-02 01:35:34 +0000490 // Walk the preds of DestBB.
491 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
492 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
493 if (BBPreds.count(Pred)) { // Common predecessor?
494 BBI = DestBB->begin();
495 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
496 const Value *V1 = PN->getIncomingValueForBlock(Pred);
497 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000498
Chris Lattnerc3748562007-04-02 01:35:34 +0000499 // If V2 is a phi node in BB, look up what the mapped value will be.
500 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
501 if (V2PN->getParent() == BB)
502 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000503
Chris Lattnerc3748562007-04-02 01:35:34 +0000504 // If there is a conflict, bail out.
505 if (V1 != V2) return false;
506 }
507 }
508 }
509
510 return true;
511}
512
513
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000514/// Eliminate a basic block that has only phi's and an unconditional branch in
515/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000516void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000517 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
518 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000519
David Greene74e2d492010-01-05 01:27:11 +0000520 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000521
Chris Lattnerc3748562007-04-02 01:35:34 +0000522 // If the destination block has a single pred, then this is a trivial edge,
523 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000524 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000525 if (SinglePred != DestBB) {
526 // Remember if SinglePred was the entry block of the function. If so, we
527 // will need to move BB back to the entry position.
528 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000529 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000530
Chris Lattner8a172da2008-11-28 19:54:49 +0000531 if (isEntry && BB != &BB->getParent()->getEntryBlock())
532 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000533
David Greene74e2d492010-01-05 01:27:11 +0000534 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000535 return;
536 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000537 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000538
Chris Lattnerc3748562007-04-02 01:35:34 +0000539 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
540 // to handle the new incoming edges it is about to have.
541 PHINode *PN;
542 for (BasicBlock::iterator BBI = DestBB->begin();
543 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
544 // Remove the incoming value for BB, and remember it.
545 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000546
Chris Lattnerc3748562007-04-02 01:35:34 +0000547 // Two options: either the InVal is a phi node defined in BB or it is some
548 // value that dominates BB.
549 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
550 if (InValPhi && InValPhi->getParent() == BB) {
551 // Add all of the input values of the input PHI as inputs of this phi.
552 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
553 PN->addIncoming(InValPhi->getIncomingValue(i),
554 InValPhi->getIncomingBlock(i));
555 } else {
556 // Otherwise, add one instance of the dominating value for each edge that
557 // we will be adding.
558 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
559 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
560 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
561 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000562 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
563 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000564 }
565 }
566 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000567
Chris Lattnerc3748562007-04-02 01:35:34 +0000568 // The PHIs are now updated, change everything that refers to BB to use
569 // DestBB and remove BB.
570 BB->replaceAllUsesWith(DestBB);
571 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000572 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000573
David Greene74e2d492010-01-05 01:27:11 +0000574 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000575}
576
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000577// Computes a map of base pointer relocation instructions to corresponding
578// derived pointer relocation instructions given a vector of all relocate calls
579static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000580 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
581 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
582 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000583 // Collect information in two maps: one primarily for locating the base object
584 // while filling the second map; the second map is the final structure holding
585 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000586 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
587 for (auto *ThisRelocate : AllRelocateCalls) {
588 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
589 ThisRelocate->getDerivedPtrIndex());
590 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000591 }
592 for (auto &Item : RelocateIdxMap) {
593 std::pair<unsigned, unsigned> Key = Item.first;
594 if (Key.first == Key.second)
595 // Base relocation: nothing to insert
596 continue;
597
Manuel Jacob83eefa62016-01-05 04:03:00 +0000598 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000599 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000600
601 // We're iterating over RelocateIdxMap so we cannot modify it.
602 auto MaybeBase = RelocateIdxMap.find(BaseKey);
603 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000604 // TODO: We might want to insert a new base object relocate and gep off
605 // that, if there are enough derived object relocates.
606 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000607
608 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000609 }
610}
611
612// Accepts a GEP and extracts the operands into a vector provided they're all
613// small integer constants
614static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
615 SmallVectorImpl<Value *> &OffsetV) {
616 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
617 // Only accept small constant integer operands
618 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
619 if (!Op || Op->getZExtValue() > 20)
620 return false;
621 }
622
623 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
624 OffsetV.push_back(GEP->getOperand(i));
625 return true;
626}
627
628// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
629// replace, computes a replacement, and affects it.
630static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000631simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
632 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000633 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000634 for (GCRelocateInst *ToReplace : Targets) {
635 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000636 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000637 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000638 // A duplicate relocate call. TODO: coalesce duplicates.
639 continue;
640 }
641
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000642 if (RelocatedBase->getParent() != ToReplace->getParent()) {
643 // Base and derived relocates are in different basic blocks.
644 // In this case transform is only valid when base dominates derived
645 // relocate. However it would be too expensive to check dominance
646 // for each such relocate, so we skip the whole transformation.
647 continue;
648 }
649
Manuel Jacob83eefa62016-01-05 04:03:00 +0000650 Value *Base = ToReplace->getBasePtr();
651 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000652 if (!Derived || Derived->getPointerOperand() != Base)
653 continue;
654
655 SmallVector<Value *, 2> OffsetV;
656 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
657 continue;
658
659 // Create a Builder and replace the target callsite with a gep
Sanjay Patel545a4562016-01-20 18:59:16 +0000660 assert(RelocatedBase->getNextNode() &&
661 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000662
663 // Insert after RelocatedBase
664 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000665 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000666
667 // If gc_relocate does not match the actual type, cast it to the right type.
668 // In theory, there must be a bitcast after gc_relocate if the type does not
669 // match, and we should reuse it to get the derived pointer. But it could be
670 // cases like this:
671 // bb1:
672 // ...
673 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
674 // br label %merge
675 //
676 // bb2:
677 // ...
678 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
679 // br label %merge
680 //
681 // merge:
682 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
683 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
684 //
685 // In this case, we can not find the bitcast any more. So we insert a new bitcast
686 // no matter there is already one or not. In this way, we can handle all cases, and
687 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000688 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000689 if (RelocatedBase->getType() != Base->getType()) {
690 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000691 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000692 }
David Blaikie68d535c2015-03-24 22:38:16 +0000693 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000694 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000695 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000696 // If the newly generated derived pointer's type does not match the original derived
697 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000698 Value *ActualReplacement = Replacement;
699 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000700 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000701 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000702 }
703 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000704 ToReplace->eraseFromParent();
705
706 MadeChange = true;
707 }
708 return MadeChange;
709}
710
711// Turns this:
712//
713// %base = ...
714// %ptr = gep %base + 15
715// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
716// %base' = relocate(%tok, i32 4, i32 4)
717// %ptr' = relocate(%tok, i32 4, i32 5)
718// %val = load %ptr'
719//
720// into this:
721//
722// %base = ...
723// %ptr = gep %base + 15
724// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
725// %base' = gc.relocate(%tok, i32 4, i32 4)
726// %ptr' = gep %base' + 15
727// %val = load %ptr'
728bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
729 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000730 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000731
732 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000733 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000734 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000735 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000736
737 // We need atleast one base pointer relocation + one derived pointer
738 // relocation to mangle
739 if (AllRelocateCalls.size() < 2)
740 return false;
741
742 // RelocateInstMap is a mapping from the base relocate instruction to the
743 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000744 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000745 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
746 if (RelocateInstMap.empty())
747 return false;
748
749 for (auto &Item : RelocateInstMap)
750 // Item.first is the RelocatedBase to offset against
751 // Item.second is the vector of Targets to replace
752 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
753 return MadeChange;
754}
755
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000756/// SinkCast - Sink the specified cast instruction into its user blocks
757static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000758 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000759
Chris Lattnerf2836d12007-03-31 04:06:36 +0000760 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000761 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000762
Chris Lattnerf2836d12007-03-31 04:06:36 +0000763 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000764 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000765 UI != E; ) {
766 Use &TheUse = UI.getUse();
767 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000768
Chris Lattnerf2836d12007-03-31 04:06:36 +0000769 // Figure out which BB this cast is used in. For PHI's this is the
770 // appropriate predecessor block.
771 BasicBlock *UserBB = User->getParent();
772 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000773 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000774 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000775
Chris Lattnerf2836d12007-03-31 04:06:36 +0000776 // Preincrement use iterator so we don't invalidate it.
777 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000778
David Majnemer0c80e2e2016-04-27 19:36:38 +0000779 // The first insertion point of a block containing an EH pad is after the
780 // pad. If the pad is the user, we cannot sink the cast past the pad.
781 if (User->isEHPad())
782 continue;
783
Andrew Kaylord0430e82015-11-23 19:16:15 +0000784 // If the block selected to receive the cast is an EH pad that does not
785 // allow non-PHI instructions before the terminator, we can't sink the
786 // cast.
787 if (UserBB->getTerminator()->isEHPad())
788 continue;
789
Chris Lattnerf2836d12007-03-31 04:06:36 +0000790 // If this user is in the same block as the cast, don't change the cast.
791 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000792
Chris Lattnerf2836d12007-03-31 04:06:36 +0000793 // If we have already inserted a cast into this block, use it.
794 CastInst *&InsertedCast = InsertedCasts[UserBB];
795
796 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000797 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000798 assert(InsertPt != UserBB->end());
799 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
800 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000801 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000802
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000803 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000804 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000805 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000806 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000807 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000808
Chris Lattnerf2836d12007-03-31 04:06:36 +0000809 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000810 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000811 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000812 MadeChange = true;
813 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000814
Chris Lattnerf2836d12007-03-31 04:06:36 +0000815 return MadeChange;
816}
817
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000818/// If the specified cast instruction is a noop copy (e.g. it's casting from
819/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
820/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000821///
822/// Return true if any changes are made.
823///
Mehdi Amini44ede332015-07-09 02:09:04 +0000824static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
825 const DataLayout &DL) {
Justin Lebar3e50a5b2016-11-21 22:49:15 +0000826 // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
827 // than sinking only nop casts, but is helpful on some platforms.
828 if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
829 if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
830 ASC->getDestAddressSpace()))
831 return false;
832 }
833
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000834 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000835 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
836 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000837
838 // This is an fp<->int conversion?
839 if (SrcVT.isInteger() != DstVT.isInteger())
840 return false;
841
842 // If this is an extension, it will be a zero or sign extension, which
843 // isn't a noop.
844 if (SrcVT.bitsLT(DstVT)) return false;
845
846 // If these values will be promoted, find out what they will be promoted
847 // to. This helps us consider truncates on PPC as noop copies when they
848 // are.
849 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
850 TargetLowering::TypePromoteInteger)
851 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
852 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
853 TargetLowering::TypePromoteInteger)
854 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
855
856 // If, after promotion, these are the same types, this is a noop copy.
857 if (SrcVT != DstVT)
858 return false;
859
860 return SinkCast(CI);
861}
862
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000863/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
864/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000865///
866/// Return true if any changes were made.
867static bool CombineUAddWithOverflow(CmpInst *CI) {
868 Value *A, *B;
869 Instruction *AddI;
870 if (!match(CI,
871 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
872 return false;
873
874 Type *Ty = AddI->getType();
875 if (!isa<IntegerType>(Ty))
876 return false;
877
878 // We don't want to move around uses of condition values this late, so we we
879 // check if it is legal to create the call to the intrinsic in the basic
880 // block containing the icmp:
881
882 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
883 return false;
884
885#ifndef NDEBUG
886 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
887 // for now:
888 if (AddI->hasOneUse())
889 assert(*AddI->user_begin() == CI && "expected!");
890#endif
891
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000892 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000893 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
894
895 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
896
897 auto *UAddWithOverflow =
898 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
899 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
900 auto *Overflow =
901 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
902
903 CI->replaceAllUsesWith(Overflow);
904 AddI->replaceAllUsesWith(UAdd);
905 CI->eraseFromParent();
906 AddI->eraseFromParent();
907 return true;
908}
909
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000910/// Sink the given CmpInst into user blocks to reduce the number of virtual
911/// registers that must be created and coalesced. This is a clear win except on
912/// targets with multiple condition code registers (PowerPC), where it might
913/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000914///
915/// Return true if any changes are made.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000916static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000917 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000918
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000919 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
Peter Zotov8efe38a2016-04-03 19:32:13 +0000920 if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000921 return false;
922
923 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000924 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000925
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000926 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000927 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000928 UI != E; ) {
929 Use &TheUse = UI.getUse();
930 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000931
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000932 // Preincrement use iterator so we don't invalidate it.
933 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000934
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000935 // Don't bother for PHI nodes.
936 if (isa<PHINode>(User))
937 continue;
938
939 // Figure out which BB this cmp is used in.
940 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000941
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000942 // If this user is in the same block as the cmp, don't change the cmp.
943 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000944
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000945 // If we have already inserted a cmp into this block, use it.
946 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
947
948 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000949 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000950 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000951 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000952 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
953 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Wolfgang Piebe51bede2016-10-06 21:43:45 +0000954 // Propagate the debug info.
955 InsertedCmp->setDebugLoc(CI->getDebugLoc());
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000956 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000957
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000958 // Replace a use of the cmp with a use of the new cmp.
959 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000960 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000961 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000962 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000963
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000964 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000965 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000966 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000967 MadeChange = true;
968 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000969
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000970 return MadeChange;
971}
972
Peter Zotovf87e5502016-04-03 17:11:53 +0000973static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
Peter Zotov8efe38a2016-04-03 19:32:13 +0000974 if (SinkCmpExpression(CI, TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000975 return true;
976
977 if (CombineUAddWithOverflow(CI))
978 return true;
979
980 return false;
981}
982
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000983/// Check if the candidates could be combined with a shift instruction, which
984/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000985/// 1. Truncate instruction
986/// 2. And instruction and the imm is a mask of the low bits:
987/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000988static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000989 if (!isa<TruncInst>(User)) {
990 if (User->getOpcode() != Instruction::And ||
991 !isa<ConstantInt>(User->getOperand(1)))
992 return false;
993
Quentin Colombetd4f44692014-04-22 01:20:34 +0000994 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000995
Quentin Colombetd4f44692014-04-22 01:20:34 +0000996 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000997 return false;
998 }
999 return true;
1000}
1001
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001002/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +00001003static bool
Yi Jiangd069f632014-04-21 19:34:27 +00001004SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
1005 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +00001006 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001007 BasicBlock *UserBB = User->getParent();
1008 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
1009 TruncInst *TruncI = dyn_cast<TruncInst>(User);
1010 bool MadeChange = false;
1011
1012 for (Value::user_iterator TruncUI = TruncI->user_begin(),
1013 TruncE = TruncI->user_end();
1014 TruncUI != TruncE;) {
1015
1016 Use &TruncTheUse = TruncUI.getUse();
1017 Instruction *TruncUser = cast<Instruction>(*TruncUI);
1018 // Preincrement use iterator so we don't invalidate it.
1019
1020 ++TruncUI;
1021
1022 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
1023 if (!ISDOpcode)
1024 continue;
1025
Tim Northovere2239ff2014-07-29 10:20:22 +00001026 // If the use is actually a legal node, there will not be an
1027 // implicit truncate.
1028 // FIXME: always querying the result type is just an
1029 // approximation; some nodes' legality is determined by the
1030 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +00001031 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00001032 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +00001033 continue;
1034
1035 // Don't bother for PHI nodes.
1036 if (isa<PHINode>(TruncUser))
1037 continue;
1038
1039 BasicBlock *TruncUserBB = TruncUser->getParent();
1040
1041 if (UserBB == TruncUserBB)
1042 continue;
1043
1044 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
1045 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
1046
1047 if (!InsertedShift && !InsertedTrunc) {
1048 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001049 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001050 // Sink the shift
1051 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001052 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1053 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001054 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001055 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1056 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001057
1058 // Sink the trunc
1059 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1060 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001061 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001062
1063 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001064 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001065
1066 MadeChange = true;
1067
1068 TruncTheUse = InsertedTrunc;
1069 }
1070 }
1071 return MadeChange;
1072}
1073
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001074/// Sink the shift *right* instruction into user blocks if the uses could
1075/// potentially be combined with this shift instruction and generate BitExtract
1076/// instruction. It will only be applied if the architecture supports BitExtract
1077/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001078/// BB1:
1079/// %x.extract.shift = lshr i64 %arg1, 32
1080/// BB2:
1081/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1082/// ==>
1083///
1084/// BB2:
1085/// %x.extract.shift.1 = lshr i64 %arg1, 32
1086/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1087///
1088/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1089/// instruction.
1090/// Return true if any changes are made.
1091static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001092 const TargetLowering &TLI,
1093 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001094 BasicBlock *DefBB = ShiftI->getParent();
1095
1096 /// Only insert instructions in each block once.
1097 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1098
Mehdi Amini44ede332015-07-09 02:09:04 +00001099 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001100
1101 bool MadeChange = false;
1102 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1103 UI != E;) {
1104 Use &TheUse = UI.getUse();
1105 Instruction *User = cast<Instruction>(*UI);
1106 // Preincrement use iterator so we don't invalidate it.
1107 ++UI;
1108
1109 // Don't bother for PHI nodes.
1110 if (isa<PHINode>(User))
1111 continue;
1112
1113 if (!isExtractBitsCandidateUse(User))
1114 continue;
1115
1116 BasicBlock *UserBB = User->getParent();
1117
1118 if (UserBB == DefBB) {
1119 // If the shift and truncate instruction are in the same BB. The use of
1120 // the truncate(TruncUse) may still introduce another truncate if not
1121 // legal. In this case, we would like to sink both shift and truncate
1122 // instruction to the BB of TruncUse.
1123 // for example:
1124 // BB1:
1125 // i64 shift.result = lshr i64 opnd, imm
1126 // trunc.result = trunc shift.result to i16
1127 //
1128 // BB2:
1129 // ----> We will have an implicit truncate here if the architecture does
1130 // not have i16 compare.
1131 // cmp i16 trunc.result, opnd2
1132 //
1133 if (isa<TruncInst>(User) && shiftIsLegal
1134 // If the type of the truncate is legal, no trucate will be
1135 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001136 &&
1137 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001138 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001139 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001140
1141 continue;
1142 }
1143 // If we have already inserted a shift into this block, use it.
1144 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1145
1146 if (!InsertedShift) {
1147 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001148 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001149
1150 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001151 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1152 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001153 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001154 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1155 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001156
1157 MadeChange = true;
1158 }
1159
1160 // Replace a use of the shift with a use of the new shift.
1161 TheUse = InsertedShift;
1162 }
1163
1164 // If we removed all uses, nuke the shift.
1165 if (ShiftI->use_empty())
1166 ShiftI->eraseFromParent();
1167
1168 return MadeChange;
1169}
1170
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001171// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001172// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1173// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001174// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001175// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001176//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001177// %1 = bitcast i8* %addr to i32*
1178// %2 = extractelement <16 x i1> %mask, i32 0
1179// %3 = icmp eq i1 %2, true
1180// br i1 %3, label %cond.load, label %else
1181//
1182//cond.load: ; preds = %0
1183// %4 = getelementptr i32* %1, i32 0
1184// %5 = load i32* %4
1185// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1186// br label %else
1187//
1188//else: ; preds = %0, %cond.load
1189// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1190// %7 = extractelement <16 x i1> %mask, i32 1
1191// %8 = icmp eq i1 %7, true
1192// br i1 %8, label %cond.load1, label %else2
1193//
1194//cond.load1: ; preds = %else
1195// %9 = getelementptr i32* %1, i32 1
1196// %10 = load i32* %9
1197// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1198// br label %else2
1199//
1200//else2: ; preds = %else, %cond.load1
1201// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1202// %12 = extractelement <16 x i1> %mask, i32 2
1203// %13 = icmp eq i1 %12, true
1204// br i1 %13, label %cond.load4, label %else5
1205//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001206static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001207 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001208 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001209 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001210 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001211
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001212 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1213 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001214 assert(VecType && "Unexpected return type of masked load intrinsic");
1215
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001216 Type *EltTy = CI->getType()->getVectorElementType();
1217
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001218 IRBuilder<> Builder(CI->getContext());
1219 Instruction *InsertPt = CI;
1220 BasicBlock *IfBlock = CI->getParent();
1221 BasicBlock *CondBlock = nullptr;
1222 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001223
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001224 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001225 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1226
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001227 // Short-cut if the mask is all-true.
1228 bool IsAllOnesMask = isa<Constant>(Mask) &&
1229 cast<Constant>(Mask)->isAllOnesValue();
1230
1231 if (IsAllOnesMask) {
1232 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1233 CI->replaceAllUsesWith(NewI);
1234 CI->eraseFromParent();
1235 return;
1236 }
1237
1238 // Adjust alignment for the scalar instruction.
1239 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001240 // Bitcast %addr fron i8* to EltTy*
1241 Type *NewPtrType =
1242 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1243 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001244 unsigned VectorWidth = VecType->getNumElements();
1245
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001246 Value *UndefVal = UndefValue::get(VecType);
1247
1248 // The result vector
1249 Value *VResult = UndefVal;
1250
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001251 if (isa<ConstantVector>(Mask)) {
1252 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1253 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1254 continue;
1255 Value *Gep =
1256 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1257 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1258 VResult = Builder.CreateInsertElement(VResult, Load,
1259 Builder.getInt32(Idx));
1260 }
1261 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1262 CI->replaceAllUsesWith(NewI);
1263 CI->eraseFromParent();
1264 return;
1265 }
1266
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001267 PHINode *Phi = nullptr;
1268 Value *PrevPhi = UndefVal;
1269
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001270 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1271
1272 // Fill the "else" block, created in the previous iteration
1273 //
1274 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1275 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1276 // %to_load = icmp eq i1 %mask_1, true
1277 // br i1 %to_load, label %cond.load, label %else
1278 //
1279 if (Idx > 0) {
1280 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1281 Phi->addIncoming(VResult, CondBlock);
1282 Phi->addIncoming(PrevPhi, PrevIfBlock);
1283 PrevPhi = Phi;
1284 VResult = Phi;
1285 }
1286
1287 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1288 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1289 ConstantInt::get(Predicate->getType(), 1));
1290
1291 // Create "cond" block
1292 //
1293 // %EltAddr = getelementptr i32* %1, i32 0
1294 // %Elt = load i32* %EltAddr
1295 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1296 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001297 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001298 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001299
1300 Value *Gep =
1301 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001302 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001303 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1304
1305 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001306 BasicBlock *NewIfBlock =
1307 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001308 Builder.SetInsertPoint(InsertPt);
1309 Instruction *OldBr = IfBlock->getTerminator();
1310 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1311 OldBr->eraseFromParent();
1312 PrevIfBlock = IfBlock;
1313 IfBlock = NewIfBlock;
1314 }
1315
1316 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1317 Phi->addIncoming(VResult, CondBlock);
1318 Phi->addIncoming(PrevPhi, PrevIfBlock);
1319 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1320 CI->replaceAllUsesWith(NewI);
1321 CI->eraseFromParent();
1322}
1323
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001324// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001325// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1326// <16 x i1> %mask)
1327// to a chain of basic blocks, that stores element one-by-one if
1328// the appropriate mask bit is set
1329//
1330// %1 = bitcast i8* %addr to i32*
1331// %2 = extractelement <16 x i1> %mask, i32 0
1332// %3 = icmp eq i1 %2, true
1333// br i1 %3, label %cond.store, label %else
1334//
1335// cond.store: ; preds = %0
1336// %4 = extractelement <16 x i32> %val, i32 0
1337// %5 = getelementptr i32* %1, i32 0
1338// store i32 %4, i32* %5
1339// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001340//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001341// else: ; preds = %0, %cond.store
1342// %6 = extractelement <16 x i1> %mask, i32 1
1343// %7 = icmp eq i1 %6, true
1344// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001345//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001346// cond.store1: ; preds = %else
1347// %8 = extractelement <16 x i32> %val, i32 1
1348// %9 = getelementptr i32* %1, i32 1
1349// store i32 %8, i32* %9
1350// br label %else2
1351// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001352static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001353 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001354 Value *Ptr = CI->getArgOperand(1);
1355 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001356 Value *Mask = CI->getArgOperand(3);
1357
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001358 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001359 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001360 assert(VecType && "Unexpected data type in masked store intrinsic");
1361
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001362 Type *EltTy = VecType->getElementType();
1363
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001364 IRBuilder<> Builder(CI->getContext());
1365 Instruction *InsertPt = CI;
1366 BasicBlock *IfBlock = CI->getParent();
1367 Builder.SetInsertPoint(InsertPt);
1368 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1369
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001370 // Short-cut if the mask is all-true.
1371 bool IsAllOnesMask = isa<Constant>(Mask) &&
1372 cast<Constant>(Mask)->isAllOnesValue();
1373
1374 if (IsAllOnesMask) {
1375 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1376 CI->eraseFromParent();
1377 return;
1378 }
1379
1380 // Adjust alignment for the scalar instruction.
1381 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001382 // Bitcast %addr fron i8* to EltTy*
1383 Type *NewPtrType =
1384 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1385 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001386 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001387
1388 if (isa<ConstantVector>(Mask)) {
1389 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1390 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1391 continue;
1392 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1393 Value *Gep =
1394 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1395 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1396 }
1397 CI->eraseFromParent();
1398 return;
1399 }
1400
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001401 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1402
1403 // Fill the "else" block, created in the previous iteration
1404 //
1405 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1406 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001407 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001408 //
1409 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1410 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1411 ConstantInt::get(Predicate->getType(), 1));
1412
1413 // Create "cond" block
1414 //
1415 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1416 // %EltAddr = getelementptr i32* %1, i32 0
1417 // %store i32 %OneElt, i32* %EltAddr
1418 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001419 BasicBlock *CondBlock =
1420 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001421 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001422
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001423 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001424 Value *Gep =
1425 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001426 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001427
1428 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001429 BasicBlock *NewIfBlock =
1430 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001431 Builder.SetInsertPoint(InsertPt);
1432 Instruction *OldBr = IfBlock->getTerminator();
1433 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1434 OldBr->eraseFromParent();
1435 IfBlock = NewIfBlock;
1436 }
1437 CI->eraseFromParent();
1438}
1439
Elena Demikhovsky09285852015-10-25 15:37:55 +00001440// Translate a masked gather intrinsic like
1441// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1442// <16 x i1> %Mask, <16 x i32> %Src)
1443// to a chain of basic blocks, with loading element one-by-one if
1444// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001445//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001446// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1447// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1448// % ToLoad0 = icmp eq i1 % Mask0, true
1449// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001450//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001451// cond.load:
1452// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1453// % Load0 = load i32, i32* % Ptr0, align 4
1454// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1455// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001456//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001457// else:
1458// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1459// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1460// % ToLoad1 = icmp eq i1 % Mask1, true
1461// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001462//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001463// cond.load1:
1464// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1465// % Load1 = load i32, i32* % Ptr1, align 4
1466// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1467// br label %else2
1468// . . .
1469// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1470// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001471static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001472 Value *Ptrs = CI->getArgOperand(0);
1473 Value *Alignment = CI->getArgOperand(1);
1474 Value *Mask = CI->getArgOperand(2);
1475 Value *Src0 = CI->getArgOperand(3);
1476
1477 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1478
1479 assert(VecType && "Unexpected return type of masked load intrinsic");
1480
1481 IRBuilder<> Builder(CI->getContext());
1482 Instruction *InsertPt = CI;
1483 BasicBlock *IfBlock = CI->getParent();
1484 BasicBlock *CondBlock = nullptr;
1485 BasicBlock *PrevIfBlock = CI->getParent();
1486 Builder.SetInsertPoint(InsertPt);
1487 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1488
1489 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1490
1491 Value *UndefVal = UndefValue::get(VecType);
1492
1493 // The result vector
1494 Value *VResult = UndefVal;
1495 unsigned VectorWidth = VecType->getNumElements();
1496
1497 // Shorten the way if the mask is a vector of constants.
1498 bool IsConstMask = isa<ConstantVector>(Mask);
1499
1500 if (IsConstMask) {
1501 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1502 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1503 continue;
1504 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1505 "Ptr" + Twine(Idx));
1506 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1507 "Load" + Twine(Idx));
1508 VResult = Builder.CreateInsertElement(VResult, Load,
1509 Builder.getInt32(Idx),
1510 "Res" + Twine(Idx));
1511 }
1512 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1513 CI->replaceAllUsesWith(NewI);
1514 CI->eraseFromParent();
1515 return;
1516 }
1517
1518 PHINode *Phi = nullptr;
1519 Value *PrevPhi = UndefVal;
1520
1521 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1522
1523 // Fill the "else" block, created in the previous iteration
1524 //
1525 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1526 // %ToLoad1 = icmp eq i1 %Mask1, true
1527 // br i1 %ToLoad1, label %cond.load, label %else
1528 //
1529 if (Idx > 0) {
1530 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1531 Phi->addIncoming(VResult, CondBlock);
1532 Phi->addIncoming(PrevPhi, PrevIfBlock);
1533 PrevPhi = Phi;
1534 VResult = Phi;
1535 }
1536
1537 Value *Predicate = Builder.CreateExtractElement(Mask,
1538 Builder.getInt32(Idx),
1539 "Mask" + Twine(Idx));
1540 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1541 ConstantInt::get(Predicate->getType(), 1),
1542 "ToLoad" + Twine(Idx));
1543
1544 // Create "cond" block
1545 //
1546 // %EltAddr = getelementptr i32* %1, i32 0
1547 // %Elt = load i32* %EltAddr
1548 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1549 //
1550 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1551 Builder.SetInsertPoint(InsertPt);
1552
1553 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1554 "Ptr" + Twine(Idx));
1555 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1556 "Load" + Twine(Idx));
1557 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1558 "Res" + Twine(Idx));
1559
1560 // Create "else" block, fill it in the next iteration
1561 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1562 Builder.SetInsertPoint(InsertPt);
1563 Instruction *OldBr = IfBlock->getTerminator();
1564 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1565 OldBr->eraseFromParent();
1566 PrevIfBlock = IfBlock;
1567 IfBlock = NewIfBlock;
1568 }
1569
1570 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1571 Phi->addIncoming(VResult, CondBlock);
1572 Phi->addIncoming(PrevPhi, PrevIfBlock);
1573 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1574 CI->replaceAllUsesWith(NewI);
1575 CI->eraseFromParent();
1576}
1577
1578// Translate a masked scatter intrinsic, like
1579// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1580// <16 x i1> %Mask)
1581// to a chain of basic blocks, that stores element one-by-one if
1582// the appropriate mask bit is set.
1583//
1584// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1585// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1586// % ToStore0 = icmp eq i1 % Mask0, true
1587// br i1 %ToStore0, label %cond.store, label %else
1588//
1589// cond.store:
1590// % Elt0 = extractelement <16 x i32> %Src, i32 0
1591// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1592// store i32 %Elt0, i32* % Ptr0, align 4
1593// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001594//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001595// else:
1596// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1597// % ToStore1 = icmp eq i1 % Mask1, true
1598// br i1 % ToStore1, label %cond.store1, label %else2
1599//
1600// cond.store1:
1601// % Elt1 = extractelement <16 x i32> %Src, i32 1
1602// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1603// store i32 % Elt1, i32* % Ptr1, align 4
1604// br label %else2
1605// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001606static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001607 Value *Src = CI->getArgOperand(0);
1608 Value *Ptrs = CI->getArgOperand(1);
1609 Value *Alignment = CI->getArgOperand(2);
1610 Value *Mask = CI->getArgOperand(3);
1611
1612 assert(isa<VectorType>(Src->getType()) &&
1613 "Unexpected data type in masked scatter intrinsic");
1614 assert(isa<VectorType>(Ptrs->getType()) &&
1615 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1616 "Vector of pointers is expected in masked scatter intrinsic");
1617
1618 IRBuilder<> Builder(CI->getContext());
1619 Instruction *InsertPt = CI;
1620 BasicBlock *IfBlock = CI->getParent();
1621 Builder.SetInsertPoint(InsertPt);
1622 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1623
1624 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1625 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1626
1627 // Shorten the way if the mask is a vector of constants.
1628 bool IsConstMask = isa<ConstantVector>(Mask);
1629
1630 if (IsConstMask) {
1631 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1632 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1633 continue;
1634 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1635 "Elt" + Twine(Idx));
1636 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1637 "Ptr" + Twine(Idx));
1638 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1639 }
1640 CI->eraseFromParent();
1641 return;
1642 }
1643 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1644 // Fill the "else" block, created in the previous iteration
1645 //
1646 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1647 // % ToStore = icmp eq i1 % Mask1, true
1648 // br i1 % ToStore, label %cond.store, label %else
1649 //
1650 Value *Predicate = Builder.CreateExtractElement(Mask,
1651 Builder.getInt32(Idx),
1652 "Mask" + Twine(Idx));
1653 Value *Cmp =
1654 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1655 ConstantInt::get(Predicate->getType(), 1),
1656 "ToStore" + Twine(Idx));
1657
1658 // Create "cond" block
1659 //
1660 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1661 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1662 // %store i32 % Elt1, i32* % Ptr1
1663 //
1664 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1665 Builder.SetInsertPoint(InsertPt);
1666
1667 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1668 "Elt" + Twine(Idx));
1669 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1670 "Ptr" + Twine(Idx));
1671 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1672
1673 // Create "else" block, fill it in the next iteration
1674 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1675 Builder.SetInsertPoint(InsertPt);
1676 Instruction *OldBr = IfBlock->getTerminator();
1677 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1678 OldBr->eraseFromParent();
1679 IfBlock = NewIfBlock;
1680 }
1681 CI->eraseFromParent();
1682}
1683
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001684/// If counting leading or trailing zeros is an expensive operation and a zero
1685/// input is defined, add a check for zero to avoid calling the intrinsic.
1686///
1687/// We want to transform:
1688/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1689///
1690/// into:
1691/// entry:
1692/// %cmpz = icmp eq i64 %A, 0
1693/// br i1 %cmpz, label %cond.end, label %cond.false
1694/// cond.false:
1695/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1696/// br label %cond.end
1697/// cond.end:
1698/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1699///
1700/// If the transform is performed, return true and set ModifiedDT to true.
1701static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1702 const TargetLowering *TLI,
1703 const DataLayout *DL,
1704 bool &ModifiedDT) {
1705 if (!TLI || !DL)
1706 return false;
1707
1708 // If a zero input is undefined, it doesn't make sense to despeculate that.
1709 if (match(CountZeros->getOperand(1), m_One()))
1710 return false;
1711
1712 // If it's cheap to speculate, there's nothing to do.
1713 auto IntrinsicID = CountZeros->getIntrinsicID();
1714 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1715 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1716 return false;
1717
1718 // Only handle legal scalar cases. Anything else requires too much work.
1719 Type *Ty = CountZeros->getType();
1720 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
Jun Bum Limbe11bdc2016-05-13 18:38:35 +00001721 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001722 return false;
1723
1724 // The intrinsic will be sunk behind a compare against zero and branch.
1725 BasicBlock *StartBlock = CountZeros->getParent();
1726 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1727
1728 // Create another block after the count zero intrinsic. A PHI will be added
1729 // in this block to select the result of the intrinsic or the bit-width
1730 // constant if the input to the intrinsic is zero.
1731 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1732 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1733
1734 // Set up a builder to create a compare, conditional branch, and PHI.
1735 IRBuilder<> Builder(CountZeros->getContext());
1736 Builder.SetInsertPoint(StartBlock->getTerminator());
1737 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1738
1739 // Replace the unconditional branch that was created by the first split with
1740 // a compare against zero and a conditional branch.
1741 Value *Zero = Constant::getNullValue(Ty);
1742 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1743 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1744 StartBlock->getTerminator()->eraseFromParent();
1745
1746 // Create a PHI in the end block to select either the output of the intrinsic
1747 // or the bit width of the operand.
1748 Builder.SetInsertPoint(&EndBlock->front());
1749 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1750 CountZeros->replaceAllUsesWith(PN);
1751 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1752 PN->addIncoming(BitWidth, StartBlock);
1753 PN->addIncoming(CountZeros, CallBlock);
1754
1755 // We are explicitly handling the zero case, so we can set the intrinsic's
1756 // undefined zero argument to 'true'. This will also prevent reprocessing the
1757 // intrinsic; we only despeculate when a zero input is defined.
1758 CountZeros->setArgOperand(1, Builder.getTrue());
1759 ModifiedDT = true;
1760 return true;
1761}
1762
Sanjay Patelfc580a62015-09-21 23:03:16 +00001763bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001764 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001765
Chris Lattner7a277142011-01-15 07:14:54 +00001766 // Lower inline assembly if we can.
1767 // If we found an inline asm expession, and if the target knows how to
1768 // lower it to normal LLVM code, do so now.
1769 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1770 if (TLI->ExpandInlineAsm(CI)) {
1771 // Avoid invalidating the iterator.
1772 CurInstIterator = BB->begin();
1773 // Avoid processing instructions out of order, which could cause
1774 // reuse before a value is defined.
1775 SunkAddrs.clear();
1776 return true;
1777 }
1778 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001779 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001780 return true;
1781 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001782
John Brawn0dbcd652015-03-18 12:01:59 +00001783 // Align the pointer arguments to this call if the target thinks it's a good
1784 // idea
1785 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001786 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001787 for (auto &Arg : CI->arg_operands()) {
1788 // We want to align both objects whose address is used directly and
1789 // objects whose address is used in casts and GEPs, though it only makes
1790 // sense for GEPs if the offset is a multiple of the desired alignment and
1791 // if size - offset meets the size threshold.
1792 if (!Arg->getType()->isPointerTy())
1793 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001794 APInt Offset(DL->getPointerSizeInBits(
1795 cast<PointerType>(Arg->getType())->getAddressSpace()),
1796 0);
1797 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001798 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001799 if ((Offset2 & (PrefAlign-1)) != 0)
1800 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001801 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001802 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1803 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001804 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001805 // Global variables can only be aligned if they are defined in this
1806 // object (i.e. they are uniquely initialized in this object), and
1807 // over-aligning global variables that have an explicit section is
1808 // forbidden.
1809 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001810 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
Tim Northover918f0502016-07-18 18:28:52 +00001811 GV->getPointerAlignment(*DL) < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001812 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001813 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001814 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001815 }
1816 // If this is a memcpy (or similar) then we may be able to improve the
1817 // alignment
1818 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001819 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001820 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001821 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001822 if (Align > MI->getAlignment())
1823 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001824 }
1825 }
1826
Philip Reamesac115ed2016-03-09 23:13:12 +00001827 // If we have a cold call site, try to sink addressing computation into the
1828 // cold block. This interacts with our handling for loads and stores to
1829 // ensure that we can fold all uses of a potential addressing computation
1830 // into their uses. TODO: generalize this to work over profiling data
1831 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1832 for (auto &Arg : CI->arg_operands()) {
1833 if (!Arg->getType()->isPointerTy())
1834 continue;
1835 unsigned AS = Arg->getType()->getPointerAddressSpace();
1836 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1837 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001838
Eric Christopher4b7948e2010-03-11 02:41:03 +00001839 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001840 if (II) {
1841 switch (II->getIntrinsicID()) {
1842 default: break;
1843 case Intrinsic::objectsize: {
1844 // Lower all uses of llvm.objectsize.*
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001845 uint64_t Size;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001846 Type *ReturnTy = CI->getType();
Petar Jovanovic644b8c12016-04-13 12:25:25 +00001847 Constant *RetVal = nullptr;
1848 ConstantInt *Op1 = cast<ConstantInt>(II->getArgOperand(1));
1849 ObjSizeMode Mode = Op1->isZero() ? ObjSizeMode::Max : ObjSizeMode::Min;
1850 if (getObjectSize(II->getArgOperand(0),
1851 Size, *DL, TLInfo, false, Mode)) {
1852 RetVal = ConstantInt::get(ReturnTy, Size);
1853 } else {
1854 RetVal = ConstantInt::get(ReturnTy,
1855 Mode == ObjSizeMode::Min ? 0 : -1ULL);
1856 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001857 // Substituting this can cause recursive simplifications, which can
1858 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1859 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001860 Value *CurValue = &*CurInstIterator;
1861 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001862
Sanjay Patel545a4562016-01-20 18:59:16 +00001863 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001864
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001865 // If the iterator instruction was recursively deleted, start over at the
1866 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001867 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001868 CurInstIterator = BB->begin();
1869 SunkAddrs.clear();
1870 }
1871 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001872 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001873 case Intrinsic::masked_load: {
1874 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001875 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001876 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001877 ModifiedDT = true;
1878 return true;
1879 }
1880 return false;
1881 }
1882 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001883 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001884 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001885 ModifiedDT = true;
1886 return true;
1887 }
1888 return false;
1889 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001890 case Intrinsic::masked_gather: {
1891 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001892 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001893 ModifiedDT = true;
1894 return true;
1895 }
1896 return false;
1897 }
1898 case Intrinsic::masked_scatter: {
1899 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001900 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001901 ModifiedDT = true;
1902 return true;
1903 }
1904 return false;
1905 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001906 case Intrinsic::aarch64_stlxr:
1907 case Intrinsic::aarch64_stxr: {
1908 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1909 if (!ExtVal || !ExtVal->hasOneUse() ||
1910 ExtVal->getParent() == CI->getParent())
1911 return false;
1912 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1913 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001914 // Mark this instruction as "inserted by CGP", so that other
1915 // optimizations don't touch it.
1916 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001917 return true;
1918 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001919 case Intrinsic::invariant_group_barrier:
1920 II->replaceAllUsesWith(II->getArgOperand(0));
1921 II->eraseFromParent();
1922 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001923
1924 case Intrinsic::cttz:
1925 case Intrinsic::ctlz:
1926 // If counting zeros is expensive, try to avoid it.
1927 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001928 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001929
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001930 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001931 // Unknown address space.
1932 // TODO: Target hook to pick which address space the intrinsic cares
1933 // about?
1934 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001935 SmallVector<Value*, 2> PtrOps;
1936 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001937 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001938 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001939 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001940 return true;
1941 }
Pete Cooper615fd892012-03-13 20:59:56 +00001942 }
1943
Eric Christopher4b7948e2010-03-11 02:41:03 +00001944 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001945 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001946
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001947 // Lower all default uses of _chk calls. This is very similar
1948 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001949 // to fortified library functions (e.g. __memcpy_chk) that have the default
1950 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001951 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001952 if (Value *V = Simplifier.optimizeCall(CI)) {
1953 CI->replaceAllUsesWith(V);
1954 CI->eraseFromParent();
1955 return true;
1956 }
1957 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001958}
Chris Lattner1b93be52011-01-15 07:25:29 +00001959
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001960/// Look for opportunities to duplicate return instructions to the predecessor
1961/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001962/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001963/// bb0:
1964/// %tmp0 = tail call i32 @f0()
1965/// br label %return
1966/// bb1:
1967/// %tmp1 = tail call i32 @f1()
1968/// br label %return
1969/// bb2:
1970/// %tmp2 = tail call i32 @f2()
1971/// br label %return
1972/// return:
1973/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1974/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001975/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001976///
1977/// =>
1978///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001979/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001980/// bb0:
1981/// %tmp0 = tail call i32 @f0()
1982/// ret i32 %tmp0
1983/// bb1:
1984/// %tmp1 = tail call i32 @f1()
1985/// ret i32 %tmp1
1986/// bb2:
1987/// %tmp2 = tail call i32 @f2()
1988/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001989/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001990bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001991 if (!TLI)
1992 return false;
1993
Michael Kuperstein71321562016-09-07 20:29:49 +00001994 ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
1995 if (!RetI)
Benjamin Kramer455fa352012-11-23 19:17:06 +00001996 return false;
1997
Craig Topperc0196b12014-04-14 00:51:57 +00001998 PHINode *PN = nullptr;
1999 BitCastInst *BCI = nullptr;
Michael Kuperstein71321562016-09-07 20:29:49 +00002000 Value *V = RetI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00002001 if (V) {
2002 BCI = dyn_cast<BitCastInst>(V);
2003 if (BCI)
2004 V = BCI->getOperand(0);
2005
2006 PN = dyn_cast<PHINode>(V);
2007 if (!PN)
2008 return false;
2009 }
Evan Cheng0663f232011-03-21 01:19:09 +00002010
Cameron Zwarich4649f172011-03-24 04:52:10 +00002011 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002012 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00002013
Cameron Zwarich4649f172011-03-24 04:52:10 +00002014 // Make sure there are no instructions between the PHI and return, or that the
2015 // return is the first instruction in the block.
2016 if (PN) {
2017 BasicBlock::iterator BI = BB->begin();
2018 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00002019 if (&*BI == BCI)
2020 // Also skip over the bitcast.
2021 ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002022 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002023 return false;
2024 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002025 BasicBlock::iterator BI = BB->begin();
2026 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
Michael Kuperstein71321562016-09-07 20:29:49 +00002027 if (&*BI != RetI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002028 return false;
2029 }
Evan Cheng0663f232011-03-21 01:19:09 +00002030
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002031 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
2032 /// call.
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002033 const Function *F = BB->getParent();
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002034 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00002035 if (PN) {
2036 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
2037 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
2038 // Make sure the phi value is indeed produced by the tail call.
2039 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002040 TLI->mayBeEmittedAsTailCall(CI) &&
2041 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002042 TailCalls.push_back(CI);
2043 }
2044 } else {
2045 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002046 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00002047 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002048 continue;
2049
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00002050 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00002051 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
2052 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002053 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
2054 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00002055 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00002056
Cameron Zwarich4649f172011-03-24 04:52:10 +00002057 CallInst *CI = dyn_cast<CallInst>(&*RI);
Michael Kupersteinf79af6f2016-09-08 00:48:37 +00002058 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
2059 attributesPermitTailCall(F, CI, RetI, *TLI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00002060 TailCalls.push_back(CI);
2061 }
Evan Cheng0663f232011-03-21 01:19:09 +00002062 }
2063
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002064 bool Changed = false;
2065 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2066 CallInst *CI = TailCalls[i];
2067 CallSite CS(CI);
2068
2069 // Conservatively require the attributes of the call to match those of the
2070 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002071 AttributeSet CalleeAttrs = CS.getAttributes();
2072 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002073 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002074 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002075 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002076 continue;
2077
2078 // Make sure the call instruction is followed by an unconditional branch to
2079 // the return block.
2080 BasicBlock *CallBB = CI->getParent();
2081 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2082 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2083 continue;
2084
2085 // Duplicate the return into CallBB.
Michael Kuperstein71321562016-09-07 20:29:49 +00002086 (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002087 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002088 ++NumRetsDup;
2089 }
2090
2091 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002092 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002093 BB->eraseFromParent();
2094
2095 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002096}
2097
Chris Lattner728f9022008-11-25 07:09:13 +00002098//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002099// Memory Optimization
2100//===----------------------------------------------------------------------===//
2101
Chandler Carruthc8925912013-01-05 02:09:22 +00002102namespace {
2103
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002104/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002105/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002106struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002107 Value *BaseReg;
2108 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002109 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002110 void print(raw_ostream &OS) const;
2111 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002112
Chandler Carruthc8925912013-01-05 02:09:22 +00002113 bool operator==(const ExtAddrMode& O) const {
2114 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2115 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2116 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2117 }
2118};
2119
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002120#ifndef NDEBUG
2121static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2122 AM.print(OS);
2123 return OS;
2124}
2125#endif
2126
Chandler Carruthc8925912013-01-05 02:09:22 +00002127void ExtAddrMode::print(raw_ostream &OS) const {
2128 bool NeedPlus = false;
2129 OS << "[";
2130 if (BaseGV) {
2131 OS << (NeedPlus ? " + " : "")
2132 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002133 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002134 NeedPlus = true;
2135 }
2136
Richard Trieuc0f91212014-05-30 03:15:17 +00002137 if (BaseOffs) {
2138 OS << (NeedPlus ? " + " : "")
2139 << BaseOffs;
2140 NeedPlus = true;
2141 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002142
2143 if (BaseReg) {
2144 OS << (NeedPlus ? " + " : "")
2145 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002146 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002147 NeedPlus = true;
2148 }
2149 if (Scale) {
2150 OS << (NeedPlus ? " + " : "")
2151 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002152 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002153 }
2154
2155 OS << ']';
2156}
2157
2158#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002159LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002160 print(dbgs());
2161 dbgs() << '\n';
2162}
2163#endif
2164
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002165/// \brief This class provides transaction based operation on the IR.
2166/// Every change made through this class is recorded in the internal state and
2167/// can be undone (rollback) until commit is called.
2168class TypePromotionTransaction {
2169
2170 /// \brief This represents the common interface of the individual transaction.
2171 /// Each class implements the logic for doing one specific modification on
2172 /// the IR via the TypePromotionTransaction.
2173 class TypePromotionAction {
2174 protected:
2175 /// The Instruction modified.
2176 Instruction *Inst;
2177
2178 public:
2179 /// \brief Constructor of the action.
2180 /// The constructor performs the related action on the IR.
2181 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2182
2183 virtual ~TypePromotionAction() {}
2184
2185 /// \brief Undo the modification done by this action.
2186 /// When this method is called, the IR must be in the same state as it was
2187 /// before this action was applied.
2188 /// \pre Undoing the action works if and only if the IR is in the exact same
2189 /// state as it was directly after this action was applied.
2190 virtual void undo() = 0;
2191
2192 /// \brief Advocate every change made by this action.
2193 /// When the results on the IR of the action are to be kept, it is important
2194 /// to call this function, otherwise hidden information may be kept forever.
2195 virtual void commit() {
2196 // Nothing to be done, this action is not doing anything.
2197 }
2198 };
2199
2200 /// \brief Utility to remember the position of an instruction.
2201 class InsertionHandler {
2202 /// Position of an instruction.
2203 /// Either an instruction:
2204 /// - Is the first in a basic block: BB is used.
2205 /// - Has a previous instructon: PrevInst is used.
2206 union {
2207 Instruction *PrevInst;
2208 BasicBlock *BB;
2209 } Point;
2210 /// Remember whether or not the instruction had a previous instruction.
2211 bool HasPrevInstruction;
2212
2213 public:
2214 /// \brief Record the position of \p Inst.
2215 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002216 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002217 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2218 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002219 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002220 else
2221 Point.BB = Inst->getParent();
2222 }
2223
2224 /// \brief Insert \p Inst at the recorded position.
2225 void insert(Instruction *Inst) {
2226 if (HasPrevInstruction) {
2227 if (Inst->getParent())
2228 Inst->removeFromParent();
2229 Inst->insertAfter(Point.PrevInst);
2230 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002231 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002232 if (Inst->getParent())
2233 Inst->moveBefore(Position);
2234 else
2235 Inst->insertBefore(Position);
2236 }
2237 }
2238 };
2239
2240 /// \brief Move an instruction before another.
2241 class InstructionMoveBefore : public TypePromotionAction {
2242 /// Original position of the instruction.
2243 InsertionHandler Position;
2244
2245 public:
2246 /// \brief Move \p Inst before \p Before.
2247 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2248 : TypePromotionAction(Inst), Position(Inst) {
2249 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2250 Inst->moveBefore(Before);
2251 }
2252
2253 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002254 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002255 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2256 Position.insert(Inst);
2257 }
2258 };
2259
2260 /// \brief Set the operand of an instruction with a new value.
2261 class OperandSetter : public TypePromotionAction {
2262 /// Original operand of the instruction.
2263 Value *Origin;
2264 /// Index of the modified instruction.
2265 unsigned Idx;
2266
2267 public:
2268 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2269 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2270 : TypePromotionAction(Inst), Idx(Idx) {
2271 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2272 << "for:" << *Inst << "\n"
2273 << "with:" << *NewVal << "\n");
2274 Origin = Inst->getOperand(Idx);
2275 Inst->setOperand(Idx, NewVal);
2276 }
2277
2278 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002279 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002280 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2281 << "for: " << *Inst << "\n"
2282 << "with: " << *Origin << "\n");
2283 Inst->setOperand(Idx, Origin);
2284 }
2285 };
2286
2287 /// \brief Hide the operands of an instruction.
2288 /// Do as if this instruction was not using any of its operands.
2289 class OperandsHider : public TypePromotionAction {
2290 /// The list of original operands.
2291 SmallVector<Value *, 4> OriginalValues;
2292
2293 public:
2294 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2295 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2296 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2297 unsigned NumOpnds = Inst->getNumOperands();
2298 OriginalValues.reserve(NumOpnds);
2299 for (unsigned It = 0; It < NumOpnds; ++It) {
2300 // Save the current operand.
2301 Value *Val = Inst->getOperand(It);
2302 OriginalValues.push_back(Val);
2303 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002304 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002305 // that we are not willing to pay.
2306 Inst->setOperand(It, UndefValue::get(Val->getType()));
2307 }
2308 }
2309
2310 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002311 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2313 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2314 Inst->setOperand(It, OriginalValues[It]);
2315 }
2316 };
2317
2318 /// \brief Build a truncate instruction.
2319 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002320 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002321 public:
2322 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2323 /// result.
2324 /// trunc Opnd to Ty.
2325 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2326 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002327 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2328 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002329 }
2330
Quentin Colombetac55b152014-09-16 22:36:07 +00002331 /// \brief Get the built value.
2332 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002333
2334 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002335 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002336 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2337 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2338 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002339 }
2340 };
2341
2342 /// \brief Build a sign extension instruction.
2343 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002344 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002345 public:
2346 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2347 /// result.
2348 /// sext Opnd to Ty.
2349 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002350 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002351 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002352 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2353 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002354 }
2355
Quentin Colombetac55b152014-09-16 22:36:07 +00002356 /// \brief Get the built value.
2357 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002358
2359 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002360 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002361 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2362 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2363 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002364 }
2365 };
2366
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002367 /// \brief Build a zero extension instruction.
2368 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002369 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002370 public:
2371 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2372 /// result.
2373 /// zext Opnd to Ty.
2374 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002375 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002376 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002377 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2378 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002379 }
2380
Quentin Colombetac55b152014-09-16 22:36:07 +00002381 /// \brief Get the built value.
2382 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002383
2384 /// \brief Remove the built instruction.
2385 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002386 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2387 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2388 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002389 }
2390 };
2391
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392 /// \brief Mutate an instruction to another type.
2393 class TypeMutator : public TypePromotionAction {
2394 /// Record the original type.
2395 Type *OrigTy;
2396
2397 public:
2398 /// \brief Mutate the type of \p Inst into \p NewTy.
2399 TypeMutator(Instruction *Inst, Type *NewTy)
2400 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2401 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2402 << "\n");
2403 Inst->mutateType(NewTy);
2404 }
2405
2406 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002407 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002408 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2409 << "\n");
2410 Inst->mutateType(OrigTy);
2411 }
2412 };
2413
2414 /// \brief Replace the uses of an instruction by another instruction.
2415 class UsesReplacer : public TypePromotionAction {
2416 /// Helper structure to keep track of the replaced uses.
2417 struct InstructionAndIdx {
2418 /// The instruction using the instruction.
2419 Instruction *Inst;
2420 /// The index where this instruction is used for Inst.
2421 unsigned Idx;
2422 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2423 : Inst(Inst), Idx(Idx) {}
2424 };
2425
2426 /// Keep track of the original uses (pair Instruction, Index).
2427 SmallVector<InstructionAndIdx, 4> OriginalUses;
2428 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2429
2430 public:
2431 /// \brief Replace all the use of \p Inst by \p New.
2432 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2433 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2434 << "\n");
2435 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002436 for (Use &U : Inst->uses()) {
2437 Instruction *UserI = cast<Instruction>(U.getUser());
2438 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 }
2440 // Now, we can replace the uses.
2441 Inst->replaceAllUsesWith(New);
2442 }
2443
2444 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002445 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002446 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2447 for (use_iterator UseIt = OriginalUses.begin(),
2448 EndIt = OriginalUses.end();
2449 UseIt != EndIt; ++UseIt) {
2450 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2451 }
2452 }
2453 };
2454
2455 /// \brief Remove an instruction from the IR.
2456 class InstructionRemover : public TypePromotionAction {
2457 /// Original position of the instruction.
2458 InsertionHandler Inserter;
2459 /// Helper structure to hide all the link to the instruction. In other
2460 /// words, this helps to do as if the instruction was removed.
2461 OperandsHider Hider;
2462 /// Keep track of the uses replaced, if any.
2463 UsesReplacer *Replacer;
2464
2465 public:
2466 /// \brief Remove all reference of \p Inst and optinally replace all its
2467 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002468 /// \pre If !Inst->use_empty(), then New != nullptr
2469 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002470 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002471 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002472 if (New)
2473 Replacer = new UsesReplacer(Inst, New);
2474 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2475 Inst->removeFromParent();
2476 }
2477
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002478 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002479
2480 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002481 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002482
2483 /// \brief Resurrect the instruction and reassign it to the proper uses if
2484 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002485 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002486 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2487 Inserter.insert(Inst);
2488 if (Replacer)
2489 Replacer->undo();
2490 Hider.undo();
2491 }
2492 };
2493
2494public:
2495 /// Restoration point.
2496 /// The restoration point is a pointer to an action instead of an iterator
2497 /// because the iterator may be invalidated but not the pointer.
2498 typedef const TypePromotionAction *ConstRestorationPt;
2499 /// Advocate every changes made in that transaction.
2500 void commit();
2501 /// Undo all the changes made after the given point.
2502 void rollback(ConstRestorationPt Point);
2503 /// Get the current restoration point.
2504 ConstRestorationPt getRestorationPoint() const;
2505
2506 /// \name API for IR modification with state keeping to support rollback.
2507 /// @{
2508 /// Same as Instruction::setOperand.
2509 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2510 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002511 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002512 /// Same as Value::replaceAllUsesWith.
2513 void replaceAllUsesWith(Instruction *Inst, Value *New);
2514 /// Same as Value::mutateType.
2515 void mutateType(Instruction *Inst, Type *NewTy);
2516 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002517 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002518 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002519 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002520 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002521 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002522 /// Same as Instruction::moveBefore.
2523 void moveBefore(Instruction *Inst, Instruction *Before);
2524 /// @}
2525
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002526private:
2527 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002528 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2529 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002530};
2531
2532void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2533 Value *NewVal) {
2534 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002535 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002536}
2537
2538void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2539 Value *NewVal) {
2540 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002541 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002542}
2543
2544void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2545 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002546 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002547}
2548
2549void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002550 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002551}
2552
Quentin Colombetac55b152014-09-16 22:36:07 +00002553Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2554 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002555 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002556 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002557 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002558 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002559}
2560
Quentin Colombetac55b152014-09-16 22:36:07 +00002561Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2562 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002563 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002564 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002565 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002566 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002567}
2568
Quentin Colombetac55b152014-09-16 22:36:07 +00002569Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2570 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002571 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002572 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002573 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002574 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002575}
2576
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002577void TypePromotionTransaction::moveBefore(Instruction *Inst,
2578 Instruction *Before) {
2579 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002580 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002581}
2582
2583TypePromotionTransaction::ConstRestorationPt
2584TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002585 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002586}
2587
2588void TypePromotionTransaction::commit() {
2589 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002590 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002591 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002592 Actions.clear();
2593}
2594
2595void TypePromotionTransaction::rollback(
2596 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002597 while (!Actions.empty() && Point != Actions.back().get()) {
2598 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002600 }
2601}
2602
Chandler Carruthc8925912013-01-05 02:09:22 +00002603/// \brief A helper class for matching addressing modes.
2604///
2605/// This encapsulates the logic for matching the target-legal addressing modes.
2606class AddressingModeMatcher {
2607 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002608 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002609 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002610 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002611
2612 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2613 /// the memory instruction that we're computing this address for.
2614 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002615 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002616 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002617
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002618 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002619 /// part of the return value of this addressing mode matching stuff.
2620 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002621
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002622 /// The instructions inserted by other CodeGenPrepare optimizations.
2623 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002624 /// A map from the instructions to their type before promotion.
2625 InstrToOrigTy &PromotedInsts;
2626 /// The ongoing transaction where every action should be registered.
2627 TypePromotionTransaction &TPT;
2628
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002629 /// This is set to true when we should not do profitability checks.
2630 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002631 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002632
Eric Christopherd75c00c2015-02-26 22:38:34 +00002633 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002634 const TargetMachine &TM, Type *AT, unsigned AS,
2635 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002636 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002637 InstrToOrigTy &PromotedInsts,
2638 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002639 : AddrModeInsts(AMI), TM(TM),
2640 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2641 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002642 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2643 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2644 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002645 IgnoreProfitability = false;
2646 }
2647public:
Stephen Lin837bba12013-07-15 17:55:02 +00002648
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002649 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002650 /// give an access type of AccessTy. This returns a list of involved
2651 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002652 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002653 /// optimizations.
2654 /// \p PromotedInsts maps the instructions to their type before promotion.
2655 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002656 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002657 Instruction *MemoryInst,
2658 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002659 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002660 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002661 InstrToOrigTy &PromotedInsts,
2662 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002663 ExtAddrMode Result;
2664
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002665 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002666 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002667 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002668 (void)Success; assert(Success && "Couldn't select *anything*?");
2669 return Result;
2670 }
2671private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002672 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2673 bool matchAddr(Value *V, unsigned Depth);
2674 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002675 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002676 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002677 ExtAddrMode &AMBefore,
2678 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002679 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2680 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002681 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002682};
2683
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002684/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002685/// Return true and update AddrMode if this addr mode is legal for the target,
2686/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002687bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002688 unsigned Depth) {
2689 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2690 // mode. Just process that directly.
2691 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002692 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002693
Chandler Carruthc8925912013-01-05 02:09:22 +00002694 // If the scale is 0, it takes nothing to add this.
2695 if (Scale == 0)
2696 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002697
Chandler Carruthc8925912013-01-05 02:09:22 +00002698 // If we already have a scale of this value, we can add to it, otherwise, we
2699 // need an available scale field.
2700 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2701 return false;
2702
2703 ExtAddrMode TestAddrMode = AddrMode;
2704
2705 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2706 // [A+B + A*7] -> [B+A*8].
2707 TestAddrMode.Scale += Scale;
2708 TestAddrMode.ScaledReg = ScaleReg;
2709
2710 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002711 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002712 return false;
2713
2714 // It was legal, so commit it.
2715 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002716
Chandler Carruthc8925912013-01-05 02:09:22 +00002717 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2718 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2719 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002720 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002721 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2722 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2723 TestAddrMode.ScaledReg = AddLHS;
2724 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002725
Chandler Carruthc8925912013-01-05 02:09:22 +00002726 // If this addressing mode is legal, commit it and remember that we folded
2727 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002728 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002729 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2730 AddrMode = TestAddrMode;
2731 return true;
2732 }
2733 }
2734
2735 // Otherwise, not (x+c)*scale, just return what we have.
2736 return true;
2737}
2738
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002739/// This is a little filter, which returns true if an addressing computation
2740/// involving I might be folded into a load/store accessing it.
2741/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002742/// the set of instructions that MatchOperationAddr can.
2743static bool MightBeFoldableInst(Instruction *I) {
2744 switch (I->getOpcode()) {
2745 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002746 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002747 // Don't touch identity bitcasts.
2748 if (I->getType() == I->getOperand(0)->getType())
2749 return false;
2750 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2751 case Instruction::PtrToInt:
2752 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2753 return true;
2754 case Instruction::IntToPtr:
2755 // We know the input is intptr_t, so this is foldable.
2756 return true;
2757 case Instruction::Add:
2758 return true;
2759 case Instruction::Mul:
2760 case Instruction::Shl:
2761 // Can only handle X*C and X << C.
2762 return isa<ConstantInt>(I->getOperand(1));
2763 case Instruction::GetElementPtr:
2764 return true;
2765 default:
2766 return false;
2767 }
2768}
2769
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002770/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2771/// \note \p Val is assumed to be the product of some type promotion.
2772/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2773/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002774static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2775 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002776 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2777 if (!PromotedInst)
2778 return false;
2779 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2780 // If the ISDOpcode is undefined, it was undefined before the promotion.
2781 if (!ISDOpcode)
2782 return true;
2783 // Otherwise, check if the promoted instruction is legal or not.
2784 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002785 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002786}
2787
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002788/// \brief Hepler class to perform type promotion.
2789class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002790 /// \brief Utility function to check whether or not a sign or zero extension
2791 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2792 /// either using the operands of \p Inst or promoting \p Inst.
2793 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002794 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002795 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002796 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002797 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002798 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002799 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002800 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002801 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2802 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002803
2804 /// \brief Utility function to determine if \p OpIdx should be promoted when
2805 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002806 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002807 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002808 }
2809
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002810 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002811 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002812 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002813 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002814 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002815 /// Newly added extensions are inserted in \p Exts.
2816 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002817 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002818 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002819 static Value *promoteOperandForTruncAndAnyExt(
2820 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002821 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002822 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002823 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002824
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002825 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002826 /// operand is promotable and is not a supported trunc or sext.
2827 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002828 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002829 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002830 /// Newly added extensions are inserted in \p Exts.
2831 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002832 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002833 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002834 static Value *promoteOperandForOther(Instruction *Ext,
2835 TypePromotionTransaction &TPT,
2836 InstrToOrigTy &PromotedInsts,
2837 unsigned &CreatedInstsCost,
2838 SmallVectorImpl<Instruction *> *Exts,
2839 SmallVectorImpl<Instruction *> *Truncs,
2840 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002841
2842 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002843 static Value *signExtendOperandForOther(
2844 Instruction *Ext, TypePromotionTransaction &TPT,
2845 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2846 SmallVectorImpl<Instruction *> *Exts,
2847 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2848 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2849 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002850 }
2851
2852 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002853 static Value *zeroExtendOperandForOther(
2854 Instruction *Ext, TypePromotionTransaction &TPT,
2855 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2856 SmallVectorImpl<Instruction *> *Exts,
2857 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2858 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2859 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002860 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002861
2862public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002863 /// Type for the utility function that promotes the operand of Ext.
2864 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002865 InstrToOrigTy &PromotedInsts,
2866 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002867 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002868 SmallVectorImpl<Instruction *> *Truncs,
2869 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002870 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2871 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002872 /// \return NULL if no promotable action is possible with the current
2873 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002874 /// \p InsertedInsts keeps track of all the instructions inserted by the
2875 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002876 /// because we do not want to promote these instructions as CodeGenPrepare
2877 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2878 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002879 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002880 const TargetLowering &TLI,
2881 const InstrToOrigTy &PromotedInsts);
2882};
2883
2884bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002885 Type *ConsideredExtType,
2886 const InstrToOrigTy &PromotedInsts,
2887 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002888 // The promotion helper does not know how to deal with vector types yet.
2889 // To be able to fix that, we would need to fix the places where we
2890 // statically extend, e.g., constants and such.
2891 if (Inst->getType()->isVectorTy())
2892 return false;
2893
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002894 // We can always get through zext.
2895 if (isa<ZExtInst>(Inst))
2896 return true;
2897
2898 // sext(sext) is ok too.
2899 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002900 return true;
2901
2902 // We can get through binary operator, if it is legal. In other words, the
2903 // binary operator must have a nuw or nsw flag.
2904 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2905 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002906 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2907 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002908 return true;
2909
2910 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002911 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002912 if (!isa<TruncInst>(Inst))
2913 return false;
2914
2915 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002916 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002917 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002918 if (!OpndVal->getType()->isIntegerTy() ||
2919 OpndVal->getType()->getIntegerBitWidth() >
2920 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002921 return false;
2922
2923 // If the operand of the truncate is not an instruction, we will not have
2924 // any information on the dropped bits.
2925 // (Actually we could for constant but it is not worth the extra logic).
2926 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2927 if (!Opnd)
2928 return false;
2929
2930 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002931 // I.e., check that trunc just drops extended bits of the same kind of
2932 // the extension.
2933 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002934 const Type *OpndType;
2935 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002936 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2937 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002938 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2939 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002940 else
2941 return false;
2942
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002943 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002944 return Inst->getType()->getIntegerBitWidth() >=
2945 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002946}
2947
2948TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002949 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002950 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002951 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2952 "Unexpected instruction type");
2953 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2954 Type *ExtTy = Ext->getType();
2955 bool IsSExt = isa<SExtInst>(Ext);
2956 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002957 // get through.
2958 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002959 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002960 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002961
2962 // Do not promote if the operand has been added by codegenprepare.
2963 // Otherwise, it means we are undoing an optimization that is likely to be
2964 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002965 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002966 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002967
2968 // SExt or Trunc instructions.
2969 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002970 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2971 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002972 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002973
2974 // Regular instruction.
2975 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002976 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002977 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002978 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002979}
2980
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002981Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002982 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002983 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002984 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002985 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002986 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2987 // get through it and this method should not be called.
2988 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002989 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002990 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002991 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002992 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002993 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002994 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002995 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002996 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2997 TPT.replaceAllUsesWith(SExt, ZExt);
2998 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002999 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003000 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003001 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
3002 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00003003 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
3004 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00003005 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003006
3007 // Remove dead code.
3008 if (SExtOpnd->use_empty())
3009 TPT.eraseInstruction(SExtOpnd);
3010
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003011 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00003012 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003013 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00003014 if (ExtInst) {
3015 if (Exts)
3016 Exts->push_back(ExtInst);
3017 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
3018 }
Quentin Colombetac55b152014-09-16 22:36:07 +00003019 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003020 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003021
Quentin Colombet9dcb7242014-09-15 18:26:58 +00003022 // At this point we have: ext ty opnd to ty.
3023 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
3024 Value *NextVal = ExtInst->getOperand(0);
3025 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003026 return NextVal;
3027}
3028
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003029Value *TypePromotionHelper::promoteOperandForOther(
3030 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003031 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003032 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003033 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
3034 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003035 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003036 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003037 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00003038 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003039 if (!ExtOpnd->hasOneUse()) {
3040 // ExtOpnd will be promoted.
3041 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003042 // promoted version.
3043 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003044 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00003045 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
3046 ITrunc->removeFromParent();
3047 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003048 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003049 if (Truncs)
3050 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00003051 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003052
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003053 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003054 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003055 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003056 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003057 }
3058
3059 // Get through the Instruction:
3060 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003061 // 2. Replace the uses of Ext by Inst.
3062 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003063
3064 // Remember the original type of the instruction before promotion.
3065 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003066 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3067 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003068 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003069 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003070 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003071 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003072 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003073 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003074
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003075 DEBUG(dbgs() << "Propagate Ext to operands\n");
3076 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003077 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003078 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3079 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3080 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003081 DEBUG(dbgs() << "No need to propagate\n");
3082 continue;
3083 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003084 // Check if we can statically extend the operand.
3085 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003086 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003087 DEBUG(dbgs() << "Statically extend\n");
3088 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3089 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3090 : Cst->getValue().zext(BitWidth);
3091 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003092 continue;
3093 }
3094 // UndefValue are typed, so we have to statically sign extend them.
3095 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003096 DEBUG(dbgs() << "Statically extend\n");
3097 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003098 continue;
3099 }
3100
3101 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003102 // Check if Ext was reused to extend an operand.
3103 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003104 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003105 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003106 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3107 : TPT.createZExt(Ext, Opnd, Ext->getType());
3108 if (!isa<Instruction>(ValForExtOpnd)) {
3109 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3110 continue;
3111 }
3112 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003113 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003114 if (Exts)
3115 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003116 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003117
3118 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003119 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3120 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003121 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003122 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003123 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003124 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003125 if (ExtForOpnd == Ext) {
3126 DEBUG(dbgs() << "Extension is useless now\n");
3127 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003128 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003129 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003130}
3131
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003132/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003133/// \p NewCost gives the cost of extension instructions created by the
3134/// promotion.
3135/// \p OldCost gives the cost of extension instructions before the promotion
3136/// plus the number of instructions that have been
3137/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003138/// \p PromotedOperand is the value that has been promoted.
3139/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003140bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003141 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3142 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3143 // The cost of the new extensions is greater than the cost of the
3144 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003145 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003146 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003147 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003148 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003149 return true;
3150 // The promotion is neutral but it may help folding the sign extension in
3151 // loads for instance.
3152 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003153 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003154}
3155
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003156/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003157/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003158/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003159/// If \p MovedAway is not NULL, it contains the information of whether or
3160/// not AddrInst has to be folded into the addressing mode on success.
3161/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3162/// because it has been moved away.
3163/// Thus AddrInst must not be added in the matched instructions.
3164/// This state can happen when AddrInst is a sext, since it may be moved away.
3165/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3166/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003167bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003168 unsigned Depth,
3169 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003170 // Avoid exponential behavior on extremely deep expression trees.
3171 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003172
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003173 // By default, all matched instructions stay in place.
3174 if (MovedAway)
3175 *MovedAway = false;
3176
Chandler Carruthc8925912013-01-05 02:09:22 +00003177 switch (Opcode) {
3178 case Instruction::PtrToInt:
3179 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003180 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003181 case Instruction::IntToPtr: {
3182 auto AS = AddrInst->getType()->getPointerAddressSpace();
3183 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003184 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003185 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003186 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003187 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003188 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003189 case Instruction::BitCast:
3190 // BitCast is always a noop, and we can handle it as long as it is
3191 // int->int or pointer->pointer (we don't want int<->fp or something).
3192 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3193 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3194 // Don't touch identity bitcasts. These were probably put here by LSR,
3195 // and we don't want to mess around with them. Assume it knows what it
3196 // is doing.
3197 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003198 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003199 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003200 case Instruction::AddrSpaceCast: {
3201 unsigned SrcAS
3202 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3203 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3204 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003205 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003206 return false;
3207 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003208 case Instruction::Add: {
3209 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3210 ExtAddrMode BackupAddrMode = AddrMode;
3211 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003212 // Start a transaction at this point.
3213 // The LHS may match but not the RHS.
3214 // Therefore, we need a higher level restoration point to undo partially
3215 // matched operation.
3216 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3217 TPT.getRestorationPoint();
3218
Sanjay Patelfc580a62015-09-21 23:03:16 +00003219 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3220 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003221 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003222
Chandler Carruthc8925912013-01-05 02:09:22 +00003223 // Restore the old addr mode info.
3224 AddrMode = BackupAddrMode;
3225 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003226 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003227
Chandler Carruthc8925912013-01-05 02:09:22 +00003228 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003229 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3230 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003231 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003232
Chandler Carruthc8925912013-01-05 02:09:22 +00003233 // Otherwise we definitely can't merge the ADD in.
3234 AddrMode = BackupAddrMode;
3235 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003236 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003237 break;
3238 }
3239 //case Instruction::Or:
3240 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3241 //break;
3242 case Instruction::Mul:
3243 case Instruction::Shl: {
3244 // Can only handle X*C and X << C.
3245 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003246 if (!RHS)
3247 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003248 int64_t Scale = RHS->getSExtValue();
3249 if (Opcode == Instruction::Shl)
3250 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003251
Sanjay Patelfc580a62015-09-21 23:03:16 +00003252 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003253 }
3254 case Instruction::GetElementPtr: {
3255 // Scan the GEP. We check it if it contains constant offsets and at most
3256 // one variable offset.
3257 int VariableOperand = -1;
3258 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003259
Chandler Carruthc8925912013-01-05 02:09:22 +00003260 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003261 gep_type_iterator GTI = gep_type_begin(AddrInst);
3262 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
Peter Collingbourneab85225b2016-12-02 02:24:42 +00003263 if (StructType *STy = GTI.getStructTypeOrNull()) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003264 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003265 unsigned Idx =
3266 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3267 ConstantOffset += SL->getElementOffset(Idx);
3268 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003269 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003270 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3271 ConstantOffset += CI->getSExtValue()*TypeSize;
3272 } else if (TypeSize) { // Scales of zero don't do anything.
3273 // We only allow one variable index at the moment.
3274 if (VariableOperand != -1)
3275 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003276
Chandler Carruthc8925912013-01-05 02:09:22 +00003277 // Remember the variable index.
3278 VariableOperand = i;
3279 VariableScale = TypeSize;
3280 }
3281 }
3282 }
Stephen Lin837bba12013-07-15 17:55:02 +00003283
Chandler Carruthc8925912013-01-05 02:09:22 +00003284 // A common case is for the GEP to only do a constant offset. In this case,
3285 // just add it to the disp field and check validity.
3286 if (VariableOperand == -1) {
3287 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003288 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003289 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003290 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003291 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003292 return true;
3293 }
3294 AddrMode.BaseOffs -= ConstantOffset;
3295 return false;
3296 }
3297
3298 // Save the valid addressing mode in case we can't match.
3299 ExtAddrMode BackupAddrMode = AddrMode;
3300 unsigned OldSize = AddrModeInsts.size();
3301
3302 // See if the scale and offset amount is valid for this target.
3303 AddrMode.BaseOffs += ConstantOffset;
3304
3305 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003306 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003307 // If it couldn't be matched, just stuff the value in a register.
3308 if (AddrMode.HasBaseReg) {
3309 AddrMode = BackupAddrMode;
3310 AddrModeInsts.resize(OldSize);
3311 return false;
3312 }
3313 AddrMode.HasBaseReg = true;
3314 AddrMode.BaseReg = AddrInst->getOperand(0);
3315 }
3316
3317 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003318 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003319 Depth)) {
3320 // If it couldn't be matched, try stuffing the base into a register
3321 // instead of matching it, and retrying the match of the scale.
3322 AddrMode = BackupAddrMode;
3323 AddrModeInsts.resize(OldSize);
3324 if (AddrMode.HasBaseReg)
3325 return false;
3326 AddrMode.HasBaseReg = true;
3327 AddrMode.BaseReg = AddrInst->getOperand(0);
3328 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003329 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003330 VariableScale, Depth)) {
3331 // If even that didn't work, bail.
3332 AddrMode = BackupAddrMode;
3333 AddrModeInsts.resize(OldSize);
3334 return false;
3335 }
3336 }
3337
3338 return true;
3339 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003340 case Instruction::SExt:
3341 case Instruction::ZExt: {
3342 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3343 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003344 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003345
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003346 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003347 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003348 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003349 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003350 if (!TPH)
3351 return false;
3352
3353 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3354 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003355 unsigned CreatedInstsCost = 0;
3356 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003357 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003358 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003359 // SExt has been moved away.
3360 // Thus either it will be rematched later in the recursive calls or it is
3361 // gone. Anyway, we must not fold it into the addressing mode at this point.
3362 // E.g.,
3363 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003364 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003365 // addr = gep base, idx
3366 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003367 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003368 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3369 // addr = gep base, op <- match
3370 if (MovedAway)
3371 *MovedAway = true;
3372
3373 assert(PromotedOperand &&
3374 "TypePromotionHelper should have filtered out those cases");
3375
3376 ExtAddrMode BackupAddrMode = AddrMode;
3377 unsigned OldSize = AddrModeInsts.size();
3378
Sanjay Patelfc580a62015-09-21 23:03:16 +00003379 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003380 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003381 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003382 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003383 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003384 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003385 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003386 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003387 AddrMode = BackupAddrMode;
3388 AddrModeInsts.resize(OldSize);
3389 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3390 TPT.rollback(LastKnownGood);
3391 return false;
3392 }
3393 return true;
3394 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003395 }
3396 return false;
3397}
3398
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003399/// If we can, try to add the value of 'Addr' into the current addressing mode.
3400/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3401/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3402/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003403///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003404bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003405 // Start a transaction at this point that we will rollback if the matching
3406 // fails.
3407 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3408 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003409 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3410 // Fold in immediates if legal for the target.
3411 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003412 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003413 return true;
3414 AddrMode.BaseOffs -= CI->getSExtValue();
3415 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3416 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003417 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003418 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003419 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003420 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003421 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003422 }
3423 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3424 ExtAddrMode BackupAddrMode = AddrMode;
3425 unsigned OldSize = AddrModeInsts.size();
3426
3427 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003428 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003429 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003430 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003431 // to check here.
3432 if (MovedAway)
3433 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003434 // Okay, it's possible to fold this. Check to see if it is actually
3435 // *profitable* to do so. We use a simple cost model to avoid increasing
3436 // register pressure too much.
3437 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003438 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003439 AddrModeInsts.push_back(I);
3440 return true;
3441 }
Stephen Lin837bba12013-07-15 17:55:02 +00003442
Chandler Carruthc8925912013-01-05 02:09:22 +00003443 // It isn't profitable to do this, roll back.
3444 //cerr << "NOT FOLDING: " << *I;
3445 AddrMode = BackupAddrMode;
3446 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003447 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003448 }
3449 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003450 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003451 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003452 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003453 } else if (isa<ConstantPointerNull>(Addr)) {
3454 // Null pointer gets folded without affecting the addressing mode.
3455 return true;
3456 }
3457
3458 // Worse case, the target should support [reg] addressing modes. :)
3459 if (!AddrMode.HasBaseReg) {
3460 AddrMode.HasBaseReg = true;
3461 AddrMode.BaseReg = Addr;
3462 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003463 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003464 return true;
3465 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003466 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003467 }
3468
3469 // If the base register is already taken, see if we can do [r+r].
3470 if (AddrMode.Scale == 0) {
3471 AddrMode.Scale = 1;
3472 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003473 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003474 return true;
3475 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003476 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003477 }
3478 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003479 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003480 return false;
3481}
3482
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003483/// Check to see if all uses of OpVal by the specified inline asm call are due
3484/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003485static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003486 const TargetMachine &TM) {
3487 const Function *F = CI->getParent()->getParent();
3488 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3489 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003490 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003491 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3492 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003493 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3494 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003495
Chandler Carruthc8925912013-01-05 02:09:22 +00003496 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003497 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003498
3499 // If this asm operand is our Value*, and if it isn't an indirect memory
3500 // operand, we can't fold it!
3501 if (OpInfo.CallOperandVal == OpVal &&
3502 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3503 !OpInfo.isIndirect))
3504 return false;
3505 }
3506
3507 return true;
3508}
3509
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003510/// Recursively walk all the uses of I until we find a memory use.
3511/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003512/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003513static bool FindAllMemoryUses(
3514 Instruction *I,
3515 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3516 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003517 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003518 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003519 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003520
Chandler Carruthc8925912013-01-05 02:09:22 +00003521 // If this is an obviously unfoldable instruction, bail out.
3522 if (!MightBeFoldableInst(I))
3523 return true;
3524
Philip Reamesac115ed2016-03-09 23:13:12 +00003525 const bool OptSize = I->getFunction()->optForSize();
3526
Chandler Carruthc8925912013-01-05 02:09:22 +00003527 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003528 for (Use &U : I->uses()) {
3529 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003530
Chandler Carruthcdf47882014-03-09 03:16:01 +00003531 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3532 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003533 continue;
3534 }
Stephen Lin837bba12013-07-15 17:55:02 +00003535
Chandler Carruthcdf47882014-03-09 03:16:01 +00003536 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3537 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003538 if (opNo == 0) return true; // Storing addr, not into addr.
3539 MemoryUses.push_back(std::make_pair(SI, opNo));
3540 continue;
3541 }
Stephen Lin837bba12013-07-15 17:55:02 +00003542
Chandler Carruthcdf47882014-03-09 03:16:01 +00003543 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003544 // If this is a cold call, we can sink the addressing calculation into
3545 // the cold path. See optimizeCallInst
3546 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3547 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003548
Chandler Carruthc8925912013-01-05 02:09:22 +00003549 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3550 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003551
Chandler Carruthc8925912013-01-05 02:09:22 +00003552 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003553 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003554 return true;
3555 continue;
3556 }
Stephen Lin837bba12013-07-15 17:55:02 +00003557
Eric Christopher11e4df72015-02-26 22:38:43 +00003558 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003559 return true;
3560 }
3561
3562 return false;
3563}
3564
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003565/// Return true if Val is already known to be live at the use site that we're
3566/// folding it into. If so, there is no cost to include it in the addressing
3567/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3568/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003569bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003570 Value *KnownLive2) {
3571 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003572 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003573 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003574
Chandler Carruthc8925912013-01-05 02:09:22 +00003575 // All values other than instructions and arguments (e.g. constants) are live.
3576 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003577
Chandler Carruthc8925912013-01-05 02:09:22 +00003578 // If Val is a constant sized alloca in the entry block, it is live, this is
3579 // true because it is just a reference to the stack/frame pointer, which is
3580 // live for the whole function.
3581 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3582 if (AI->isStaticAlloca())
3583 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003584
Chandler Carruthc8925912013-01-05 02:09:22 +00003585 // Check to see if this value is already used in the memory instruction's
3586 // block. If so, it's already live into the block at the very least, so we
3587 // can reasonably fold it.
3588 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3589}
3590
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003591/// It is possible for the addressing mode of the machine to fold the specified
3592/// instruction into a load or store that ultimately uses it.
3593/// However, the specified instruction has multiple uses.
3594/// Given this, it may actually increase register pressure to fold it
3595/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003596///
3597/// X = ...
3598/// Y = X+1
3599/// use(Y) -> nonload/store
3600/// Z = Y+1
3601/// load Z
3602///
3603/// In this case, Y has multiple uses, and can be folded into the load of Z
3604/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3605/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3606/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3607/// number of computations either.
3608///
3609/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3610/// X was live across 'load Z' for other reasons, we actually *would* want to
3611/// fold the addressing mode in the Z case. This would make Y die earlier.
3612bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003613isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003614 ExtAddrMode &AMAfter) {
3615 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003616
Chandler Carruthc8925912013-01-05 02:09:22 +00003617 // AMBefore is the addressing mode before this instruction was folded into it,
3618 // and AMAfter is the addressing mode after the instruction was folded. Get
3619 // the set of registers referenced by AMAfter and subtract out those
3620 // referenced by AMBefore: this is the set of values which folding in this
3621 // address extends the lifetime of.
3622 //
3623 // Note that there are only two potential values being referenced here,
3624 // BaseReg and ScaleReg (global addresses are always available, as are any
3625 // folded immediates).
3626 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003627
Chandler Carruthc8925912013-01-05 02:09:22 +00003628 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3629 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003630 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003631 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003632 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003633 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003634
3635 // If folding this instruction (and it's subexprs) didn't extend any live
3636 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003637 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003638 return true;
3639
Philip Reamesac115ed2016-03-09 23:13:12 +00003640 // If all uses of this instruction can have the address mode sunk into them,
3641 // we can remove the addressing mode and effectively trade one live register
3642 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003643 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003644 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3645 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003646 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003647 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003648
Chandler Carruthc8925912013-01-05 02:09:22 +00003649 // Now that we know that all uses of this instruction are part of a chain of
3650 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003651 // into a memory use, loop over each of these memory operation uses and see
3652 // if they could *actually* fold the instruction. The assumption is that
3653 // addressing modes are cheap and that duplicating the computation involved
3654 // many times is worthwhile, even on a fastpath. For sinking candidates
3655 // (i.e. cold call sites), this serves as a way to prevent excessive code
3656 // growth since most architectures have some reasonable small and fast way to
3657 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003658 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3659 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3660 Instruction *User = MemoryUses[i].first;
3661 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003662
Chandler Carruthc8925912013-01-05 02:09:22 +00003663 // Get the access type of this use. If the use isn't a pointer, we don't
3664 // know what it accesses.
3665 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003666 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3667 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003668 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003669 Type *AddressAccessTy = AddrTy->getElementType();
3670 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003671
Chandler Carruthc8925912013-01-05 02:09:22 +00003672 // Do a match against the root of this address, ignoring profitability. This
3673 // will tell us if the addressing mode for the memory operation will
3674 // *actually* cover the shared instruction.
3675 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003676 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3677 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003678 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003679 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003680 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003681 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003682 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003683 (void)Success; assert(Success && "Couldn't select *anything*?");
3684
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003685 // The match was to check the profitability, the changes made are not
3686 // part of the original matcher. Therefore, they should be dropped
3687 // otherwise the original matcher will not present the right state.
3688 TPT.rollback(LastKnownGood);
3689
Chandler Carruthc8925912013-01-05 02:09:22 +00003690 // If the match didn't cover I, then it won't be shared by it.
David Majnemer0d955d02016-08-11 22:21:41 +00003691 if (!is_contained(MatchedAddrModeInsts, I))
Chandler Carruthc8925912013-01-05 02:09:22 +00003692 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003693
Chandler Carruthc8925912013-01-05 02:09:22 +00003694 MatchedAddrModeInsts.clear();
3695 }
Stephen Lin837bba12013-07-15 17:55:02 +00003696
Chandler Carruthc8925912013-01-05 02:09:22 +00003697 return true;
3698}
3699
3700} // end anonymous namespace
3701
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003702/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003703/// different basic block than BB.
3704static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3705 if (Instruction *I = dyn_cast<Instruction>(V))
3706 return I->getParent() != BB;
3707 return false;
3708}
3709
Philip Reamesac115ed2016-03-09 23:13:12 +00003710/// Sink addressing mode computation immediate before MemoryInst if doing so
3711/// can be done without increasing register pressure. The need for the
3712/// register pressure constraint means this can end up being an all or nothing
3713/// decision for all uses of the same addressing computation.
3714///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003715/// Load and Store Instructions often have addressing modes that can do
3716/// significant amounts of computation. As such, instruction selection will try
3717/// to get the load or store to do as much computation as possible for the
3718/// program. The problem is that isel can only see within a single block. As
3719/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003720///
3721/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003722/// operands. It's also used to sink addressing computations feeding into cold
3723/// call sites into their (cold) basic block.
3724///
3725/// The motivation for handling sinking into cold blocks is that doing so can
3726/// both enable other address mode sinking (by satisfying the register pressure
3727/// constraint above), and reduce register pressure globally (by removing the
3728/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003729bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003730 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003731 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003732
3733 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003734 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003735 SmallVector<Value*, 8> worklist;
3736 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003737 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003738
Owen Anderson8ba5f392010-11-27 08:15:55 +00003739 // Use a worklist to iteratively look through PHI nodes, and ensure that
3740 // the addressing mode obtained from the non-PHI roots of the graph
3741 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003742 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003743 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003744 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003745 SmallVector<Instruction*, 16> AddrModeInsts;
3746 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003747 TypePromotionTransaction TPT;
3748 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3749 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003750 while (!worklist.empty()) {
3751 Value *V = worklist.back();
3752 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003753
Owen Anderson8ba5f392010-11-27 08:15:55 +00003754 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003755 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003756 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003757 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003758 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003759
Owen Anderson8ba5f392010-11-27 08:15:55 +00003760 // For a PHI node, push all of its incoming values.
3761 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003762 for (Value *IncValue : P->incoming_values())
3763 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003764 continue;
3765 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003766
Philip Reamesac115ed2016-03-09 23:13:12 +00003767 // For non-PHIs, determine the addressing mode being computed. Note that
3768 // the result may differ depending on what other uses our candidate
3769 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003770 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003771 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003772 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003773 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003774
3775 // This check is broken into two cases with very similar code to avoid using
3776 // getNumUses() as much as possible. Some values have a lot of uses, so
3777 // calling getNumUses() unconditionally caused a significant compile-time
3778 // regression.
3779 if (!Consensus) {
3780 Consensus = V;
3781 AddrMode = NewAddrMode;
3782 AddrModeInsts = NewAddrModeInsts;
3783 continue;
3784 } else if (NewAddrMode == AddrMode) {
3785 if (!IsNumUsesConsensusValid) {
3786 NumUsesConsensus = Consensus->getNumUses();
3787 IsNumUsesConsensusValid = true;
3788 }
3789
3790 // Ensure that the obtained addressing mode is equivalent to that obtained
3791 // for all other roots of the PHI traversal. Also, when choosing one
3792 // such root as representative, select the one with the most uses in order
3793 // to keep the cost modeling heuristics in AddressingModeMatcher
3794 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003795 unsigned NumUses = V->getNumUses();
3796 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003797 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003798 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003799 AddrModeInsts = NewAddrModeInsts;
3800 }
3801 continue;
3802 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003803
Craig Topperc0196b12014-04-14 00:51:57 +00003804 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003805 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003806 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003807
Owen Anderson8ba5f392010-11-27 08:15:55 +00003808 // If the addressing mode couldn't be determined, or if multiple different
3809 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003810 if (!Consensus) {
3811 TPT.rollback(LastKnownGood);
3812 return false;
3813 }
3814 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003815
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003816 // If all the instructions matched are already in this BB, don't do anything.
Justin Lebar838c7f52016-11-21 22:49:11 +00003817 if (none_of(AddrModeInsts, [&](Value *V) {
3818 return IsNonLocalValue(V, MemoryInst->getParent());
3819 })) {
David Greene74e2d492010-01-05 01:27:11 +00003820 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003821 return false;
3822 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003823
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003824 // Insert this computation right after this user. Since our caller is
3825 // scanning from the top of the BB to the bottom, reuse of the expr are
3826 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003827 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003828
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003829 // Now that we determined the addressing expression we want to use and know
3830 // that we have to sink it into this block. Check to see if we have already
3831 // done this for some other load/store instr in this block. If so, reuse the
3832 // computation.
3833 Value *&SunkAddr = SunkAddrs[Addr];
3834 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003835 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003836 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003837 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003838 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003839 } else if (AddrSinkUsingGEPs ||
3840 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003841 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3842 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003843 // By default, we use the GEP-based method when AA is used later. This
3844 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3845 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003846 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003847 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003848 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003849
3850 // First, find the pointer.
3851 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3852 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003853 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003854 }
3855
3856 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3857 // We can't add more than one pointer together, nor can we scale a
3858 // pointer (both of which seem meaningless).
3859 if (ResultPtr || AddrMode.Scale != 1)
3860 return false;
3861
3862 ResultPtr = AddrMode.ScaledReg;
3863 AddrMode.Scale = 0;
3864 }
3865
3866 if (AddrMode.BaseGV) {
3867 if (ResultPtr)
3868 return false;
3869
3870 ResultPtr = AddrMode.BaseGV;
3871 }
3872
3873 // If the real base value actually came from an inttoptr, then the matcher
3874 // will look through it and provide only the integer value. In that case,
3875 // use it here.
3876 if (!ResultPtr && AddrMode.BaseReg) {
3877 ResultPtr =
3878 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003879 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003880 } else if (!ResultPtr && AddrMode.Scale == 1) {
3881 ResultPtr =
3882 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3883 AddrMode.Scale = 0;
3884 }
3885
3886 if (!ResultPtr &&
3887 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3888 SunkAddr = Constant::getNullValue(Addr->getType());
3889 } else if (!ResultPtr) {
3890 return false;
3891 } else {
3892 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003893 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3894 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003895
3896 // Start with the base register. Do this first so that subsequent address
3897 // matching finds it last, which will prevent it from trying to match it
3898 // as the scaled value in case it happens to be a mul. That would be
3899 // problematic if we've sunk a different mul for the scale, because then
3900 // we'd end up sinking both muls.
3901 if (AddrMode.BaseReg) {
3902 Value *V = AddrMode.BaseReg;
3903 if (V->getType() != IntPtrTy)
3904 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3905
3906 ResultIndex = V;
3907 }
3908
3909 // Add the scale value.
3910 if (AddrMode.Scale) {
3911 Value *V = AddrMode.ScaledReg;
3912 if (V->getType() == IntPtrTy) {
3913 // done.
3914 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3915 cast<IntegerType>(V->getType())->getBitWidth()) {
3916 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3917 } else {
3918 // It is only safe to sign extend the BaseReg if we know that the math
3919 // required to create it did not overflow before we extend it. Since
3920 // the original IR value was tossed in favor of a constant back when
3921 // the AddrMode was created we need to bail out gracefully if widths
3922 // do not match instead of extending it.
3923 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3924 if (I && (ResultIndex != AddrMode.BaseReg))
3925 I->eraseFromParent();
3926 return false;
3927 }
3928
3929 if (AddrMode.Scale != 1)
3930 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3931 "sunkaddr");
3932 if (ResultIndex)
3933 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3934 else
3935 ResultIndex = V;
3936 }
3937
3938 // Add in the Base Offset if present.
3939 if (AddrMode.BaseOffs) {
3940 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3941 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003942 // We need to add this separately from the scale above to help with
3943 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003944 if (ResultPtr->getType() != I8PtrTy)
3945 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003946 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003947 }
3948
3949 ResultIndex = V;
3950 }
3951
3952 if (!ResultIndex) {
3953 SunkAddr = ResultPtr;
3954 } else {
3955 if (ResultPtr->getType() != I8PtrTy)
3956 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003957 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003958 }
3959
3960 if (SunkAddr->getType() != Addr->getType())
3961 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3962 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003963 } else {
David Greene74e2d492010-01-05 01:27:11 +00003964 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003965 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003966 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003967 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003968
3969 // Start with the base register. Do this first so that subsequent address
3970 // matching finds it last, which will prevent it from trying to match it
3971 // as the scaled value in case it happens to be a mul. That would be
3972 // problematic if we've sunk a different mul for the scale, because then
3973 // we'd end up sinking both muls.
3974 if (AddrMode.BaseReg) {
3975 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003976 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003977 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003978 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003979 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003980 Result = V;
3981 }
3982
3983 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003984 if (AddrMode.Scale) {
3985 Value *V = AddrMode.ScaledReg;
3986 if (V->getType() == IntPtrTy) {
3987 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003988 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003989 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003990 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3991 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003992 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003993 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003994 // It is only safe to sign extend the BaseReg if we know that the math
3995 // required to create it did not overflow before we extend it. Since
3996 // the original IR value was tossed in favor of a constant back when
3997 // the AddrMode was created we need to bail out gracefully if widths
3998 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003999 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00004000 if (I && (Result != AddrMode.BaseReg))
4001 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00004002 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004003 }
4004 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00004005 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
4006 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004007 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004008 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004009 else
4010 Result = V;
4011 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004012
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004013 // Add in the BaseGV if present.
4014 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00004015 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004016 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004017 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004018 else
4019 Result = V;
4020 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004021
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004022 // Add in the Base Offset if present.
4023 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00004024 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004025 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00004026 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004027 else
4028 Result = V;
4029 }
4030
Craig Topperc0196b12014-04-14 00:51:57 +00004031 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00004032 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004033 else
Devang Patelc10e52a2011-09-06 18:49:53 +00004034 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004035 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00004036
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004037 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00004038
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004039 // If we have no uses, recursively delete the value and all dead instructions
4040 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00004041 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004042 // This can cause recursive deletion, which can invalidate our iterator.
4043 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004044 Value *CurValue = &*CurInstIterator;
4045 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004046 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00004047
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00004048 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004049
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00004050 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00004051 // If the iterator instruction was recursively deleted, start over at the
4052 // start of the block.
4053 CurInstIterator = BB->begin();
4054 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004055 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004056 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004057 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004058 return true;
4059}
4060
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004061/// If there are any memory operands, use OptimizeMemoryInst to sink their
4062/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004063bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004064 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004065
Eric Christopher11e4df72015-02-26 22:38:43 +00004066 const TargetRegisterInfo *TRI =
4067 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004068 TargetLowering::AsmOperandInfoVector TargetConstraints =
4069 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004070 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004071 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4072 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004073
Evan Cheng1da25002008-02-26 02:42:37 +00004074 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004075 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004076
Eli Friedman666bbe32008-02-26 18:37:49 +00004077 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4078 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004079 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004080 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004081 } else if (OpInfo.Type == InlineAsm::isInput)
4082 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004083 }
4084
4085 return MadeChange;
4086}
4087
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004088/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4089/// sign extensions.
4090static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4091 assert(!Inst->use_empty() && "Input must have at least one use");
4092 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4093 bool IsSExt = isa<SExtInst>(FirstUser);
4094 Type *ExtTy = FirstUser->getType();
4095 for (const User *U : Inst->users()) {
4096 const Instruction *UI = cast<Instruction>(U);
4097 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4098 return false;
4099 Type *CurTy = UI->getType();
4100 // Same input and output types: Same instruction after CSE.
4101 if (CurTy == ExtTy)
4102 continue;
4103
4104 // If IsSExt is true, we are in this situation:
4105 // a = Inst
4106 // b = sext ty1 a to ty2
4107 // c = sext ty1 a to ty3
4108 // Assuming ty2 is shorter than ty3, this could be turned into:
4109 // a = Inst
4110 // b = sext ty1 a to ty2
4111 // c = sext ty2 b to ty3
4112 // However, the last sext is not free.
4113 if (IsSExt)
4114 return false;
4115
4116 // This is a ZExt, maybe this is free to extend from one type to another.
4117 // In that case, we would not account for a different use.
4118 Type *NarrowTy;
4119 Type *LargeTy;
4120 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4121 CurTy->getScalarType()->getIntegerBitWidth()) {
4122 NarrowTy = CurTy;
4123 LargeTy = ExtTy;
4124 } else {
4125 NarrowTy = ExtTy;
4126 LargeTy = CurTy;
4127 }
4128
4129 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4130 return false;
4131 }
4132 // All uses are the same or can be derived from one another for free.
4133 return true;
4134}
4135
4136/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4137/// load instruction.
4138/// If an ext(load) can be formed, it is returned via \p LI for the load
4139/// and \p Inst for the extension.
4140/// Otherwise LI == nullptr and Inst == nullptr.
4141/// When some promotion happened, \p TPT contains the proper state to
4142/// revert them.
4143///
4144/// \return true when promoting was necessary to expose the ext(load)
4145/// opportunity, false otherwise.
4146///
4147/// Example:
4148/// \code
4149/// %ld = load i32* %addr
4150/// %add = add nuw i32 %ld, 4
4151/// %zext = zext i32 %add to i64
4152/// \endcode
4153/// =>
4154/// \code
4155/// %ld = load i32* %addr
4156/// %zext = zext i32 %ld to i64
4157/// %add = add nuw i64 %zext, 4
4158/// \encode
4159/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004160bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004161 LoadInst *&LI, Instruction *&Inst,
4162 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004163 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004164 // Iterate over all the extensions to see if one form an ext(load).
4165 for (auto I : Exts) {
4166 // Check if we directly have ext(load).
4167 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4168 Inst = I;
4169 // No promotion happened here.
4170 return false;
4171 }
4172 // Check whether or not we want to do any promotion.
4173 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4174 continue;
4175 // Get the action to perform the promotion.
4176 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004177 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004178 // Check if we can promote.
4179 if (!TPH)
4180 continue;
4181 // Save the current state.
4182 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4183 TPT.getRestorationPoint();
4184 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004185 unsigned NewCreatedInstsCost = 0;
4186 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004187 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004188 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4189 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004190 assert(PromotedVal &&
4191 "TypePromotionHelper should have filtered out those cases");
4192
4193 // We would be able to merge only one extension in a load.
4194 // Therefore, if we have more than 1 new extension we heuristically
4195 // cut this search path, because it means we degrade the code quality.
4196 // With exactly 2, the transformation is neutral, because we will merge
4197 // one extension but leave one. However, we optimistically keep going,
4198 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004199 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4200 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004201 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004202 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004203 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004204 // The promotion is not profitable, rollback to the previous state.
4205 TPT.rollback(LastKnownGood);
4206 continue;
4207 }
4208 // The promotion is profitable.
4209 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004210 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004211 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004212 // If we have created a new extension, i.e., now we have two
4213 // extensions. We must make sure one of them is merged with
4214 // the load, otherwise we may degrade the code quality.
4215 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4216 // Promotion happened.
4217 return true;
4218 // If this does not help to expose an ext(load) then, rollback.
4219 TPT.rollback(LastKnownGood);
4220 }
4221 // None of the extension can form an ext(load).
4222 LI = nullptr;
4223 Inst = nullptr;
4224 return false;
4225}
4226
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004227/// Move a zext or sext fed by a load into the same basic block as the load,
4228/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4229/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004230/// \p I[in/out] the extension may be modified during the process if some
4231/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004232///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004233bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Chandler Carruth0f139b42016-11-04 06:54:00 +00004234 // ExtLoad formation infrastructure requires TLI to be effective.
4235 if (!TLI)
4236 return false;
4237
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004238 // Try to promote a chain of computation if it allows to form
4239 // an extended load.
4240 TypePromotionTransaction TPT;
4241 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4242 TPT.getRestorationPoint();
4243 SmallVector<Instruction *, 1> Exts;
4244 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004245 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004246 LoadInst *LI = nullptr;
4247 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004248 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004249 if (!LI || !I) {
4250 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4251 "the code must remain the same");
4252 I = OldExt;
4253 return false;
4254 }
Dan Gohman99429a02009-10-16 20:59:35 +00004255
4256 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004257 // Make the cheap checks first if we did not promote.
4258 // If we promoted, we need to check if it is indeed profitable.
4259 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004260 return false;
4261
Mehdi Amini44ede332015-07-09 02:09:04 +00004262 EVT VT = TLI->getValueType(*DL, I->getType());
4263 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004264
Dan Gohman99429a02009-10-16 20:59:35 +00004265 // If the load has other users and the truncate is not free, this probably
4266 // isn't worthwhile.
Chandler Carruth0f139b42016-11-04 06:54:00 +00004267 if (!LI->hasOneUse() &&
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004268 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004269 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4270 I = OldExt;
4271 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004272 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004273 }
Dan Gohman99429a02009-10-16 20:59:35 +00004274
4275 // Check whether the target supports casts folded into loads.
4276 unsigned LType;
4277 if (isa<ZExtInst>(I))
4278 LType = ISD::ZEXTLOAD;
4279 else {
4280 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4281 LType = ISD::SEXTLOAD;
4282 }
Chandler Carruth0f139b42016-11-04 06:54:00 +00004283 if (!TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004284 I = OldExt;
4285 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004286 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004287 }
Dan Gohman99429a02009-10-16 20:59:35 +00004288
4289 // Move the extend into the same block as the load, so that SelectionDAG
4290 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004291 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004292 I->removeFromParent();
4293 I->insertAfter(LI);
Andrea Di Biagiofa90c692016-10-17 11:32:26 +00004294 // CGP does not check if the zext would be speculatively executed when moved
4295 // to the same basic block as the load. Preserving its original location would
4296 // pessimize the debugging experience, as well as negatively impact the
4297 // quality of sample pgo. We don't want to use "line 0" as that has a
4298 // size cost in the line-table section and logically the zext can be seen as
4299 // part of the load. Therefore we conservatively reuse the same debug location
4300 // for the load and the zext.
4301 I->setDebugLoc(LI->getDebugLoc());
Cameron Zwarichced753f2011-01-05 17:27:27 +00004302 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004303 return true;
4304}
4305
Sanjay Patelfc580a62015-09-21 23:03:16 +00004306bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004307 BasicBlock *DefBB = I->getParent();
4308
Bob Wilsonff714f92010-09-21 21:44:14 +00004309 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004310 // other uses of the source with result of extension.
4311 Value *Src = I->getOperand(0);
4312 if (Src->hasOneUse())
4313 return false;
4314
Evan Cheng2011df42007-12-13 07:50:36 +00004315 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004316 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004317 return false;
4318
Evan Cheng7bc89422007-12-12 00:51:06 +00004319 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004320 // this block.
4321 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004322 return false;
4323
Evan Chengd3d80172007-12-05 23:58:20 +00004324 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004325 for (User *U : I->users()) {
4326 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004327
4328 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004329 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004330 if (UserBB == DefBB) continue;
4331 DefIsLiveOut = true;
4332 break;
4333 }
4334 if (!DefIsLiveOut)
4335 return false;
4336
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004337 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004338 for (User *U : Src->users()) {
4339 Instruction *UI = cast<Instruction>(U);
4340 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004341 if (UserBB == DefBB) continue;
4342 // Be conservative. We don't want this xform to end up introducing
4343 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004344 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004345 return false;
4346 }
4347
Evan Chengd3d80172007-12-05 23:58:20 +00004348 // InsertedTruncs - Only insert one trunc in each block once.
4349 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4350
4351 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004352 for (Use &U : Src->uses()) {
4353 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004354
4355 // Figure out which BB this ext is used in.
4356 BasicBlock *UserBB = User->getParent();
4357 if (UserBB == DefBB) continue;
4358
4359 // Both src and def are live in this block. Rewrite the use.
4360 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4361
4362 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004363 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004364 assert(InsertPt != UserBB->end());
4365 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004366 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004367 }
4368
4369 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004370 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004371 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004372 MadeChange = true;
4373 }
4374
4375 return MadeChange;
4376}
4377
Geoff Berry5256fca2015-11-20 22:34:39 +00004378// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4379// just after the load if the target can fold this into one extload instruction,
4380// with the hope of eliminating some of the other later "and" instructions using
4381// the loaded value. "and"s that are made trivially redundant by the insertion
4382// of the new "and" are removed by this function, while others (e.g. those whose
4383// path from the load goes through a phi) are left for isel to potentially
4384// remove.
4385//
4386// For example:
4387//
4388// b0:
4389// x = load i32
4390// ...
4391// b1:
4392// y = and x, 0xff
4393// z = use y
4394//
4395// becomes:
4396//
4397// b0:
4398// x = load i32
4399// x' = and x, 0xff
4400// ...
4401// b1:
4402// z = use x'
4403//
4404// whereas:
4405//
4406// b0:
4407// x1 = load i32
4408// ...
4409// b1:
4410// x2 = load i32
4411// ...
4412// b2:
4413// x = phi x1, x2
4414// y = and x, 0xff
4415//
4416// becomes (after a call to optimizeLoadExt for each load):
4417//
4418// b0:
4419// x1 = load i32
4420// x1' = and x1, 0xff
4421// ...
4422// b1:
4423// x2 = load i32
4424// x2' = and x2, 0xff
4425// ...
4426// b2:
4427// x = phi x1', x2'
4428// y = and x, 0xff
4429//
4430
4431bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4432
4433 if (!Load->isSimple() ||
4434 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4435 return false;
4436
4437 // Skip loads we've already transformed or have no reason to transform.
4438 if (Load->hasOneUse()) {
4439 User *LoadUser = *Load->user_begin();
4440 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4441 !dyn_cast<PHINode>(LoadUser))
4442 return false;
4443 }
4444
4445 // Look at all uses of Load, looking through phis, to determine how many bits
4446 // of the loaded value are needed.
4447 SmallVector<Instruction *, 8> WorkList;
4448 SmallPtrSet<Instruction *, 16> Visited;
4449 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4450 for (auto *U : Load->users())
4451 WorkList.push_back(cast<Instruction>(U));
4452
4453 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4454 unsigned BitWidth = LoadResultVT.getSizeInBits();
4455 APInt DemandBits(BitWidth, 0);
4456 APInt WidestAndBits(BitWidth, 0);
4457
4458 while (!WorkList.empty()) {
4459 Instruction *I = WorkList.back();
4460 WorkList.pop_back();
4461
4462 // Break use-def graph loops.
4463 if (!Visited.insert(I).second)
4464 continue;
4465
4466 // For a PHI node, push all of its users.
4467 if (auto *Phi = dyn_cast<PHINode>(I)) {
4468 for (auto *U : Phi->users())
4469 WorkList.push_back(cast<Instruction>(U));
4470 continue;
4471 }
4472
4473 switch (I->getOpcode()) {
4474 case llvm::Instruction::And: {
4475 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4476 if (!AndC)
4477 return false;
4478 APInt AndBits = AndC->getValue();
4479 DemandBits |= AndBits;
4480 // Keep track of the widest and mask we see.
4481 if (AndBits.ugt(WidestAndBits))
4482 WidestAndBits = AndBits;
4483 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4484 AndsToMaybeRemove.push_back(I);
4485 break;
4486 }
4487
4488 case llvm::Instruction::Shl: {
4489 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4490 if (!ShlC)
4491 return false;
4492 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4493 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4494 DemandBits |= ShlDemandBits;
4495 break;
4496 }
4497
4498 case llvm::Instruction::Trunc: {
4499 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4500 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4501 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4502 DemandBits |= TruncBits;
4503 break;
4504 }
4505
4506 default:
4507 return false;
4508 }
4509 }
4510
4511 uint32_t ActiveBits = DemandBits.getActiveBits();
4512 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4513 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4514 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4515 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4516 // followed by an AND.
4517 // TODO: Look into removing this restriction by fixing backends to either
4518 // return false for isLoadExtLegal for i1 or have them select this pattern to
4519 // a single instruction.
4520 //
4521 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4522 // mask, since these are the only ands that will be removed by isel.
4523 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4524 WidestAndBits != DemandBits)
4525 return false;
4526
4527 LLVMContext &Ctx = Load->getType()->getContext();
4528 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4529 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4530
4531 // Reject cases that won't be matched as extloads.
4532 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4533 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4534 return false;
4535
4536 IRBuilder<> Builder(Load->getNextNode());
4537 auto *NewAnd = dyn_cast<Instruction>(
4538 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4539
4540 // Replace all uses of load with new and (except for the use of load in the
4541 // new and itself).
4542 Load->replaceAllUsesWith(NewAnd);
4543 NewAnd->setOperand(0, Load);
4544
4545 // Remove any and instructions that are now redundant.
4546 for (auto *And : AndsToMaybeRemove)
4547 // Check that the and mask is the same as the one we decided to put on the
4548 // new and.
4549 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4550 And->replaceAllUsesWith(NewAnd);
4551 if (&*CurInstIterator == And)
4552 CurInstIterator = std::next(And->getIterator());
4553 And->eraseFromParent();
4554 ++NumAndUses;
4555 }
4556
4557 ++NumAndsAdded;
4558 return true;
4559}
4560
Sanjay Patel69a50a12015-10-19 21:59:12 +00004561/// Check if V (an operand of a select instruction) is an expensive instruction
4562/// that is only used once.
4563static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4564 auto *I = dyn_cast<Instruction>(V);
4565 // If it's safe to speculatively execute, then it should not have side
4566 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004567 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4568 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004569}
4570
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004571/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004572static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
Sanjay Pateld66607b2016-04-26 17:11:17 +00004573 const TargetLowering *TLI,
Sanjay Patel69a50a12015-10-19 21:59:12 +00004574 SelectInst *SI) {
Sanjay Pateld66607b2016-04-26 17:11:17 +00004575 // If even a predictable select is cheap, then a branch can't be cheaper.
4576 if (!TLI->isPredictableSelectExpensive())
4577 return false;
4578
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004579 // FIXME: This should use the same heuristics as IfConversion to determine
Sanjay Pateld66607b2016-04-26 17:11:17 +00004580 // whether a select is better represented as a branch.
4581
4582 // If metadata tells us that the select condition is obviously predictable,
4583 // then we want to replace the select with a branch.
4584 uint64_t TrueWeight, FalseWeight;
4585 if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
4586 uint64_t Max = std::max(TrueWeight, FalseWeight);
4587 uint64_t Sum = TrueWeight + FalseWeight;
Sanjay Patelc7b91e62016-05-09 17:31:55 +00004588 if (Sum != 0) {
4589 auto Probability = BranchProbability::getBranchProbability(Max, Sum);
4590 if (Probability > TLI->getPredictableBranchThreshold())
4591 return true;
4592 }
Sanjay Pateld66607b2016-04-26 17:11:17 +00004593 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004594
4595 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4596
Sanjay Patel4e652762015-09-28 22:14:51 +00004597 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4598 // comparison condition. If the compare has more than one use, there's
4599 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004600 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004601 return false;
4602
Sanjay Patel69a50a12015-10-19 21:59:12 +00004603 // If either operand of the select is expensive and only needed on one side
4604 // of the select, we should form a branch.
4605 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4606 sinkSelectOperand(TTI, SI->getFalseValue()))
4607 return true;
4608
4609 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004610}
4611
Dehao Chen9bbb9412016-09-12 20:23:28 +00004612/// If \p isTrue is true, return the true value of \p SI, otherwise return
4613/// false value of \p SI. If the true/false value of \p SI is defined by any
4614/// select instructions in \p Selects, look through the defining select
4615/// instruction until the true/false value is not defined in \p Selects.
4616static Value *getTrueOrFalseValue(
4617 SelectInst *SI, bool isTrue,
4618 const SmallPtrSet<const Instruction *, 2> &Selects) {
4619 Value *V;
4620
4621 for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
4622 DefSI = dyn_cast<SelectInst>(V)) {
Dehao Chenc32d7122016-09-12 20:29:54 +00004623 assert(DefSI->getCondition() == SI->getCondition() &&
Dehao Chen9bbb9412016-09-12 20:23:28 +00004624 "The condition of DefSI does not match with SI");
4625 V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
4626 }
4627 return V;
4628}
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004629
Nadav Rotem9d832022012-09-02 12:10:19 +00004630/// If we have a SelectInst that will likely profit from branch prediction,
4631/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004632bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Dehao Chen9bbb9412016-09-12 20:23:28 +00004633 // Find all consecutive select instructions that share the same condition.
4634 SmallVector<SelectInst *, 2> ASI;
4635 ASI.push_back(SI);
4636 for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
4637 It != SI->getParent()->end(); ++It) {
4638 SelectInst *I = dyn_cast<SelectInst>(&*It);
4639 if (I && SI->getCondition() == I->getCondition()) {
4640 ASI.push_back(I);
4641 } else {
4642 break;
4643 }
4644 }
4645
4646 SelectInst *LastSI = ASI.back();
4647 // Increment the current iterator to skip all the rest of select instructions
4648 // because they will be either "not lowered" or "all lowered" to branch.
4649 CurInstIterator = std::next(LastSI->getIterator());
4650
Nadav Rotem9d832022012-09-02 12:10:19 +00004651 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4652
4653 // Can we convert the 'select' to CF ?
Sanjay Patela31b0c02016-04-26 00:47:39 +00004654 if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
4655 SI->getMetadata(LLVMContext::MD_unpredictable))
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004656 return false;
4657
Nadav Rotem9d832022012-09-02 12:10:19 +00004658 TargetLowering::SelectSupportKind SelectKind;
4659 if (VectorCond)
4660 SelectKind = TargetLowering::VectorMaskSelect;
4661 else if (SI->getType()->isVectorTy())
4662 SelectKind = TargetLowering::ScalarCondVectorVal;
4663 else
4664 SelectKind = TargetLowering::ScalarValSelect;
4665
Sanjay Pateld66607b2016-04-26 17:11:17 +00004666 if (TLI->isSelectSupported(SelectKind) &&
4667 !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
4668 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004669
4670 ModifiedDT = true;
4671
Sanjay Patel69a50a12015-10-19 21:59:12 +00004672 // Transform a sequence like this:
4673 // start:
4674 // %cmp = cmp uge i32 %a, %b
4675 // %sel = select i1 %cmp, i32 %c, i32 %d
4676 //
4677 // Into:
4678 // start:
4679 // %cmp = cmp uge i32 %a, %b
4680 // br i1 %cmp, label %select.true, label %select.false
4681 // select.true:
4682 // br label %select.end
4683 // select.false:
4684 // br label %select.end
4685 // select.end:
4686 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4687 //
4688 // In addition, we may sink instructions that produce %c or %d from
4689 // the entry block into the destination(s) of the new branch.
4690 // If the true or false blocks do not contain a sunken instruction, that
4691 // block and its branch may be optimized away. In that case, one side of the
4692 // first branch will point directly to select.end, and the corresponding PHI
4693 // predecessor block will be the start block.
4694
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004695 // First, we split the block containing the select into 2 blocks.
4696 BasicBlock *StartBlock = SI->getParent();
Dehao Chen9bbb9412016-09-12 20:23:28 +00004697 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004698 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004699
Sanjay Patel69a50a12015-10-19 21:59:12 +00004700 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004701 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004702
4703 // These are the new basic blocks for the conditional branch.
4704 // At least one will become an actual new basic block.
4705 BasicBlock *TrueBlock = nullptr;
4706 BasicBlock *FalseBlock = nullptr;
Dehao Chen9bbb9412016-09-12 20:23:28 +00004707 BranchInst *TrueBranch = nullptr;
4708 BranchInst *FalseBranch = nullptr;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004709
4710 // Sink expensive instructions into the conditional blocks to avoid executing
4711 // them speculatively.
Dehao Chen9bbb9412016-09-12 20:23:28 +00004712 for (SelectInst *SI : ASI) {
4713 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4714 if (TrueBlock == nullptr) {
4715 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4716 EndBlock->getParent(), EndBlock);
4717 TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4718 }
4719 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4720 TrueInst->moveBefore(TrueBranch);
4721 }
4722 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4723 if (FalseBlock == nullptr) {
4724 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4725 EndBlock->getParent(), EndBlock);
4726 FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4727 }
4728 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4729 FalseInst->moveBefore(FalseBranch);
4730 }
Sanjay Patel69a50a12015-10-19 21:59:12 +00004731 }
4732
4733 // If there was nothing to sink, then arbitrarily choose the 'false' side
4734 // for a new input value to the PHI.
4735 if (TrueBlock == FalseBlock) {
4736 assert(TrueBlock == nullptr &&
4737 "Unexpected basic block transform while optimizing select");
4738
4739 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4740 EndBlock->getParent(), EndBlock);
4741 BranchInst::Create(EndBlock, FalseBlock);
4742 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004743
4744 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004745 // If we did not create a new block for one of the 'true' or 'false' paths
4746 // of the condition, it means that side of the branch goes to the end block
4747 // directly and the path originates from the start block from the point of
4748 // view of the new PHI.
Xinliang David Li241e6c72016-09-03 21:26:36 +00004749 BasicBlock *TT, *FT;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004750 if (TrueBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004751 TT = EndBlock;
4752 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004753 TrueBlock = StartBlock;
4754 } else if (FalseBlock == nullptr) {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004755 TT = TrueBlock;
4756 FT = EndBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004757 FalseBlock = StartBlock;
4758 } else {
Xinliang David Li241e6c72016-09-03 21:26:36 +00004759 TT = TrueBlock;
4760 FT = FalseBlock;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004761 }
Xinliang David Li241e6c72016-09-03 21:26:36 +00004762 IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004763
Dehao Chen9bbb9412016-09-12 20:23:28 +00004764 SmallPtrSet<const Instruction *, 2> INS;
4765 INS.insert(ASI.begin(), ASI.end());
4766 // Use reverse iterator because later select may use the value of the
4767 // earlier select, and we need to propagate value through earlier select
4768 // to get the PHI operand.
4769 for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
4770 SelectInst *SI = *It;
4771 // The select itself is replaced with a PHI Node.
4772 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
4773 PN->takeName(SI);
4774 PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
4775 PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004776
Dehao Chen9bbb9412016-09-12 20:23:28 +00004777 SI->replaceAllUsesWith(PN);
4778 SI->eraseFromParent();
4779 INS.erase(SI);
4780 ++NumSelectsExpanded;
4781 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004782
4783 // Instruct OptimizeBlock to skip to the next block.
4784 CurInstIterator = StartBlock->end();
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004785 return true;
4786}
4787
Benjamin Kramer573ff362014-03-01 17:24:40 +00004788static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004789 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4790 int SplatElem = -1;
4791 for (unsigned i = 0; i < Mask.size(); ++i) {
4792 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4793 return false;
4794 SplatElem = Mask[i];
4795 }
4796
4797 return true;
4798}
4799
4800/// Some targets have expensive vector shifts if the lanes aren't all the same
4801/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4802/// it's often worth sinking a shufflevector splat down to its use so that
4803/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004804bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004805 BasicBlock *DefBB = SVI->getParent();
4806
4807 // Only do this xform if variable vector shifts are particularly expensive.
4808 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4809 return false;
4810
4811 // We only expect better codegen by sinking a shuffle if we can recognise a
4812 // constant splat.
4813 if (!isBroadcastShuffle(SVI))
4814 return false;
4815
4816 // InsertedShuffles - Only insert a shuffle in each block once.
4817 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4818
4819 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004820 for (User *U : SVI->users()) {
4821 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004822
4823 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004824 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004825 if (UserBB == DefBB) continue;
4826
4827 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004828 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004829
4830 // Everything checks out, sink the shuffle if the user's block doesn't
4831 // already have a copy.
4832 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4833
4834 if (!InsertedShuffle) {
4835 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004836 assert(InsertPt != UserBB->end());
4837 InsertedShuffle =
4838 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4839 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004840 }
4841
Chandler Carruthcdf47882014-03-09 03:16:01 +00004842 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004843 MadeChange = true;
4844 }
4845
4846 // If we removed all uses, nuke the shuffle.
4847 if (SVI->use_empty()) {
4848 SVI->eraseFromParent();
4849 MadeChange = true;
4850 }
4851
4852 return MadeChange;
4853}
4854
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004855bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4856 if (!TLI || !DL)
4857 return false;
4858
4859 Value *Cond = SI->getCondition();
4860 Type *OldType = Cond->getType();
4861 LLVMContext &Context = Cond->getContext();
4862 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4863 unsigned RegWidth = RegType.getSizeInBits();
4864
4865 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4866 return false;
4867
4868 // If the register width is greater than the type width, expand the condition
4869 // of the switch instruction and each case constant to the width of the
4870 // register. By widening the type of the switch condition, subsequent
4871 // comparisons (for case comparisons) will not need to be extended to the
4872 // preferred register width, so we will potentially eliminate N-1 extends,
4873 // where N is the number of cases in the switch.
4874 auto *NewType = Type::getIntNTy(Context, RegWidth);
4875
4876 // Zero-extend the switch condition and case constants unless the switch
4877 // condition is a function argument that is already being sign-extended.
4878 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4879 // everything instead.
4880 Instruction::CastOps ExtType = Instruction::ZExt;
4881 if (auto *Arg = dyn_cast<Argument>(Cond))
4882 if (Arg->hasSExtAttr())
4883 ExtType = Instruction::SExt;
4884
4885 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4886 ExtInst->insertBefore(SI);
4887 SI->setCondition(ExtInst);
4888 for (SwitchInst::CaseIt Case : SI->cases()) {
4889 APInt NarrowConst = Case.getCaseValue()->getValue();
4890 APInt WideConst = (ExtType == Instruction::ZExt) ?
4891 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4892 Case.setValue(ConstantInt::get(Context, WideConst));
4893 }
4894
4895 return true;
4896}
4897
Quentin Colombetc32615d2014-10-31 17:52:53 +00004898namespace {
4899/// \brief Helper class to promote a scalar operation to a vector one.
4900/// This class is used to move downward extractelement transition.
4901/// E.g.,
4902/// a = vector_op <2 x i32>
4903/// b = extractelement <2 x i32> a, i32 0
4904/// c = scalar_op b
4905/// store c
4906///
4907/// =>
4908/// a = vector_op <2 x i32>
4909/// c = vector_op a (equivalent to scalar_op on the related lane)
4910/// * d = extractelement <2 x i32> c, i32 0
4911/// * store d
4912/// Assuming both extractelement and store can be combine, we get rid of the
4913/// transition.
4914class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004915 /// DataLayout associated with the current module.
4916 const DataLayout &DL;
4917
Quentin Colombetc32615d2014-10-31 17:52:53 +00004918 /// Used to perform some checks on the legality of vector operations.
4919 const TargetLowering &TLI;
4920
4921 /// Used to estimated the cost of the promoted chain.
4922 const TargetTransformInfo &TTI;
4923
4924 /// The transition being moved downwards.
4925 Instruction *Transition;
4926 /// The sequence of instructions to be promoted.
4927 SmallVector<Instruction *, 4> InstsToBePromoted;
4928 /// Cost of combining a store and an extract.
4929 unsigned StoreExtractCombineCost;
4930 /// Instruction that will be combined with the transition.
4931 Instruction *CombineInst;
4932
4933 /// \brief The instruction that represents the current end of the transition.
4934 /// Since we are faking the promotion until we reach the end of the chain
4935 /// of computation, we need a way to get the current end of the transition.
4936 Instruction *getEndOfTransition() const {
4937 if (InstsToBePromoted.empty())
4938 return Transition;
4939 return InstsToBePromoted.back();
4940 }
4941
4942 /// \brief Return the index of the original value in the transition.
4943 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4944 /// c, is at index 0.
4945 unsigned getTransitionOriginalValueIdx() const {
4946 assert(isa<ExtractElementInst>(Transition) &&
4947 "Other kind of transitions are not supported yet");
4948 return 0;
4949 }
4950
4951 /// \brief Return the index of the index in the transition.
4952 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4953 /// is at index 1.
4954 unsigned getTransitionIdx() const {
4955 assert(isa<ExtractElementInst>(Transition) &&
4956 "Other kind of transitions are not supported yet");
4957 return 1;
4958 }
4959
4960 /// \brief Get the type of the transition.
4961 /// This is the type of the original value.
4962 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4963 /// transition is <2 x i32>.
4964 Type *getTransitionType() const {
4965 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4966 }
4967
4968 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4969 /// I.e., we have the following sequence:
4970 /// Def = Transition <ty1> a to <ty2>
4971 /// b = ToBePromoted <ty2> Def, ...
4972 /// =>
4973 /// b = ToBePromoted <ty1> a, ...
4974 /// Def = Transition <ty1> ToBePromoted to <ty2>
4975 void promoteImpl(Instruction *ToBePromoted);
4976
4977 /// \brief Check whether or not it is profitable to promote all the
4978 /// instructions enqueued to be promoted.
4979 bool isProfitableToPromote() {
4980 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4981 unsigned Index = isa<ConstantInt>(ValIdx)
4982 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4983 : -1;
4984 Type *PromotedType = getTransitionType();
4985
4986 StoreInst *ST = cast<StoreInst>(CombineInst);
4987 unsigned AS = ST->getPointerAddressSpace();
4988 unsigned Align = ST->getAlignment();
4989 // Check if this store is supported.
4990 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004991 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4992 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004993 // If this is not supported, there is no way we can combine
4994 // the extract with the store.
4995 return false;
4996 }
4997
4998 // The scalar chain of computation has to pay for the transition
4999 // scalar to vector.
5000 // The vector chain has to account for the combining cost.
5001 uint64_t ScalarCost =
5002 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
5003 uint64_t VectorCost = StoreExtractCombineCost;
5004 for (const auto &Inst : InstsToBePromoted) {
5005 // Compute the cost.
5006 // By construction, all instructions being promoted are arithmetic ones.
5007 // Moreover, one argument is a constant that can be viewed as a splat
5008 // constant.
5009 Value *Arg0 = Inst->getOperand(0);
5010 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
5011 isa<ConstantFP>(Arg0);
5012 TargetTransformInfo::OperandValueKind Arg0OVK =
5013 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5014 : TargetTransformInfo::OK_AnyValue;
5015 TargetTransformInfo::OperandValueKind Arg1OVK =
5016 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
5017 : TargetTransformInfo::OK_AnyValue;
5018 ScalarCost += TTI.getArithmeticInstrCost(
5019 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
5020 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
5021 Arg0OVK, Arg1OVK);
5022 }
5023 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
5024 << ScalarCost << "\nVector: " << VectorCost << '\n');
5025 return ScalarCost > VectorCost;
5026 }
5027
5028 /// \brief Generate a constant vector with \p Val with the same
5029 /// number of elements as the transition.
5030 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00005031 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00005032 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
5033 /// otherwise we generate a vector with as many undef as possible:
5034 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
5035 /// used at the index of the extract.
5036 Value *getConstantVector(Constant *Val, bool UseSplat) const {
5037 unsigned ExtractIdx = UINT_MAX;
5038 if (!UseSplat) {
5039 // If we cannot determine where the constant must be, we have to
5040 // use a splat constant.
5041 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
5042 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
5043 ExtractIdx = CstVal->getSExtValue();
5044 else
5045 UseSplat = true;
5046 }
5047
5048 unsigned End = getTransitionType()->getVectorNumElements();
5049 if (UseSplat)
5050 return ConstantVector::getSplat(End, Val);
5051
5052 SmallVector<Constant *, 4> ConstVec;
5053 UndefValue *UndefVal = UndefValue::get(Val->getType());
5054 for (unsigned Idx = 0; Idx != End; ++Idx) {
5055 if (Idx == ExtractIdx)
5056 ConstVec.push_back(Val);
5057 else
5058 ConstVec.push_back(UndefVal);
5059 }
5060 return ConstantVector::get(ConstVec);
5061 }
5062
5063 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
5064 /// in \p Use can trigger undefined behavior.
5065 static bool canCauseUndefinedBehavior(const Instruction *Use,
5066 unsigned OperandIdx) {
5067 // This is not safe to introduce undef when the operand is on
5068 // the right hand side of a division-like instruction.
5069 if (OperandIdx != 1)
5070 return false;
5071 switch (Use->getOpcode()) {
5072 default:
5073 return false;
5074 case Instruction::SDiv:
5075 case Instruction::UDiv:
5076 case Instruction::SRem:
5077 case Instruction::URem:
5078 return true;
5079 case Instruction::FDiv:
5080 case Instruction::FRem:
5081 return !Use->hasNoNaNs();
5082 }
5083 llvm_unreachable(nullptr);
5084 }
5085
5086public:
Mehdi Amini44ede332015-07-09 02:09:04 +00005087 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
5088 const TargetTransformInfo &TTI, Instruction *Transition,
5089 unsigned CombineCost)
5090 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00005091 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
5092 assert(Transition && "Do not know how to promote null");
5093 }
5094
5095 /// \brief Check if we can promote \p ToBePromoted to \p Type.
5096 bool canPromote(const Instruction *ToBePromoted) const {
5097 // We could support CastInst too.
5098 return isa<BinaryOperator>(ToBePromoted);
5099 }
5100
5101 /// \brief Check if it is profitable to promote \p ToBePromoted
5102 /// by moving downward the transition through.
5103 bool shouldPromote(const Instruction *ToBePromoted) const {
5104 // Promote only if all the operands can be statically expanded.
5105 // Indeed, we do not want to introduce any new kind of transitions.
5106 for (const Use &U : ToBePromoted->operands()) {
5107 const Value *Val = U.get();
5108 if (Val == getEndOfTransition()) {
5109 // If the use is a division and the transition is on the rhs,
5110 // we cannot promote the operation, otherwise we may create a
5111 // division by zero.
5112 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
5113 return false;
5114 continue;
5115 }
5116 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
5117 !isa<ConstantFP>(Val))
5118 return false;
5119 }
5120 // Check that the resulting operation is legal.
5121 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
5122 if (!ISDOpcode)
5123 return false;
5124 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00005125 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00005126 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00005127 }
5128
5129 /// \brief Check whether or not \p Use can be combined
5130 /// with the transition.
5131 /// I.e., is it possible to do Use(Transition) => AnotherUse?
5132 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
5133
5134 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5135 void enqueueForPromotion(Instruction *ToBePromoted) {
5136 InstsToBePromoted.push_back(ToBePromoted);
5137 }
5138
5139 /// \brief Set the instruction that will be combined with the transition.
5140 void recordCombineInstruction(Instruction *ToBeCombined) {
5141 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5142 CombineInst = ToBeCombined;
5143 }
5144
5145 /// \brief Promote all the instructions enqueued for promotion if it is
5146 /// is profitable.
5147 /// \return True if the promotion happened, false otherwise.
5148 bool promote() {
5149 // Check if there is something to promote.
5150 // Right now, if we do not have anything to combine with,
5151 // we assume the promotion is not profitable.
5152 if (InstsToBePromoted.empty() || !CombineInst)
5153 return false;
5154
5155 // Check cost.
5156 if (!StressStoreExtract && !isProfitableToPromote())
5157 return false;
5158
5159 // Promote.
5160 for (auto &ToBePromoted : InstsToBePromoted)
5161 promoteImpl(ToBePromoted);
5162 InstsToBePromoted.clear();
5163 return true;
5164 }
5165};
5166} // End of anonymous namespace.
5167
5168void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5169 // At this point, we know that all the operands of ToBePromoted but Def
5170 // can be statically promoted.
5171 // For Def, we need to use its parameter in ToBePromoted:
5172 // b = ToBePromoted ty1 a
5173 // Def = Transition ty1 b to ty2
5174 // Move the transition down.
5175 // 1. Replace all uses of the promoted operation by the transition.
5176 // = ... b => = ... Def.
5177 assert(ToBePromoted->getType() == Transition->getType() &&
5178 "The type of the result of the transition does not match "
5179 "the final type");
5180 ToBePromoted->replaceAllUsesWith(Transition);
5181 // 2. Update the type of the uses.
5182 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5183 Type *TransitionTy = getTransitionType();
5184 ToBePromoted->mutateType(TransitionTy);
5185 // 3. Update all the operands of the promoted operation with promoted
5186 // operands.
5187 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5188 for (Use &U : ToBePromoted->operands()) {
5189 Value *Val = U.get();
5190 Value *NewVal = nullptr;
5191 if (Val == Transition)
5192 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5193 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5194 isa<ConstantFP>(Val)) {
5195 // Use a splat constant if it is not safe to use undef.
5196 NewVal = getConstantVector(
5197 cast<Constant>(Val),
5198 isa<UndefValue>(Val) ||
5199 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5200 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005201 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5202 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005203 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5204 }
5205 Transition->removeFromParent();
5206 Transition->insertAfter(ToBePromoted);
5207 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5208}
5209
5210/// Some targets can do store(extractelement) with one instruction.
5211/// Try to push the extractelement towards the stores when the target
5212/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005213bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005214 unsigned CombineCost = UINT_MAX;
5215 if (DisableStoreExtract || !TLI ||
5216 (!StressStoreExtract &&
5217 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5218 Inst->getOperand(1), CombineCost)))
5219 return false;
5220
5221 // At this point we know that Inst is a vector to scalar transition.
5222 // Try to move it down the def-use chain, until:
5223 // - We can combine the transition with its single use
5224 // => we got rid of the transition.
5225 // - We escape the current basic block
5226 // => we would need to check that we are moving it at a cheaper place and
5227 // we do not do that for now.
5228 BasicBlock *Parent = Inst->getParent();
5229 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005230 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005231 // If the transition has more than one use, assume this is not going to be
5232 // beneficial.
5233 while (Inst->hasOneUse()) {
5234 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5235 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5236
5237 if (ToBePromoted->getParent() != Parent) {
5238 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5239 << ToBePromoted->getParent()->getName()
5240 << ") than the transition (" << Parent->getName() << ").\n");
5241 return false;
5242 }
5243
5244 if (VPH.canCombine(ToBePromoted)) {
5245 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5246 << "will be combined with: " << *ToBePromoted << '\n');
5247 VPH.recordCombineInstruction(ToBePromoted);
5248 bool Changed = VPH.promote();
5249 NumStoreExtractExposed += Changed;
5250 return Changed;
5251 }
5252
5253 DEBUG(dbgs() << "Try promoting.\n");
5254 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5255 return false;
5256
5257 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5258
5259 VPH.enqueueForPromotion(ToBePromoted);
5260 Inst = ToBePromoted;
5261 }
5262 return false;
5263}
5264
Sanjay Patelfc580a62015-09-21 23:03:16 +00005265bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005266 // Bail out if we inserted the instruction to prevent optimizations from
5267 // stepping on each other's toes.
5268 if (InsertedInsts.count(I))
5269 return false;
5270
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005271 if (PHINode *P = dyn_cast<PHINode>(I)) {
5272 // It is possible for very late stage optimizations (such as SimplifyCFG)
5273 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5274 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005275 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005276 P->replaceAllUsesWith(V);
5277 P->eraseFromParent();
5278 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005279 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005280 }
Chris Lattneree588de2011-01-15 07:29:01 +00005281 return false;
5282 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005283
Chris Lattneree588de2011-01-15 07:29:01 +00005284 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005285 // If the source of the cast is a constant, then this should have
5286 // already been constant folded. The only reason NOT to constant fold
5287 // it is if something (e.g. LSR) was careful to place the constant
5288 // evaluation in a block other than then one that uses it (e.g. to hoist
5289 // the address of globals out of a loop). If this is the case, we don't
5290 // want to forward-subst the cast.
5291 if (isa<Constant>(CI->getOperand(0)))
5292 return false;
5293
Mehdi Amini44ede332015-07-09 02:09:04 +00005294 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005295 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005296
Chris Lattneree588de2011-01-15 07:29:01 +00005297 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005298 /// Sink a zext or sext into its user blocks if the target type doesn't
5299 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005300 if (TLI &&
5301 TLI->getTypeAction(CI->getContext(),
5302 TLI->getValueType(*DL, CI->getType())) ==
5303 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005304 return SinkCast(CI);
5305 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005306 bool MadeChange = moveExtToFormExtLoad(I);
5307 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005308 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005309 }
Chris Lattneree588de2011-01-15 07:29:01 +00005310 return false;
5311 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005312
Chris Lattneree588de2011-01-15 07:29:01 +00005313 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005314 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005315 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005316
Chris Lattneree588de2011-01-15 07:29:01 +00005317 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00005318 LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005319 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005320 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005321 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005322 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5323 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005324 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005325 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005326 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005327
Chris Lattneree588de2011-01-15 07:29:01 +00005328 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Sanjoy Das00757272016-12-16 20:29:39 +00005329 SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005330 if (TLI) {
5331 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005332 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005333 SI->getOperand(0)->getType(), AS);
5334 }
Chris Lattneree588de2011-01-15 07:29:01 +00005335 return false;
5336 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005337
Yi Jiangd069f632014-04-21 19:34:27 +00005338 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5339
5340 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5341 BinOp->getOpcode() == Instruction::LShr)) {
5342 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5343 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005344 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005345
5346 return false;
5347 }
5348
Chris Lattneree588de2011-01-15 07:29:01 +00005349 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005350 if (GEPI->hasAllZeroIndices()) {
5351 /// The GEP operand must be a pointer, so must its result -> BitCast
5352 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5353 GEPI->getName(), GEPI);
5354 GEPI->replaceAllUsesWith(NC);
5355 GEPI->eraseFromParent();
5356 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005357 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005358 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005359 }
Chris Lattneree588de2011-01-15 07:29:01 +00005360 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005361 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005362
Chris Lattneree588de2011-01-15 07:29:01 +00005363 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005364 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005365
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005366 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005367 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005368
Tim Northoveraeb8e062014-02-19 10:02:43 +00005369 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005370 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005371
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005372 if (auto *Switch = dyn_cast<SwitchInst>(I))
5373 return optimizeSwitchInst(Switch);
5374
Quentin Colombetc32615d2014-10-31 17:52:53 +00005375 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005376 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005377
Chris Lattneree588de2011-01-15 07:29:01 +00005378 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005379}
5380
James Molloyf01488e2016-01-15 09:20:19 +00005381/// Given an OR instruction, check to see if this is a bitreverse
5382/// idiom. If so, insert the new intrinsic and return true.
5383static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5384 const TargetLowering &TLI) {
5385 if (!I.getType()->isIntegerTy() ||
5386 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5387 TLI.getValueType(DL, I.getType(), true)))
5388 return false;
5389
5390 SmallVector<Instruction*, 4> Insts;
Chad Rosiera00df492016-05-25 16:22:14 +00005391 if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
James Molloyf01488e2016-01-15 09:20:19 +00005392 return false;
5393 Instruction *LastInst = Insts.back();
5394 I.replaceAllUsesWith(LastInst);
5395 RecursivelyDeleteTriviallyDeadInstructions(&I);
5396 return true;
5397}
5398
Chris Lattnerf2836d12007-03-31 04:06:36 +00005399// In this pass we look for GEP and cast instructions that are used
5400// across basic blocks and rewrite them to improve basic-block-at-a-time
5401// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005402bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005403 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005404 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005405
Chris Lattner7a277142011-01-15 07:14:54 +00005406 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005407 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005408 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005409 if (ModifiedDT)
5410 return true;
5411 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005412
James Molloyf01488e2016-01-15 09:20:19 +00005413 bool MadeBitReverse = true;
5414 while (TLI && MadeBitReverse) {
5415 MadeBitReverse = false;
5416 for (auto &I : reverse(BB)) {
5417 if (makeBitReverse(I, *DL, *TLI)) {
5418 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005419 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005420 break;
5421 }
5422 }
5423 }
James Molloy3ef84c42016-01-15 10:36:01 +00005424 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005425
Chris Lattnerf2836d12007-03-31 04:06:36 +00005426 return MadeChange;
5427}
Devang Patel53771ba2011-08-18 00:50:51 +00005428
5429// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005430// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005431// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005432bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005433 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005434 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005435 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005436 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005437 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005438 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005439 // Leave dbg.values that refer to an alloca alone. These
5440 // instrinsics describe the address of a variable (= the alloca)
5441 // being taken. They should not be moved next to the alloca
5442 // (and to the beginning of the scope), but rather stay close to
5443 // where said address is used.
5444 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005445 PrevNonDbgInst = Insn;
5446 continue;
5447 }
5448
5449 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5450 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005451 // If VI is a phi in a block with an EHPad terminator, we can't insert
5452 // after it.
5453 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5454 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005455 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5456 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005457 if (isa<PHINode>(VI))
5458 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5459 else
5460 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005461 MadeChange = true;
5462 ++NumDbgValueMoved;
5463 }
5464 }
5465 }
5466 return MadeChange;
5467}
Tim Northovercea0abb2014-03-29 08:22:29 +00005468
5469// If there is a sequence that branches based on comparing a single bit
5470// against zero that can be combined into a single instruction, and the
5471// target supports folding these into a single instruction, sink the
5472// mask and compare into the branch uses. Do this before OptimizeBlock ->
5473// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5474// searched for.
5475bool CodeGenPrepare::sinkAndCmp(Function &F) {
5476 if (!EnableAndCmpSinking)
5477 return false;
5478 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5479 return false;
5480 bool MadeChange = false;
Sanjay Patel892f1672016-04-11 20:13:44 +00005481 for (BasicBlock &BB : F) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005482 // Does this BB end with the following?
5483 // %andVal = and %val, #single-bit-set
5484 // %icmpVal = icmp %andResult, 0
5485 // br i1 %cmpVal label %dest1, label %dest2"
Sanjay Patel892f1672016-04-11 20:13:44 +00005486 BranchInst *Brcc = dyn_cast<BranchInst>(BB.getTerminator());
Tim Northovercea0abb2014-03-29 08:22:29 +00005487 if (!Brcc || !Brcc->isConditional())
5488 continue;
5489 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005490 if (!Cmp || Cmp->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005491 continue;
5492 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5493 if (!Zero || !Zero->isZero())
5494 continue;
5495 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
Sanjay Patel892f1672016-04-11 20:13:44 +00005496 if (!And || And->getOpcode() != Instruction::And || And->getParent() != &BB)
Tim Northovercea0abb2014-03-29 08:22:29 +00005497 continue;
5498 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5499 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5500 continue;
Sanjay Patel892f1672016-04-11 20:13:44 +00005501 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB.dump());
Tim Northovercea0abb2014-03-29 08:22:29 +00005502
5503 // Push the "and; icmp" for any users that are conditional branches.
5504 // Since there can only be one branch use per BB, we don't need to keep
5505 // track of which BBs we insert into.
Sanjay Patel892f1672016-04-11 20:13:44 +00005506 for (Use &TheUse : Cmp->uses()) {
Tim Northovercea0abb2014-03-29 08:22:29 +00005507 // Find brcc use.
Sanjay Patel892f1672016-04-11 20:13:44 +00005508 BranchInst *BrccUser = dyn_cast<BranchInst>(TheUse);
Tim Northovercea0abb2014-03-29 08:22:29 +00005509 if (!BrccUser || !BrccUser->isConditional())
5510 continue;
5511 BasicBlock *UserBB = BrccUser->getParent();
Sanjay Patel892f1672016-04-11 20:13:44 +00005512 if (UserBB == &BB) continue;
Tim Northovercea0abb2014-03-29 08:22:29 +00005513 DEBUG(dbgs() << "found Brcc use\n");
5514
5515 // Sink the "and; icmp" to use.
5516 MadeChange = true;
5517 BinaryOperator *NewAnd =
5518 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5519 BrccUser);
5520 CmpInst *NewCmp =
5521 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5522 "", BrccUser);
5523 TheUse = NewCmp;
5524 ++NumAndCmpsMoved;
5525 DEBUG(BrccUser->getParent()->dump());
5526 }
5527 }
5528 return MadeChange;
5529}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005530
5531/// \brief Scale down both weights to fit into uint32_t.
5532static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5533 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5534 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5535 NewTrue = NewTrue / Scale;
5536 NewFalse = NewFalse / Scale;
5537}
5538
5539/// \brief Some targets prefer to split a conditional branch like:
5540/// \code
5541/// %0 = icmp ne i32 %a, 0
5542/// %1 = icmp ne i32 %b, 0
5543/// %or.cond = or i1 %0, %1
5544/// br i1 %or.cond, label %TrueBB, label %FalseBB
5545/// \endcode
5546/// into multiple branch instructions like:
5547/// \code
5548/// bb1:
5549/// %0 = icmp ne i32 %a, 0
5550/// br i1 %0, label %TrueBB, label %bb2
5551/// bb2:
5552/// %1 = icmp ne i32 %b, 0
5553/// br i1 %1, label %TrueBB, label %FalseBB
5554/// \endcode
5555/// This usually allows instruction selection to do even further optimizations
5556/// and combine the compare with the branch instruction. Currently this is
5557/// applied for targets which have "cheap" jump instructions.
5558///
5559/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5560///
5561bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005562 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005563 return false;
5564
5565 bool MadeChange = false;
5566 for (auto &BB : F) {
5567 // Does this BB end with the following?
5568 // %cond1 = icmp|fcmp|binary instruction ...
5569 // %cond2 = icmp|fcmp|binary instruction ...
5570 // %cond.or = or|and i1 %cond1, cond2
5571 // br i1 %cond.or label %dest1, label %dest2"
5572 BinaryOperator *LogicOp;
5573 BasicBlock *TBB, *FBB;
5574 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5575 continue;
5576
Sanjay Patel42574202015-09-02 19:23:23 +00005577 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5578 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5579 continue;
5580
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005581 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005582 Value *Cond1, *Cond2;
5583 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5584 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005585 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005586 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5587 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005588 Opc = Instruction::Or;
5589 else
5590 continue;
5591
5592 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5593 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5594 continue;
5595
5596 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5597
5598 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005599 auto TmpBB =
5600 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5601 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005602
5603 // Update original basic block by using the first condition directly by the
5604 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005605 Br1->setCondition(Cond1);
5606 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005607
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005608 // Depending on the conditon we have to either replace the true or the false
5609 // successor of the original branch instruction.
5610 if (Opc == Instruction::And)
5611 Br1->setSuccessor(0, TmpBB);
5612 else
5613 Br1->setSuccessor(1, TmpBB);
5614
5615 // Fill in the new basic block.
5616 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005617 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5618 I->removeFromParent();
5619 I->insertBefore(Br2);
5620 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005621
5622 // Update PHI nodes in both successors. The original BB needs to be
5623 // replaced in one succesor's PHI nodes, because the branch comes now from
5624 // the newly generated BB (NewBB). In the other successor we need to add one
5625 // incoming edge to the PHI nodes, because both branch instructions target
5626 // now the same successor. Depending on the original branch condition
5627 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
Simon Pilgrimf2fbf432016-11-20 13:47:59 +00005628 // we perform the correct update for the PHI nodes.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005629 // This doesn't change the successor order of the just created branch
5630 // instruction (or any other instruction).
5631 if (Opc == Instruction::Or)
5632 std::swap(TBB, FBB);
5633
5634 // Replace the old BB with the new BB.
5635 for (auto &I : *TBB) {
5636 PHINode *PN = dyn_cast<PHINode>(&I);
5637 if (!PN)
5638 break;
5639 int i;
5640 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5641 PN->setIncomingBlock(i, TmpBB);
5642 }
5643
5644 // Add another incoming edge form the new BB.
5645 for (auto &I : *FBB) {
5646 PHINode *PN = dyn_cast<PHINode>(&I);
5647 if (!PN)
5648 break;
5649 auto *Val = PN->getIncomingValueForBlock(&BB);
5650 PN->addIncoming(Val, TmpBB);
5651 }
5652
5653 // Update the branch weights (from SelectionDAGBuilder::
5654 // FindMergedConditions).
5655 if (Opc == Instruction::Or) {
5656 // Codegen X | Y as:
5657 // BB1:
5658 // jmp_if_X TBB
5659 // jmp TmpBB
5660 // TmpBB:
5661 // jmp_if_Y TBB
5662 // jmp FBB
5663 //
5664
5665 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5666 // The requirement is that
5667 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5668 // = TrueProb for orignal BB.
5669 // Assuming the orignal weights are A and B, one choice is to set BB1's
5670 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5671 // assumes that
5672 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5673 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5674 // TmpBB, but the math is more complicated.
5675 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005676 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005677 uint64_t NewTrueWeight = TrueWeight;
5678 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5679 scaleWeights(NewTrueWeight, NewFalseWeight);
5680 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5681 .createBranchWeights(TrueWeight, FalseWeight));
5682
5683 NewTrueWeight = TrueWeight;
5684 NewFalseWeight = 2 * FalseWeight;
5685 scaleWeights(NewTrueWeight, NewFalseWeight);
5686 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5687 .createBranchWeights(TrueWeight, FalseWeight));
5688 }
5689 } else {
5690 // Codegen X & Y as:
5691 // BB1:
5692 // jmp_if_X TmpBB
5693 // jmp FBB
5694 // TmpBB:
5695 // jmp_if_Y TBB
5696 // jmp FBB
5697 //
5698 // This requires creation of TmpBB after CurBB.
5699
5700 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5701 // The requirement is that
5702 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5703 // = FalseProb for orignal BB.
5704 // Assuming the orignal weights are A and B, one choice is to set BB1's
5705 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5706 // assumes that
5707 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5708 uint64_t TrueWeight, FalseWeight;
Sanjay Pateldc88bd62016-04-23 20:01:22 +00005709 if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005710 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5711 uint64_t NewFalseWeight = FalseWeight;
5712 scaleWeights(NewTrueWeight, NewFalseWeight);
5713 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5714 .createBranchWeights(TrueWeight, FalseWeight));
5715
5716 NewTrueWeight = 2 * TrueWeight;
5717 NewFalseWeight = FalseWeight;
5718 scaleWeights(NewTrueWeight, NewFalseWeight);
5719 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5720 .createBranchWeights(TrueWeight, FalseWeight));
5721 }
5722 }
5723
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005724 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005725 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005726 ModifiedDT = true;
5727
5728 MadeChange = true;
5729
5730 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5731 TmpBB->dump());
5732 }
5733 return MadeChange;
5734}