blob: 922689e26db11511d629d720c26276fe8cd19d73 [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"
Chandler Carruth62d42152015-01-15 02:16:27 +000021#include "llvm/Analysis/TargetLibraryInfo.h"
Quentin Colombetc32615d2014-10-31 17:52:53 +000022#include "llvm/Analysis/TargetTransformInfo.h"
Sanjay Patel69a50a12015-10-19 21:59:12 +000023#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000024#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000029#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000030#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/IRBuilder.h"
32#include "llvm/IR/InlineAsm.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000035#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000036#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000037#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000038#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000039#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000040#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000041#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000042#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000044#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000045#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000046#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000048#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000049#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000050#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000051using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000052using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000053
Chandler Carruth1b9dde02014-04-22 02:02:50 +000054#define DEBUG_TYPE "codegenprepare"
55
Cameron Zwarichced753f2011-01-05 17:27:27 +000056STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000057STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
58STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000059STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
60 "sunken Cmps");
61STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
62 "of sunken Casts");
63STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
64 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000065STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
66STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
67STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000068STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000069STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000070STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000071STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000072
Cameron Zwarich338d3622011-03-11 21:52:04 +000073static cl::opt<bool> DisableBranchOpts(
74 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
75 cl::desc("Disable branch optimizations in CodeGenPrepare"));
76
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000077static cl::opt<bool>
78 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
79 cl::desc("Disable GC optimizations in CodeGenPrepare"));
80
Benjamin Kramer3d38c172012-05-06 14:25:16 +000081static cl::opt<bool> DisableSelectToBranch(
82 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
83 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000084
Hal Finkelc3998302014-04-12 00:59:48 +000085static cl::opt<bool> AddrSinkUsingGEPs(
86 "addr-sink-using-gep", cl::Hidden, cl::init(false),
87 cl::desc("Address sinking in CGP using GEPs."));
88
Tim Northovercea0abb2014-03-29 08:22:29 +000089static cl::opt<bool> EnableAndCmpSinking(
90 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
91 cl::desc("Enable sinkinig and/cmp into branches."));
92
Quentin Colombetc32615d2014-10-31 17:52:53 +000093static cl::opt<bool> DisableStoreExtract(
94 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
95 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
96
97static cl::opt<bool> StressStoreExtract(
98 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
99 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
100
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000101static cl::opt<bool> DisableExtLdPromotion(
102 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
103 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
104 "CodeGenPrepare"));
105
106static cl::opt<bool> StressExtLdPromotion(
107 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
108 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
109 "optimization in CodeGenPrepare"));
110
Eric Christopherc1ea1492008-09-24 05:32:41 +0000111namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000112typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000113typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000114typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000115class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000116
Chris Lattner2dd09db2009-09-02 06:11:42 +0000117 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000118 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000119 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000120 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000121 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000122
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000123 /// As we scan instructions optimizing them, this is the next instruction
124 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000125 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000126
Evan Cheng0663f232011-03-21 01:19:09 +0000127 /// Keeps track of non-local addresses that have been sunk into a block.
128 /// This allows us to avoid inserting duplicate code for blocks with
129 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000130 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000131
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000132 /// Keeps track of all instructions inserted for the current function.
133 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000134 /// Keeps track of the type of the related instruction before their
135 /// promotion for the current function.
136 InstrToOrigTy PromotedInsts;
137
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000138 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000139 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000140
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000141 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000142 bool OptSize;
143
Mehdi Amini4fe37982015-07-07 18:45:17 +0000144 /// DataLayout for the Function being processed.
145 const DataLayout *DL;
146
Chris Lattnerf2836d12007-03-31 04:06:36 +0000147 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000148 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000149 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000150 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000151 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
152 }
Craig Topper4584cd52014-03-07 09:26:03 +0000153 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000154
Craig Topper4584cd52014-03-07 09:26:03 +0000155 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000156
Craig Topper4584cd52014-03-07 09:26:03 +0000157 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000158 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000159 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000160 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000161 }
162
Chris Lattnerf2836d12007-03-31 04:06:36 +0000163 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000164 bool eliminateFallThrough(Function &F);
165 bool eliminateMostlyEmptyBlocks(Function &F);
166 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
167 void eliminateMostlyEmptyBlock(BasicBlock *BB);
168 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
169 bool optimizeInst(Instruction *I, bool& ModifiedDT);
170 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000171 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000172 bool optimizeInlineAsmInst(CallInst *CS);
173 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
174 bool moveExtToFormExtLoad(Instruction *&I);
175 bool optimizeExtUses(Instruction *I);
176 bool optimizeSelectInst(SelectInst *SI);
177 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
178 bool optimizeExtractElementInst(Instruction *Inst);
179 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
180 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000181 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000182 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000183 Instruction *&Inst,
184 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000185 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000186 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000187 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000188 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000189 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000190}
Devang Patel09f162c2007-05-01 21:15:47 +0000191
Devang Patel8c78a0b2007-05-03 01:11:54 +0000192char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000193INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
194 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000195
Bill Wendling7a639ea2013-06-19 21:07:11 +0000196FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
197 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000198}
199
Chris Lattnerf2836d12007-03-31 04:06:36 +0000200bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000201 if (skipOptnoneFunction(F))
202 return false;
203
Mehdi Amini4fe37982015-07-07 18:45:17 +0000204 DL = &F.getParent()->getDataLayout();
205
Chris Lattnerf2836d12007-03-31 04:06:36 +0000206 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000207 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000208 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000209 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000210
Devang Patel8f606d72011-03-24 15:35:25 +0000211 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000212 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000213 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000214 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000215 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000216 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000217
Preston Gurdcdf540d2012-09-04 18:22:17 +0000218 /// This optimization identifies DIV instructions that can be
219 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000220 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000221 const DenseMap<unsigned int, unsigned int> &BypassWidths =
222 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000223 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000224 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000225 }
226
227 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000228 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000229 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000230
Devang Patel53771ba2011-08-18 00:50:51 +0000231 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000232 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000233 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000234 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000235
Tim Northovercea0abb2014-03-29 08:22:29 +0000236 // If there is a mask, compare against zero, and branch that can be combined
237 // into a single target instruction, push the mask and compare into branch
238 // users. Do this before OptimizeBlock -> OptimizeInst ->
239 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000240 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000241 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000242 EverMadeChange |= splitBranchCondition(F);
243 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000244
Chris Lattnerc3748562007-04-02 01:35:34 +0000245 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000246 while (MadeChange) {
247 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000248 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000249 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000250 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000251 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000252
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000253 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000254 if (ModifiedDTOnIteration)
255 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000256 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000257 EverMadeChange |= MadeChange;
258 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000259
260 SunkAddrs.clear();
261
Cameron Zwarich338d3622011-03-11 21:52:04 +0000262 if (!DisableBranchOpts) {
263 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000264 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000265 for (BasicBlock &BB : F) {
266 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
267 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000268 if (!MadeChange) continue;
269
270 for (SmallVectorImpl<BasicBlock*>::iterator
271 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
272 if (pred_begin(*II) == pred_end(*II))
273 WorkList.insert(*II);
274 }
275
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000276 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000277 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000278 while (!WorkList.empty()) {
279 BasicBlock *BB = *WorkList.begin();
280 WorkList.erase(BB);
281 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
282
283 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000284
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000285 for (SmallVectorImpl<BasicBlock*>::iterator
286 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
287 if (pred_begin(*II) == pred_end(*II))
288 WorkList.insert(*II);
289 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000290
Nadav Rotem70409992012-08-14 05:19:07 +0000291 // Merge pairs of basic blocks with unconditional branches, connected by
292 // a single edge.
293 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000294 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000295
Cameron Zwarich338d3622011-03-11 21:52:04 +0000296 EverMadeChange |= MadeChange;
297 }
298
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000299 if (!DisableGCOpts) {
300 SmallVector<Instruction *, 2> Statepoints;
301 for (BasicBlock &BB : F)
302 for (Instruction &I : BB)
303 if (isStatepoint(I))
304 Statepoints.push_back(&I);
305 for (auto &I : Statepoints)
306 EverMadeChange |= simplifyOffsetableRelocate(*I);
307 }
308
Chris Lattnerf2836d12007-03-31 04:06:36 +0000309 return EverMadeChange;
310}
311
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000312/// Merge basic blocks which are connected by a single edge, where one of the
313/// basic blocks has a single successor pointing to the other basic block,
314/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000315bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000316 bool Changed = false;
317 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000318 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000319 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000320 // If the destination block has a single pred, then this is a trivial
321 // edge, just collapse it.
322 BasicBlock *SinglePred = BB->getSinglePredecessor();
323
Evan Cheng64a223a2012-09-28 23:58:57 +0000324 // Don't merge if BB's address is taken.
325 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000326
327 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
328 if (Term && !Term->isConditional()) {
329 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000330 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000331 // Remember if SinglePred was the entry block of the function.
332 // If so, we will need to move BB back to the entry position.
333 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000334 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000335
336 if (isEntry && BB != &BB->getParent()->getEntryBlock())
337 BB->moveBefore(&BB->getParent()->getEntryBlock());
338
339 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000340 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000341 }
342 }
343 return Changed;
344}
345
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000346/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
347/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
348/// edges in ways that are non-optimal for isel. Start by eliminating these
349/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000350bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000351 bool MadeChange = false;
352 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000353 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000354 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000355
356 // If this block doesn't end with an uncond branch, ignore it.
357 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
358 if (!BI || !BI->isUnconditional())
359 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000360
Dale Johannesen4026b042009-03-27 01:13:37 +0000361 // If the instruction before the branch (skipping debug info) isn't a phi
362 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000363 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000364 if (BBI != BB->begin()) {
365 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000366 while (isa<DbgInfoIntrinsic>(BBI)) {
367 if (BBI == BB->begin())
368 break;
369 --BBI;
370 }
371 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
372 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000373 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000374
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 // Do not break infinite loops.
376 BasicBlock *DestBB = BI->getSuccessor(0);
377 if (DestBB == BB)
378 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000379
Sanjay Patelfc580a62015-09-21 23:03:16 +0000380 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000381 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000382
Sanjay Patelfc580a62015-09-21 23:03:16 +0000383 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 MadeChange = true;
385 }
386 return MadeChange;
387}
388
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000389/// Return true if we can merge BB into DestBB if there is a single
390/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000391/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000392bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000393 const BasicBlock *DestBB) const {
394 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
395 // the successor. If there are more complex condition (e.g. preheaders),
396 // don't mess around with them.
397 BasicBlock::const_iterator BBI = BB->begin();
398 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000399 for (const User *U : PN->users()) {
400 const Instruction *UI = cast<Instruction>(U);
401 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000402 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000403 // If User is inside DestBB block and it is a PHINode then check
404 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000405 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000406 if (UI->getParent() == DestBB) {
407 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000408 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
409 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
410 if (Insn && Insn->getParent() == BB &&
411 Insn->getParent() != UPN->getIncomingBlock(I))
412 return false;
413 }
414 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000415 }
416 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000417
Chris Lattnerc3748562007-04-02 01:35:34 +0000418 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
419 // and DestBB may have conflicting incoming values for the block. If so, we
420 // can't merge the block.
421 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
422 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000423
Chris Lattnerc3748562007-04-02 01:35:34 +0000424 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000425 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
427 // It is faster to get preds from a PHI than with pred_iterator.
428 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
429 BBPreds.insert(BBPN->getIncomingBlock(i));
430 } else {
431 BBPreds.insert(pred_begin(BB), pred_end(BB));
432 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000433
Chris Lattnerc3748562007-04-02 01:35:34 +0000434 // Walk the preds of DestBB.
435 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
436 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
437 if (BBPreds.count(Pred)) { // Common predecessor?
438 BBI = DestBB->begin();
439 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
440 const Value *V1 = PN->getIncomingValueForBlock(Pred);
441 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000442
Chris Lattnerc3748562007-04-02 01:35:34 +0000443 // If V2 is a phi node in BB, look up what the mapped value will be.
444 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
445 if (V2PN->getParent() == BB)
446 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000447
Chris Lattnerc3748562007-04-02 01:35:34 +0000448 // If there is a conflict, bail out.
449 if (V1 != V2) return false;
450 }
451 }
452 }
453
454 return true;
455}
456
457
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000458/// Eliminate a basic block that has only phi's and an unconditional branch in
459/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000460void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000461 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
462 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000463
David Greene74e2d492010-01-05 01:27:11 +0000464 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000465
Chris Lattnerc3748562007-04-02 01:35:34 +0000466 // If the destination block has a single pred, then this is a trivial edge,
467 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000468 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000469 if (SinglePred != DestBB) {
470 // Remember if SinglePred was the entry block of the function. If so, we
471 // will need to move BB back to the entry position.
472 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000473 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000474
Chris Lattner8a172da2008-11-28 19:54:49 +0000475 if (isEntry && BB != &BB->getParent()->getEntryBlock())
476 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000477
David Greene74e2d492010-01-05 01:27:11 +0000478 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000479 return;
480 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000481 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000482
Chris Lattnerc3748562007-04-02 01:35:34 +0000483 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
484 // to handle the new incoming edges it is about to have.
485 PHINode *PN;
486 for (BasicBlock::iterator BBI = DestBB->begin();
487 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
488 // Remove the incoming value for BB, and remember it.
489 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000490
Chris Lattnerc3748562007-04-02 01:35:34 +0000491 // Two options: either the InVal is a phi node defined in BB or it is some
492 // value that dominates BB.
493 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
494 if (InValPhi && InValPhi->getParent() == BB) {
495 // Add all of the input values of the input PHI as inputs of this phi.
496 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
497 PN->addIncoming(InValPhi->getIncomingValue(i),
498 InValPhi->getIncomingBlock(i));
499 } else {
500 // Otherwise, add one instance of the dominating value for each edge that
501 // we will be adding.
502 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
503 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
504 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
505 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000506 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
507 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000508 }
509 }
510 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000511
Chris Lattnerc3748562007-04-02 01:35:34 +0000512 // The PHIs are now updated, change everything that refers to BB to use
513 // DestBB and remove BB.
514 BB->replaceAllUsesWith(DestBB);
515 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000516 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000517
David Greene74e2d492010-01-05 01:27:11 +0000518 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000519}
520
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000521// Computes a map of base pointer relocation instructions to corresponding
522// derived pointer relocation instructions given a vector of all relocate calls
523static void computeBaseDerivedRelocateMap(
524 const SmallVectorImpl<User *> &AllRelocateCalls,
525 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
526 RelocateInstMap) {
527 // Collect information in two maps: one primarily for locating the base object
528 // while filling the second map; the second map is the final structure holding
529 // a mapping between Base and corresponding Derived relocate calls
530 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
531 for (auto &U : AllRelocateCalls) {
532 GCRelocateOperands ThisRelocate(U);
533 IntrinsicInst *I = cast<IntrinsicInst>(U);
Sanjoy Das499d7032015-05-06 02:36:26 +0000534 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
535 ThisRelocate.getDerivedPtrIndex());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000536 RelocateIdxMap.insert(std::make_pair(K, I));
537 }
538 for (auto &Item : RelocateIdxMap) {
539 std::pair<unsigned, unsigned> Key = Item.first;
540 if (Key.first == Key.second)
541 // Base relocation: nothing to insert
542 continue;
543
544 IntrinsicInst *I = Item.second;
545 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000546
547 // We're iterating over RelocateIdxMap so we cannot modify it.
548 auto MaybeBase = RelocateIdxMap.find(BaseKey);
549 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000550 // TODO: We might want to insert a new base object relocate and gep off
551 // that, if there are enough derived object relocates.
552 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000553
554 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000555 }
556}
557
558// Accepts a GEP and extracts the operands into a vector provided they're all
559// small integer constants
560static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
561 SmallVectorImpl<Value *> &OffsetV) {
562 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
563 // Only accept small constant integer operands
564 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
565 if (!Op || Op->getZExtValue() > 20)
566 return false;
567 }
568
569 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
570 OffsetV.push_back(GEP->getOperand(i));
571 return true;
572}
573
574// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
575// replace, computes a replacement, and affects it.
576static bool
577simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
578 const SmallVectorImpl<IntrinsicInst *> &Targets) {
579 bool MadeChange = false;
580 for (auto &ToReplace : Targets) {
581 GCRelocateOperands MasterRelocate(RelocatedBase);
582 GCRelocateOperands ThisRelocate(ToReplace);
583
Sanjoy Das499d7032015-05-06 02:36:26 +0000584 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000585 "Not relocating a derived object of the original base object");
Sanjoy Das499d7032015-05-06 02:36:26 +0000586 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000587 // A duplicate relocate call. TODO: coalesce duplicates.
588 continue;
589 }
590
Sanjoy Das499d7032015-05-06 02:36:26 +0000591 Value *Base = ThisRelocate.getBasePtr();
592 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000593 if (!Derived || Derived->getPointerOperand() != Base)
594 continue;
595
596 SmallVector<Value *, 2> OffsetV;
597 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
598 continue;
599
600 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000601 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
602
603 // Insert after RelocatedBase
604 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000605 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000606
607 // If gc_relocate does not match the actual type, cast it to the right type.
608 // In theory, there must be a bitcast after gc_relocate if the type does not
609 // match, and we should reuse it to get the derived pointer. But it could be
610 // cases like this:
611 // bb1:
612 // ...
613 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
614 // br label %merge
615 //
616 // bb2:
617 // ...
618 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
619 // br label %merge
620 //
621 // merge:
622 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
623 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
624 //
625 // In this case, we can not find the bitcast any more. So we insert a new bitcast
626 // no matter there is already one or not. In this way, we can handle all cases, and
627 // the extra bitcast should be optimized away in later passes.
628 Instruction *ActualRelocatedBase = RelocatedBase;
629 if (RelocatedBase->getType() != Base->getType()) {
630 ActualRelocatedBase =
631 cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000632 }
David Blaikie68d535c2015-03-24 22:38:16 +0000633 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000634 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000635 Instruction *ReplacementInst = cast<Instruction>(Replacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000636 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000637 // If the newly generated derived pointer's type does not match the original derived
638 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
639 Instruction *ActualReplacement = ReplacementInst;
640 if (ReplacementInst->getType() != ToReplace->getType()) {
641 ActualReplacement =
642 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000643 }
644 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000645 ToReplace->eraseFromParent();
646
647 MadeChange = true;
648 }
649 return MadeChange;
650}
651
652// Turns this:
653//
654// %base = ...
655// %ptr = gep %base + 15
656// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
657// %base' = relocate(%tok, i32 4, i32 4)
658// %ptr' = relocate(%tok, i32 4, i32 5)
659// %val = load %ptr'
660//
661// into this:
662//
663// %base = ...
664// %ptr = gep %base + 15
665// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
666// %base' = gc.relocate(%tok, i32 4, i32 4)
667// %ptr' = gep %base' + 15
668// %val = load %ptr'
669bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
670 bool MadeChange = false;
671 SmallVector<User *, 2> AllRelocateCalls;
672
673 for (auto *U : I.users())
674 if (isGCRelocate(dyn_cast<Instruction>(U)))
675 // Collect all the relocate calls associated with a statepoint
676 AllRelocateCalls.push_back(U);
677
678 // We need atleast one base pointer relocation + one derived pointer
679 // relocation to mangle
680 if (AllRelocateCalls.size() < 2)
681 return false;
682
683 // RelocateInstMap is a mapping from the base relocate instruction to the
684 // corresponding derived relocate instructions
685 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
686 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
687 if (RelocateInstMap.empty())
688 return false;
689
690 for (auto &Item : RelocateInstMap)
691 // Item.first is the RelocatedBase to offset against
692 // Item.second is the vector of Targets to replace
693 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
694 return MadeChange;
695}
696
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000697/// SinkCast - Sink the specified cast instruction into its user blocks
698static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000699 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000700
Chris Lattnerf2836d12007-03-31 04:06:36 +0000701 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000702 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000703
Chris Lattnerf2836d12007-03-31 04:06:36 +0000704 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000705 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000706 UI != E; ) {
707 Use &TheUse = UI.getUse();
708 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000709
Chris Lattnerf2836d12007-03-31 04:06:36 +0000710 // Figure out which BB this cast is used in. For PHI's this is the
711 // appropriate predecessor block.
712 BasicBlock *UserBB = User->getParent();
713 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000714 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000715 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000716
Chris Lattnerf2836d12007-03-31 04:06:36 +0000717 // Preincrement use iterator so we don't invalidate it.
718 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000719
Chris Lattnerf2836d12007-03-31 04:06:36 +0000720 // If this user is in the same block as the cast, don't change the cast.
721 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000722
Chris Lattnerf2836d12007-03-31 04:06:36 +0000723 // If we have already inserted a cast into this block, use it.
724 CastInst *&InsertedCast = InsertedCasts[UserBB];
725
726 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000727 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000728 assert(InsertPt != UserBB->end());
729 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
730 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000731 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000732
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000733 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000734 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000735 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000736 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000737 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000738
Chris Lattnerf2836d12007-03-31 04:06:36 +0000739 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000740 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000741 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000742 MadeChange = true;
743 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000744
Chris Lattnerf2836d12007-03-31 04:06:36 +0000745 return MadeChange;
746}
747
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000748/// If the specified cast instruction is a noop copy (e.g. it's casting from
749/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
750/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000751///
752/// Return true if any changes are made.
753///
Mehdi Amini44ede332015-07-09 02:09:04 +0000754static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
755 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000756 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000757 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
758 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000759
760 // This is an fp<->int conversion?
761 if (SrcVT.isInteger() != DstVT.isInteger())
762 return false;
763
764 // If this is an extension, it will be a zero or sign extension, which
765 // isn't a noop.
766 if (SrcVT.bitsLT(DstVT)) return false;
767
768 // If these values will be promoted, find out what they will be promoted
769 // to. This helps us consider truncates on PPC as noop copies when they
770 // are.
771 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
772 TargetLowering::TypePromoteInteger)
773 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
774 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
775 TargetLowering::TypePromoteInteger)
776 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
777
778 // If, after promotion, these are the same types, this is a noop copy.
779 if (SrcVT != DstVT)
780 return false;
781
782 return SinkCast(CI);
783}
784
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000785/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
786/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000787///
788/// Return true if any changes were made.
789static bool CombineUAddWithOverflow(CmpInst *CI) {
790 Value *A, *B;
791 Instruction *AddI;
792 if (!match(CI,
793 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
794 return false;
795
796 Type *Ty = AddI->getType();
797 if (!isa<IntegerType>(Ty))
798 return false;
799
800 // We don't want to move around uses of condition values this late, so we we
801 // check if it is legal to create the call to the intrinsic in the basic
802 // block containing the icmp:
803
804 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
805 return false;
806
807#ifndef NDEBUG
808 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
809 // for now:
810 if (AddI->hasOneUse())
811 assert(*AddI->user_begin() == CI && "expected!");
812#endif
813
814 Module *M = CI->getParent()->getParent()->getParent();
815 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
816
817 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
818
819 auto *UAddWithOverflow =
820 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
821 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
822 auto *Overflow =
823 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
824
825 CI->replaceAllUsesWith(Overflow);
826 AddI->replaceAllUsesWith(UAdd);
827 CI->eraseFromParent();
828 AddI->eraseFromParent();
829 return true;
830}
831
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000832/// Sink the given CmpInst into user blocks to reduce the number of virtual
833/// registers that must be created and coalesced. This is a clear win except on
834/// targets with multiple condition code registers (PowerPC), where it might
835/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000836///
837/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000838static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000839 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000840
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000841 /// Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000842 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000843
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000844 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000845 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000846 UI != E; ) {
847 Use &TheUse = UI.getUse();
848 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000849
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000850 // Preincrement use iterator so we don't invalidate it.
851 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000852
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000853 // Don't bother for PHI nodes.
854 if (isa<PHINode>(User))
855 continue;
856
857 // Figure out which BB this cmp is used in.
858 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000859
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000860 // If this user is in the same block as the cmp, don't change the cmp.
861 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000862
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000863 // If we have already inserted a cmp into this block, use it.
864 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
865
866 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000867 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000868 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000869 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000870 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
871 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000872 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000873
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000874 // Replace a use of the cmp with a use of the new cmp.
875 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000876 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000877 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000878 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000879
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000880 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000881 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000882 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000883 MadeChange = true;
884 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000885
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000886 return MadeChange;
887}
888
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000889static bool OptimizeCmpExpression(CmpInst *CI) {
890 if (SinkCmpExpression(CI))
891 return true;
892
893 if (CombineUAddWithOverflow(CI))
894 return true;
895
896 return false;
897}
898
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000899/// Check if the candidates could be combined with a shift instruction, which
900/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000901/// 1. Truncate instruction
902/// 2. And instruction and the imm is a mask of the low bits:
903/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000904static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000905 if (!isa<TruncInst>(User)) {
906 if (User->getOpcode() != Instruction::And ||
907 !isa<ConstantInt>(User->getOperand(1)))
908 return false;
909
Quentin Colombetd4f44692014-04-22 01:20:34 +0000910 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000911
Quentin Colombetd4f44692014-04-22 01:20:34 +0000912 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000913 return false;
914 }
915 return true;
916}
917
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000918/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000919static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000920SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
921 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000922 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000923 BasicBlock *UserBB = User->getParent();
924 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
925 TruncInst *TruncI = dyn_cast<TruncInst>(User);
926 bool MadeChange = false;
927
928 for (Value::user_iterator TruncUI = TruncI->user_begin(),
929 TruncE = TruncI->user_end();
930 TruncUI != TruncE;) {
931
932 Use &TruncTheUse = TruncUI.getUse();
933 Instruction *TruncUser = cast<Instruction>(*TruncUI);
934 // Preincrement use iterator so we don't invalidate it.
935
936 ++TruncUI;
937
938 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
939 if (!ISDOpcode)
940 continue;
941
Tim Northovere2239ff2014-07-29 10:20:22 +0000942 // If the use is actually a legal node, there will not be an
943 // implicit truncate.
944 // FIXME: always querying the result type is just an
945 // approximation; some nodes' legality is determined by the
946 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000947 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000948 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000949 continue;
950
951 // Don't bother for PHI nodes.
952 if (isa<PHINode>(TruncUser))
953 continue;
954
955 BasicBlock *TruncUserBB = TruncUser->getParent();
956
957 if (UserBB == TruncUserBB)
958 continue;
959
960 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
961 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
962
963 if (!InsertedShift && !InsertedTrunc) {
964 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000965 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000966 // Sink the shift
967 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000968 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
969 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000970 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000971 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
972 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000973
974 // Sink the trunc
975 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
976 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000977 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000978
979 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000980 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000981
982 MadeChange = true;
983
984 TruncTheUse = InsertedTrunc;
985 }
986 }
987 return MadeChange;
988}
989
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000990/// Sink the shift *right* instruction into user blocks if the uses could
991/// potentially be combined with this shift instruction and generate BitExtract
992/// instruction. It will only be applied if the architecture supports BitExtract
993/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +0000994/// BB1:
995/// %x.extract.shift = lshr i64 %arg1, 32
996/// BB2:
997/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
998/// ==>
999///
1000/// BB2:
1001/// %x.extract.shift.1 = lshr i64 %arg1, 32
1002/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1003///
1004/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1005/// instruction.
1006/// Return true if any changes are made.
1007static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001008 const TargetLowering &TLI,
1009 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001010 BasicBlock *DefBB = ShiftI->getParent();
1011
1012 /// Only insert instructions in each block once.
1013 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1014
Mehdi Amini44ede332015-07-09 02:09:04 +00001015 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001016
1017 bool MadeChange = false;
1018 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1019 UI != E;) {
1020 Use &TheUse = UI.getUse();
1021 Instruction *User = cast<Instruction>(*UI);
1022 // Preincrement use iterator so we don't invalidate it.
1023 ++UI;
1024
1025 // Don't bother for PHI nodes.
1026 if (isa<PHINode>(User))
1027 continue;
1028
1029 if (!isExtractBitsCandidateUse(User))
1030 continue;
1031
1032 BasicBlock *UserBB = User->getParent();
1033
1034 if (UserBB == DefBB) {
1035 // If the shift and truncate instruction are in the same BB. The use of
1036 // the truncate(TruncUse) may still introduce another truncate if not
1037 // legal. In this case, we would like to sink both shift and truncate
1038 // instruction to the BB of TruncUse.
1039 // for example:
1040 // BB1:
1041 // i64 shift.result = lshr i64 opnd, imm
1042 // trunc.result = trunc shift.result to i16
1043 //
1044 // BB2:
1045 // ----> We will have an implicit truncate here if the architecture does
1046 // not have i16 compare.
1047 // cmp i16 trunc.result, opnd2
1048 //
1049 if (isa<TruncInst>(User) && shiftIsLegal
1050 // If the type of the truncate is legal, no trucate will be
1051 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001052 &&
1053 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001054 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001055 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001056
1057 continue;
1058 }
1059 // If we have already inserted a shift into this block, use it.
1060 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1061
1062 if (!InsertedShift) {
1063 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001064 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001065
1066 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001067 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1068 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001069 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001070 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1071 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001072
1073 MadeChange = true;
1074 }
1075
1076 // Replace a use of the shift with a use of the new shift.
1077 TheUse = InsertedShift;
1078 }
1079
1080 // If we removed all uses, nuke the shift.
1081 if (ShiftI->use_empty())
1082 ShiftI->eraseFromParent();
1083
1084 return MadeChange;
1085}
1086
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001087// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001088// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1089// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001090// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001091// the appropriate mask bit is set
1092//
1093// %1 = bitcast i8* %addr to i32*
1094// %2 = extractelement <16 x i1> %mask, i32 0
1095// %3 = icmp eq i1 %2, true
1096// br i1 %3, label %cond.load, label %else
1097//
1098//cond.load: ; preds = %0
1099// %4 = getelementptr i32* %1, i32 0
1100// %5 = load i32* %4
1101// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1102// br label %else
1103//
1104//else: ; preds = %0, %cond.load
1105// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1106// %7 = extractelement <16 x i1> %mask, i32 1
1107// %8 = icmp eq i1 %7, true
1108// br i1 %8, label %cond.load1, label %else2
1109//
1110//cond.load1: ; preds = %else
1111// %9 = getelementptr i32* %1, i32 1
1112// %10 = load i32* %9
1113// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1114// br label %else2
1115//
1116//else2: ; preds = %else, %cond.load1
1117// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1118// %12 = extractelement <16 x i1> %mask, i32 2
1119// %13 = icmp eq i1 %12, true
1120// br i1 %13, label %cond.load4, label %else5
1121//
1122static void ScalarizeMaskedLoad(CallInst *CI) {
1123 Value *Ptr = CI->getArgOperand(0);
1124 Value *Src0 = CI->getArgOperand(3);
1125 Value *Mask = CI->getArgOperand(2);
1126 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1127 Type *EltTy = VecType->getElementType();
1128
1129 assert(VecType && "Unexpected return type of masked load intrinsic");
1130
1131 IRBuilder<> Builder(CI->getContext());
1132 Instruction *InsertPt = CI;
1133 BasicBlock *IfBlock = CI->getParent();
1134 BasicBlock *CondBlock = nullptr;
1135 BasicBlock *PrevIfBlock = CI->getParent();
1136 Builder.SetInsertPoint(InsertPt);
1137
1138 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1139
1140 // Bitcast %addr fron i8* to EltTy*
1141 Type *NewPtrType =
1142 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1143 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1144 Value *UndefVal = UndefValue::get(VecType);
1145
1146 // The result vector
1147 Value *VResult = UndefVal;
1148
1149 PHINode *Phi = nullptr;
1150 Value *PrevPhi = UndefVal;
1151
1152 unsigned VectorWidth = VecType->getNumElements();
1153 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1154
1155 // Fill the "else" block, created in the previous iteration
1156 //
1157 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1158 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1159 // %to_load = icmp eq i1 %mask_1, true
1160 // br i1 %to_load, label %cond.load, label %else
1161 //
1162 if (Idx > 0) {
1163 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1164 Phi->addIncoming(VResult, CondBlock);
1165 Phi->addIncoming(PrevPhi, PrevIfBlock);
1166 PrevPhi = Phi;
1167 VResult = Phi;
1168 }
1169
1170 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1171 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1172 ConstantInt::get(Predicate->getType(), 1));
1173
1174 // Create "cond" block
1175 //
1176 // %EltAddr = getelementptr i32* %1, i32 0
1177 // %Elt = load i32* %EltAddr
1178 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1179 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001180 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001181 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001182
1183 Value *Gep =
1184 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001185 LoadInst* Load = Builder.CreateLoad(Gep, false);
1186 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1187
1188 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001189 BasicBlock *NewIfBlock =
1190 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001191 Builder.SetInsertPoint(InsertPt);
1192 Instruction *OldBr = IfBlock->getTerminator();
1193 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1194 OldBr->eraseFromParent();
1195 PrevIfBlock = IfBlock;
1196 IfBlock = NewIfBlock;
1197 }
1198
1199 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1200 Phi->addIncoming(VResult, CondBlock);
1201 Phi->addIncoming(PrevPhi, PrevIfBlock);
1202 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1203 CI->replaceAllUsesWith(NewI);
1204 CI->eraseFromParent();
1205}
1206
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001207// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001208// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1209// <16 x i1> %mask)
1210// to a chain of basic blocks, that stores element one-by-one if
1211// the appropriate mask bit is set
1212//
1213// %1 = bitcast i8* %addr to i32*
1214// %2 = extractelement <16 x i1> %mask, i32 0
1215// %3 = icmp eq i1 %2, true
1216// br i1 %3, label %cond.store, label %else
1217//
1218// cond.store: ; preds = %0
1219// %4 = extractelement <16 x i32> %val, i32 0
1220// %5 = getelementptr i32* %1, i32 0
1221// store i32 %4, i32* %5
1222// br label %else
1223//
1224// else: ; preds = %0, %cond.store
1225// %6 = extractelement <16 x i1> %mask, i32 1
1226// %7 = icmp eq i1 %6, true
1227// br i1 %7, label %cond.store1, label %else2
1228//
1229// cond.store1: ; preds = %else
1230// %8 = extractelement <16 x i32> %val, i32 1
1231// %9 = getelementptr i32* %1, i32 1
1232// store i32 %8, i32* %9
1233// br label %else2
1234// . . .
1235static void ScalarizeMaskedStore(CallInst *CI) {
1236 Value *Ptr = CI->getArgOperand(1);
1237 Value *Src = CI->getArgOperand(0);
1238 Value *Mask = CI->getArgOperand(3);
1239
1240 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1241 Type *EltTy = VecType->getElementType();
1242
1243 assert(VecType && "Unexpected data type in masked store intrinsic");
1244
1245 IRBuilder<> Builder(CI->getContext());
1246 Instruction *InsertPt = CI;
1247 BasicBlock *IfBlock = CI->getParent();
1248 Builder.SetInsertPoint(InsertPt);
1249 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1250
1251 // Bitcast %addr fron i8* to EltTy*
1252 Type *NewPtrType =
1253 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1254 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1255
1256 unsigned VectorWidth = VecType->getNumElements();
1257 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1258
1259 // Fill the "else" block, created in the previous iteration
1260 //
1261 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1262 // %to_store = icmp eq i1 %mask_1, true
1263 // br i1 %to_load, label %cond.store, label %else
1264 //
1265 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1266 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1267 ConstantInt::get(Predicate->getType(), 1));
1268
1269 // Create "cond" block
1270 //
1271 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1272 // %EltAddr = getelementptr i32* %1, i32 0
1273 // %store i32 %OneElt, i32* %EltAddr
1274 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001275 BasicBlock *CondBlock =
1276 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001277 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001278
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001279 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001280 Value *Gep =
1281 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001282 Builder.CreateStore(OneElt, Gep);
1283
1284 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001285 BasicBlock *NewIfBlock =
1286 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001287 Builder.SetInsertPoint(InsertPt);
1288 Instruction *OldBr = IfBlock->getTerminator();
1289 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1290 OldBr->eraseFromParent();
1291 IfBlock = NewIfBlock;
1292 }
1293 CI->eraseFromParent();
1294}
1295
Sanjay Patelfc580a62015-09-21 23:03:16 +00001296bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001297 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001298
Chris Lattner7a277142011-01-15 07:14:54 +00001299 // Lower inline assembly if we can.
1300 // If we found an inline asm expession, and if the target knows how to
1301 // lower it to normal LLVM code, do so now.
1302 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1303 if (TLI->ExpandInlineAsm(CI)) {
1304 // Avoid invalidating the iterator.
1305 CurInstIterator = BB->begin();
1306 // Avoid processing instructions out of order, which could cause
1307 // reuse before a value is defined.
1308 SunkAddrs.clear();
1309 return true;
1310 }
1311 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001312 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001313 return true;
1314 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001315
John Brawn0dbcd652015-03-18 12:01:59 +00001316 // Align the pointer arguments to this call if the target thinks it's a good
1317 // idea
1318 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001319 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001320 for (auto &Arg : CI->arg_operands()) {
1321 // We want to align both objects whose address is used directly and
1322 // objects whose address is used in casts and GEPs, though it only makes
1323 // sense for GEPs if the offset is a multiple of the desired alignment and
1324 // if size - offset meets the size threshold.
1325 if (!Arg->getType()->isPointerTy())
1326 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001327 APInt Offset(DL->getPointerSizeInBits(
1328 cast<PointerType>(Arg->getType())->getAddressSpace()),
1329 0);
1330 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001331 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001332 if ((Offset2 & (PrefAlign-1)) != 0)
1333 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001334 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001335 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1336 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001337 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001338 // Global variables can only be aligned if they are defined in this
1339 // object (i.e. they are uniquely initialized in this object), and
1340 // over-aligning global variables that have an explicit section is
1341 // forbidden.
1342 GlobalVariable *GV;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001343 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1344 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1345 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1346 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001347 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001348 }
1349 // If this is a memcpy (or similar) then we may be able to improve the
1350 // alignment
1351 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001352 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001353 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001354 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
John Brawn0dbcd652015-03-18 12:01:59 +00001355 if (Align > MI->getAlignment())
1356 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1357 }
1358 }
1359
Eric Christopher4b7948e2010-03-11 02:41:03 +00001360 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001361 if (II) {
1362 switch (II->getIntrinsicID()) {
1363 default: break;
1364 case Intrinsic::objectsize: {
1365 // Lower all uses of llvm.objectsize.*
1366 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1367 Type *ReturnTy = CI->getType();
1368 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001369
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001370 // Substituting this can cause recursive simplifications, which can
1371 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1372 // happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001373 WeakVH IterHandle(&*CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001374
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001375 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001376 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001377
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001378 // If the iterator instruction was recursively deleted, start over at the
1379 // start of the block.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001380 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001381 CurInstIterator = BB->begin();
1382 SunkAddrs.clear();
1383 }
1384 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001385 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001386 case Intrinsic::masked_load: {
1387 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001388 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001389 ScalarizeMaskedLoad(CI);
1390 ModifiedDT = true;
1391 return true;
1392 }
1393 return false;
1394 }
1395 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001396 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001397 ScalarizeMaskedStore(CI);
1398 ModifiedDT = true;
1399 return true;
1400 }
1401 return false;
1402 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001403 case Intrinsic::aarch64_stlxr:
1404 case Intrinsic::aarch64_stxr: {
1405 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1406 if (!ExtVal || !ExtVal->hasOneUse() ||
1407 ExtVal->getParent() == CI->getParent())
1408 return false;
1409 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1410 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001411 // Mark this instruction as "inserted by CGP", so that other
1412 // optimizations don't touch it.
1413 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001414 return true;
1415 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001416 case Intrinsic::invariant_group_barrier:
1417 II->replaceAllUsesWith(II->getArgOperand(0));
1418 II->eraseFromParent();
1419 return true;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001420 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001421
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001422 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001423 // Unknown address space.
1424 // TODO: Target hook to pick which address space the intrinsic cares
1425 // about?
1426 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001427 SmallVector<Value*, 2> PtrOps;
1428 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001429 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001430 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001431 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001432 return true;
1433 }
Pete Cooper615fd892012-03-13 20:59:56 +00001434 }
1435
Eric Christopher4b7948e2010-03-11 02:41:03 +00001436 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001437 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001438
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001439 // Lower all default uses of _chk calls. This is very similar
1440 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001441 // to fortified library functions (e.g. __memcpy_chk) that have the default
1442 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001443 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001444 if (Value *V = Simplifier.optimizeCall(CI)) {
1445 CI->replaceAllUsesWith(V);
1446 CI->eraseFromParent();
1447 return true;
1448 }
1449 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001450}
Chris Lattner1b93be52011-01-15 07:25:29 +00001451
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001452/// Look for opportunities to duplicate return instructions to the predecessor
1453/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001454/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001455/// bb0:
1456/// %tmp0 = tail call i32 @f0()
1457/// br label %return
1458/// bb1:
1459/// %tmp1 = tail call i32 @f1()
1460/// br label %return
1461/// bb2:
1462/// %tmp2 = tail call i32 @f2()
1463/// br label %return
1464/// return:
1465/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1466/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001467/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001468///
1469/// =>
1470///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001471/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001472/// bb0:
1473/// %tmp0 = tail call i32 @f0()
1474/// ret i32 %tmp0
1475/// bb1:
1476/// %tmp1 = tail call i32 @f1()
1477/// ret i32 %tmp1
1478/// bb2:
1479/// %tmp2 = tail call i32 @f2()
1480/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001481/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001482bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001483 if (!TLI)
1484 return false;
1485
Benjamin Kramer455fa352012-11-23 19:17:06 +00001486 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1487 if (!RI)
1488 return false;
1489
Craig Topperc0196b12014-04-14 00:51:57 +00001490 PHINode *PN = nullptr;
1491 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001492 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001493 if (V) {
1494 BCI = dyn_cast<BitCastInst>(V);
1495 if (BCI)
1496 V = BCI->getOperand(0);
1497
1498 PN = dyn_cast<PHINode>(V);
1499 if (!PN)
1500 return false;
1501 }
Evan Cheng0663f232011-03-21 01:19:09 +00001502
Cameron Zwarich4649f172011-03-24 04:52:10 +00001503 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001504 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001505
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001506 // It's not safe to eliminate the sign / zero extension of the return value.
1507 // See llvm::isInTailCallPosition().
1508 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001509 AttributeSet CallerAttrs = F->getAttributes();
1510 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1511 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001512 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001513
Cameron Zwarich4649f172011-03-24 04:52:10 +00001514 // Make sure there are no instructions between the PHI and return, or that the
1515 // return is the first instruction in the block.
1516 if (PN) {
1517 BasicBlock::iterator BI = BB->begin();
1518 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001519 if (&*BI == BCI)
1520 // Also skip over the bitcast.
1521 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001522 if (&*BI != RI)
1523 return false;
1524 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001525 BasicBlock::iterator BI = BB->begin();
1526 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1527 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001528 return false;
1529 }
Evan Cheng0663f232011-03-21 01:19:09 +00001530
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001531 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1532 /// call.
1533 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001534 if (PN) {
1535 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1536 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1537 // Make sure the phi value is indeed produced by the tail call.
1538 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1539 TLI->mayBeEmittedAsTailCall(CI))
1540 TailCalls.push_back(CI);
1541 }
1542 } else {
1543 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001544 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001545 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001546 continue;
1547
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001548 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001549 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1550 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001551 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1552 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001553 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001554
Cameron Zwarich4649f172011-03-24 04:52:10 +00001555 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001556 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001557 TailCalls.push_back(CI);
1558 }
Evan Cheng0663f232011-03-21 01:19:09 +00001559 }
1560
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001561 bool Changed = false;
1562 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1563 CallInst *CI = TailCalls[i];
1564 CallSite CS(CI);
1565
1566 // Conservatively require the attributes of the call to match those of the
1567 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001568 AttributeSet CalleeAttrs = CS.getAttributes();
1569 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001570 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001571 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001572 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001573 continue;
1574
1575 // Make sure the call instruction is followed by an unconditional branch to
1576 // the return block.
1577 BasicBlock *CallBB = CI->getParent();
1578 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1579 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1580 continue;
1581
1582 // Duplicate the return into CallBB.
1583 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001584 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001585 ++NumRetsDup;
1586 }
1587
1588 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001589 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001590 BB->eraseFromParent();
1591
1592 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001593}
1594
Chris Lattner728f9022008-11-25 07:09:13 +00001595//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001596// Memory Optimization
1597//===----------------------------------------------------------------------===//
1598
Chandler Carruthc8925912013-01-05 02:09:22 +00001599namespace {
1600
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001601/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00001602/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001603struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001604 Value *BaseReg;
1605 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001606 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001607 void print(raw_ostream &OS) const;
1608 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001609
Chandler Carruthc8925912013-01-05 02:09:22 +00001610 bool operator==(const ExtAddrMode& O) const {
1611 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1612 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1613 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1614 }
1615};
1616
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001617#ifndef NDEBUG
1618static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1619 AM.print(OS);
1620 return OS;
1621}
1622#endif
1623
Chandler Carruthc8925912013-01-05 02:09:22 +00001624void ExtAddrMode::print(raw_ostream &OS) const {
1625 bool NeedPlus = false;
1626 OS << "[";
1627 if (BaseGV) {
1628 OS << (NeedPlus ? " + " : "")
1629 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001630 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001631 NeedPlus = true;
1632 }
1633
Richard Trieuc0f91212014-05-30 03:15:17 +00001634 if (BaseOffs) {
1635 OS << (NeedPlus ? " + " : "")
1636 << BaseOffs;
1637 NeedPlus = true;
1638 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001639
1640 if (BaseReg) {
1641 OS << (NeedPlus ? " + " : "")
1642 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001643 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001644 NeedPlus = true;
1645 }
1646 if (Scale) {
1647 OS << (NeedPlus ? " + " : "")
1648 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001649 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001650 }
1651
1652 OS << ']';
1653}
1654
1655#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1656void ExtAddrMode::dump() const {
1657 print(dbgs());
1658 dbgs() << '\n';
1659}
1660#endif
1661
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001662/// \brief This class provides transaction based operation on the IR.
1663/// Every change made through this class is recorded in the internal state and
1664/// can be undone (rollback) until commit is called.
1665class TypePromotionTransaction {
1666
1667 /// \brief This represents the common interface of the individual transaction.
1668 /// Each class implements the logic for doing one specific modification on
1669 /// the IR via the TypePromotionTransaction.
1670 class TypePromotionAction {
1671 protected:
1672 /// The Instruction modified.
1673 Instruction *Inst;
1674
1675 public:
1676 /// \brief Constructor of the action.
1677 /// The constructor performs the related action on the IR.
1678 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1679
1680 virtual ~TypePromotionAction() {}
1681
1682 /// \brief Undo the modification done by this action.
1683 /// When this method is called, the IR must be in the same state as it was
1684 /// before this action was applied.
1685 /// \pre Undoing the action works if and only if the IR is in the exact same
1686 /// state as it was directly after this action was applied.
1687 virtual void undo() = 0;
1688
1689 /// \brief Advocate every change made by this action.
1690 /// When the results on the IR of the action are to be kept, it is important
1691 /// to call this function, otherwise hidden information may be kept forever.
1692 virtual void commit() {
1693 // Nothing to be done, this action is not doing anything.
1694 }
1695 };
1696
1697 /// \brief Utility to remember the position of an instruction.
1698 class InsertionHandler {
1699 /// Position of an instruction.
1700 /// Either an instruction:
1701 /// - Is the first in a basic block: BB is used.
1702 /// - Has a previous instructon: PrevInst is used.
1703 union {
1704 Instruction *PrevInst;
1705 BasicBlock *BB;
1706 } Point;
1707 /// Remember whether or not the instruction had a previous instruction.
1708 bool HasPrevInstruction;
1709
1710 public:
1711 /// \brief Record the position of \p Inst.
1712 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001713 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001714 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1715 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001716 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001717 else
1718 Point.BB = Inst->getParent();
1719 }
1720
1721 /// \brief Insert \p Inst at the recorded position.
1722 void insert(Instruction *Inst) {
1723 if (HasPrevInstruction) {
1724 if (Inst->getParent())
1725 Inst->removeFromParent();
1726 Inst->insertAfter(Point.PrevInst);
1727 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001728 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001729 if (Inst->getParent())
1730 Inst->moveBefore(Position);
1731 else
1732 Inst->insertBefore(Position);
1733 }
1734 }
1735 };
1736
1737 /// \brief Move an instruction before another.
1738 class InstructionMoveBefore : public TypePromotionAction {
1739 /// Original position of the instruction.
1740 InsertionHandler Position;
1741
1742 public:
1743 /// \brief Move \p Inst before \p Before.
1744 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1745 : TypePromotionAction(Inst), Position(Inst) {
1746 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1747 Inst->moveBefore(Before);
1748 }
1749
1750 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001751 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001752 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1753 Position.insert(Inst);
1754 }
1755 };
1756
1757 /// \brief Set the operand of an instruction with a new value.
1758 class OperandSetter : public TypePromotionAction {
1759 /// Original operand of the instruction.
1760 Value *Origin;
1761 /// Index of the modified instruction.
1762 unsigned Idx;
1763
1764 public:
1765 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1766 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1767 : TypePromotionAction(Inst), Idx(Idx) {
1768 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1769 << "for:" << *Inst << "\n"
1770 << "with:" << *NewVal << "\n");
1771 Origin = Inst->getOperand(Idx);
1772 Inst->setOperand(Idx, NewVal);
1773 }
1774
1775 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001776 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001777 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1778 << "for: " << *Inst << "\n"
1779 << "with: " << *Origin << "\n");
1780 Inst->setOperand(Idx, Origin);
1781 }
1782 };
1783
1784 /// \brief Hide the operands of an instruction.
1785 /// Do as if this instruction was not using any of its operands.
1786 class OperandsHider : public TypePromotionAction {
1787 /// The list of original operands.
1788 SmallVector<Value *, 4> OriginalValues;
1789
1790 public:
1791 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1792 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1793 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1794 unsigned NumOpnds = Inst->getNumOperands();
1795 OriginalValues.reserve(NumOpnds);
1796 for (unsigned It = 0; It < NumOpnds; ++It) {
1797 // Save the current operand.
1798 Value *Val = Inst->getOperand(It);
1799 OriginalValues.push_back(Val);
1800 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00001801 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001802 // that we are not willing to pay.
1803 Inst->setOperand(It, UndefValue::get(Val->getType()));
1804 }
1805 }
1806
1807 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001808 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001809 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1810 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1811 Inst->setOperand(It, OriginalValues[It]);
1812 }
1813 };
1814
1815 /// \brief Build a truncate instruction.
1816 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001817 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001818 public:
1819 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1820 /// result.
1821 /// trunc Opnd to Ty.
1822 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1823 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001824 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1825 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001826 }
1827
Quentin Colombetac55b152014-09-16 22:36:07 +00001828 /// \brief Get the built value.
1829 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001830
1831 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001832 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001833 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1834 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1835 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001836 }
1837 };
1838
1839 /// \brief Build a sign extension instruction.
1840 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001841 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001842 public:
1843 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1844 /// result.
1845 /// sext Opnd to Ty.
1846 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001847 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001848 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001849 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1850 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001851 }
1852
Quentin Colombetac55b152014-09-16 22:36:07 +00001853 /// \brief Get the built value.
1854 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001855
1856 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001857 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001858 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1859 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1860 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001861 }
1862 };
1863
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001864 /// \brief Build a zero extension instruction.
1865 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001866 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001867 public:
1868 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1869 /// result.
1870 /// zext Opnd to Ty.
1871 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001872 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001873 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001874 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1875 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001876 }
1877
Quentin Colombetac55b152014-09-16 22:36:07 +00001878 /// \brief Get the built value.
1879 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001880
1881 /// \brief Remove the built instruction.
1882 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001883 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1884 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1885 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001886 }
1887 };
1888
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001889 /// \brief Mutate an instruction to another type.
1890 class TypeMutator : public TypePromotionAction {
1891 /// Record the original type.
1892 Type *OrigTy;
1893
1894 public:
1895 /// \brief Mutate the type of \p Inst into \p NewTy.
1896 TypeMutator(Instruction *Inst, Type *NewTy)
1897 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1898 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1899 << "\n");
1900 Inst->mutateType(NewTy);
1901 }
1902
1903 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001904 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001905 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1906 << "\n");
1907 Inst->mutateType(OrigTy);
1908 }
1909 };
1910
1911 /// \brief Replace the uses of an instruction by another instruction.
1912 class UsesReplacer : public TypePromotionAction {
1913 /// Helper structure to keep track of the replaced uses.
1914 struct InstructionAndIdx {
1915 /// The instruction using the instruction.
1916 Instruction *Inst;
1917 /// The index where this instruction is used for Inst.
1918 unsigned Idx;
1919 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1920 : Inst(Inst), Idx(Idx) {}
1921 };
1922
1923 /// Keep track of the original uses (pair Instruction, Index).
1924 SmallVector<InstructionAndIdx, 4> OriginalUses;
1925 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1926
1927 public:
1928 /// \brief Replace all the use of \p Inst by \p New.
1929 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1930 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1931 << "\n");
1932 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001933 for (Use &U : Inst->uses()) {
1934 Instruction *UserI = cast<Instruction>(U.getUser());
1935 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001936 }
1937 // Now, we can replace the uses.
1938 Inst->replaceAllUsesWith(New);
1939 }
1940
1941 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001942 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001943 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1944 for (use_iterator UseIt = OriginalUses.begin(),
1945 EndIt = OriginalUses.end();
1946 UseIt != EndIt; ++UseIt) {
1947 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1948 }
1949 }
1950 };
1951
1952 /// \brief Remove an instruction from the IR.
1953 class InstructionRemover : public TypePromotionAction {
1954 /// Original position of the instruction.
1955 InsertionHandler Inserter;
1956 /// Helper structure to hide all the link to the instruction. In other
1957 /// words, this helps to do as if the instruction was removed.
1958 OperandsHider Hider;
1959 /// Keep track of the uses replaced, if any.
1960 UsesReplacer *Replacer;
1961
1962 public:
1963 /// \brief Remove all reference of \p Inst and optinally replace all its
1964 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001965 /// \pre If !Inst->use_empty(), then New != nullptr
1966 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001967 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001968 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001969 if (New)
1970 Replacer = new UsesReplacer(Inst, New);
1971 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1972 Inst->removeFromParent();
1973 }
1974
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00001975 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001976
1977 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001978 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001979
1980 /// \brief Resurrect the instruction and reassign it to the proper uses if
1981 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001982 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001983 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1984 Inserter.insert(Inst);
1985 if (Replacer)
1986 Replacer->undo();
1987 Hider.undo();
1988 }
1989 };
1990
1991public:
1992 /// Restoration point.
1993 /// The restoration point is a pointer to an action instead of an iterator
1994 /// because the iterator may be invalidated but not the pointer.
1995 typedef const TypePromotionAction *ConstRestorationPt;
1996 /// Advocate every changes made in that transaction.
1997 void commit();
1998 /// Undo all the changes made after the given point.
1999 void rollback(ConstRestorationPt Point);
2000 /// Get the current restoration point.
2001 ConstRestorationPt getRestorationPoint() const;
2002
2003 /// \name API for IR modification with state keeping to support rollback.
2004 /// @{
2005 /// Same as Instruction::setOperand.
2006 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2007 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002008 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002009 /// Same as Value::replaceAllUsesWith.
2010 void replaceAllUsesWith(Instruction *Inst, Value *New);
2011 /// Same as Value::mutateType.
2012 void mutateType(Instruction *Inst, Type *NewTy);
2013 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002014 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002015 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002016 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002017 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002018 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002019 /// Same as Instruction::moveBefore.
2020 void moveBefore(Instruction *Inst, Instruction *Before);
2021 /// @}
2022
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002023private:
2024 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002025 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2026 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002027};
2028
2029void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2030 Value *NewVal) {
2031 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002032 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002033}
2034
2035void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2036 Value *NewVal) {
2037 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002038 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002039}
2040
2041void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2042 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002043 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002044}
2045
2046void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002047 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002048}
2049
Quentin Colombetac55b152014-09-16 22:36:07 +00002050Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2051 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002052 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002053 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002054 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002055 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002056}
2057
Quentin Colombetac55b152014-09-16 22:36:07 +00002058Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2059 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002060 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002061 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002062 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002063 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002064}
2065
Quentin Colombetac55b152014-09-16 22:36:07 +00002066Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2067 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002068 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002069 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002070 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002071 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002072}
2073
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002074void TypePromotionTransaction::moveBefore(Instruction *Inst,
2075 Instruction *Before) {
2076 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002077 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002078}
2079
2080TypePromotionTransaction::ConstRestorationPt
2081TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002082 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002083}
2084
2085void TypePromotionTransaction::commit() {
2086 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002087 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002088 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002089 Actions.clear();
2090}
2091
2092void TypePromotionTransaction::rollback(
2093 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002094 while (!Actions.empty() && Point != Actions.back().get()) {
2095 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002096 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002097 }
2098}
2099
Chandler Carruthc8925912013-01-05 02:09:22 +00002100/// \brief A helper class for matching addressing modes.
2101///
2102/// This encapsulates the logic for matching the target-legal addressing modes.
2103class AddressingModeMatcher {
2104 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002105 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002106 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002107 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002108
2109 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2110 /// the memory instruction that we're computing this address for.
2111 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002112 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002113 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002114
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002115 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002116 /// part of the return value of this addressing mode matching stuff.
2117 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002118
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002119 /// The instructions inserted by other CodeGenPrepare optimizations.
2120 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002121 /// A map from the instructions to their type before promotion.
2122 InstrToOrigTy &PromotedInsts;
2123 /// The ongoing transaction where every action should be registered.
2124 TypePromotionTransaction &TPT;
2125
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002126 /// This is set to true when we should not do profitability checks.
2127 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002128 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002129
Eric Christopherd75c00c2015-02-26 22:38:34 +00002130 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002131 const TargetMachine &TM, Type *AT, unsigned AS,
2132 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002133 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002134 InstrToOrigTy &PromotedInsts,
2135 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002136 : AddrModeInsts(AMI), TM(TM),
2137 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2138 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002139 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2140 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2141 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002142 IgnoreProfitability = false;
2143 }
2144public:
Stephen Lin837bba12013-07-15 17:55:02 +00002145
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002146 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002147 /// give an access type of AccessTy. This returns a list of involved
2148 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002149 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002150 /// optimizations.
2151 /// \p PromotedInsts maps the instructions to their type before promotion.
2152 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002153 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002154 Instruction *MemoryInst,
2155 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002156 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002157 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002158 InstrToOrigTy &PromotedInsts,
2159 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002160 ExtAddrMode Result;
2161
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002162 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002163 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002164 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002165 (void)Success; assert(Success && "Couldn't select *anything*?");
2166 return Result;
2167 }
2168private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002169 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2170 bool matchAddr(Value *V, unsigned Depth);
2171 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002172 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002173 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002174 ExtAddrMode &AMBefore,
2175 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002176 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2177 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002178 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002179};
2180
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002181/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002182/// Return true and update AddrMode if this addr mode is legal for the target,
2183/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002184bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002185 unsigned Depth) {
2186 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2187 // mode. Just process that directly.
2188 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002189 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002190
Chandler Carruthc8925912013-01-05 02:09:22 +00002191 // If the scale is 0, it takes nothing to add this.
2192 if (Scale == 0)
2193 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002194
Chandler Carruthc8925912013-01-05 02:09:22 +00002195 // If we already have a scale of this value, we can add to it, otherwise, we
2196 // need an available scale field.
2197 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2198 return false;
2199
2200 ExtAddrMode TestAddrMode = AddrMode;
2201
2202 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2203 // [A+B + A*7] -> [B+A*8].
2204 TestAddrMode.Scale += Scale;
2205 TestAddrMode.ScaledReg = ScaleReg;
2206
2207 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002208 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002209 return false;
2210
2211 // It was legal, so commit it.
2212 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002213
Chandler Carruthc8925912013-01-05 02:09:22 +00002214 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2215 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2216 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002217 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002218 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2219 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2220 TestAddrMode.ScaledReg = AddLHS;
2221 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002222
Chandler Carruthc8925912013-01-05 02:09:22 +00002223 // If this addressing mode is legal, commit it and remember that we folded
2224 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002225 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002226 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2227 AddrMode = TestAddrMode;
2228 return true;
2229 }
2230 }
2231
2232 // Otherwise, not (x+c)*scale, just return what we have.
2233 return true;
2234}
2235
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002236/// This is a little filter, which returns true if an addressing computation
2237/// involving I might be folded into a load/store accessing it.
2238/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002239/// the set of instructions that MatchOperationAddr can.
2240static bool MightBeFoldableInst(Instruction *I) {
2241 switch (I->getOpcode()) {
2242 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002243 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002244 // Don't touch identity bitcasts.
2245 if (I->getType() == I->getOperand(0)->getType())
2246 return false;
2247 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2248 case Instruction::PtrToInt:
2249 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2250 return true;
2251 case Instruction::IntToPtr:
2252 // We know the input is intptr_t, so this is foldable.
2253 return true;
2254 case Instruction::Add:
2255 return true;
2256 case Instruction::Mul:
2257 case Instruction::Shl:
2258 // Can only handle X*C and X << C.
2259 return isa<ConstantInt>(I->getOperand(1));
2260 case Instruction::GetElementPtr:
2261 return true;
2262 default:
2263 return false;
2264 }
2265}
2266
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002267/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2268/// \note \p Val is assumed to be the product of some type promotion.
2269/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2270/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002271static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2272 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002273 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2274 if (!PromotedInst)
2275 return false;
2276 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2277 // If the ISDOpcode is undefined, it was undefined before the promotion.
2278 if (!ISDOpcode)
2279 return true;
2280 // Otherwise, check if the promoted instruction is legal or not.
2281 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002282 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002283}
2284
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002285/// \brief Hepler class to perform type promotion.
2286class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002287 /// \brief Utility function to check whether or not a sign or zero extension
2288 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2289 /// either using the operands of \p Inst or promoting \p Inst.
2290 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002291 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002292 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002293 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002294 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002295 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002296 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002297 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002298 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2299 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002300
2301 /// \brief Utility function to determine if \p OpIdx should be promoted when
2302 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002303 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002304 if (isa<SelectInst>(Inst) && OpIdx == 0)
2305 return false;
2306 return true;
2307 }
2308
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002309 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002310 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002311 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002312 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002313 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002314 /// Newly added extensions are inserted in \p Exts.
2315 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002316 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002317 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002318 static Value *promoteOperandForTruncAndAnyExt(
2319 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002320 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002321 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002322 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002323
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002324 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002325 /// operand is promotable and is not a supported trunc or sext.
2326 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002327 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002328 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002329 /// Newly added extensions are inserted in \p Exts.
2330 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002331 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002332 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002333 static Value *promoteOperandForOther(Instruction *Ext,
2334 TypePromotionTransaction &TPT,
2335 InstrToOrigTy &PromotedInsts,
2336 unsigned &CreatedInstsCost,
2337 SmallVectorImpl<Instruction *> *Exts,
2338 SmallVectorImpl<Instruction *> *Truncs,
2339 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002340
2341 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002342 static Value *signExtendOperandForOther(
2343 Instruction *Ext, TypePromotionTransaction &TPT,
2344 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2345 SmallVectorImpl<Instruction *> *Exts,
2346 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2347 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2348 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002349 }
2350
2351 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002352 static Value *zeroExtendOperandForOther(
2353 Instruction *Ext, TypePromotionTransaction &TPT,
2354 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2355 SmallVectorImpl<Instruction *> *Exts,
2356 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2357 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2358 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002359 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002360
2361public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002362 /// Type for the utility function that promotes the operand of Ext.
2363 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002364 InstrToOrigTy &PromotedInsts,
2365 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002366 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002367 SmallVectorImpl<Instruction *> *Truncs,
2368 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002369 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2370 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002371 /// \return NULL if no promotable action is possible with the current
2372 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002373 /// \p InsertedInsts keeps track of all the instructions inserted by the
2374 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002375 /// because we do not want to promote these instructions as CodeGenPrepare
2376 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2377 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002378 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002379 const TargetLowering &TLI,
2380 const InstrToOrigTy &PromotedInsts);
2381};
2382
2383bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002384 Type *ConsideredExtType,
2385 const InstrToOrigTy &PromotedInsts,
2386 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002387 // The promotion helper does not know how to deal with vector types yet.
2388 // To be able to fix that, we would need to fix the places where we
2389 // statically extend, e.g., constants and such.
2390 if (Inst->getType()->isVectorTy())
2391 return false;
2392
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002393 // We can always get through zext.
2394 if (isa<ZExtInst>(Inst))
2395 return true;
2396
2397 // sext(sext) is ok too.
2398 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002399 return true;
2400
2401 // We can get through binary operator, if it is legal. In other words, the
2402 // binary operator must have a nuw or nsw flag.
2403 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2404 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002405 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2406 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002407 return true;
2408
2409 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002410 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002411 if (!isa<TruncInst>(Inst))
2412 return false;
2413
2414 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002415 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002416 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002417 if (!OpndVal->getType()->isIntegerTy() ||
2418 OpndVal->getType()->getIntegerBitWidth() >
2419 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002420 return false;
2421
2422 // If the operand of the truncate is not an instruction, we will not have
2423 // any information on the dropped bits.
2424 // (Actually we could for constant but it is not worth the extra logic).
2425 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2426 if (!Opnd)
2427 return false;
2428
2429 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002430 // I.e., check that trunc just drops extended bits of the same kind of
2431 // the extension.
2432 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002433 const Type *OpndType;
2434 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002435 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2436 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002437 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2438 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002439 else
2440 return false;
2441
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002442 // #2 check that the truncate just drops extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002443 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2444 return true;
2445
2446 return false;
2447}
2448
2449TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002450 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002451 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002452 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2453 "Unexpected instruction type");
2454 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2455 Type *ExtTy = Ext->getType();
2456 bool IsSExt = isa<SExtInst>(Ext);
2457 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002458 // get through.
2459 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002460 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002461 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002462
2463 // Do not promote if the operand has been added by codegenprepare.
2464 // Otherwise, it means we are undoing an optimization that is likely to be
2465 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002466 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002467 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002468
2469 // SExt or Trunc instructions.
2470 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002471 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2472 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002473 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002474
2475 // Regular instruction.
2476 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002477 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002478 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002479 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002480}
2481
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002482Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002483 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002484 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002485 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002486 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002487 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2488 // get through it and this method should not be called.
2489 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002490 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002491 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002492 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002493 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002494 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002495 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002496 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002497 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2498 TPT.replaceAllUsesWith(SExt, ZExt);
2499 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002500 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002501 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002502 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2503 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002504 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2505 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002506 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002507
2508 // Remove dead code.
2509 if (SExtOpnd->use_empty())
2510 TPT.eraseInstruction(SExtOpnd);
2511
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002512 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002513 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002514 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002515 if (ExtInst) {
2516 if (Exts)
2517 Exts->push_back(ExtInst);
2518 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2519 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002520 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002521 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002522
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002523 // At this point we have: ext ty opnd to ty.
2524 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2525 Value *NextVal = ExtInst->getOperand(0);
2526 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002527 return NextVal;
2528}
2529
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002530Value *TypePromotionHelper::promoteOperandForOther(
2531 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002532 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002533 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002534 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2535 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002536 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002537 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002538 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002539 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002540 if (!ExtOpnd->hasOneUse()) {
2541 // ExtOpnd will be promoted.
2542 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002543 // promoted version.
2544 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002545 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002546 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2547 ITrunc->removeFromParent();
2548 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002549 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002550 if (Truncs)
2551 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002552 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002553
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002554 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002555 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002556 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002557 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002558 }
2559
2560 // Get through the Instruction:
2561 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002562 // 2. Replace the uses of Ext by Inst.
2563 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002564
2565 // Remember the original type of the instruction before promotion.
2566 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002567 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2568 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002569 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002570 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002571 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002572 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002573 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002574 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002575
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002576 DEBUG(dbgs() << "Propagate Ext to operands\n");
2577 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002578 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002579 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2580 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2581 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002582 DEBUG(dbgs() << "No need to propagate\n");
2583 continue;
2584 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002585 // Check if we can statically extend the operand.
2586 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002587 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002588 DEBUG(dbgs() << "Statically extend\n");
2589 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2590 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2591 : Cst->getValue().zext(BitWidth);
2592 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002593 continue;
2594 }
2595 // UndefValue are typed, so we have to statically sign extend them.
2596 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002597 DEBUG(dbgs() << "Statically extend\n");
2598 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002599 continue;
2600 }
2601
2602 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002603 // Check if Ext was reused to extend an operand.
2604 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002605 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002606 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002607 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2608 : TPT.createZExt(Ext, Opnd, Ext->getType());
2609 if (!isa<Instruction>(ValForExtOpnd)) {
2610 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2611 continue;
2612 }
2613 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002614 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002615 if (Exts)
2616 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002617 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002618
2619 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002620 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2621 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002622 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002623 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002624 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002625 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002626 if (ExtForOpnd == Ext) {
2627 DEBUG(dbgs() << "Extension is useless now\n");
2628 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002629 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002630 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002631}
2632
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002633/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002634/// \p NewCost gives the cost of extension instructions created by the
2635/// promotion.
2636/// \p OldCost gives the cost of extension instructions before the promotion
2637/// plus the number of instructions that have been
2638/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00002639/// \p PromotedOperand is the value that has been promoted.
2640/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002641bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00002642 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2643 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2644 // The cost of the new extensions is greater than the cost of the
2645 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00002646 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002647 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002648 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002649 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002650 return true;
2651 // The promotion is neutral but it may help folding the sign extension in
2652 // loads for instance.
2653 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00002654 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002655}
2656
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002657/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002658/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002659/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002660/// If \p MovedAway is not NULL, it contains the information of whether or
2661/// not AddrInst has to be folded into the addressing mode on success.
2662/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2663/// because it has been moved away.
2664/// Thus AddrInst must not be added in the matched instructions.
2665/// This state can happen when AddrInst is a sext, since it may be moved away.
2666/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2667/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002668bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002669 unsigned Depth,
2670 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002671 // Avoid exponential behavior on extremely deep expression trees.
2672 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002673
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002674 // By default, all matched instructions stay in place.
2675 if (MovedAway)
2676 *MovedAway = false;
2677
Chandler Carruthc8925912013-01-05 02:09:22 +00002678 switch (Opcode) {
2679 case Instruction::PtrToInt:
2680 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002681 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00002682 case Instruction::IntToPtr: {
2683 auto AS = AddrInst->getType()->getPointerAddressSpace();
2684 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00002685 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00002686 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002687 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00002688 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00002689 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002690 case Instruction::BitCast:
2691 // BitCast is always a noop, and we can handle it as long as it is
2692 // int->int or pointer->pointer (we don't want int<->fp or something).
2693 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2694 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2695 // Don't touch identity bitcasts. These were probably put here by LSR,
2696 // and we don't want to mess around with them. Assume it knows what it
2697 // is doing.
2698 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00002699 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00002700 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00002701 case Instruction::AddrSpaceCast: {
2702 unsigned SrcAS
2703 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2704 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2705 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00002706 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00002707 return false;
2708 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002709 case Instruction::Add: {
2710 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2711 ExtAddrMode BackupAddrMode = AddrMode;
2712 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002713 // Start a transaction at this point.
2714 // The LHS may match but not the RHS.
2715 // Therefore, we need a higher level restoration point to undo partially
2716 // matched operation.
2717 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2718 TPT.getRestorationPoint();
2719
Sanjay Patelfc580a62015-09-21 23:03:16 +00002720 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
2721 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00002722 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002723
Chandler Carruthc8925912013-01-05 02:09:22 +00002724 // Restore the old addr mode info.
2725 AddrMode = BackupAddrMode;
2726 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002727 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002728
Chandler Carruthc8925912013-01-05 02:09:22 +00002729 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002730 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
2731 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00002732 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002733
Chandler Carruthc8925912013-01-05 02:09:22 +00002734 // Otherwise we definitely can't merge the ADD in.
2735 AddrMode = BackupAddrMode;
2736 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002737 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002738 break;
2739 }
2740 //case Instruction::Or:
2741 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2742 //break;
2743 case Instruction::Mul:
2744 case Instruction::Shl: {
2745 // Can only handle X*C and X << C.
2746 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002747 if (!RHS)
2748 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002749 int64_t Scale = RHS->getSExtValue();
2750 if (Opcode == Instruction::Shl)
2751 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002752
Sanjay Patelfc580a62015-09-21 23:03:16 +00002753 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00002754 }
2755 case Instruction::GetElementPtr: {
2756 // Scan the GEP. We check it if it contains constant offsets and at most
2757 // one variable offset.
2758 int VariableOperand = -1;
2759 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002760
Chandler Carruthc8925912013-01-05 02:09:22 +00002761 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00002762 gep_type_iterator GTI = gep_type_begin(AddrInst);
2763 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2764 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002765 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00002766 unsigned Idx =
2767 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2768 ConstantOffset += SL->getElementOffset(Idx);
2769 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002770 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00002771 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2772 ConstantOffset += CI->getSExtValue()*TypeSize;
2773 } else if (TypeSize) { // Scales of zero don't do anything.
2774 // We only allow one variable index at the moment.
2775 if (VariableOperand != -1)
2776 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002777
Chandler Carruthc8925912013-01-05 02:09:22 +00002778 // Remember the variable index.
2779 VariableOperand = i;
2780 VariableScale = TypeSize;
2781 }
2782 }
2783 }
Stephen Lin837bba12013-07-15 17:55:02 +00002784
Chandler Carruthc8925912013-01-05 02:09:22 +00002785 // A common case is for the GEP to only do a constant offset. In this case,
2786 // just add it to the disp field and check validity.
2787 if (VariableOperand == -1) {
2788 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002789 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002790 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002791 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002792 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00002793 return true;
2794 }
2795 AddrMode.BaseOffs -= ConstantOffset;
2796 return false;
2797 }
2798
2799 // Save the valid addressing mode in case we can't match.
2800 ExtAddrMode BackupAddrMode = AddrMode;
2801 unsigned OldSize = AddrModeInsts.size();
2802
2803 // See if the scale and offset amount is valid for this target.
2804 AddrMode.BaseOffs += ConstantOffset;
2805
2806 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002807 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002808 // If it couldn't be matched, just stuff the value in a register.
2809 if (AddrMode.HasBaseReg) {
2810 AddrMode = BackupAddrMode;
2811 AddrModeInsts.resize(OldSize);
2812 return false;
2813 }
2814 AddrMode.HasBaseReg = true;
2815 AddrMode.BaseReg = AddrInst->getOperand(0);
2816 }
2817
2818 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002819 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002820 Depth)) {
2821 // If it couldn't be matched, try stuffing the base into a register
2822 // instead of matching it, and retrying the match of the scale.
2823 AddrMode = BackupAddrMode;
2824 AddrModeInsts.resize(OldSize);
2825 if (AddrMode.HasBaseReg)
2826 return false;
2827 AddrMode.HasBaseReg = true;
2828 AddrMode.BaseReg = AddrInst->getOperand(0);
2829 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00002830 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00002831 VariableScale, Depth)) {
2832 // If even that didn't work, bail.
2833 AddrMode = BackupAddrMode;
2834 AddrModeInsts.resize(OldSize);
2835 return false;
2836 }
2837 }
2838
2839 return true;
2840 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002841 case Instruction::SExt:
2842 case Instruction::ZExt: {
2843 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2844 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002845 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002846
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002847 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002848 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002849 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002850 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002851 if (!TPH)
2852 return false;
2853
2854 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2855 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00002856 unsigned CreatedInstsCost = 0;
2857 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002858 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00002859 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002860 // SExt has been moved away.
2861 // Thus either it will be rematched later in the recursive calls or it is
2862 // gone. Anyway, we must not fold it into the addressing mode at this point.
2863 // E.g.,
2864 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002865 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002866 // addr = gep base, idx
2867 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002868 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002869 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2870 // addr = gep base, op <- match
2871 if (MovedAway)
2872 *MovedAway = true;
2873
2874 assert(PromotedOperand &&
2875 "TypePromotionHelper should have filtered out those cases");
2876
2877 ExtAddrMode BackupAddrMode = AddrMode;
2878 unsigned OldSize = AddrModeInsts.size();
2879
Sanjay Patelfc580a62015-09-21 23:03:16 +00002880 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002881 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00002882 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002883 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00002884 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002885 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002886 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00002887 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002888 AddrMode = BackupAddrMode;
2889 AddrModeInsts.resize(OldSize);
2890 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2891 TPT.rollback(LastKnownGood);
2892 return false;
2893 }
2894 return true;
2895 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002896 }
2897 return false;
2898}
2899
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002900/// If we can, try to add the value of 'Addr' into the current addressing mode.
2901/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
2902/// unmodified. This assumes that Addr is either a pointer type or intptr_t
2903/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00002904///
Sanjay Patelfc580a62015-09-21 23:03:16 +00002905bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002906 // Start a transaction at this point that we will rollback if the matching
2907 // fails.
2908 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2909 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002910 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2911 // Fold in immediates if legal for the target.
2912 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002913 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002914 return true;
2915 AddrMode.BaseOffs -= CI->getSExtValue();
2916 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2917 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002918 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002919 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002920 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002921 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002922 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002923 }
2924 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2925 ExtAddrMode BackupAddrMode = AddrMode;
2926 unsigned OldSize = AddrModeInsts.size();
2927
2928 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002929 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00002930 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002931 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002932 // to check here.
2933 if (MovedAway)
2934 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002935 // Okay, it's possible to fold this. Check to see if it is actually
2936 // *profitable* to do so. We use a simple cost model to avoid increasing
2937 // register pressure too much.
2938 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00002939 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002940 AddrModeInsts.push_back(I);
2941 return true;
2942 }
Stephen Lin837bba12013-07-15 17:55:02 +00002943
Chandler Carruthc8925912013-01-05 02:09:22 +00002944 // It isn't profitable to do this, roll back.
2945 //cerr << "NOT FOLDING: " << *I;
2946 AddrMode = BackupAddrMode;
2947 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002948 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002949 }
2950 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00002951 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00002952 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002953 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002954 } else if (isa<ConstantPointerNull>(Addr)) {
2955 // Null pointer gets folded without affecting the addressing mode.
2956 return true;
2957 }
2958
2959 // Worse case, the target should support [reg] addressing modes. :)
2960 if (!AddrMode.HasBaseReg) {
2961 AddrMode.HasBaseReg = true;
2962 AddrMode.BaseReg = Addr;
2963 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002964 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002965 return true;
2966 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002967 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002968 }
2969
2970 // If the base register is already taken, see if we can do [r+r].
2971 if (AddrMode.Scale == 0) {
2972 AddrMode.Scale = 1;
2973 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002974 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002975 return true;
2976 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002977 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002978 }
2979 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002980 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002981 return false;
2982}
2983
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002984/// Check to see if all uses of OpVal by the specified inline asm call are due
2985/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00002986static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00002987 const TargetMachine &TM) {
2988 const Function *F = CI->getParent()->getParent();
2989 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2990 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00002991 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002992 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
2993 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00002994 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2995 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002996
Chandler Carruthc8925912013-01-05 02:09:22 +00002997 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00002998 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00002999
3000 // If this asm operand is our Value*, and if it isn't an indirect memory
3001 // operand, we can't fold it!
3002 if (OpInfo.CallOperandVal == OpVal &&
3003 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3004 !OpInfo.isIndirect))
3005 return false;
3006 }
3007
3008 return true;
3009}
3010
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003011/// Recursively walk all the uses of I until we find a memory use.
3012/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003013/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003014static bool FindAllMemoryUses(
3015 Instruction *I,
3016 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3017 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003018 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003019 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003020 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003021
Chandler Carruthc8925912013-01-05 02:09:22 +00003022 // If this is an obviously unfoldable instruction, bail out.
3023 if (!MightBeFoldableInst(I))
3024 return true;
3025
3026 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003027 for (Use &U : I->uses()) {
3028 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003029
Chandler Carruthcdf47882014-03-09 03:16:01 +00003030 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3031 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003032 continue;
3033 }
Stephen Lin837bba12013-07-15 17:55:02 +00003034
Chandler Carruthcdf47882014-03-09 03:16:01 +00003035 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3036 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003037 if (opNo == 0) return true; // Storing addr, not into addr.
3038 MemoryUses.push_back(std::make_pair(SI, opNo));
3039 continue;
3040 }
Stephen Lin837bba12013-07-15 17:55:02 +00003041
Chandler Carruthcdf47882014-03-09 03:16:01 +00003042 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003043 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3044 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003045
Chandler Carruthc8925912013-01-05 02:09:22 +00003046 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003047 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003048 return true;
3049 continue;
3050 }
Stephen Lin837bba12013-07-15 17:55:02 +00003051
Eric Christopher11e4df72015-02-26 22:38:43 +00003052 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003053 return true;
3054 }
3055
3056 return false;
3057}
3058
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003059/// Return true if Val is already known to be live at the use site that we're
3060/// folding it into. If so, there is no cost to include it in the addressing
3061/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3062/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003063bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003064 Value *KnownLive2) {
3065 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003066 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003067 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003068
Chandler Carruthc8925912013-01-05 02:09:22 +00003069 // All values other than instructions and arguments (e.g. constants) are live.
3070 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003071
Chandler Carruthc8925912013-01-05 02:09:22 +00003072 // If Val is a constant sized alloca in the entry block, it is live, this is
3073 // true because it is just a reference to the stack/frame pointer, which is
3074 // live for the whole function.
3075 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3076 if (AI->isStaticAlloca())
3077 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003078
Chandler Carruthc8925912013-01-05 02:09:22 +00003079 // Check to see if this value is already used in the memory instruction's
3080 // block. If so, it's already live into the block at the very least, so we
3081 // can reasonably fold it.
3082 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3083}
3084
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003085/// It is possible for the addressing mode of the machine to fold the specified
3086/// instruction into a load or store that ultimately uses it.
3087/// However, the specified instruction has multiple uses.
3088/// Given this, it may actually increase register pressure to fold it
3089/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003090///
3091/// X = ...
3092/// Y = X+1
3093/// use(Y) -> nonload/store
3094/// Z = Y+1
3095/// load Z
3096///
3097/// In this case, Y has multiple uses, and can be folded into the load of Z
3098/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3099/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3100/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3101/// number of computations either.
3102///
3103/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3104/// X was live across 'load Z' for other reasons, we actually *would* want to
3105/// fold the addressing mode in the Z case. This would make Y die earlier.
3106bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003107isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003108 ExtAddrMode &AMAfter) {
3109 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003110
Chandler Carruthc8925912013-01-05 02:09:22 +00003111 // AMBefore is the addressing mode before this instruction was folded into it,
3112 // and AMAfter is the addressing mode after the instruction was folded. Get
3113 // the set of registers referenced by AMAfter and subtract out those
3114 // referenced by AMBefore: this is the set of values which folding in this
3115 // address extends the lifetime of.
3116 //
3117 // Note that there are only two potential values being referenced here,
3118 // BaseReg and ScaleReg (global addresses are always available, as are any
3119 // folded immediates).
3120 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003121
Chandler Carruthc8925912013-01-05 02:09:22 +00003122 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3123 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003124 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003125 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003126 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003127 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003128
3129 // If folding this instruction (and it's subexprs) didn't extend any live
3130 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003131 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003132 return true;
3133
3134 // If all uses of this instruction are ultimately load/store/inlineasm's,
3135 // check to see if their addressing modes will include this instruction. If
3136 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3137 // uses.
3138 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3139 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003140 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003141 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003142
Chandler Carruthc8925912013-01-05 02:09:22 +00003143 // Now that we know that all uses of this instruction are part of a chain of
3144 // computation involving only operations that could theoretically be folded
3145 // into a memory use, loop over each of these uses and see if they could
3146 // *actually* fold the instruction.
3147 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3148 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3149 Instruction *User = MemoryUses[i].first;
3150 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003151
Chandler Carruthc8925912013-01-05 02:09:22 +00003152 // Get the access type of this use. If the use isn't a pointer, we don't
3153 // know what it accesses.
3154 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003155 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3156 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003157 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003158 Type *AddressAccessTy = AddrTy->getElementType();
3159 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003160
Chandler Carruthc8925912013-01-05 02:09:22 +00003161 // Do a match against the root of this address, ignoring profitability. This
3162 // will tell us if the addressing mode for the memory operation will
3163 // *actually* cover the shared instruction.
3164 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003165 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3166 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003167 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003168 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003169 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003170 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003171 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003172 (void)Success; assert(Success && "Couldn't select *anything*?");
3173
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003174 // The match was to check the profitability, the changes made are not
3175 // part of the original matcher. Therefore, they should be dropped
3176 // otherwise the original matcher will not present the right state.
3177 TPT.rollback(LastKnownGood);
3178
Chandler Carruthc8925912013-01-05 02:09:22 +00003179 // If the match didn't cover I, then it won't be shared by it.
3180 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3181 I) == MatchedAddrModeInsts.end())
3182 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003183
Chandler Carruthc8925912013-01-05 02:09:22 +00003184 MatchedAddrModeInsts.clear();
3185 }
Stephen Lin837bba12013-07-15 17:55:02 +00003186
Chandler Carruthc8925912013-01-05 02:09:22 +00003187 return true;
3188}
3189
3190} // end anonymous namespace
3191
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003192/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003193/// different basic block than BB.
3194static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3195 if (Instruction *I = dyn_cast<Instruction>(V))
3196 return I->getParent() != BB;
3197 return false;
3198}
3199
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003200/// Load and Store Instructions often have addressing modes that can do
3201/// significant amounts of computation. As such, instruction selection will try
3202/// to get the load or store to do as much computation as possible for the
3203/// program. The problem is that isel can only see within a single block. As
3204/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003205///
3206/// This method is used to optimize both load/store and inline asms with memory
3207/// operands.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003208bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003209 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003210 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003211
3212 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003213 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003214 SmallVector<Value*, 8> worklist;
3215 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003216 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003217
Owen Anderson8ba5f392010-11-27 08:15:55 +00003218 // Use a worklist to iteratively look through PHI nodes, and ensure that
3219 // the addressing mode obtained from the non-PHI roots of the graph
3220 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003221 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003222 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003223 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003224 SmallVector<Instruction*, 16> AddrModeInsts;
3225 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003226 TypePromotionTransaction TPT;
3227 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3228 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003229 while (!worklist.empty()) {
3230 Value *V = worklist.back();
3231 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003232
Owen Anderson8ba5f392010-11-27 08:15:55 +00003233 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003234 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003235 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003236 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003237 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003238
Owen Anderson8ba5f392010-11-27 08:15:55 +00003239 // For a PHI node, push all of its incoming values.
3240 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003241 for (Value *IncValue : P->incoming_values())
3242 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003243 continue;
3244 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003245
Owen Anderson8ba5f392010-11-27 08:15:55 +00003246 // For non-PHIs, determine the addressing mode being computed.
3247 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003248 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003249 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003250 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003251
3252 // This check is broken into two cases with very similar code to avoid using
3253 // getNumUses() as much as possible. Some values have a lot of uses, so
3254 // calling getNumUses() unconditionally caused a significant compile-time
3255 // regression.
3256 if (!Consensus) {
3257 Consensus = V;
3258 AddrMode = NewAddrMode;
3259 AddrModeInsts = NewAddrModeInsts;
3260 continue;
3261 } else if (NewAddrMode == AddrMode) {
3262 if (!IsNumUsesConsensusValid) {
3263 NumUsesConsensus = Consensus->getNumUses();
3264 IsNumUsesConsensusValid = true;
3265 }
3266
3267 // Ensure that the obtained addressing mode is equivalent to that obtained
3268 // for all other roots of the PHI traversal. Also, when choosing one
3269 // such root as representative, select the one with the most uses in order
3270 // to keep the cost modeling heuristics in AddressingModeMatcher
3271 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003272 unsigned NumUses = V->getNumUses();
3273 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003274 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003275 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003276 AddrModeInsts = NewAddrModeInsts;
3277 }
3278 continue;
3279 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003280
Craig Topperc0196b12014-04-14 00:51:57 +00003281 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003282 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003283 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003284
Owen Anderson8ba5f392010-11-27 08:15:55 +00003285 // If the addressing mode couldn't be determined, or if multiple different
3286 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003287 if (!Consensus) {
3288 TPT.rollback(LastKnownGood);
3289 return false;
3290 }
3291 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003292
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003293 // Check to see if any of the instructions supersumed by this addr mode are
3294 // non-local to I's BB.
3295 bool AnyNonLocal = false;
3296 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003297 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003298 AnyNonLocal = true;
3299 break;
3300 }
3301 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003302
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003303 // If all the instructions matched are already in this BB, don't do anything.
3304 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003305 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003306 return false;
3307 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003308
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003309 // Insert this computation right after this user. Since our caller is
3310 // scanning from the top of the BB to the bottom, reuse of the expr are
3311 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003312 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003313
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003314 // Now that we determined the addressing expression we want to use and know
3315 // that we have to sink it into this block. Check to see if we have already
3316 // done this for some other load/store instr in this block. If so, reuse the
3317 // computation.
3318 Value *&SunkAddr = SunkAddrs[Addr];
3319 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003320 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003321 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003322 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003323 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003324 } else if (AddrSinkUsingGEPs ||
3325 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003326 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3327 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003328 // By default, we use the GEP-based method when AA is used later. This
3329 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3330 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003331 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003332 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003333 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003334
3335 // First, find the pointer.
3336 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3337 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003338 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003339 }
3340
3341 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3342 // We can't add more than one pointer together, nor can we scale a
3343 // pointer (both of which seem meaningless).
3344 if (ResultPtr || AddrMode.Scale != 1)
3345 return false;
3346
3347 ResultPtr = AddrMode.ScaledReg;
3348 AddrMode.Scale = 0;
3349 }
3350
3351 if (AddrMode.BaseGV) {
3352 if (ResultPtr)
3353 return false;
3354
3355 ResultPtr = AddrMode.BaseGV;
3356 }
3357
3358 // If the real base value actually came from an inttoptr, then the matcher
3359 // will look through it and provide only the integer value. In that case,
3360 // use it here.
3361 if (!ResultPtr && AddrMode.BaseReg) {
3362 ResultPtr =
3363 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003364 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003365 } else if (!ResultPtr && AddrMode.Scale == 1) {
3366 ResultPtr =
3367 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3368 AddrMode.Scale = 0;
3369 }
3370
3371 if (!ResultPtr &&
3372 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3373 SunkAddr = Constant::getNullValue(Addr->getType());
3374 } else if (!ResultPtr) {
3375 return false;
3376 } else {
3377 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003378 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3379 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003380
3381 // Start with the base register. Do this first so that subsequent address
3382 // matching finds it last, which will prevent it from trying to match it
3383 // as the scaled value in case it happens to be a mul. That would be
3384 // problematic if we've sunk a different mul for the scale, because then
3385 // we'd end up sinking both muls.
3386 if (AddrMode.BaseReg) {
3387 Value *V = AddrMode.BaseReg;
3388 if (V->getType() != IntPtrTy)
3389 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3390
3391 ResultIndex = V;
3392 }
3393
3394 // Add the scale value.
3395 if (AddrMode.Scale) {
3396 Value *V = AddrMode.ScaledReg;
3397 if (V->getType() == IntPtrTy) {
3398 // done.
3399 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3400 cast<IntegerType>(V->getType())->getBitWidth()) {
3401 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3402 } else {
3403 // It is only safe to sign extend the BaseReg if we know that the math
3404 // required to create it did not overflow before we extend it. Since
3405 // the original IR value was tossed in favor of a constant back when
3406 // the AddrMode was created we need to bail out gracefully if widths
3407 // do not match instead of extending it.
3408 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3409 if (I && (ResultIndex != AddrMode.BaseReg))
3410 I->eraseFromParent();
3411 return false;
3412 }
3413
3414 if (AddrMode.Scale != 1)
3415 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3416 "sunkaddr");
3417 if (ResultIndex)
3418 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3419 else
3420 ResultIndex = V;
3421 }
3422
3423 // Add in the Base Offset if present.
3424 if (AddrMode.BaseOffs) {
3425 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3426 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003427 // We need to add this separately from the scale above to help with
3428 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003429 if (ResultPtr->getType() != I8PtrTy)
3430 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003431 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003432 }
3433
3434 ResultIndex = V;
3435 }
3436
3437 if (!ResultIndex) {
3438 SunkAddr = ResultPtr;
3439 } else {
3440 if (ResultPtr->getType() != I8PtrTy)
3441 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003442 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003443 }
3444
3445 if (SunkAddr->getType() != Addr->getType())
3446 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3447 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003448 } else {
David Greene74e2d492010-01-05 01:27:11 +00003449 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003450 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003451 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003452 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003453
3454 // Start with the base register. Do this first so that subsequent address
3455 // matching finds it last, which will prevent it from trying to match it
3456 // as the scaled value in case it happens to be a mul. That would be
3457 // problematic if we've sunk a different mul for the scale, because then
3458 // we'd end up sinking both muls.
3459 if (AddrMode.BaseReg) {
3460 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003461 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003462 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003463 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003464 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003465 Result = V;
3466 }
3467
3468 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003469 if (AddrMode.Scale) {
3470 Value *V = AddrMode.ScaledReg;
3471 if (V->getType() == IntPtrTy) {
3472 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003473 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003474 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003475 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3476 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003477 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003478 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003479 // It is only safe to sign extend the BaseReg if we know that the math
3480 // required to create it did not overflow before we extend it. Since
3481 // the original IR value was tossed in favor of a constant back when
3482 // the AddrMode was created we need to bail out gracefully if widths
3483 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003484 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003485 if (I && (Result != AddrMode.BaseReg))
3486 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003487 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003488 }
3489 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003490 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3491 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003492 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003493 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003494 else
3495 Result = V;
3496 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003497
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003498 // Add in the BaseGV if present.
3499 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003500 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003501 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003502 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003503 else
3504 Result = V;
3505 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003506
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003507 // Add in the Base Offset if present.
3508 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003509 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003510 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003511 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003512 else
3513 Result = V;
3514 }
3515
Craig Topperc0196b12014-04-14 00:51:57 +00003516 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003517 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003518 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003519 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003520 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003521
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003522 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003523
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003524 // If we have no uses, recursively delete the value and all dead instructions
3525 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003526 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003527 // This can cause recursive deletion, which can invalidate our iterator.
3528 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003529 WeakVH IterHandle(&*CurInstIterator);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003530 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003531
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003532 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003533
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003534 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003535 // If the iterator instruction was recursively deleted, start over at the
3536 // start of the block.
3537 CurInstIterator = BB->begin();
3538 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003539 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003540 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003541 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003542 return true;
3543}
3544
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003545/// If there are any memory operands, use OptimizeMemoryInst to sink their
3546/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003547bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003548 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003549
Eric Christopher11e4df72015-02-26 22:38:43 +00003550 const TargetRegisterInfo *TRI =
3551 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003552 TargetLowering::AsmOperandInfoVector TargetConstraints =
3553 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003554 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003555 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3556 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003557
Evan Cheng1da25002008-02-26 02:42:37 +00003558 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003559 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003560
Eli Friedman666bbe32008-02-26 18:37:49 +00003561 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3562 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003563 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003564 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003565 } else if (OpInfo.Type == InlineAsm::isInput)
3566 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003567 }
3568
3569 return MadeChange;
3570}
3571
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003572/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3573/// sign extensions.
3574static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3575 assert(!Inst->use_empty() && "Input must have at least one use");
3576 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3577 bool IsSExt = isa<SExtInst>(FirstUser);
3578 Type *ExtTy = FirstUser->getType();
3579 for (const User *U : Inst->users()) {
3580 const Instruction *UI = cast<Instruction>(U);
3581 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3582 return false;
3583 Type *CurTy = UI->getType();
3584 // Same input and output types: Same instruction after CSE.
3585 if (CurTy == ExtTy)
3586 continue;
3587
3588 // If IsSExt is true, we are in this situation:
3589 // a = Inst
3590 // b = sext ty1 a to ty2
3591 // c = sext ty1 a to ty3
3592 // Assuming ty2 is shorter than ty3, this could be turned into:
3593 // a = Inst
3594 // b = sext ty1 a to ty2
3595 // c = sext ty2 b to ty3
3596 // However, the last sext is not free.
3597 if (IsSExt)
3598 return false;
3599
3600 // This is a ZExt, maybe this is free to extend from one type to another.
3601 // In that case, we would not account for a different use.
3602 Type *NarrowTy;
3603 Type *LargeTy;
3604 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3605 CurTy->getScalarType()->getIntegerBitWidth()) {
3606 NarrowTy = CurTy;
3607 LargeTy = ExtTy;
3608 } else {
3609 NarrowTy = ExtTy;
3610 LargeTy = CurTy;
3611 }
3612
3613 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3614 return false;
3615 }
3616 // All uses are the same or can be derived from one another for free.
3617 return true;
3618}
3619
3620/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3621/// load instruction.
3622/// If an ext(load) can be formed, it is returned via \p LI for the load
3623/// and \p Inst for the extension.
3624/// Otherwise LI == nullptr and Inst == nullptr.
3625/// When some promotion happened, \p TPT contains the proper state to
3626/// revert them.
3627///
3628/// \return true when promoting was necessary to expose the ext(load)
3629/// opportunity, false otherwise.
3630///
3631/// Example:
3632/// \code
3633/// %ld = load i32* %addr
3634/// %add = add nuw i32 %ld, 4
3635/// %zext = zext i32 %add to i64
3636/// \endcode
3637/// =>
3638/// \code
3639/// %ld = load i32* %addr
3640/// %zext = zext i32 %ld to i64
3641/// %add = add nuw i64 %zext, 4
3642/// \encode
3643/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003644bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003645 LoadInst *&LI, Instruction *&Inst,
3646 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003647 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003648 // Iterate over all the extensions to see if one form an ext(load).
3649 for (auto I : Exts) {
3650 // Check if we directly have ext(load).
3651 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3652 Inst = I;
3653 // No promotion happened here.
3654 return false;
3655 }
3656 // Check whether or not we want to do any promotion.
3657 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3658 continue;
3659 // Get the action to perform the promotion.
3660 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003661 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003662 // Check if we can promote.
3663 if (!TPH)
3664 continue;
3665 // Save the current state.
3666 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3667 TPT.getRestorationPoint();
3668 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003669 unsigned NewCreatedInstsCost = 0;
3670 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003671 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003672 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3673 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003674 assert(PromotedVal &&
3675 "TypePromotionHelper should have filtered out those cases");
3676
3677 // We would be able to merge only one extension in a load.
3678 // Therefore, if we have more than 1 new extension we heuristically
3679 // cut this search path, because it means we degrade the code quality.
3680 // With exactly 2, the transformation is neutral, because we will merge
3681 // one extension but leave one. However, we optimistically keep going,
3682 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003683 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3684 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003685 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00003686 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00003687 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003688 // The promotion is not profitable, rollback to the previous state.
3689 TPT.rollback(LastKnownGood);
3690 continue;
3691 }
3692 // The promotion is profitable.
3693 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003694 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003695 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003696 // If we have created a new extension, i.e., now we have two
3697 // extensions. We must make sure one of them is merged with
3698 // the load, otherwise we may degrade the code quality.
3699 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3700 // Promotion happened.
3701 return true;
3702 // If this does not help to expose an ext(load) then, rollback.
3703 TPT.rollback(LastKnownGood);
3704 }
3705 // None of the extension can form an ext(load).
3706 LI = nullptr;
3707 Inst = nullptr;
3708 return false;
3709}
3710
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003711/// Move a zext or sext fed by a load into the same basic block as the load,
3712/// unless conditions are unfavorable. This allows SelectionDAG to fold the
3713/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003714/// \p I[in/out] the extension may be modified during the process if some
3715/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003716///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003717bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003718 // Try to promote a chain of computation if it allows to form
3719 // an extended load.
3720 TypePromotionTransaction TPT;
3721 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3722 TPT.getRestorationPoint();
3723 SmallVector<Instruction *, 1> Exts;
3724 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003725 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003726 LoadInst *LI = nullptr;
3727 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003728 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003729 if (!LI || !I) {
3730 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3731 "the code must remain the same");
3732 I = OldExt;
3733 return false;
3734 }
Dan Gohman99429a02009-10-16 20:59:35 +00003735
3736 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003737 // Make the cheap checks first if we did not promote.
3738 // If we promoted, we need to check if it is indeed profitable.
3739 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003740 return false;
3741
Mehdi Amini44ede332015-07-09 02:09:04 +00003742 EVT VT = TLI->getValueType(*DL, I->getType());
3743 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003744
Dan Gohman99429a02009-10-16 20:59:35 +00003745 // If the load has other users and the truncate is not free, this probably
3746 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003747 if (!LI->hasOneUse() && TLI &&
3748 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003749 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3750 I = OldExt;
3751 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003752 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003753 }
Dan Gohman99429a02009-10-16 20:59:35 +00003754
3755 // Check whether the target supports casts folded into loads.
3756 unsigned LType;
3757 if (isa<ZExtInst>(I))
3758 LType = ISD::ZEXTLOAD;
3759 else {
3760 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3761 LType = ISD::SEXTLOAD;
3762 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003763 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003764 I = OldExt;
3765 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003766 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003767 }
Dan Gohman99429a02009-10-16 20:59:35 +00003768
3769 // Move the extend into the same block as the load, so that SelectionDAG
3770 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003771 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003772 I->removeFromParent();
3773 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003774 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003775 return true;
3776}
3777
Sanjay Patelfc580a62015-09-21 23:03:16 +00003778bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00003779 BasicBlock *DefBB = I->getParent();
3780
Bob Wilsonff714f92010-09-21 21:44:14 +00003781 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003782 // other uses of the source with result of extension.
3783 Value *Src = I->getOperand(0);
3784 if (Src->hasOneUse())
3785 return false;
3786
Evan Cheng2011df42007-12-13 07:50:36 +00003787 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003788 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003789 return false;
3790
Evan Cheng7bc89422007-12-12 00:51:06 +00003791 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003792 // this block.
3793 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003794 return false;
3795
Evan Chengd3d80172007-12-05 23:58:20 +00003796 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003797 for (User *U : I->users()) {
3798 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003799
3800 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003801 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003802 if (UserBB == DefBB) continue;
3803 DefIsLiveOut = true;
3804 break;
3805 }
3806 if (!DefIsLiveOut)
3807 return false;
3808
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003809 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003810 for (User *U : Src->users()) {
3811 Instruction *UI = cast<Instruction>(U);
3812 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003813 if (UserBB == DefBB) continue;
3814 // Be conservative. We don't want this xform to end up introducing
3815 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003816 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003817 return false;
3818 }
3819
Evan Chengd3d80172007-12-05 23:58:20 +00003820 // InsertedTruncs - Only insert one trunc in each block once.
3821 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3822
3823 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003824 for (Use &U : Src->uses()) {
3825 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003826
3827 // Figure out which BB this ext is used in.
3828 BasicBlock *UserBB = User->getParent();
3829 if (UserBB == DefBB) continue;
3830
3831 // Both src and def are live in this block. Rewrite the use.
3832 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3833
3834 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003835 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003836 assert(InsertPt != UserBB->end());
3837 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003838 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003839 }
3840
3841 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003842 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003843 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003844 MadeChange = true;
3845 }
3846
3847 return MadeChange;
3848}
3849
Sanjay Patel69a50a12015-10-19 21:59:12 +00003850/// Check if V (an operand of a select instruction) is an expensive instruction
3851/// that is only used once.
3852static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
3853 auto *I = dyn_cast<Instruction>(V);
3854 // If it's safe to speculatively execute, then it should not have side
3855 // effects; therefore, it's safe to sink and possibly *not* execute.
3856 if (I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
3857 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive)
3858 return true;
3859
3860 return false;
3861}
3862
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003863/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00003864static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
3865 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003866 // FIXME: This should use the same heuristics as IfConversion to determine
3867 // whether a select is better represented as a branch. This requires that
3868 // branch probability metadata is preserved for the select, which is not the
3869 // case currently.
3870
3871 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3872
Sanjay Patel4e652762015-09-28 22:14:51 +00003873 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
3874 // comparison condition. If the compare has more than one use, there's
3875 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00003876 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003877 return false;
3878
3879 Value *CmpOp0 = Cmp->getOperand(0);
3880 Value *CmpOp1 = Cmp->getOperand(1);
3881
Sanjay Patel4e652762015-09-28 22:14:51 +00003882 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
3883 // on a load from memory. But if the load is used more than once, do not
3884 // change the select to a branch because the load is probably needed
3885 // regardless of whether the branch is taken or not.
Sanjay Patel69a50a12015-10-19 21:59:12 +00003886 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3887 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
3888 return true;
3889
3890 // If either operand of the select is expensive and only needed on one side
3891 // of the select, we should form a branch.
3892 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
3893 sinkSelectOperand(TTI, SI->getFalseValue()))
3894 return true;
3895
3896 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003897}
3898
3899
Nadav Rotem9d832022012-09-02 12:10:19 +00003900/// If we have a SelectInst that will likely profit from branch prediction,
3901/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003902bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003903 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3904
3905 // Can we convert the 'select' to CF ?
3906 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003907 return false;
3908
Nadav Rotem9d832022012-09-02 12:10:19 +00003909 TargetLowering::SelectSupportKind SelectKind;
3910 if (VectorCond)
3911 SelectKind = TargetLowering::VectorMaskSelect;
3912 else if (SI->getType()->isVectorTy())
3913 SelectKind = TargetLowering::ScalarCondVectorVal;
3914 else
3915 SelectKind = TargetLowering::ScalarValSelect;
3916
3917 // Do we have efficient codegen support for this kind of 'selects' ?
3918 if (TLI->isSelectSupported(SelectKind)) {
3919 // We have efficient codegen support for the select instruction.
3920 // Check if it is profitable to keep this 'select'.
3921 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00003922 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00003923 return false;
3924 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003925
3926 ModifiedDT = true;
3927
Sanjay Patel69a50a12015-10-19 21:59:12 +00003928 // Transform a sequence like this:
3929 // start:
3930 // %cmp = cmp uge i32 %a, %b
3931 // %sel = select i1 %cmp, i32 %c, i32 %d
3932 //
3933 // Into:
3934 // start:
3935 // %cmp = cmp uge i32 %a, %b
3936 // br i1 %cmp, label %select.true, label %select.false
3937 // select.true:
3938 // br label %select.end
3939 // select.false:
3940 // br label %select.end
3941 // select.end:
3942 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
3943 //
3944 // In addition, we may sink instructions that produce %c or %d from
3945 // the entry block into the destination(s) of the new branch.
3946 // If the true or false blocks do not contain a sunken instruction, that
3947 // block and its branch may be optimized away. In that case, one side of the
3948 // first branch will point directly to select.end, and the corresponding PHI
3949 // predecessor block will be the start block.
3950
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003951 // First, we split the block containing the select into 2 blocks.
3952 BasicBlock *StartBlock = SI->getParent();
3953 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00003954 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003955
Sanjay Patel69a50a12015-10-19 21:59:12 +00003956 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003957 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00003958
3959 // These are the new basic blocks for the conditional branch.
3960 // At least one will become an actual new basic block.
3961 BasicBlock *TrueBlock = nullptr;
3962 BasicBlock *FalseBlock = nullptr;
3963
3964 // Sink expensive instructions into the conditional blocks to avoid executing
3965 // them speculatively.
3966 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
3967 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
3968 EndBlock->getParent(), EndBlock);
3969 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
3970 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
3971 TrueInst->moveBefore(TrueBranch);
3972 }
3973 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
3974 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
3975 EndBlock->getParent(), EndBlock);
3976 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
3977 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
3978 FalseInst->moveBefore(FalseBranch);
3979 }
3980
3981 // If there was nothing to sink, then arbitrarily choose the 'false' side
3982 // for a new input value to the PHI.
3983 if (TrueBlock == FalseBlock) {
3984 assert(TrueBlock == nullptr &&
3985 "Unexpected basic block transform while optimizing select");
3986
3987 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
3988 EndBlock->getParent(), EndBlock);
3989 BranchInst::Create(EndBlock, FalseBlock);
3990 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003991
3992 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00003993 // If we did not create a new block for one of the 'true' or 'false' paths
3994 // of the condition, it means that side of the branch goes to the end block
3995 // directly and the path originates from the start block from the point of
3996 // view of the new PHI.
3997 if (TrueBlock == nullptr) {
3998 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
3999 TrueBlock = StartBlock;
4000 } else if (FalseBlock == nullptr) {
4001 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4002 FalseBlock = StartBlock;
4003 } else {
4004 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4005 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004006
4007 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004008 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004009 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004010 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4011 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4012
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004013 SI->replaceAllUsesWith(PN);
4014 SI->eraseFromParent();
4015
4016 // Instruct OptimizeBlock to skip to the next block.
4017 CurInstIterator = StartBlock->end();
4018 ++NumSelectsExpanded;
4019 return true;
4020}
4021
Benjamin Kramer573ff362014-03-01 17:24:40 +00004022static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004023 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4024 int SplatElem = -1;
4025 for (unsigned i = 0; i < Mask.size(); ++i) {
4026 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4027 return false;
4028 SplatElem = Mask[i];
4029 }
4030
4031 return true;
4032}
4033
4034/// Some targets have expensive vector shifts if the lanes aren't all the same
4035/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4036/// it's often worth sinking a shufflevector splat down to its use so that
4037/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004038bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004039 BasicBlock *DefBB = SVI->getParent();
4040
4041 // Only do this xform if variable vector shifts are particularly expensive.
4042 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4043 return false;
4044
4045 // We only expect better codegen by sinking a shuffle if we can recognise a
4046 // constant splat.
4047 if (!isBroadcastShuffle(SVI))
4048 return false;
4049
4050 // InsertedShuffles - Only insert a shuffle in each block once.
4051 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4052
4053 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004054 for (User *U : SVI->users()) {
4055 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004056
4057 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004058 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004059 if (UserBB == DefBB) continue;
4060
4061 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004062 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004063
4064 // Everything checks out, sink the shuffle if the user's block doesn't
4065 // already have a copy.
4066 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4067
4068 if (!InsertedShuffle) {
4069 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004070 assert(InsertPt != UserBB->end());
4071 InsertedShuffle =
4072 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4073 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004074 }
4075
Chandler Carruthcdf47882014-03-09 03:16:01 +00004076 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004077 MadeChange = true;
4078 }
4079
4080 // If we removed all uses, nuke the shuffle.
4081 if (SVI->use_empty()) {
4082 SVI->eraseFromParent();
4083 MadeChange = true;
4084 }
4085
4086 return MadeChange;
4087}
4088
Quentin Colombetc32615d2014-10-31 17:52:53 +00004089namespace {
4090/// \brief Helper class to promote a scalar operation to a vector one.
4091/// This class is used to move downward extractelement transition.
4092/// E.g.,
4093/// a = vector_op <2 x i32>
4094/// b = extractelement <2 x i32> a, i32 0
4095/// c = scalar_op b
4096/// store c
4097///
4098/// =>
4099/// a = vector_op <2 x i32>
4100/// c = vector_op a (equivalent to scalar_op on the related lane)
4101/// * d = extractelement <2 x i32> c, i32 0
4102/// * store d
4103/// Assuming both extractelement and store can be combine, we get rid of the
4104/// transition.
4105class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004106 /// DataLayout associated with the current module.
4107 const DataLayout &DL;
4108
Quentin Colombetc32615d2014-10-31 17:52:53 +00004109 /// Used to perform some checks on the legality of vector operations.
4110 const TargetLowering &TLI;
4111
4112 /// Used to estimated the cost of the promoted chain.
4113 const TargetTransformInfo &TTI;
4114
4115 /// The transition being moved downwards.
4116 Instruction *Transition;
4117 /// The sequence of instructions to be promoted.
4118 SmallVector<Instruction *, 4> InstsToBePromoted;
4119 /// Cost of combining a store and an extract.
4120 unsigned StoreExtractCombineCost;
4121 /// Instruction that will be combined with the transition.
4122 Instruction *CombineInst;
4123
4124 /// \brief The instruction that represents the current end of the transition.
4125 /// Since we are faking the promotion until we reach the end of the chain
4126 /// of computation, we need a way to get the current end of the transition.
4127 Instruction *getEndOfTransition() const {
4128 if (InstsToBePromoted.empty())
4129 return Transition;
4130 return InstsToBePromoted.back();
4131 }
4132
4133 /// \brief Return the index of the original value in the transition.
4134 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4135 /// c, is at index 0.
4136 unsigned getTransitionOriginalValueIdx() const {
4137 assert(isa<ExtractElementInst>(Transition) &&
4138 "Other kind of transitions are not supported yet");
4139 return 0;
4140 }
4141
4142 /// \brief Return the index of the index in the transition.
4143 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4144 /// is at index 1.
4145 unsigned getTransitionIdx() const {
4146 assert(isa<ExtractElementInst>(Transition) &&
4147 "Other kind of transitions are not supported yet");
4148 return 1;
4149 }
4150
4151 /// \brief Get the type of the transition.
4152 /// This is the type of the original value.
4153 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4154 /// transition is <2 x i32>.
4155 Type *getTransitionType() const {
4156 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4157 }
4158
4159 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4160 /// I.e., we have the following sequence:
4161 /// Def = Transition <ty1> a to <ty2>
4162 /// b = ToBePromoted <ty2> Def, ...
4163 /// =>
4164 /// b = ToBePromoted <ty1> a, ...
4165 /// Def = Transition <ty1> ToBePromoted to <ty2>
4166 void promoteImpl(Instruction *ToBePromoted);
4167
4168 /// \brief Check whether or not it is profitable to promote all the
4169 /// instructions enqueued to be promoted.
4170 bool isProfitableToPromote() {
4171 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4172 unsigned Index = isa<ConstantInt>(ValIdx)
4173 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4174 : -1;
4175 Type *PromotedType = getTransitionType();
4176
4177 StoreInst *ST = cast<StoreInst>(CombineInst);
4178 unsigned AS = ST->getPointerAddressSpace();
4179 unsigned Align = ST->getAlignment();
4180 // Check if this store is supported.
4181 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004182 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4183 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004184 // If this is not supported, there is no way we can combine
4185 // the extract with the store.
4186 return false;
4187 }
4188
4189 // The scalar chain of computation has to pay for the transition
4190 // scalar to vector.
4191 // The vector chain has to account for the combining cost.
4192 uint64_t ScalarCost =
4193 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4194 uint64_t VectorCost = StoreExtractCombineCost;
4195 for (const auto &Inst : InstsToBePromoted) {
4196 // Compute the cost.
4197 // By construction, all instructions being promoted are arithmetic ones.
4198 // Moreover, one argument is a constant that can be viewed as a splat
4199 // constant.
4200 Value *Arg0 = Inst->getOperand(0);
4201 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4202 isa<ConstantFP>(Arg0);
4203 TargetTransformInfo::OperandValueKind Arg0OVK =
4204 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4205 : TargetTransformInfo::OK_AnyValue;
4206 TargetTransformInfo::OperandValueKind Arg1OVK =
4207 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4208 : TargetTransformInfo::OK_AnyValue;
4209 ScalarCost += TTI.getArithmeticInstrCost(
4210 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4211 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4212 Arg0OVK, Arg1OVK);
4213 }
4214 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4215 << ScalarCost << "\nVector: " << VectorCost << '\n');
4216 return ScalarCost > VectorCost;
4217 }
4218
4219 /// \brief Generate a constant vector with \p Val with the same
4220 /// number of elements as the transition.
4221 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004222 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004223 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4224 /// otherwise we generate a vector with as many undef as possible:
4225 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4226 /// used at the index of the extract.
4227 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4228 unsigned ExtractIdx = UINT_MAX;
4229 if (!UseSplat) {
4230 // If we cannot determine where the constant must be, we have to
4231 // use a splat constant.
4232 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4233 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4234 ExtractIdx = CstVal->getSExtValue();
4235 else
4236 UseSplat = true;
4237 }
4238
4239 unsigned End = getTransitionType()->getVectorNumElements();
4240 if (UseSplat)
4241 return ConstantVector::getSplat(End, Val);
4242
4243 SmallVector<Constant *, 4> ConstVec;
4244 UndefValue *UndefVal = UndefValue::get(Val->getType());
4245 for (unsigned Idx = 0; Idx != End; ++Idx) {
4246 if (Idx == ExtractIdx)
4247 ConstVec.push_back(Val);
4248 else
4249 ConstVec.push_back(UndefVal);
4250 }
4251 return ConstantVector::get(ConstVec);
4252 }
4253
4254 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4255 /// in \p Use can trigger undefined behavior.
4256 static bool canCauseUndefinedBehavior(const Instruction *Use,
4257 unsigned OperandIdx) {
4258 // This is not safe to introduce undef when the operand is on
4259 // the right hand side of a division-like instruction.
4260 if (OperandIdx != 1)
4261 return false;
4262 switch (Use->getOpcode()) {
4263 default:
4264 return false;
4265 case Instruction::SDiv:
4266 case Instruction::UDiv:
4267 case Instruction::SRem:
4268 case Instruction::URem:
4269 return true;
4270 case Instruction::FDiv:
4271 case Instruction::FRem:
4272 return !Use->hasNoNaNs();
4273 }
4274 llvm_unreachable(nullptr);
4275 }
4276
4277public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004278 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4279 const TargetTransformInfo &TTI, Instruction *Transition,
4280 unsigned CombineCost)
4281 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004282 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4283 assert(Transition && "Do not know how to promote null");
4284 }
4285
4286 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4287 bool canPromote(const Instruction *ToBePromoted) const {
4288 // We could support CastInst too.
4289 return isa<BinaryOperator>(ToBePromoted);
4290 }
4291
4292 /// \brief Check if it is profitable to promote \p ToBePromoted
4293 /// by moving downward the transition through.
4294 bool shouldPromote(const Instruction *ToBePromoted) const {
4295 // Promote only if all the operands can be statically expanded.
4296 // Indeed, we do not want to introduce any new kind of transitions.
4297 for (const Use &U : ToBePromoted->operands()) {
4298 const Value *Val = U.get();
4299 if (Val == getEndOfTransition()) {
4300 // If the use is a division and the transition is on the rhs,
4301 // we cannot promote the operation, otherwise we may create a
4302 // division by zero.
4303 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4304 return false;
4305 continue;
4306 }
4307 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4308 !isa<ConstantFP>(Val))
4309 return false;
4310 }
4311 // Check that the resulting operation is legal.
4312 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4313 if (!ISDOpcode)
4314 return false;
4315 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004316 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004317 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004318 }
4319
4320 /// \brief Check whether or not \p Use can be combined
4321 /// with the transition.
4322 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4323 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4324
4325 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4326 void enqueueForPromotion(Instruction *ToBePromoted) {
4327 InstsToBePromoted.push_back(ToBePromoted);
4328 }
4329
4330 /// \brief Set the instruction that will be combined with the transition.
4331 void recordCombineInstruction(Instruction *ToBeCombined) {
4332 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4333 CombineInst = ToBeCombined;
4334 }
4335
4336 /// \brief Promote all the instructions enqueued for promotion if it is
4337 /// is profitable.
4338 /// \return True if the promotion happened, false otherwise.
4339 bool promote() {
4340 // Check if there is something to promote.
4341 // Right now, if we do not have anything to combine with,
4342 // we assume the promotion is not profitable.
4343 if (InstsToBePromoted.empty() || !CombineInst)
4344 return false;
4345
4346 // Check cost.
4347 if (!StressStoreExtract && !isProfitableToPromote())
4348 return false;
4349
4350 // Promote.
4351 for (auto &ToBePromoted : InstsToBePromoted)
4352 promoteImpl(ToBePromoted);
4353 InstsToBePromoted.clear();
4354 return true;
4355 }
4356};
4357} // End of anonymous namespace.
4358
4359void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4360 // At this point, we know that all the operands of ToBePromoted but Def
4361 // can be statically promoted.
4362 // For Def, we need to use its parameter in ToBePromoted:
4363 // b = ToBePromoted ty1 a
4364 // Def = Transition ty1 b to ty2
4365 // Move the transition down.
4366 // 1. Replace all uses of the promoted operation by the transition.
4367 // = ... b => = ... Def.
4368 assert(ToBePromoted->getType() == Transition->getType() &&
4369 "The type of the result of the transition does not match "
4370 "the final type");
4371 ToBePromoted->replaceAllUsesWith(Transition);
4372 // 2. Update the type of the uses.
4373 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4374 Type *TransitionTy = getTransitionType();
4375 ToBePromoted->mutateType(TransitionTy);
4376 // 3. Update all the operands of the promoted operation with promoted
4377 // operands.
4378 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4379 for (Use &U : ToBePromoted->operands()) {
4380 Value *Val = U.get();
4381 Value *NewVal = nullptr;
4382 if (Val == Transition)
4383 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4384 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4385 isa<ConstantFP>(Val)) {
4386 // Use a splat constant if it is not safe to use undef.
4387 NewVal = getConstantVector(
4388 cast<Constant>(Val),
4389 isa<UndefValue>(Val) ||
4390 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4391 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004392 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4393 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004394 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4395 }
4396 Transition->removeFromParent();
4397 Transition->insertAfter(ToBePromoted);
4398 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4399}
4400
4401/// Some targets can do store(extractelement) with one instruction.
4402/// Try to push the extractelement towards the stores when the target
4403/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004404bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004405 unsigned CombineCost = UINT_MAX;
4406 if (DisableStoreExtract || !TLI ||
4407 (!StressStoreExtract &&
4408 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4409 Inst->getOperand(1), CombineCost)))
4410 return false;
4411
4412 // At this point we know that Inst is a vector to scalar transition.
4413 // Try to move it down the def-use chain, until:
4414 // - We can combine the transition with its single use
4415 // => we got rid of the transition.
4416 // - We escape the current basic block
4417 // => we would need to check that we are moving it at a cheaper place and
4418 // we do not do that for now.
4419 BasicBlock *Parent = Inst->getParent();
4420 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00004421 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00004422 // If the transition has more than one use, assume this is not going to be
4423 // beneficial.
4424 while (Inst->hasOneUse()) {
4425 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4426 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4427
4428 if (ToBePromoted->getParent() != Parent) {
4429 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4430 << ToBePromoted->getParent()->getName()
4431 << ") than the transition (" << Parent->getName() << ").\n");
4432 return false;
4433 }
4434
4435 if (VPH.canCombine(ToBePromoted)) {
4436 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4437 << "will be combined with: " << *ToBePromoted << '\n');
4438 VPH.recordCombineInstruction(ToBePromoted);
4439 bool Changed = VPH.promote();
4440 NumStoreExtractExposed += Changed;
4441 return Changed;
4442 }
4443
4444 DEBUG(dbgs() << "Try promoting.\n");
4445 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4446 return false;
4447
4448 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4449
4450 VPH.enqueueForPromotion(ToBePromoted);
4451 Inst = ToBePromoted;
4452 }
4453 return false;
4454}
4455
Sanjay Patelfc580a62015-09-21 23:03:16 +00004456bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004457 // Bail out if we inserted the instruction to prevent optimizations from
4458 // stepping on each other's toes.
4459 if (InsertedInsts.count(I))
4460 return false;
4461
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004462 if (PHINode *P = dyn_cast<PHINode>(I)) {
4463 // It is possible for very late stage optimizations (such as SimplifyCFG)
4464 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4465 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00004466 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004467 P->replaceAllUsesWith(V);
4468 P->eraseFromParent();
4469 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004470 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004471 }
Chris Lattneree588de2011-01-15 07:29:01 +00004472 return false;
4473 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004474
Chris Lattneree588de2011-01-15 07:29:01 +00004475 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004476 // If the source of the cast is a constant, then this should have
4477 // already been constant folded. The only reason NOT to constant fold
4478 // it is if something (e.g. LSR) was careful to place the constant
4479 // evaluation in a block other than then one that uses it (e.g. to hoist
4480 // the address of globals out of a loop). If this is the case, we don't
4481 // want to forward-subst the cast.
4482 if (isa<Constant>(CI->getOperand(0)))
4483 return false;
4484
Mehdi Amini44ede332015-07-09 02:09:04 +00004485 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00004486 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004487
Chris Lattneree588de2011-01-15 07:29:01 +00004488 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004489 /// Sink a zext or sext into its user blocks if the target type doesn't
4490 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00004491 if (TLI &&
4492 TLI->getTypeAction(CI->getContext(),
4493 TLI->getValueType(*DL, CI->getType())) ==
4494 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004495 return SinkCast(CI);
4496 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00004497 bool MadeChange = moveExtToFormExtLoad(I);
4498 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004499 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004500 }
Chris Lattneree588de2011-01-15 07:29:01 +00004501 return false;
4502 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004503
Chris Lattneree588de2011-01-15 07:29:01 +00004504 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004505 if (!TLI || !TLI->hasMultipleConditionRegisters())
4506 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004507
Chris Lattneree588de2011-01-15 07:29:01 +00004508 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004509 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004510 if (TLI) {
4511 unsigned AS = LI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00004512 return optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004513 }
Hans Wennborgf3254832012-10-30 11:23:25 +00004514 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004515 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004516
Chris Lattneree588de2011-01-15 07:29:01 +00004517 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004518 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004519 if (TLI) {
4520 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00004521 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004522 SI->getOperand(0)->getType(), AS);
4523 }
Chris Lattneree588de2011-01-15 07:29:01 +00004524 return false;
4525 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004526
Yi Jiangd069f632014-04-21 19:34:27 +00004527 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4528
4529 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4530 BinOp->getOpcode() == Instruction::LShr)) {
4531 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4532 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00004533 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00004534
4535 return false;
4536 }
4537
Chris Lattneree588de2011-01-15 07:29:01 +00004538 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004539 if (GEPI->hasAllZeroIndices()) {
4540 /// The GEP operand must be a pointer, so must its result -> BitCast
4541 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4542 GEPI->getName(), GEPI);
4543 GEPI->replaceAllUsesWith(NC);
4544 GEPI->eraseFromParent();
4545 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004546 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004547 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004548 }
Chris Lattneree588de2011-01-15 07:29:01 +00004549 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004550 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004551
Chris Lattneree588de2011-01-15 07:29:01 +00004552 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004553 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004554
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004555 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004556 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004557
Tim Northoveraeb8e062014-02-19 10:02:43 +00004558 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004559 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004560
Quentin Colombetc32615d2014-10-31 17:52:53 +00004561 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00004562 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00004563
Chris Lattneree588de2011-01-15 07:29:01 +00004564 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004565}
4566
Chris Lattnerf2836d12007-03-31 04:06:36 +00004567// In this pass we look for GEP and cast instructions that are used
4568// across basic blocks and rewrite them to improve basic-block-at-a-time
4569// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004570bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004571 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004572 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004573
Chris Lattner7a277142011-01-15 07:14:54 +00004574 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004575 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004576 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004577 if (ModifiedDT)
4578 return true;
4579 }
Sanjay Patelfc580a62015-09-21 23:03:16 +00004580 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Benjamin Kramer455fa352012-11-23 19:17:06 +00004581
Chris Lattnerf2836d12007-03-31 04:06:36 +00004582 return MadeChange;
4583}
Devang Patel53771ba2011-08-18 00:50:51 +00004584
4585// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004586// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004587// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004588bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00004589 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004590 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004591 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004592 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004593 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00004594 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004595 // Leave dbg.values that refer to an alloca alone. These
4596 // instrinsics describe the address of a variable (= the alloca)
4597 // being taken. They should not be moved next to the alloca
4598 // (and to the beginning of the scope), but rather stay close to
4599 // where said address is used.
4600 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004601 PrevNonDbgInst = Insn;
4602 continue;
4603 }
4604
4605 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4606 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4607 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4608 DVI->removeFromParent();
4609 if (isa<PHINode>(VI))
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004610 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
Devang Patel53771ba2011-08-18 00:50:51 +00004611 else
4612 DVI->insertAfter(VI);
4613 MadeChange = true;
4614 ++NumDbgValueMoved;
4615 }
4616 }
4617 }
4618 return MadeChange;
4619}
Tim Northovercea0abb2014-03-29 08:22:29 +00004620
4621// If there is a sequence that branches based on comparing a single bit
4622// against zero that can be combined into a single instruction, and the
4623// target supports folding these into a single instruction, sink the
4624// mask and compare into the branch uses. Do this before OptimizeBlock ->
4625// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4626// searched for.
4627bool CodeGenPrepare::sinkAndCmp(Function &F) {
4628 if (!EnableAndCmpSinking)
4629 return false;
4630 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4631 return false;
4632 bool MadeChange = false;
4633 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004634 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00004635
4636 // Does this BB end with the following?
4637 // %andVal = and %val, #single-bit-set
4638 // %icmpVal = icmp %andResult, 0
4639 // br i1 %cmpVal label %dest1, label %dest2"
4640 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4641 if (!Brcc || !Brcc->isConditional())
4642 continue;
4643 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4644 if (!Cmp || Cmp->getParent() != BB)
4645 continue;
4646 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4647 if (!Zero || !Zero->isZero())
4648 continue;
4649 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4650 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4651 continue;
4652 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4653 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4654 continue;
4655 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4656
4657 // Push the "and; icmp" for any users that are conditional branches.
4658 // Since there can only be one branch use per BB, we don't need to keep
4659 // track of which BBs we insert into.
4660 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4661 UI != E; ) {
4662 Use &TheUse = *UI;
4663 // Find brcc use.
4664 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4665 ++UI;
4666 if (!BrccUser || !BrccUser->isConditional())
4667 continue;
4668 BasicBlock *UserBB = BrccUser->getParent();
4669 if (UserBB == BB) continue;
4670 DEBUG(dbgs() << "found Brcc use\n");
4671
4672 // Sink the "and; icmp" to use.
4673 MadeChange = true;
4674 BinaryOperator *NewAnd =
4675 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4676 BrccUser);
4677 CmpInst *NewCmp =
4678 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4679 "", BrccUser);
4680 TheUse = NewCmp;
4681 ++NumAndCmpsMoved;
4682 DEBUG(BrccUser->getParent()->dump());
4683 }
4684 }
4685 return MadeChange;
4686}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004687
Juergen Ributzka194350a2014-12-09 17:32:12 +00004688/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4689/// success, or returns false if no or invalid metadata was found.
4690static bool extractBranchMetadata(BranchInst *BI,
4691 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4692 assert(BI->isConditional() &&
4693 "Looking for probabilities on unconditional branch?");
4694 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4695 if (!ProfileData || ProfileData->getNumOperands() != 3)
4696 return false;
4697
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004698 const auto *CITrue =
4699 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4700 const auto *CIFalse =
4701 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004702 if (!CITrue || !CIFalse)
4703 return false;
4704
4705 ProbTrue = CITrue->getValue().getZExtValue();
4706 ProbFalse = CIFalse->getValue().getZExtValue();
4707
4708 return true;
4709}
4710
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004711/// \brief Scale down both weights to fit into uint32_t.
4712static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4713 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4714 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4715 NewTrue = NewTrue / Scale;
4716 NewFalse = NewFalse / Scale;
4717}
4718
4719/// \brief Some targets prefer to split a conditional branch like:
4720/// \code
4721/// %0 = icmp ne i32 %a, 0
4722/// %1 = icmp ne i32 %b, 0
4723/// %or.cond = or i1 %0, %1
4724/// br i1 %or.cond, label %TrueBB, label %FalseBB
4725/// \endcode
4726/// into multiple branch instructions like:
4727/// \code
4728/// bb1:
4729/// %0 = icmp ne i32 %a, 0
4730/// br i1 %0, label %TrueBB, label %bb2
4731/// bb2:
4732/// %1 = icmp ne i32 %b, 0
4733/// br i1 %1, label %TrueBB, label %FalseBB
4734/// \endcode
4735/// This usually allows instruction selection to do even further optimizations
4736/// and combine the compare with the branch instruction. Currently this is
4737/// applied for targets which have "cheap" jump instructions.
4738///
4739/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4740///
4741bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00004742 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004743 return false;
4744
4745 bool MadeChange = false;
4746 for (auto &BB : F) {
4747 // Does this BB end with the following?
4748 // %cond1 = icmp|fcmp|binary instruction ...
4749 // %cond2 = icmp|fcmp|binary instruction ...
4750 // %cond.or = or|and i1 %cond1, cond2
4751 // br i1 %cond.or label %dest1, label %dest2"
4752 BinaryOperator *LogicOp;
4753 BasicBlock *TBB, *FBB;
4754 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4755 continue;
4756
Sanjay Patel42574202015-09-02 19:23:23 +00004757 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4758 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
4759 continue;
4760
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004761 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004762 Value *Cond1, *Cond2;
4763 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4764 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004765 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004766 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4767 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004768 Opc = Instruction::Or;
4769 else
4770 continue;
4771
4772 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4773 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4774 continue;
4775
4776 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4777
4778 // Create a new BB.
4779 auto *InsertBefore = std::next(Function::iterator(BB))
4780 .getNodePtrUnchecked();
4781 auto TmpBB = BasicBlock::Create(BB.getContext(),
4782 BB.getName() + ".cond.split",
4783 BB.getParent(), InsertBefore);
4784
4785 // Update original basic block by using the first condition directly by the
4786 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004787 Br1->setCondition(Cond1);
4788 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004789
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004790 // Depending on the conditon we have to either replace the true or the false
4791 // successor of the original branch instruction.
4792 if (Opc == Instruction::And)
4793 Br1->setSuccessor(0, TmpBB);
4794 else
4795 Br1->setSuccessor(1, TmpBB);
4796
4797 // Fill in the new basic block.
4798 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004799 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4800 I->removeFromParent();
4801 I->insertBefore(Br2);
4802 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004803
4804 // Update PHI nodes in both successors. The original BB needs to be
4805 // replaced in one succesor's PHI nodes, because the branch comes now from
4806 // the newly generated BB (NewBB). In the other successor we need to add one
4807 // incoming edge to the PHI nodes, because both branch instructions target
4808 // now the same successor. Depending on the original branch condition
4809 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4810 // we perfrom the correct update for the PHI nodes.
4811 // This doesn't change the successor order of the just created branch
4812 // instruction (or any other instruction).
4813 if (Opc == Instruction::Or)
4814 std::swap(TBB, FBB);
4815
4816 // Replace the old BB with the new BB.
4817 for (auto &I : *TBB) {
4818 PHINode *PN = dyn_cast<PHINode>(&I);
4819 if (!PN)
4820 break;
4821 int i;
4822 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4823 PN->setIncomingBlock(i, TmpBB);
4824 }
4825
4826 // Add another incoming edge form the new BB.
4827 for (auto &I : *FBB) {
4828 PHINode *PN = dyn_cast<PHINode>(&I);
4829 if (!PN)
4830 break;
4831 auto *Val = PN->getIncomingValueForBlock(&BB);
4832 PN->addIncoming(Val, TmpBB);
4833 }
4834
4835 // Update the branch weights (from SelectionDAGBuilder::
4836 // FindMergedConditions).
4837 if (Opc == Instruction::Or) {
4838 // Codegen X | Y as:
4839 // BB1:
4840 // jmp_if_X TBB
4841 // jmp TmpBB
4842 // TmpBB:
4843 // jmp_if_Y TBB
4844 // jmp FBB
4845 //
4846
4847 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4848 // The requirement is that
4849 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4850 // = TrueProb for orignal BB.
4851 // Assuming the orignal weights are A and B, one choice is to set BB1's
4852 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4853 // assumes that
4854 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4855 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4856 // TmpBB, but the math is more complicated.
4857 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004858 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004859 uint64_t NewTrueWeight = TrueWeight;
4860 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4861 scaleWeights(NewTrueWeight, NewFalseWeight);
4862 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4863 .createBranchWeights(TrueWeight, FalseWeight));
4864
4865 NewTrueWeight = TrueWeight;
4866 NewFalseWeight = 2 * FalseWeight;
4867 scaleWeights(NewTrueWeight, NewFalseWeight);
4868 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4869 .createBranchWeights(TrueWeight, FalseWeight));
4870 }
4871 } else {
4872 // Codegen X & Y as:
4873 // BB1:
4874 // jmp_if_X TmpBB
4875 // jmp FBB
4876 // TmpBB:
4877 // jmp_if_Y TBB
4878 // jmp FBB
4879 //
4880 // This requires creation of TmpBB after CurBB.
4881
4882 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4883 // The requirement is that
4884 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4885 // = FalseProb for orignal BB.
4886 // Assuming the orignal weights are A and B, one choice is to set BB1's
4887 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4888 // assumes that
4889 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4890 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004891 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004892 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4893 uint64_t NewFalseWeight = FalseWeight;
4894 scaleWeights(NewTrueWeight, NewFalseWeight);
4895 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4896 .createBranchWeights(TrueWeight, FalseWeight));
4897
4898 NewTrueWeight = 2 * TrueWeight;
4899 NewFalseWeight = FalseWeight;
4900 scaleWeights(NewTrueWeight, NewFalseWeight);
4901 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4902 .createBranchWeights(TrueWeight, FalseWeight));
4903 }
4904 }
4905
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004906 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00004907 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004908 ModifiedDT = true;
4909
4910 MadeChange = true;
4911
4912 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4913 TmpBB->dump());
4914 }
4915 return MadeChange;
4916}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004917
4918void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00004919 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00004920 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
4921}