blob: 5844124d85655141e62c35e36a45d0ee69684b5b [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");
Geoff Berry5256fca2015-11-20 22:34:39 +000067STATISTIC(NumAndsAdded,
68 "Number of and mask instructions added to form ext loads");
69STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
Evan Cheng0663f232011-03-21 01:19:09 +000070STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000071STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000072STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000073STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000074STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000075
Cameron Zwarich338d3622011-03-11 21:52:04 +000076static cl::opt<bool> DisableBranchOpts(
77 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
78 cl::desc("Disable branch optimizations in CodeGenPrepare"));
79
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000080static cl::opt<bool>
81 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
82 cl::desc("Disable GC optimizations in CodeGenPrepare"));
83
Benjamin Kramer3d38c172012-05-06 14:25:16 +000084static cl::opt<bool> DisableSelectToBranch(
85 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
86 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000087
Hal Finkelc3998302014-04-12 00:59:48 +000088static cl::opt<bool> AddrSinkUsingGEPs(
89 "addr-sink-using-gep", cl::Hidden, cl::init(false),
90 cl::desc("Address sinking in CGP using GEPs."));
91
Tim Northovercea0abb2014-03-29 08:22:29 +000092static cl::opt<bool> EnableAndCmpSinking(
93 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
94 cl::desc("Enable sinkinig and/cmp into branches."));
95
Quentin Colombetc32615d2014-10-31 17:52:53 +000096static cl::opt<bool> DisableStoreExtract(
97 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
98 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
99
100static cl::opt<bool> StressStoreExtract(
101 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
102 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
103
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000104static cl::opt<bool> DisableExtLdPromotion(
105 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
106 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
107 "CodeGenPrepare"));
108
109static cl::opt<bool> StressExtLdPromotion(
110 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
111 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
112 "optimization in CodeGenPrepare"));
113
Eric Christopherc1ea1492008-09-24 05:32:41 +0000114namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000115typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000116typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000117typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000118class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000119
Chris Lattner2dd09db2009-09-02 06:11:42 +0000120 class CodeGenPrepare : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000121 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000122 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000123 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000124 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000125
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000126 /// As we scan instructions optimizing them, this is the next instruction
127 /// to optimize. Transforms that can invalidate this should update it.
Chris Lattner7a277142011-01-15 07:14:54 +0000128 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000129
Evan Cheng0663f232011-03-21 01:19:09 +0000130 /// Keeps track of non-local addresses that have been sunk into a block.
131 /// This allows us to avoid inserting duplicate code for blocks with
132 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000133 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000134
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000135 /// Keeps track of all instructions inserted for the current function.
136 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000137 /// Keeps track of the type of the related instruction before their
138 /// promotion for the current function.
139 InstrToOrigTy PromotedInsts;
140
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000141 /// True if CFG is modified in any way.
Devang Patel8f606d72011-03-24 15:35:25 +0000142 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000143
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000144 /// True if optimizing for size.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000145 bool OptSize;
146
Mehdi Amini4fe37982015-07-07 18:45:17 +0000147 /// DataLayout for the Function being processed.
148 const DataLayout *DL;
149
Chris Lattnerf2836d12007-03-31 04:06:36 +0000150 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000151 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000152 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000153 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000154 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
155 }
Craig Topper4584cd52014-03-07 09:26:03 +0000156 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000157
Craig Topper4584cd52014-03-07 09:26:03 +0000158 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000159
Craig Topper4584cd52014-03-07 09:26:03 +0000160 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000161 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000162 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000163 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000164 }
165
Chris Lattnerf2836d12007-03-31 04:06:36 +0000166 private:
Sanjay Patelfc580a62015-09-21 23:03:16 +0000167 bool eliminateFallThrough(Function &F);
168 bool eliminateMostlyEmptyBlocks(Function &F);
169 bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
170 void eliminateMostlyEmptyBlock(BasicBlock *BB);
171 bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
172 bool optimizeInst(Instruction *I, bool& ModifiedDT);
173 bool optimizeMemoryInst(Instruction *I, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000174 Type *AccessTy, unsigned AS);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000175 bool optimizeInlineAsmInst(CallInst *CS);
176 bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
177 bool moveExtToFormExtLoad(Instruction *&I);
178 bool optimizeExtUses(Instruction *I);
Geoff Berry5256fca2015-11-20 22:34:39 +0000179 bool optimizeLoadExt(LoadInst *I);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000180 bool optimizeSelectInst(SelectInst *SI);
181 bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
Sanjay Patel0ed9aea2015-11-02 23:22:49 +0000182 bool optimizeSwitchInst(SwitchInst *CI);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000183 bool optimizeExtractElementInst(Instruction *Inst);
184 bool dupRetToEnableTailCallOpts(BasicBlock *BB);
185 bool placeDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000186 bool sinkAndCmp(Function &F);
Sanjay Patelfc580a62015-09-21 23:03:16 +0000187 bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000188 Instruction *&Inst,
189 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000190 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000191 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000192 bool simplifyOffsetableRelocate(Instruction &I);
Piotr Padlewski6c15ec42015-09-15 18:32:14 +0000193 void stripInvariantGroupMetadata(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000194 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000195}
Devang Patel09f162c2007-05-01 21:15:47 +0000196
Devang Patel8c78a0b2007-05-03 01:11:54 +0000197char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000198INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
199 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000200
Bill Wendling7a639ea2013-06-19 21:07:11 +0000201FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
202 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000203}
204
Chris Lattnerf2836d12007-03-31 04:06:36 +0000205bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000206 if (skipOptnoneFunction(F))
207 return false;
208
Mehdi Amini4fe37982015-07-07 18:45:17 +0000209 DL = &F.getParent()->getDataLayout();
210
Chris Lattnerf2836d12007-03-31 04:06:36 +0000211 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000212 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000213 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000214 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000215
Devang Patel8f606d72011-03-24 15:35:25 +0000216 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000217 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000218 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000219 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000220 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sanjay Patel82d91dd2015-08-11 19:39:36 +0000221 OptSize = F.optForSize();
Evan Cheng0663f232011-03-21 01:19:09 +0000222
Preston Gurdcdf540d2012-09-04 18:22:17 +0000223 /// This optimization identifies DIV instructions that can be
224 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000225 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000226 const DenseMap<unsigned int, unsigned int> &BypassWidths =
227 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000228 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000229 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000230 }
231
232 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000233 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000234 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000235
Devang Patel53771ba2011-08-18 00:50:51 +0000236 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000237 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000238 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000239 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000240
Tim Northovercea0abb2014-03-29 08:22:29 +0000241 // If there is a mask, compare against zero, and branch that can be combined
242 // into a single target instruction, push the mask and compare into branch
243 // users. Do this before OptimizeBlock -> OptimizeInst ->
244 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000245 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000246 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000247 EverMadeChange |= splitBranchCondition(F);
248 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000249
Chris Lattnerc3748562007-04-02 01:35:34 +0000250 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000251 while (MadeChange) {
252 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000253 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000254 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000255 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000256 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000257
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000258 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000259 if (ModifiedDTOnIteration)
260 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000261 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000262 EverMadeChange |= MadeChange;
263 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000264
265 SunkAddrs.clear();
266
Cameron Zwarich338d3622011-03-11 21:52:04 +0000267 if (!DisableBranchOpts) {
268 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000269 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000270 for (BasicBlock &BB : F) {
271 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
272 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000273 if (!MadeChange) continue;
274
275 for (SmallVectorImpl<BasicBlock*>::iterator
276 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
277 if (pred_begin(*II) == pred_end(*II))
278 WorkList.insert(*II);
279 }
280
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000281 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000282 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000283 while (!WorkList.empty()) {
284 BasicBlock *BB = *WorkList.begin();
285 WorkList.erase(BB);
286 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
287
288 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000289
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000290 for (SmallVectorImpl<BasicBlock*>::iterator
291 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
292 if (pred_begin(*II) == pred_end(*II))
293 WorkList.insert(*II);
294 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000295
Nadav Rotem70409992012-08-14 05:19:07 +0000296 // Merge pairs of basic blocks with unconditional branches, connected by
297 // a single edge.
298 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000299 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000300
Cameron Zwarich338d3622011-03-11 21:52:04 +0000301 EverMadeChange |= MadeChange;
302 }
303
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000304 if (!DisableGCOpts) {
305 SmallVector<Instruction *, 2> Statepoints;
306 for (BasicBlock &BB : F)
307 for (Instruction &I : BB)
308 if (isStatepoint(I))
309 Statepoints.push_back(&I);
310 for (auto &I : Statepoints)
311 EverMadeChange |= simplifyOffsetableRelocate(*I);
312 }
313
Chris Lattnerf2836d12007-03-31 04:06:36 +0000314 return EverMadeChange;
315}
316
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000317/// Merge basic blocks which are connected by a single edge, where one of the
318/// basic blocks has a single successor pointing to the other basic block,
319/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000320bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000321 bool Changed = false;
322 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000323 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000324 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000325 // If the destination block has a single pred, then this is a trivial
326 // edge, just collapse it.
327 BasicBlock *SinglePred = BB->getSinglePredecessor();
328
Evan Cheng64a223a2012-09-28 23:58:57 +0000329 // Don't merge if BB's address is taken.
330 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000331
332 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
333 if (Term && !Term->isConditional()) {
334 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000335 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000336 // Remember if SinglePred was the entry block of the function.
337 // If so, we will need to move BB back to the entry position.
338 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000339 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000340
341 if (isEntry && BB != &BB->getParent()->getEntryBlock())
342 BB->moveBefore(&BB->getParent()->getEntryBlock());
343
344 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000345 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000346 }
347 }
348 return Changed;
349}
350
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000351/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
352/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
353/// edges in ways that are non-optimal for isel. Start by eliminating these
354/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000355bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000356 bool MadeChange = false;
357 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000358 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000359 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000360
361 // If this block doesn't end with an uncond branch, ignore it.
362 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
363 if (!BI || !BI->isUnconditional())
364 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000365
Dale Johannesen4026b042009-03-27 01:13:37 +0000366 // If the instruction before the branch (skipping debug info) isn't a phi
367 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000368 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000369 if (BBI != BB->begin()) {
370 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000371 while (isa<DbgInfoIntrinsic>(BBI)) {
372 if (BBI == BB->begin())
373 break;
374 --BBI;
375 }
376 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
377 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000378 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000379
Chris Lattnerc3748562007-04-02 01:35:34 +0000380 // Do not break infinite loops.
381 BasicBlock *DestBB = BI->getSuccessor(0);
382 if (DestBB == BB)
383 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000384
Sanjay Patelfc580a62015-09-21 23:03:16 +0000385 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000387
Sanjay Patelfc580a62015-09-21 23:03:16 +0000388 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000389 MadeChange = true;
390 }
391 return MadeChange;
392}
393
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000394/// Return true if we can merge BB into DestBB if there is a single
395/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000396/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000397bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000398 const BasicBlock *DestBB) const {
399 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
400 // the successor. If there are more complex condition (e.g. preheaders),
401 // don't mess around with them.
402 BasicBlock::const_iterator BBI = BB->begin();
403 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000404 for (const User *U : PN->users()) {
405 const Instruction *UI = cast<Instruction>(U);
406 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000407 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000408 // If User is inside DestBB block and it is a PHINode then check
409 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000410 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000411 if (UI->getParent() == DestBB) {
412 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000413 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
414 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
415 if (Insn && Insn->getParent() == BB &&
416 Insn->getParent() != UPN->getIncomingBlock(I))
417 return false;
418 }
419 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000420 }
421 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000422
Chris Lattnerc3748562007-04-02 01:35:34 +0000423 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
424 // and DestBB may have conflicting incoming values for the block. If so, we
425 // can't merge the block.
426 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
427 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000428
Chris Lattnerc3748562007-04-02 01:35:34 +0000429 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000430 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000431 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
432 // It is faster to get preds from a PHI than with pred_iterator.
433 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
434 BBPreds.insert(BBPN->getIncomingBlock(i));
435 } else {
436 BBPreds.insert(pred_begin(BB), pred_end(BB));
437 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000438
Chris Lattnerc3748562007-04-02 01:35:34 +0000439 // Walk the preds of DestBB.
440 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
441 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
442 if (BBPreds.count(Pred)) { // Common predecessor?
443 BBI = DestBB->begin();
444 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
445 const Value *V1 = PN->getIncomingValueForBlock(Pred);
446 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000447
Chris Lattnerc3748562007-04-02 01:35:34 +0000448 // If V2 is a phi node in BB, look up what the mapped value will be.
449 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
450 if (V2PN->getParent() == BB)
451 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000452
Chris Lattnerc3748562007-04-02 01:35:34 +0000453 // If there is a conflict, bail out.
454 if (V1 != V2) return false;
455 }
456 }
457 }
458
459 return true;
460}
461
462
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000463/// Eliminate a basic block that has only phi's and an unconditional branch in
464/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000465void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000466 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
467 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000468
David Greene74e2d492010-01-05 01:27:11 +0000469 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000470
Chris Lattnerc3748562007-04-02 01:35:34 +0000471 // If the destination block has a single pred, then this is a trivial edge,
472 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000473 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000474 if (SinglePred != DestBB) {
475 // Remember if SinglePred was the entry block of the function. If so, we
476 // will need to move BB back to the entry position.
477 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000478 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000479
Chris Lattner8a172da2008-11-28 19:54:49 +0000480 if (isEntry && BB != &BB->getParent()->getEntryBlock())
481 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000482
David Greene74e2d492010-01-05 01:27:11 +0000483 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000484 return;
485 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000486 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000487
Chris Lattnerc3748562007-04-02 01:35:34 +0000488 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
489 // to handle the new incoming edges it is about to have.
490 PHINode *PN;
491 for (BasicBlock::iterator BBI = DestBB->begin();
492 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
493 // Remove the incoming value for BB, and remember it.
494 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000495
Chris Lattnerc3748562007-04-02 01:35:34 +0000496 // Two options: either the InVal is a phi node defined in BB or it is some
497 // value that dominates BB.
498 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
499 if (InValPhi && InValPhi->getParent() == BB) {
500 // Add all of the input values of the input PHI as inputs of this phi.
501 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
502 PN->addIncoming(InValPhi->getIncomingValue(i),
503 InValPhi->getIncomingBlock(i));
504 } else {
505 // Otherwise, add one instance of the dominating value for each edge that
506 // we will be adding.
507 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
508 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
509 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
510 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000511 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
512 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000513 }
514 }
515 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000516
Chris Lattnerc3748562007-04-02 01:35:34 +0000517 // The PHIs are now updated, change everything that refers to BB to use
518 // DestBB and remove BB.
519 BB->replaceAllUsesWith(DestBB);
520 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000521 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000522
David Greene74e2d492010-01-05 01:27:11 +0000523 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000524}
525
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000526// Computes a map of base pointer relocation instructions to corresponding
527// derived pointer relocation instructions given a vector of all relocate calls
528static void computeBaseDerivedRelocateMap(
529 const SmallVectorImpl<User *> &AllRelocateCalls,
530 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
531 RelocateInstMap) {
532 // Collect information in two maps: one primarily for locating the base object
533 // while filling the second map; the second map is the final structure holding
534 // a mapping between Base and corresponding Derived relocate calls
535 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
536 for (auto &U : AllRelocateCalls) {
537 GCRelocateOperands ThisRelocate(U);
538 IntrinsicInst *I = cast<IntrinsicInst>(U);
Sanjoy Das499d7032015-05-06 02:36:26 +0000539 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
540 ThisRelocate.getDerivedPtrIndex());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000541 RelocateIdxMap.insert(std::make_pair(K, I));
542 }
543 for (auto &Item : RelocateIdxMap) {
544 std::pair<unsigned, unsigned> Key = Item.first;
545 if (Key.first == Key.second)
546 // Base relocation: nothing to insert
547 continue;
548
549 IntrinsicInst *I = Item.second;
550 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000551
552 // We're iterating over RelocateIdxMap so we cannot modify it.
553 auto MaybeBase = RelocateIdxMap.find(BaseKey);
554 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000555 // TODO: We might want to insert a new base object relocate and gep off
556 // that, if there are enough derived object relocates.
557 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000558
559 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000560 }
561}
562
563// Accepts a GEP and extracts the operands into a vector provided they're all
564// small integer constants
565static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
566 SmallVectorImpl<Value *> &OffsetV) {
567 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
568 // Only accept small constant integer operands
569 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
570 if (!Op || Op->getZExtValue() > 20)
571 return false;
572 }
573
574 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
575 OffsetV.push_back(GEP->getOperand(i));
576 return true;
577}
578
579// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
580// replace, computes a replacement, and affects it.
581static bool
582simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
583 const SmallVectorImpl<IntrinsicInst *> &Targets) {
584 bool MadeChange = false;
585 for (auto &ToReplace : Targets) {
586 GCRelocateOperands MasterRelocate(RelocatedBase);
587 GCRelocateOperands ThisRelocate(ToReplace);
588
Sanjoy Das499d7032015-05-06 02:36:26 +0000589 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000590 "Not relocating a derived object of the original base object");
Sanjoy Das499d7032015-05-06 02:36:26 +0000591 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000592 // A duplicate relocate call. TODO: coalesce duplicates.
593 continue;
594 }
595
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000596 if (RelocatedBase->getParent() != ToReplace->getParent()) {
597 // Base and derived relocates are in different basic blocks.
598 // In this case transform is only valid when base dominates derived
599 // relocate. However it would be too expensive to check dominance
600 // for each such relocate, so we skip the whole transformation.
601 continue;
602 }
603
Sanjoy Das499d7032015-05-06 02:36:26 +0000604 Value *Base = ThisRelocate.getBasePtr();
605 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000606 if (!Derived || Derived->getPointerOperand() != Base)
607 continue;
608
609 SmallVector<Value *, 2> OffsetV;
610 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
611 continue;
612
613 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000614 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
615
616 // Insert after RelocatedBase
617 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000618 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000619
620 // If gc_relocate does not match the actual type, cast it to the right type.
621 // In theory, there must be a bitcast after gc_relocate if the type does not
622 // match, and we should reuse it to get the derived pointer. But it could be
623 // cases like this:
624 // bb1:
625 // ...
626 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
627 // br label %merge
628 //
629 // bb2:
630 // ...
631 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
632 // br label %merge
633 //
634 // merge:
635 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
636 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
637 //
638 // In this case, we can not find the bitcast any more. So we insert a new bitcast
639 // no matter there is already one or not. In this way, we can handle all cases, and
640 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000641 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000642 if (RelocatedBase->getType() != Base->getType()) {
643 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000644 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000645 }
David Blaikie68d535c2015-03-24 22:38:16 +0000646 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000647 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000648 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000649 // If the newly generated derived pointer's type does not match the original derived
650 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000651 Value *ActualReplacement = Replacement;
652 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000653 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000654 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000655 }
656 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000657 ToReplace->eraseFromParent();
658
659 MadeChange = true;
660 }
661 return MadeChange;
662}
663
664// Turns this:
665//
666// %base = ...
667// %ptr = gep %base + 15
668// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
669// %base' = relocate(%tok, i32 4, i32 4)
670// %ptr' = relocate(%tok, i32 4, i32 5)
671// %val = load %ptr'
672//
673// into this:
674//
675// %base = ...
676// %ptr = gep %base + 15
677// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
678// %base' = gc.relocate(%tok, i32 4, i32 4)
679// %ptr' = gep %base' + 15
680// %val = load %ptr'
681bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
682 bool MadeChange = false;
683 SmallVector<User *, 2> AllRelocateCalls;
684
685 for (auto *U : I.users())
686 if (isGCRelocate(dyn_cast<Instruction>(U)))
687 // Collect all the relocate calls associated with a statepoint
688 AllRelocateCalls.push_back(U);
689
690 // We need atleast one base pointer relocation + one derived pointer
691 // relocation to mangle
692 if (AllRelocateCalls.size() < 2)
693 return false;
694
695 // RelocateInstMap is a mapping from the base relocate instruction to the
696 // corresponding derived relocate instructions
697 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
698 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
699 if (RelocateInstMap.empty())
700 return false;
701
702 for (auto &Item : RelocateInstMap)
703 // Item.first is the RelocatedBase to offset against
704 // Item.second is the vector of Targets to replace
705 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
706 return MadeChange;
707}
708
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000709/// SinkCast - Sink the specified cast instruction into its user blocks
710static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000711 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000712
Chris Lattnerf2836d12007-03-31 04:06:36 +0000713 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000714 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000715
Chris Lattnerf2836d12007-03-31 04:06:36 +0000716 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000717 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000718 UI != E; ) {
719 Use &TheUse = UI.getUse();
720 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000721
Chris Lattnerf2836d12007-03-31 04:06:36 +0000722 // Figure out which BB this cast is used in. For PHI's this is the
723 // appropriate predecessor block.
724 BasicBlock *UserBB = User->getParent();
725 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000726 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000727 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000728
Chris Lattnerf2836d12007-03-31 04:06:36 +0000729 // Preincrement use iterator so we don't invalidate it.
730 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000731
Andrew Kaylord0430e82015-11-23 19:16:15 +0000732 // If the block selected to receive the cast is an EH pad that does not
733 // allow non-PHI instructions before the terminator, we can't sink the
734 // cast.
735 if (UserBB->getTerminator()->isEHPad())
736 continue;
737
Chris Lattnerf2836d12007-03-31 04:06:36 +0000738 // If this user is in the same block as the cast, don't change the cast.
739 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000740
Chris Lattnerf2836d12007-03-31 04:06:36 +0000741 // If we have already inserted a cast into this block, use it.
742 CastInst *&InsertedCast = InsertedCasts[UserBB];
743
744 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000745 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000746 assert(InsertPt != UserBB->end());
747 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
748 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000749 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000750
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000751 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000752 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000753 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000754 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000755 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000756
Chris Lattnerf2836d12007-03-31 04:06:36 +0000757 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000758 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000759 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000760 MadeChange = true;
761 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000762
Chris Lattnerf2836d12007-03-31 04:06:36 +0000763 return MadeChange;
764}
765
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000766/// If the specified cast instruction is a noop copy (e.g. it's casting from
767/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
768/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000769///
770/// Return true if any changes are made.
771///
Mehdi Amini44ede332015-07-09 02:09:04 +0000772static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
773 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000774 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000775 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
776 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000777
778 // This is an fp<->int conversion?
779 if (SrcVT.isInteger() != DstVT.isInteger())
780 return false;
781
782 // If this is an extension, it will be a zero or sign extension, which
783 // isn't a noop.
784 if (SrcVT.bitsLT(DstVT)) return false;
785
786 // If these values will be promoted, find out what they will be promoted
787 // to. This helps us consider truncates on PPC as noop copies when they
788 // are.
789 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
790 TargetLowering::TypePromoteInteger)
791 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
792 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
793 TargetLowering::TypePromoteInteger)
794 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
795
796 // If, after promotion, these are the same types, this is a noop copy.
797 if (SrcVT != DstVT)
798 return false;
799
800 return SinkCast(CI);
801}
802
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000803/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
804/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000805///
806/// Return true if any changes were made.
807static bool CombineUAddWithOverflow(CmpInst *CI) {
808 Value *A, *B;
809 Instruction *AddI;
810 if (!match(CI,
811 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
812 return false;
813
814 Type *Ty = AddI->getType();
815 if (!isa<IntegerType>(Ty))
816 return false;
817
818 // We don't want to move around uses of condition values this late, so we we
819 // check if it is legal to create the call to the intrinsic in the basic
820 // block containing the icmp:
821
822 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
823 return false;
824
825#ifndef NDEBUG
826 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
827 // for now:
828 if (AddI->hasOneUse())
829 assert(*AddI->user_begin() == CI && "expected!");
830#endif
831
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000832 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000833 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
834
835 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
836
837 auto *UAddWithOverflow =
838 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
839 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
840 auto *Overflow =
841 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
842
843 CI->replaceAllUsesWith(Overflow);
844 AddI->replaceAllUsesWith(UAdd);
845 CI->eraseFromParent();
846 AddI->eraseFromParent();
847 return true;
848}
849
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000850/// Sink the given CmpInst into user blocks to reduce the number of virtual
851/// registers that must be created and coalesced. This is a clear win except on
852/// targets with multiple condition code registers (PowerPC), where it might
853/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000854///
855/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000856static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000857 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000858
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000859 /// Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000860 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000861
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000862 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000863 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000864 UI != E; ) {
865 Use &TheUse = UI.getUse();
866 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000867
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000868 // Preincrement use iterator so we don't invalidate it.
869 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000870
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000871 // Don't bother for PHI nodes.
872 if (isa<PHINode>(User))
873 continue;
874
875 // Figure out which BB this cmp is used in.
876 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000877
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000878 // If this user is in the same block as the cmp, don't change the cmp.
879 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000880
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000881 // If we have already inserted a cmp into this block, use it.
882 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
883
884 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000885 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000886 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000887 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000888 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
889 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000890 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000891
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000892 // Replace a use of the cmp with a use of the new cmp.
893 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000894 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000895 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000896 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000897
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000898 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000899 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000900 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000901 MadeChange = true;
902 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000903
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000904 return MadeChange;
905}
906
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000907static bool OptimizeCmpExpression(CmpInst *CI) {
908 if (SinkCmpExpression(CI))
909 return true;
910
911 if (CombineUAddWithOverflow(CI))
912 return true;
913
914 return false;
915}
916
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000917/// Check if the candidates could be combined with a shift instruction, which
918/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000919/// 1. Truncate instruction
920/// 2. And instruction and the imm is a mask of the low bits:
921/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000922static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000923 if (!isa<TruncInst>(User)) {
924 if (User->getOpcode() != Instruction::And ||
925 !isa<ConstantInt>(User->getOperand(1)))
926 return false;
927
Quentin Colombetd4f44692014-04-22 01:20:34 +0000928 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000929
Quentin Colombetd4f44692014-04-22 01:20:34 +0000930 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000931 return false;
932 }
933 return true;
934}
935
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000936/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000937static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000938SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
939 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000940 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000941 BasicBlock *UserBB = User->getParent();
942 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
943 TruncInst *TruncI = dyn_cast<TruncInst>(User);
944 bool MadeChange = false;
945
946 for (Value::user_iterator TruncUI = TruncI->user_begin(),
947 TruncE = TruncI->user_end();
948 TruncUI != TruncE;) {
949
950 Use &TruncTheUse = TruncUI.getUse();
951 Instruction *TruncUser = cast<Instruction>(*TruncUI);
952 // Preincrement use iterator so we don't invalidate it.
953
954 ++TruncUI;
955
956 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
957 if (!ISDOpcode)
958 continue;
959
Tim Northovere2239ff2014-07-29 10:20:22 +0000960 // If the use is actually a legal node, there will not be an
961 // implicit truncate.
962 // FIXME: always querying the result type is just an
963 // approximation; some nodes' legality is determined by the
964 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000965 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000966 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000967 continue;
968
969 // Don't bother for PHI nodes.
970 if (isa<PHINode>(TruncUser))
971 continue;
972
973 BasicBlock *TruncUserBB = TruncUser->getParent();
974
975 if (UserBB == TruncUserBB)
976 continue;
977
978 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
979 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
980
981 if (!InsertedShift && !InsertedTrunc) {
982 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000983 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000984 // Sink the shift
985 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000986 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
987 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000988 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000989 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
990 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000991
992 // Sink the trunc
993 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
994 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000995 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000996
997 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000998 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000999
1000 MadeChange = true;
1001
1002 TruncTheUse = InsertedTrunc;
1003 }
1004 }
1005 return MadeChange;
1006}
1007
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001008/// Sink the shift *right* instruction into user blocks if the uses could
1009/// potentially be combined with this shift instruction and generate BitExtract
1010/// instruction. It will only be applied if the architecture supports BitExtract
1011/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001012/// BB1:
1013/// %x.extract.shift = lshr i64 %arg1, 32
1014/// BB2:
1015/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1016/// ==>
1017///
1018/// BB2:
1019/// %x.extract.shift.1 = lshr i64 %arg1, 32
1020/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1021///
1022/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1023/// instruction.
1024/// Return true if any changes are made.
1025static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001026 const TargetLowering &TLI,
1027 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001028 BasicBlock *DefBB = ShiftI->getParent();
1029
1030 /// Only insert instructions in each block once.
1031 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1032
Mehdi Amini44ede332015-07-09 02:09:04 +00001033 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001034
1035 bool MadeChange = false;
1036 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1037 UI != E;) {
1038 Use &TheUse = UI.getUse();
1039 Instruction *User = cast<Instruction>(*UI);
1040 // Preincrement use iterator so we don't invalidate it.
1041 ++UI;
1042
1043 // Don't bother for PHI nodes.
1044 if (isa<PHINode>(User))
1045 continue;
1046
1047 if (!isExtractBitsCandidateUse(User))
1048 continue;
1049
1050 BasicBlock *UserBB = User->getParent();
1051
1052 if (UserBB == DefBB) {
1053 // If the shift and truncate instruction are in the same BB. The use of
1054 // the truncate(TruncUse) may still introduce another truncate if not
1055 // legal. In this case, we would like to sink both shift and truncate
1056 // instruction to the BB of TruncUse.
1057 // for example:
1058 // BB1:
1059 // i64 shift.result = lshr i64 opnd, imm
1060 // trunc.result = trunc shift.result to i16
1061 //
1062 // BB2:
1063 // ----> We will have an implicit truncate here if the architecture does
1064 // not have i16 compare.
1065 // cmp i16 trunc.result, opnd2
1066 //
1067 if (isa<TruncInst>(User) && shiftIsLegal
1068 // If the type of the truncate is legal, no trucate will be
1069 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001070 &&
1071 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001072 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001073 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001074
1075 continue;
1076 }
1077 // If we have already inserted a shift into this block, use it.
1078 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1079
1080 if (!InsertedShift) {
1081 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001082 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001083
1084 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001085 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1086 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001087 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001088 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1089 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001090
1091 MadeChange = true;
1092 }
1093
1094 // Replace a use of the shift with a use of the new shift.
1095 TheUse = InsertedShift;
1096 }
1097
1098 // If we removed all uses, nuke the shift.
1099 if (ShiftI->use_empty())
1100 ShiftI->eraseFromParent();
1101
1102 return MadeChange;
1103}
1104
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001105// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001106// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1107// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001108// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001109// the appropriate mask bit is set
1110//
1111// %1 = bitcast i8* %addr to i32*
1112// %2 = extractelement <16 x i1> %mask, i32 0
1113// %3 = icmp eq i1 %2, true
1114// br i1 %3, label %cond.load, label %else
1115//
1116//cond.load: ; preds = %0
1117// %4 = getelementptr i32* %1, i32 0
1118// %5 = load i32* %4
1119// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1120// br label %else
1121//
1122//else: ; preds = %0, %cond.load
1123// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1124// %7 = extractelement <16 x i1> %mask, i32 1
1125// %8 = icmp eq i1 %7, true
1126// br i1 %8, label %cond.load1, label %else2
1127//
1128//cond.load1: ; preds = %else
1129// %9 = getelementptr i32* %1, i32 1
1130// %10 = load i32* %9
1131// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1132// br label %else2
1133//
1134//else2: ; preds = %else, %cond.load1
1135// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1136// %12 = extractelement <16 x i1> %mask, i32 2
1137// %13 = icmp eq i1 %12, true
1138// br i1 %13, label %cond.load4, label %else5
1139//
1140static void ScalarizeMaskedLoad(CallInst *CI) {
1141 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001142 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001143 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001144 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001145
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001146 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1147 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001148 assert(VecType && "Unexpected return type of masked load intrinsic");
1149
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001150 Type *EltTy = CI->getType()->getVectorElementType();
1151
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001152 IRBuilder<> Builder(CI->getContext());
1153 Instruction *InsertPt = CI;
1154 BasicBlock *IfBlock = CI->getParent();
1155 BasicBlock *CondBlock = nullptr;
1156 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001157
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001158 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001159 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1160
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001161 // Short-cut if the mask is all-true.
1162 bool IsAllOnesMask = isa<Constant>(Mask) &&
1163 cast<Constant>(Mask)->isAllOnesValue();
1164
1165 if (IsAllOnesMask) {
1166 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1167 CI->replaceAllUsesWith(NewI);
1168 CI->eraseFromParent();
1169 return;
1170 }
1171
1172 // Adjust alignment for the scalar instruction.
1173 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001174 // Bitcast %addr fron i8* to EltTy*
1175 Type *NewPtrType =
1176 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1177 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001178 unsigned VectorWidth = VecType->getNumElements();
1179
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001180 Value *UndefVal = UndefValue::get(VecType);
1181
1182 // The result vector
1183 Value *VResult = UndefVal;
1184
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001185 if (isa<ConstantVector>(Mask)) {
1186 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1187 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1188 continue;
1189 Value *Gep =
1190 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1191 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1192 VResult = Builder.CreateInsertElement(VResult, Load,
1193 Builder.getInt32(Idx));
1194 }
1195 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1196 CI->replaceAllUsesWith(NewI);
1197 CI->eraseFromParent();
1198 return;
1199 }
1200
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001201 PHINode *Phi = nullptr;
1202 Value *PrevPhi = UndefVal;
1203
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001204 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1205
1206 // Fill the "else" block, created in the previous iteration
1207 //
1208 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1209 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1210 // %to_load = icmp eq i1 %mask_1, true
1211 // br i1 %to_load, label %cond.load, label %else
1212 //
1213 if (Idx > 0) {
1214 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1215 Phi->addIncoming(VResult, CondBlock);
1216 Phi->addIncoming(PrevPhi, PrevIfBlock);
1217 PrevPhi = Phi;
1218 VResult = Phi;
1219 }
1220
1221 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1222 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1223 ConstantInt::get(Predicate->getType(), 1));
1224
1225 // Create "cond" block
1226 //
1227 // %EltAddr = getelementptr i32* %1, i32 0
1228 // %Elt = load i32* %EltAddr
1229 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1230 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001231 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001232 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001233
1234 Value *Gep =
1235 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001236 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001237 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1238
1239 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001240 BasicBlock *NewIfBlock =
1241 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001242 Builder.SetInsertPoint(InsertPt);
1243 Instruction *OldBr = IfBlock->getTerminator();
1244 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1245 OldBr->eraseFromParent();
1246 PrevIfBlock = IfBlock;
1247 IfBlock = NewIfBlock;
1248 }
1249
1250 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1251 Phi->addIncoming(VResult, CondBlock);
1252 Phi->addIncoming(PrevPhi, PrevIfBlock);
1253 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1254 CI->replaceAllUsesWith(NewI);
1255 CI->eraseFromParent();
1256}
1257
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001258// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001259// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1260// <16 x i1> %mask)
1261// to a chain of basic blocks, that stores element one-by-one if
1262// the appropriate mask bit is set
1263//
1264// %1 = bitcast i8* %addr to i32*
1265// %2 = extractelement <16 x i1> %mask, i32 0
1266// %3 = icmp eq i1 %2, true
1267// br i1 %3, label %cond.store, label %else
1268//
1269// cond.store: ; preds = %0
1270// %4 = extractelement <16 x i32> %val, i32 0
1271// %5 = getelementptr i32* %1, i32 0
1272// store i32 %4, i32* %5
1273// br label %else
1274//
1275// else: ; preds = %0, %cond.store
1276// %6 = extractelement <16 x i1> %mask, i32 1
1277// %7 = icmp eq i1 %6, true
1278// br i1 %7, label %cond.store1, label %else2
1279//
1280// cond.store1: ; preds = %else
1281// %8 = extractelement <16 x i32> %val, i32 1
1282// %9 = getelementptr i32* %1, i32 1
1283// store i32 %8, i32* %9
1284// br label %else2
1285// . . .
1286static void ScalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001287 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001288 Value *Ptr = CI->getArgOperand(1);
1289 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001290 Value *Mask = CI->getArgOperand(3);
1291
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001292 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001293 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001294 assert(VecType && "Unexpected data type in masked store intrinsic");
1295
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001296 Type *EltTy = VecType->getElementType();
1297
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001298 IRBuilder<> Builder(CI->getContext());
1299 Instruction *InsertPt = CI;
1300 BasicBlock *IfBlock = CI->getParent();
1301 Builder.SetInsertPoint(InsertPt);
1302 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1303
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001304 // Short-cut if the mask is all-true.
1305 bool IsAllOnesMask = isa<Constant>(Mask) &&
1306 cast<Constant>(Mask)->isAllOnesValue();
1307
1308 if (IsAllOnesMask) {
1309 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1310 CI->eraseFromParent();
1311 return;
1312 }
1313
1314 // Adjust alignment for the scalar instruction.
1315 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001316 // Bitcast %addr fron i8* to EltTy*
1317 Type *NewPtrType =
1318 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1319 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001320 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001321
1322 if (isa<ConstantVector>(Mask)) {
1323 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1324 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1325 continue;
1326 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1327 Value *Gep =
1328 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1329 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1330 }
1331 CI->eraseFromParent();
1332 return;
1333 }
1334
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001335 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1336
1337 // Fill the "else" block, created in the previous iteration
1338 //
1339 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1340 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001341 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001342 //
1343 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1344 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1345 ConstantInt::get(Predicate->getType(), 1));
1346
1347 // Create "cond" block
1348 //
1349 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1350 // %EltAddr = getelementptr i32* %1, i32 0
1351 // %store i32 %OneElt, i32* %EltAddr
1352 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001353 BasicBlock *CondBlock =
1354 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001355 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001356
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001357 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001358 Value *Gep =
1359 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001360 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001361
1362 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001363 BasicBlock *NewIfBlock =
1364 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001365 Builder.SetInsertPoint(InsertPt);
1366 Instruction *OldBr = IfBlock->getTerminator();
1367 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1368 OldBr->eraseFromParent();
1369 IfBlock = NewIfBlock;
1370 }
1371 CI->eraseFromParent();
1372}
1373
Elena Demikhovsky09285852015-10-25 15:37:55 +00001374// Translate a masked gather intrinsic like
1375// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1376// <16 x i1> %Mask, <16 x i32> %Src)
1377// to a chain of basic blocks, with loading element one-by-one if
1378// the appropriate mask bit is set
1379//
1380// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1381// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1382// % ToLoad0 = icmp eq i1 % Mask0, true
1383// br i1 % ToLoad0, label %cond.load, label %else
1384//
1385// cond.load:
1386// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1387// % Load0 = load i32, i32* % Ptr0, align 4
1388// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1389// br label %else
1390//
1391// else:
1392// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1393// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1394// % ToLoad1 = icmp eq i1 % Mask1, true
1395// br i1 % ToLoad1, label %cond.load1, label %else2
1396//
1397// cond.load1:
1398// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1399// % Load1 = load i32, i32* % Ptr1, align 4
1400// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1401// br label %else2
1402// . . .
1403// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1404// ret <16 x i32> %Result
1405static void ScalarizeMaskedGather(CallInst *CI) {
1406 Value *Ptrs = CI->getArgOperand(0);
1407 Value *Alignment = CI->getArgOperand(1);
1408 Value *Mask = CI->getArgOperand(2);
1409 Value *Src0 = CI->getArgOperand(3);
1410
1411 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1412
1413 assert(VecType && "Unexpected return type of masked load intrinsic");
1414
1415 IRBuilder<> Builder(CI->getContext());
1416 Instruction *InsertPt = CI;
1417 BasicBlock *IfBlock = CI->getParent();
1418 BasicBlock *CondBlock = nullptr;
1419 BasicBlock *PrevIfBlock = CI->getParent();
1420 Builder.SetInsertPoint(InsertPt);
1421 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1422
1423 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1424
1425 Value *UndefVal = UndefValue::get(VecType);
1426
1427 // The result vector
1428 Value *VResult = UndefVal;
1429 unsigned VectorWidth = VecType->getNumElements();
1430
1431 // Shorten the way if the mask is a vector of constants.
1432 bool IsConstMask = isa<ConstantVector>(Mask);
1433
1434 if (IsConstMask) {
1435 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1436 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1437 continue;
1438 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1439 "Ptr" + Twine(Idx));
1440 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1441 "Load" + Twine(Idx));
1442 VResult = Builder.CreateInsertElement(VResult, Load,
1443 Builder.getInt32(Idx),
1444 "Res" + Twine(Idx));
1445 }
1446 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1447 CI->replaceAllUsesWith(NewI);
1448 CI->eraseFromParent();
1449 return;
1450 }
1451
1452 PHINode *Phi = nullptr;
1453 Value *PrevPhi = UndefVal;
1454
1455 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1456
1457 // Fill the "else" block, created in the previous iteration
1458 //
1459 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1460 // %ToLoad1 = icmp eq i1 %Mask1, true
1461 // br i1 %ToLoad1, label %cond.load, label %else
1462 //
1463 if (Idx > 0) {
1464 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1465 Phi->addIncoming(VResult, CondBlock);
1466 Phi->addIncoming(PrevPhi, PrevIfBlock);
1467 PrevPhi = Phi;
1468 VResult = Phi;
1469 }
1470
1471 Value *Predicate = Builder.CreateExtractElement(Mask,
1472 Builder.getInt32(Idx),
1473 "Mask" + Twine(Idx));
1474 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1475 ConstantInt::get(Predicate->getType(), 1),
1476 "ToLoad" + Twine(Idx));
1477
1478 // Create "cond" block
1479 //
1480 // %EltAddr = getelementptr i32* %1, i32 0
1481 // %Elt = load i32* %EltAddr
1482 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1483 //
1484 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1485 Builder.SetInsertPoint(InsertPt);
1486
1487 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1488 "Ptr" + Twine(Idx));
1489 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1490 "Load" + Twine(Idx));
1491 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1492 "Res" + Twine(Idx));
1493
1494 // Create "else" block, fill it in the next iteration
1495 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1496 Builder.SetInsertPoint(InsertPt);
1497 Instruction *OldBr = IfBlock->getTerminator();
1498 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1499 OldBr->eraseFromParent();
1500 PrevIfBlock = IfBlock;
1501 IfBlock = NewIfBlock;
1502 }
1503
1504 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1505 Phi->addIncoming(VResult, CondBlock);
1506 Phi->addIncoming(PrevPhi, PrevIfBlock);
1507 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1508 CI->replaceAllUsesWith(NewI);
1509 CI->eraseFromParent();
1510}
1511
1512// Translate a masked scatter intrinsic, like
1513// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1514// <16 x i1> %Mask)
1515// to a chain of basic blocks, that stores element one-by-one if
1516// the appropriate mask bit is set.
1517//
1518// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1519// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1520// % ToStore0 = icmp eq i1 % Mask0, true
1521// br i1 %ToStore0, label %cond.store, label %else
1522//
1523// cond.store:
1524// % Elt0 = extractelement <16 x i32> %Src, i32 0
1525// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1526// store i32 %Elt0, i32* % Ptr0, align 4
1527// br label %else
1528//
1529// else:
1530// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1531// % ToStore1 = icmp eq i1 % Mask1, true
1532// br i1 % ToStore1, label %cond.store1, label %else2
1533//
1534// cond.store1:
1535// % Elt1 = extractelement <16 x i32> %Src, i32 1
1536// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1537// store i32 % Elt1, i32* % Ptr1, align 4
1538// br label %else2
1539// . . .
1540static void ScalarizeMaskedScatter(CallInst *CI) {
1541 Value *Src = CI->getArgOperand(0);
1542 Value *Ptrs = CI->getArgOperand(1);
1543 Value *Alignment = CI->getArgOperand(2);
1544 Value *Mask = CI->getArgOperand(3);
1545
1546 assert(isa<VectorType>(Src->getType()) &&
1547 "Unexpected data type in masked scatter intrinsic");
1548 assert(isa<VectorType>(Ptrs->getType()) &&
1549 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1550 "Vector of pointers is expected in masked scatter intrinsic");
1551
1552 IRBuilder<> Builder(CI->getContext());
1553 Instruction *InsertPt = CI;
1554 BasicBlock *IfBlock = CI->getParent();
1555 Builder.SetInsertPoint(InsertPt);
1556 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1557
1558 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1559 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1560
1561 // Shorten the way if the mask is a vector of constants.
1562 bool IsConstMask = isa<ConstantVector>(Mask);
1563
1564 if (IsConstMask) {
1565 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1566 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1567 continue;
1568 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1569 "Elt" + Twine(Idx));
1570 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1571 "Ptr" + Twine(Idx));
1572 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1573 }
1574 CI->eraseFromParent();
1575 return;
1576 }
1577 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1578 // Fill the "else" block, created in the previous iteration
1579 //
1580 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1581 // % ToStore = icmp eq i1 % Mask1, true
1582 // br i1 % ToStore, label %cond.store, label %else
1583 //
1584 Value *Predicate = Builder.CreateExtractElement(Mask,
1585 Builder.getInt32(Idx),
1586 "Mask" + Twine(Idx));
1587 Value *Cmp =
1588 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1589 ConstantInt::get(Predicate->getType(), 1),
1590 "ToStore" + Twine(Idx));
1591
1592 // Create "cond" block
1593 //
1594 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1595 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1596 // %store i32 % Elt1, i32* % Ptr1
1597 //
1598 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1599 Builder.SetInsertPoint(InsertPt);
1600
1601 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1602 "Elt" + Twine(Idx));
1603 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1604 "Ptr" + Twine(Idx));
1605 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1606
1607 // Create "else" block, fill it in the next iteration
1608 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1609 Builder.SetInsertPoint(InsertPt);
1610 Instruction *OldBr = IfBlock->getTerminator();
1611 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1612 OldBr->eraseFromParent();
1613 IfBlock = NewIfBlock;
1614 }
1615 CI->eraseFromParent();
1616}
1617
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001618/// If counting leading or trailing zeros is an expensive operation and a zero
1619/// input is defined, add a check for zero to avoid calling the intrinsic.
1620///
1621/// We want to transform:
1622/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1623///
1624/// into:
1625/// entry:
1626/// %cmpz = icmp eq i64 %A, 0
1627/// br i1 %cmpz, label %cond.end, label %cond.false
1628/// cond.false:
1629/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1630/// br label %cond.end
1631/// cond.end:
1632/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1633///
1634/// If the transform is performed, return true and set ModifiedDT to true.
1635static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1636 const TargetLowering *TLI,
1637 const DataLayout *DL,
1638 bool &ModifiedDT) {
1639 if (!TLI || !DL)
1640 return false;
1641
1642 // If a zero input is undefined, it doesn't make sense to despeculate that.
1643 if (match(CountZeros->getOperand(1), m_One()))
1644 return false;
1645
1646 // If it's cheap to speculate, there's nothing to do.
1647 auto IntrinsicID = CountZeros->getIntrinsicID();
1648 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1649 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1650 return false;
1651
1652 // Only handle legal scalar cases. Anything else requires too much work.
1653 Type *Ty = CountZeros->getType();
1654 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1655 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
1656 return false;
1657
1658 // The intrinsic will be sunk behind a compare against zero and branch.
1659 BasicBlock *StartBlock = CountZeros->getParent();
1660 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1661
1662 // Create another block after the count zero intrinsic. A PHI will be added
1663 // in this block to select the result of the intrinsic or the bit-width
1664 // constant if the input to the intrinsic is zero.
1665 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1666 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1667
1668 // Set up a builder to create a compare, conditional branch, and PHI.
1669 IRBuilder<> Builder(CountZeros->getContext());
1670 Builder.SetInsertPoint(StartBlock->getTerminator());
1671 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1672
1673 // Replace the unconditional branch that was created by the first split with
1674 // a compare against zero and a conditional branch.
1675 Value *Zero = Constant::getNullValue(Ty);
1676 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1677 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1678 StartBlock->getTerminator()->eraseFromParent();
1679
1680 // Create a PHI in the end block to select either the output of the intrinsic
1681 // or the bit width of the operand.
1682 Builder.SetInsertPoint(&EndBlock->front());
1683 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1684 CountZeros->replaceAllUsesWith(PN);
1685 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1686 PN->addIncoming(BitWidth, StartBlock);
1687 PN->addIncoming(CountZeros, CallBlock);
1688
1689 // We are explicitly handling the zero case, so we can set the intrinsic's
1690 // undefined zero argument to 'true'. This will also prevent reprocessing the
1691 // intrinsic; we only despeculate when a zero input is defined.
1692 CountZeros->setArgOperand(1, Builder.getTrue());
1693 ModifiedDT = true;
1694 return true;
1695}
1696
Sanjay Patelfc580a62015-09-21 23:03:16 +00001697bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001698 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001699
Chris Lattner7a277142011-01-15 07:14:54 +00001700 // Lower inline assembly if we can.
1701 // If we found an inline asm expession, and if the target knows how to
1702 // lower it to normal LLVM code, do so now.
1703 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1704 if (TLI->ExpandInlineAsm(CI)) {
1705 // Avoid invalidating the iterator.
1706 CurInstIterator = BB->begin();
1707 // Avoid processing instructions out of order, which could cause
1708 // reuse before a value is defined.
1709 SunkAddrs.clear();
1710 return true;
1711 }
1712 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001713 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001714 return true;
1715 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001716
John Brawn0dbcd652015-03-18 12:01:59 +00001717 // Align the pointer arguments to this call if the target thinks it's a good
1718 // idea
1719 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001720 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001721 for (auto &Arg : CI->arg_operands()) {
1722 // We want to align both objects whose address is used directly and
1723 // objects whose address is used in casts and GEPs, though it only makes
1724 // sense for GEPs if the offset is a multiple of the desired alignment and
1725 // if size - offset meets the size threshold.
1726 if (!Arg->getType()->isPointerTy())
1727 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001728 APInt Offset(DL->getPointerSizeInBits(
1729 cast<PointerType>(Arg->getType())->getAddressSpace()),
1730 0);
1731 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001732 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001733 if ((Offset2 & (PrefAlign-1)) != 0)
1734 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001735 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001736 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1737 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001738 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001739 // Global variables can only be aligned if they are defined in this
1740 // object (i.e. they are uniquely initialized in this object), and
1741 // over-aligning global variables that have an explicit section is
1742 // forbidden.
1743 GlobalVariable *GV;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001744 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1745 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1746 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1747 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001748 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001749 }
1750 // If this is a memcpy (or similar) then we may be able to improve the
1751 // alignment
1752 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001753 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001754 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001755 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001756 if (Align > MI->getAlignment())
1757 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001758 }
1759 }
1760
Eric Christopher4b7948e2010-03-11 02:41:03 +00001761 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001762 if (II) {
1763 switch (II->getIntrinsicID()) {
1764 default: break;
1765 case Intrinsic::objectsize: {
1766 // Lower all uses of llvm.objectsize.*
1767 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1768 Type *ReturnTy = CI->getType();
1769 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001770
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001771 // Substituting this can cause recursive simplifications, which can
1772 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1773 // happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001774 WeakVH IterHandle(&*CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001775
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001776 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001777 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001778
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001779 // If the iterator instruction was recursively deleted, start over at the
1780 // start of the block.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001781 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001782 CurInstIterator = BB->begin();
1783 SunkAddrs.clear();
1784 }
1785 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001786 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001787 case Intrinsic::masked_load: {
1788 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001789 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001790 ScalarizeMaskedLoad(CI);
1791 ModifiedDT = true;
1792 return true;
1793 }
1794 return false;
1795 }
1796 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001797 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001798 ScalarizeMaskedStore(CI);
1799 ModifiedDT = true;
1800 return true;
1801 }
1802 return false;
1803 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001804 case Intrinsic::masked_gather: {
1805 if (!TTI->isLegalMaskedGather(CI->getType())) {
1806 ScalarizeMaskedGather(CI);
1807 ModifiedDT = true;
1808 return true;
1809 }
1810 return false;
1811 }
1812 case Intrinsic::masked_scatter: {
1813 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
1814 ScalarizeMaskedScatter(CI);
1815 ModifiedDT = true;
1816 return true;
1817 }
1818 return false;
1819 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001820 case Intrinsic::aarch64_stlxr:
1821 case Intrinsic::aarch64_stxr: {
1822 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1823 if (!ExtVal || !ExtVal->hasOneUse() ||
1824 ExtVal->getParent() == CI->getParent())
1825 return false;
1826 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1827 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001828 // Mark this instruction as "inserted by CGP", so that other
1829 // optimizations don't touch it.
1830 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001831 return true;
1832 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001833 case Intrinsic::invariant_group_barrier:
1834 II->replaceAllUsesWith(II->getArgOperand(0));
1835 II->eraseFromParent();
1836 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001837
1838 case Intrinsic::cttz:
1839 case Intrinsic::ctlz:
1840 // If counting zeros is expensive, try to avoid it.
1841 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001842 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001843
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001844 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001845 // Unknown address space.
1846 // TODO: Target hook to pick which address space the intrinsic cares
1847 // about?
1848 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001849 SmallVector<Value*, 2> PtrOps;
1850 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001851 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001852 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001853 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001854 return true;
1855 }
Pete Cooper615fd892012-03-13 20:59:56 +00001856 }
1857
Eric Christopher4b7948e2010-03-11 02:41:03 +00001858 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001859 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001860
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001861 // Lower all default uses of _chk calls. This is very similar
1862 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001863 // to fortified library functions (e.g. __memcpy_chk) that have the default
1864 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001865 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001866 if (Value *V = Simplifier.optimizeCall(CI)) {
1867 CI->replaceAllUsesWith(V);
1868 CI->eraseFromParent();
1869 return true;
1870 }
1871 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001872}
Chris Lattner1b93be52011-01-15 07:25:29 +00001873
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001874/// Look for opportunities to duplicate return instructions to the predecessor
1875/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001876/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001877/// bb0:
1878/// %tmp0 = tail call i32 @f0()
1879/// br label %return
1880/// bb1:
1881/// %tmp1 = tail call i32 @f1()
1882/// br label %return
1883/// bb2:
1884/// %tmp2 = tail call i32 @f2()
1885/// br label %return
1886/// return:
1887/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1888/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001889/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001890///
1891/// =>
1892///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001893/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001894/// bb0:
1895/// %tmp0 = tail call i32 @f0()
1896/// ret i32 %tmp0
1897/// bb1:
1898/// %tmp1 = tail call i32 @f1()
1899/// ret i32 %tmp1
1900/// bb2:
1901/// %tmp2 = tail call i32 @f2()
1902/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001903/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001904bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001905 if (!TLI)
1906 return false;
1907
Benjamin Kramer455fa352012-11-23 19:17:06 +00001908 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1909 if (!RI)
1910 return false;
1911
Craig Topperc0196b12014-04-14 00:51:57 +00001912 PHINode *PN = nullptr;
1913 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001914 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001915 if (V) {
1916 BCI = dyn_cast<BitCastInst>(V);
1917 if (BCI)
1918 V = BCI->getOperand(0);
1919
1920 PN = dyn_cast<PHINode>(V);
1921 if (!PN)
1922 return false;
1923 }
Evan Cheng0663f232011-03-21 01:19:09 +00001924
Cameron Zwarich4649f172011-03-24 04:52:10 +00001925 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001926 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001927
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001928 // It's not safe to eliminate the sign / zero extension of the return value.
1929 // See llvm::isInTailCallPosition().
1930 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001931 AttributeSet CallerAttrs = F->getAttributes();
1932 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1933 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001934 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001935
Cameron Zwarich4649f172011-03-24 04:52:10 +00001936 // Make sure there are no instructions between the PHI and return, or that the
1937 // return is the first instruction in the block.
1938 if (PN) {
1939 BasicBlock::iterator BI = BB->begin();
1940 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001941 if (&*BI == BCI)
1942 // Also skip over the bitcast.
1943 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001944 if (&*BI != RI)
1945 return false;
1946 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001947 BasicBlock::iterator BI = BB->begin();
1948 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1949 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001950 return false;
1951 }
Evan Cheng0663f232011-03-21 01:19:09 +00001952
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001953 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1954 /// call.
1955 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001956 if (PN) {
1957 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1958 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1959 // Make sure the phi value is indeed produced by the tail call.
1960 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1961 TLI->mayBeEmittedAsTailCall(CI))
1962 TailCalls.push_back(CI);
1963 }
1964 } else {
1965 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001966 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001967 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001968 continue;
1969
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001970 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001971 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1972 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001973 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1974 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001975 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001976
Cameron Zwarich4649f172011-03-24 04:52:10 +00001977 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001978 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001979 TailCalls.push_back(CI);
1980 }
Evan Cheng0663f232011-03-21 01:19:09 +00001981 }
1982
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001983 bool Changed = false;
1984 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1985 CallInst *CI = TailCalls[i];
1986 CallSite CS(CI);
1987
1988 // Conservatively require the attributes of the call to match those of the
1989 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001990 AttributeSet CalleeAttrs = CS.getAttributes();
1991 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001992 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001993 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001994 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001995 continue;
1996
1997 // Make sure the call instruction is followed by an unconditional branch to
1998 // the return block.
1999 BasicBlock *CallBB = CI->getParent();
2000 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2001 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2002 continue;
2003
2004 // Duplicate the return into CallBB.
2005 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002006 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002007 ++NumRetsDup;
2008 }
2009
2010 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002011 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002012 BB->eraseFromParent();
2013
2014 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002015}
2016
Chris Lattner728f9022008-11-25 07:09:13 +00002017//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002018// Memory Optimization
2019//===----------------------------------------------------------------------===//
2020
Chandler Carruthc8925912013-01-05 02:09:22 +00002021namespace {
2022
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002023/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002024/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002025struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002026 Value *BaseReg;
2027 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002028 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002029 void print(raw_ostream &OS) const;
2030 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002031
Chandler Carruthc8925912013-01-05 02:09:22 +00002032 bool operator==(const ExtAddrMode& O) const {
2033 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2034 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2035 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2036 }
2037};
2038
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002039#ifndef NDEBUG
2040static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2041 AM.print(OS);
2042 return OS;
2043}
2044#endif
2045
Chandler Carruthc8925912013-01-05 02:09:22 +00002046void ExtAddrMode::print(raw_ostream &OS) const {
2047 bool NeedPlus = false;
2048 OS << "[";
2049 if (BaseGV) {
2050 OS << (NeedPlus ? " + " : "")
2051 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002052 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002053 NeedPlus = true;
2054 }
2055
Richard Trieuc0f91212014-05-30 03:15:17 +00002056 if (BaseOffs) {
2057 OS << (NeedPlus ? " + " : "")
2058 << BaseOffs;
2059 NeedPlus = true;
2060 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002061
2062 if (BaseReg) {
2063 OS << (NeedPlus ? " + " : "")
2064 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002065 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002066 NeedPlus = true;
2067 }
2068 if (Scale) {
2069 OS << (NeedPlus ? " + " : "")
2070 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002071 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002072 }
2073
2074 OS << ']';
2075}
2076
2077#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2078void ExtAddrMode::dump() const {
2079 print(dbgs());
2080 dbgs() << '\n';
2081}
2082#endif
2083
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002084/// \brief This class provides transaction based operation on the IR.
2085/// Every change made through this class is recorded in the internal state and
2086/// can be undone (rollback) until commit is called.
2087class TypePromotionTransaction {
2088
2089 /// \brief This represents the common interface of the individual transaction.
2090 /// Each class implements the logic for doing one specific modification on
2091 /// the IR via the TypePromotionTransaction.
2092 class TypePromotionAction {
2093 protected:
2094 /// The Instruction modified.
2095 Instruction *Inst;
2096
2097 public:
2098 /// \brief Constructor of the action.
2099 /// The constructor performs the related action on the IR.
2100 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2101
2102 virtual ~TypePromotionAction() {}
2103
2104 /// \brief Undo the modification done by this action.
2105 /// When this method is called, the IR must be in the same state as it was
2106 /// before this action was applied.
2107 /// \pre Undoing the action works if and only if the IR is in the exact same
2108 /// state as it was directly after this action was applied.
2109 virtual void undo() = 0;
2110
2111 /// \brief Advocate every change made by this action.
2112 /// When the results on the IR of the action are to be kept, it is important
2113 /// to call this function, otherwise hidden information may be kept forever.
2114 virtual void commit() {
2115 // Nothing to be done, this action is not doing anything.
2116 }
2117 };
2118
2119 /// \brief Utility to remember the position of an instruction.
2120 class InsertionHandler {
2121 /// Position of an instruction.
2122 /// Either an instruction:
2123 /// - Is the first in a basic block: BB is used.
2124 /// - Has a previous instructon: PrevInst is used.
2125 union {
2126 Instruction *PrevInst;
2127 BasicBlock *BB;
2128 } Point;
2129 /// Remember whether or not the instruction had a previous instruction.
2130 bool HasPrevInstruction;
2131
2132 public:
2133 /// \brief Record the position of \p Inst.
2134 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002135 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002136 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2137 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002138 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002139 else
2140 Point.BB = Inst->getParent();
2141 }
2142
2143 /// \brief Insert \p Inst at the recorded position.
2144 void insert(Instruction *Inst) {
2145 if (HasPrevInstruction) {
2146 if (Inst->getParent())
2147 Inst->removeFromParent();
2148 Inst->insertAfter(Point.PrevInst);
2149 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002150 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002151 if (Inst->getParent())
2152 Inst->moveBefore(Position);
2153 else
2154 Inst->insertBefore(Position);
2155 }
2156 }
2157 };
2158
2159 /// \brief Move an instruction before another.
2160 class InstructionMoveBefore : public TypePromotionAction {
2161 /// Original position of the instruction.
2162 InsertionHandler Position;
2163
2164 public:
2165 /// \brief Move \p Inst before \p Before.
2166 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2167 : TypePromotionAction(Inst), Position(Inst) {
2168 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2169 Inst->moveBefore(Before);
2170 }
2171
2172 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002173 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002174 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2175 Position.insert(Inst);
2176 }
2177 };
2178
2179 /// \brief Set the operand of an instruction with a new value.
2180 class OperandSetter : public TypePromotionAction {
2181 /// Original operand of the instruction.
2182 Value *Origin;
2183 /// Index of the modified instruction.
2184 unsigned Idx;
2185
2186 public:
2187 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2188 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2189 : TypePromotionAction(Inst), Idx(Idx) {
2190 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2191 << "for:" << *Inst << "\n"
2192 << "with:" << *NewVal << "\n");
2193 Origin = Inst->getOperand(Idx);
2194 Inst->setOperand(Idx, NewVal);
2195 }
2196
2197 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002198 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002199 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2200 << "for: " << *Inst << "\n"
2201 << "with: " << *Origin << "\n");
2202 Inst->setOperand(Idx, Origin);
2203 }
2204 };
2205
2206 /// \brief Hide the operands of an instruction.
2207 /// Do as if this instruction was not using any of its operands.
2208 class OperandsHider : public TypePromotionAction {
2209 /// The list of original operands.
2210 SmallVector<Value *, 4> OriginalValues;
2211
2212 public:
2213 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2214 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2215 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2216 unsigned NumOpnds = Inst->getNumOperands();
2217 OriginalValues.reserve(NumOpnds);
2218 for (unsigned It = 0; It < NumOpnds; ++It) {
2219 // Save the current operand.
2220 Value *Val = Inst->getOperand(It);
2221 OriginalValues.push_back(Val);
2222 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002223 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002224 // that we are not willing to pay.
2225 Inst->setOperand(It, UndefValue::get(Val->getType()));
2226 }
2227 }
2228
2229 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002230 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002231 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2232 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2233 Inst->setOperand(It, OriginalValues[It]);
2234 }
2235 };
2236
2237 /// \brief Build a truncate instruction.
2238 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002239 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002240 public:
2241 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2242 /// result.
2243 /// trunc Opnd to Ty.
2244 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2245 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002246 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2247 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002248 }
2249
Quentin Colombetac55b152014-09-16 22:36:07 +00002250 /// \brief Get the built value.
2251 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002252
2253 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002254 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002255 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2256 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2257 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002258 }
2259 };
2260
2261 /// \brief Build a sign extension instruction.
2262 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002263 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002264 public:
2265 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2266 /// result.
2267 /// sext Opnd to Ty.
2268 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002269 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002270 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002271 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2272 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002273 }
2274
Quentin Colombetac55b152014-09-16 22:36:07 +00002275 /// \brief Get the built value.
2276 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002277
2278 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002279 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002280 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2281 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2282 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002283 }
2284 };
2285
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002286 /// \brief Build a zero extension instruction.
2287 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002288 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002289 public:
2290 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2291 /// result.
2292 /// zext Opnd to Ty.
2293 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002294 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002295 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002296 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2297 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002298 }
2299
Quentin Colombetac55b152014-09-16 22:36:07 +00002300 /// \brief Get the built value.
2301 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002302
2303 /// \brief Remove the built instruction.
2304 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002305 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2306 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2307 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002308 }
2309 };
2310
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002311 /// \brief Mutate an instruction to another type.
2312 class TypeMutator : public TypePromotionAction {
2313 /// Record the original type.
2314 Type *OrigTy;
2315
2316 public:
2317 /// \brief Mutate the type of \p Inst into \p NewTy.
2318 TypeMutator(Instruction *Inst, Type *NewTy)
2319 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2320 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2321 << "\n");
2322 Inst->mutateType(NewTy);
2323 }
2324
2325 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002326 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002327 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2328 << "\n");
2329 Inst->mutateType(OrigTy);
2330 }
2331 };
2332
2333 /// \brief Replace the uses of an instruction by another instruction.
2334 class UsesReplacer : public TypePromotionAction {
2335 /// Helper structure to keep track of the replaced uses.
2336 struct InstructionAndIdx {
2337 /// The instruction using the instruction.
2338 Instruction *Inst;
2339 /// The index where this instruction is used for Inst.
2340 unsigned Idx;
2341 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2342 : Inst(Inst), Idx(Idx) {}
2343 };
2344
2345 /// Keep track of the original uses (pair Instruction, Index).
2346 SmallVector<InstructionAndIdx, 4> OriginalUses;
2347 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2348
2349 public:
2350 /// \brief Replace all the use of \p Inst by \p New.
2351 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2352 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2353 << "\n");
2354 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002355 for (Use &U : Inst->uses()) {
2356 Instruction *UserI = cast<Instruction>(U.getUser());
2357 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002358 }
2359 // Now, we can replace the uses.
2360 Inst->replaceAllUsesWith(New);
2361 }
2362
2363 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002364 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002365 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2366 for (use_iterator UseIt = OriginalUses.begin(),
2367 EndIt = OriginalUses.end();
2368 UseIt != EndIt; ++UseIt) {
2369 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2370 }
2371 }
2372 };
2373
2374 /// \brief Remove an instruction from the IR.
2375 class InstructionRemover : public TypePromotionAction {
2376 /// Original position of the instruction.
2377 InsertionHandler Inserter;
2378 /// Helper structure to hide all the link to the instruction. In other
2379 /// words, this helps to do as if the instruction was removed.
2380 OperandsHider Hider;
2381 /// Keep track of the uses replaced, if any.
2382 UsesReplacer *Replacer;
2383
2384 public:
2385 /// \brief Remove all reference of \p Inst and optinally replace all its
2386 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002387 /// \pre If !Inst->use_empty(), then New != nullptr
2388 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002389 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002390 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002391 if (New)
2392 Replacer = new UsesReplacer(Inst, New);
2393 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2394 Inst->removeFromParent();
2395 }
2396
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002397 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002398
2399 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002400 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002401
2402 /// \brief Resurrect the instruction and reassign it to the proper uses if
2403 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002404 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002405 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2406 Inserter.insert(Inst);
2407 if (Replacer)
2408 Replacer->undo();
2409 Hider.undo();
2410 }
2411 };
2412
2413public:
2414 /// Restoration point.
2415 /// The restoration point is a pointer to an action instead of an iterator
2416 /// because the iterator may be invalidated but not the pointer.
2417 typedef const TypePromotionAction *ConstRestorationPt;
2418 /// Advocate every changes made in that transaction.
2419 void commit();
2420 /// Undo all the changes made after the given point.
2421 void rollback(ConstRestorationPt Point);
2422 /// Get the current restoration point.
2423 ConstRestorationPt getRestorationPoint() const;
2424
2425 /// \name API for IR modification with state keeping to support rollback.
2426 /// @{
2427 /// Same as Instruction::setOperand.
2428 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2429 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002430 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002431 /// Same as Value::replaceAllUsesWith.
2432 void replaceAllUsesWith(Instruction *Inst, Value *New);
2433 /// Same as Value::mutateType.
2434 void mutateType(Instruction *Inst, Type *NewTy);
2435 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002436 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002437 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002438 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002439 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002440 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002441 /// Same as Instruction::moveBefore.
2442 void moveBefore(Instruction *Inst, Instruction *Before);
2443 /// @}
2444
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445private:
2446 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002447 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2448 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002449};
2450
2451void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2452 Value *NewVal) {
2453 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002454 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455}
2456
2457void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2458 Value *NewVal) {
2459 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002460 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002461}
2462
2463void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2464 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002465 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002466}
2467
2468void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002469 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002470}
2471
Quentin Colombetac55b152014-09-16 22:36:07 +00002472Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2473 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002474 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002475 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002476 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002477 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002478}
2479
Quentin Colombetac55b152014-09-16 22:36:07 +00002480Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2481 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002482 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002483 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002484 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002485 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002486}
2487
Quentin Colombetac55b152014-09-16 22:36:07 +00002488Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2489 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002490 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002491 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002492 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002493 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002494}
2495
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002496void TypePromotionTransaction::moveBefore(Instruction *Inst,
2497 Instruction *Before) {
2498 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002499 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002500}
2501
2502TypePromotionTransaction::ConstRestorationPt
2503TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002504 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002505}
2506
2507void TypePromotionTransaction::commit() {
2508 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002509 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002510 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511 Actions.clear();
2512}
2513
2514void TypePromotionTransaction::rollback(
2515 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002516 while (!Actions.empty() && Point != Actions.back().get()) {
2517 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002518 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002519 }
2520}
2521
Chandler Carruthc8925912013-01-05 02:09:22 +00002522/// \brief A helper class for matching addressing modes.
2523///
2524/// This encapsulates the logic for matching the target-legal addressing modes.
2525class AddressingModeMatcher {
2526 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002527 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002528 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002529 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002530
2531 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2532 /// the memory instruction that we're computing this address for.
2533 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002534 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002535 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002536
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002537 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002538 /// part of the return value of this addressing mode matching stuff.
2539 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002540
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002541 /// The instructions inserted by other CodeGenPrepare optimizations.
2542 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002543 /// A map from the instructions to their type before promotion.
2544 InstrToOrigTy &PromotedInsts;
2545 /// The ongoing transaction where every action should be registered.
2546 TypePromotionTransaction &TPT;
2547
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002548 /// This is set to true when we should not do profitability checks.
2549 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002550 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002551
Eric Christopherd75c00c2015-02-26 22:38:34 +00002552 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002553 const TargetMachine &TM, Type *AT, unsigned AS,
2554 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002555 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002556 InstrToOrigTy &PromotedInsts,
2557 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002558 : AddrModeInsts(AMI), TM(TM),
2559 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2560 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002561 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2562 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2563 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002564 IgnoreProfitability = false;
2565 }
2566public:
Stephen Lin837bba12013-07-15 17:55:02 +00002567
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002568 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002569 /// give an access type of AccessTy. This returns a list of involved
2570 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002571 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002572 /// optimizations.
2573 /// \p PromotedInsts maps the instructions to their type before promotion.
2574 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002575 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002576 Instruction *MemoryInst,
2577 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002578 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002579 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002580 InstrToOrigTy &PromotedInsts,
2581 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002582 ExtAddrMode Result;
2583
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002584 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002585 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002586 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002587 (void)Success; assert(Success && "Couldn't select *anything*?");
2588 return Result;
2589 }
2590private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002591 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2592 bool matchAddr(Value *V, unsigned Depth);
2593 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002594 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002595 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002596 ExtAddrMode &AMBefore,
2597 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002598 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2599 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002600 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002601};
2602
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002603/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002604/// Return true and update AddrMode if this addr mode is legal for the target,
2605/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002606bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002607 unsigned Depth) {
2608 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2609 // mode. Just process that directly.
2610 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002611 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002612
Chandler Carruthc8925912013-01-05 02:09:22 +00002613 // If the scale is 0, it takes nothing to add this.
2614 if (Scale == 0)
2615 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002616
Chandler Carruthc8925912013-01-05 02:09:22 +00002617 // If we already have a scale of this value, we can add to it, otherwise, we
2618 // need an available scale field.
2619 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2620 return false;
2621
2622 ExtAddrMode TestAddrMode = AddrMode;
2623
2624 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2625 // [A+B + A*7] -> [B+A*8].
2626 TestAddrMode.Scale += Scale;
2627 TestAddrMode.ScaledReg = ScaleReg;
2628
2629 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002630 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002631 return false;
2632
2633 // It was legal, so commit it.
2634 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002635
Chandler Carruthc8925912013-01-05 02:09:22 +00002636 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2637 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2638 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002639 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002640 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2641 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2642 TestAddrMode.ScaledReg = AddLHS;
2643 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002644
Chandler Carruthc8925912013-01-05 02:09:22 +00002645 // If this addressing mode is legal, commit it and remember that we folded
2646 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002647 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002648 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2649 AddrMode = TestAddrMode;
2650 return true;
2651 }
2652 }
2653
2654 // Otherwise, not (x+c)*scale, just return what we have.
2655 return true;
2656}
2657
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002658/// This is a little filter, which returns true if an addressing computation
2659/// involving I might be folded into a load/store accessing it.
2660/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002661/// the set of instructions that MatchOperationAddr can.
2662static bool MightBeFoldableInst(Instruction *I) {
2663 switch (I->getOpcode()) {
2664 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002665 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002666 // Don't touch identity bitcasts.
2667 if (I->getType() == I->getOperand(0)->getType())
2668 return false;
2669 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2670 case Instruction::PtrToInt:
2671 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2672 return true;
2673 case Instruction::IntToPtr:
2674 // We know the input is intptr_t, so this is foldable.
2675 return true;
2676 case Instruction::Add:
2677 return true;
2678 case Instruction::Mul:
2679 case Instruction::Shl:
2680 // Can only handle X*C and X << C.
2681 return isa<ConstantInt>(I->getOperand(1));
2682 case Instruction::GetElementPtr:
2683 return true;
2684 default:
2685 return false;
2686 }
2687}
2688
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002689/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2690/// \note \p Val is assumed to be the product of some type promotion.
2691/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2692/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002693static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2694 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002695 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2696 if (!PromotedInst)
2697 return false;
2698 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2699 // If the ISDOpcode is undefined, it was undefined before the promotion.
2700 if (!ISDOpcode)
2701 return true;
2702 // Otherwise, check if the promoted instruction is legal or not.
2703 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002704 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002705}
2706
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002707/// \brief Hepler class to perform type promotion.
2708class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002709 /// \brief Utility function to check whether or not a sign or zero extension
2710 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2711 /// either using the operands of \p Inst or promoting \p Inst.
2712 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002713 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002714 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002715 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002716 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002717 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002718 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002719 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002720 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2721 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002722
2723 /// \brief Utility function to determine if \p OpIdx should be promoted when
2724 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002725 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002726 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002727 }
2728
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002729 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002730 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002731 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002732 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002733 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002734 /// Newly added extensions are inserted in \p Exts.
2735 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002736 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002737 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002738 static Value *promoteOperandForTruncAndAnyExt(
2739 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002740 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002741 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002742 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002743
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002744 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002745 /// operand is promotable and is not a supported trunc or sext.
2746 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002747 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002748 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002749 /// Newly added extensions are inserted in \p Exts.
2750 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002751 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002752 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002753 static Value *promoteOperandForOther(Instruction *Ext,
2754 TypePromotionTransaction &TPT,
2755 InstrToOrigTy &PromotedInsts,
2756 unsigned &CreatedInstsCost,
2757 SmallVectorImpl<Instruction *> *Exts,
2758 SmallVectorImpl<Instruction *> *Truncs,
2759 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002760
2761 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002762 static Value *signExtendOperandForOther(
2763 Instruction *Ext, TypePromotionTransaction &TPT,
2764 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2765 SmallVectorImpl<Instruction *> *Exts,
2766 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2767 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2768 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002769 }
2770
2771 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002772 static Value *zeroExtendOperandForOther(
2773 Instruction *Ext, TypePromotionTransaction &TPT,
2774 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2775 SmallVectorImpl<Instruction *> *Exts,
2776 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2777 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2778 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002779 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002780
2781public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002782 /// Type for the utility function that promotes the operand of Ext.
2783 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002784 InstrToOrigTy &PromotedInsts,
2785 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002786 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002787 SmallVectorImpl<Instruction *> *Truncs,
2788 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002789 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2790 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002791 /// \return NULL if no promotable action is possible with the current
2792 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002793 /// \p InsertedInsts keeps track of all the instructions inserted by the
2794 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002795 /// because we do not want to promote these instructions as CodeGenPrepare
2796 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2797 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002798 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002799 const TargetLowering &TLI,
2800 const InstrToOrigTy &PromotedInsts);
2801};
2802
2803bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002804 Type *ConsideredExtType,
2805 const InstrToOrigTy &PromotedInsts,
2806 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002807 // The promotion helper does not know how to deal with vector types yet.
2808 // To be able to fix that, we would need to fix the places where we
2809 // statically extend, e.g., constants and such.
2810 if (Inst->getType()->isVectorTy())
2811 return false;
2812
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002813 // We can always get through zext.
2814 if (isa<ZExtInst>(Inst))
2815 return true;
2816
2817 // sext(sext) is ok too.
2818 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002819 return true;
2820
2821 // We can get through binary operator, if it is legal. In other words, the
2822 // binary operator must have a nuw or nsw flag.
2823 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2824 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002825 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2826 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002827 return true;
2828
2829 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002830 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002831 if (!isa<TruncInst>(Inst))
2832 return false;
2833
2834 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002835 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002836 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002837 if (!OpndVal->getType()->isIntegerTy() ||
2838 OpndVal->getType()->getIntegerBitWidth() >
2839 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002840 return false;
2841
2842 // If the operand of the truncate is not an instruction, we will not have
2843 // any information on the dropped bits.
2844 // (Actually we could for constant but it is not worth the extra logic).
2845 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2846 if (!Opnd)
2847 return false;
2848
2849 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002850 // I.e., check that trunc just drops extended bits of the same kind of
2851 // the extension.
2852 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002853 const Type *OpndType;
2854 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002855 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2856 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002857 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2858 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002859 else
2860 return false;
2861
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002862 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002863 return Inst->getType()->getIntegerBitWidth() >=
2864 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002865}
2866
2867TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002868 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002869 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002870 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2871 "Unexpected instruction type");
2872 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2873 Type *ExtTy = Ext->getType();
2874 bool IsSExt = isa<SExtInst>(Ext);
2875 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002876 // get through.
2877 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002878 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002879 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002880
2881 // Do not promote if the operand has been added by codegenprepare.
2882 // Otherwise, it means we are undoing an optimization that is likely to be
2883 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002884 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002885 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002886
2887 // SExt or Trunc instructions.
2888 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002889 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2890 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002891 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002892
2893 // Regular instruction.
2894 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002895 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002896 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002897 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002898}
2899
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002900Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002901 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002902 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002903 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002904 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002905 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2906 // get through it and this method should not be called.
2907 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002908 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002909 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002910 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002911 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002912 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002913 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002914 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002915 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2916 TPT.replaceAllUsesWith(SExt, ZExt);
2917 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002918 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002919 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002920 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2921 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002922 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2923 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002924 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002925
2926 // Remove dead code.
2927 if (SExtOpnd->use_empty())
2928 TPT.eraseInstruction(SExtOpnd);
2929
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002930 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002931 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002932 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002933 if (ExtInst) {
2934 if (Exts)
2935 Exts->push_back(ExtInst);
2936 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2937 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002938 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002939 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002940
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002941 // At this point we have: ext ty opnd to ty.
2942 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2943 Value *NextVal = ExtInst->getOperand(0);
2944 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002945 return NextVal;
2946}
2947
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002948Value *TypePromotionHelper::promoteOperandForOther(
2949 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002950 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002951 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002952 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2953 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002954 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002955 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002956 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002957 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002958 if (!ExtOpnd->hasOneUse()) {
2959 // ExtOpnd will be promoted.
2960 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002961 // promoted version.
2962 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002963 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002964 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2965 ITrunc->removeFromParent();
2966 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002967 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002968 if (Truncs)
2969 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002970 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002971
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002972 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002973 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002974 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002975 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002976 }
2977
2978 // Get through the Instruction:
2979 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002980 // 2. Replace the uses of Ext by Inst.
2981 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002982
2983 // Remember the original type of the instruction before promotion.
2984 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002985 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2986 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002987 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002988 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002989 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002990 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002991 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002992 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002993
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002994 DEBUG(dbgs() << "Propagate Ext to operands\n");
2995 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002996 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002997 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2998 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2999 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003000 DEBUG(dbgs() << "No need to propagate\n");
3001 continue;
3002 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003003 // Check if we can statically extend the operand.
3004 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003005 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003006 DEBUG(dbgs() << "Statically extend\n");
3007 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3008 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3009 : Cst->getValue().zext(BitWidth);
3010 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003011 continue;
3012 }
3013 // UndefValue are typed, so we have to statically sign extend them.
3014 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003015 DEBUG(dbgs() << "Statically extend\n");
3016 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003017 continue;
3018 }
3019
3020 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003021 // Check if Ext was reused to extend an operand.
3022 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003023 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003024 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003025 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3026 : TPT.createZExt(Ext, Opnd, Ext->getType());
3027 if (!isa<Instruction>(ValForExtOpnd)) {
3028 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3029 continue;
3030 }
3031 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003032 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003033 if (Exts)
3034 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003035 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003036
3037 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003038 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3039 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003040 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003041 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003042 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003043 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003044 if (ExtForOpnd == Ext) {
3045 DEBUG(dbgs() << "Extension is useless now\n");
3046 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003047 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003048 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003049}
3050
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003051/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003052/// \p NewCost gives the cost of extension instructions created by the
3053/// promotion.
3054/// \p OldCost gives the cost of extension instructions before the promotion
3055/// plus the number of instructions that have been
3056/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003057/// \p PromotedOperand is the value that has been promoted.
3058/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003059bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003060 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3061 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3062 // The cost of the new extensions is greater than the cost of the
3063 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003064 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003065 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003066 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003067 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003068 return true;
3069 // The promotion is neutral but it may help folding the sign extension in
3070 // loads for instance.
3071 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003072 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003073}
3074
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003075/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003076/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003077/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003078/// If \p MovedAway is not NULL, it contains the information of whether or
3079/// not AddrInst has to be folded into the addressing mode on success.
3080/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3081/// because it has been moved away.
3082/// Thus AddrInst must not be added in the matched instructions.
3083/// This state can happen when AddrInst is a sext, since it may be moved away.
3084/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3085/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003086bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003087 unsigned Depth,
3088 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003089 // Avoid exponential behavior on extremely deep expression trees.
3090 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003091
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003092 // By default, all matched instructions stay in place.
3093 if (MovedAway)
3094 *MovedAway = false;
3095
Chandler Carruthc8925912013-01-05 02:09:22 +00003096 switch (Opcode) {
3097 case Instruction::PtrToInt:
3098 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003099 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003100 case Instruction::IntToPtr: {
3101 auto AS = AddrInst->getType()->getPointerAddressSpace();
3102 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003103 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003104 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003105 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003106 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003107 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003108 case Instruction::BitCast:
3109 // BitCast is always a noop, and we can handle it as long as it is
3110 // int->int or pointer->pointer (we don't want int<->fp or something).
3111 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3112 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3113 // Don't touch identity bitcasts. These were probably put here by LSR,
3114 // and we don't want to mess around with them. Assume it knows what it
3115 // is doing.
3116 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003117 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003118 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003119 case Instruction::AddrSpaceCast: {
3120 unsigned SrcAS
3121 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3122 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3123 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003124 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003125 return false;
3126 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003127 case Instruction::Add: {
3128 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3129 ExtAddrMode BackupAddrMode = AddrMode;
3130 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003131 // Start a transaction at this point.
3132 // The LHS may match but not the RHS.
3133 // Therefore, we need a higher level restoration point to undo partially
3134 // matched operation.
3135 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3136 TPT.getRestorationPoint();
3137
Sanjay Patelfc580a62015-09-21 23:03:16 +00003138 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3139 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003140 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003141
Chandler Carruthc8925912013-01-05 02:09:22 +00003142 // Restore the old addr mode info.
3143 AddrMode = BackupAddrMode;
3144 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003145 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003146
Chandler Carruthc8925912013-01-05 02:09:22 +00003147 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003148 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3149 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003150 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003151
Chandler Carruthc8925912013-01-05 02:09:22 +00003152 // Otherwise we definitely can't merge the ADD in.
3153 AddrMode = BackupAddrMode;
3154 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003155 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003156 break;
3157 }
3158 //case Instruction::Or:
3159 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3160 //break;
3161 case Instruction::Mul:
3162 case Instruction::Shl: {
3163 // Can only handle X*C and X << C.
3164 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003165 if (!RHS)
3166 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003167 int64_t Scale = RHS->getSExtValue();
3168 if (Opcode == Instruction::Shl)
3169 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003170
Sanjay Patelfc580a62015-09-21 23:03:16 +00003171 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003172 }
3173 case Instruction::GetElementPtr: {
3174 // Scan the GEP. We check it if it contains constant offsets and at most
3175 // one variable offset.
3176 int VariableOperand = -1;
3177 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003178
Chandler Carruthc8925912013-01-05 02:09:22 +00003179 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003180 gep_type_iterator GTI = gep_type_begin(AddrInst);
3181 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3182 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003183 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003184 unsigned Idx =
3185 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3186 ConstantOffset += SL->getElementOffset(Idx);
3187 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003188 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003189 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3190 ConstantOffset += CI->getSExtValue()*TypeSize;
3191 } else if (TypeSize) { // Scales of zero don't do anything.
3192 // We only allow one variable index at the moment.
3193 if (VariableOperand != -1)
3194 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003195
Chandler Carruthc8925912013-01-05 02:09:22 +00003196 // Remember the variable index.
3197 VariableOperand = i;
3198 VariableScale = TypeSize;
3199 }
3200 }
3201 }
Stephen Lin837bba12013-07-15 17:55:02 +00003202
Chandler Carruthc8925912013-01-05 02:09:22 +00003203 // A common case is for the GEP to only do a constant offset. In this case,
3204 // just add it to the disp field and check validity.
3205 if (VariableOperand == -1) {
3206 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003207 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003208 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003209 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003210 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003211 return true;
3212 }
3213 AddrMode.BaseOffs -= ConstantOffset;
3214 return false;
3215 }
3216
3217 // Save the valid addressing mode in case we can't match.
3218 ExtAddrMode BackupAddrMode = AddrMode;
3219 unsigned OldSize = AddrModeInsts.size();
3220
3221 // See if the scale and offset amount is valid for this target.
3222 AddrMode.BaseOffs += ConstantOffset;
3223
3224 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003225 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003226 // If it couldn't be matched, just stuff the value in a register.
3227 if (AddrMode.HasBaseReg) {
3228 AddrMode = BackupAddrMode;
3229 AddrModeInsts.resize(OldSize);
3230 return false;
3231 }
3232 AddrMode.HasBaseReg = true;
3233 AddrMode.BaseReg = AddrInst->getOperand(0);
3234 }
3235
3236 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003237 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003238 Depth)) {
3239 // If it couldn't be matched, try stuffing the base into a register
3240 // instead of matching it, and retrying the match of the scale.
3241 AddrMode = BackupAddrMode;
3242 AddrModeInsts.resize(OldSize);
3243 if (AddrMode.HasBaseReg)
3244 return false;
3245 AddrMode.HasBaseReg = true;
3246 AddrMode.BaseReg = AddrInst->getOperand(0);
3247 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003248 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003249 VariableScale, Depth)) {
3250 // If even that didn't work, bail.
3251 AddrMode = BackupAddrMode;
3252 AddrModeInsts.resize(OldSize);
3253 return false;
3254 }
3255 }
3256
3257 return true;
3258 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003259 case Instruction::SExt:
3260 case Instruction::ZExt: {
3261 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3262 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003263 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003264
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003265 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003266 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003267 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003268 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003269 if (!TPH)
3270 return false;
3271
3272 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3273 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003274 unsigned CreatedInstsCost = 0;
3275 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003276 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003277 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003278 // SExt has been moved away.
3279 // Thus either it will be rematched later in the recursive calls or it is
3280 // gone. Anyway, we must not fold it into the addressing mode at this point.
3281 // E.g.,
3282 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003283 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003284 // addr = gep base, idx
3285 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003286 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003287 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3288 // addr = gep base, op <- match
3289 if (MovedAway)
3290 *MovedAway = true;
3291
3292 assert(PromotedOperand &&
3293 "TypePromotionHelper should have filtered out those cases");
3294
3295 ExtAddrMode BackupAddrMode = AddrMode;
3296 unsigned OldSize = AddrModeInsts.size();
3297
Sanjay Patelfc580a62015-09-21 23:03:16 +00003298 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003299 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003300 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003301 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003302 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003303 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003304 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003305 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003306 AddrMode = BackupAddrMode;
3307 AddrModeInsts.resize(OldSize);
3308 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3309 TPT.rollback(LastKnownGood);
3310 return false;
3311 }
3312 return true;
3313 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003314 }
3315 return false;
3316}
3317
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003318/// If we can, try to add the value of 'Addr' into the current addressing mode.
3319/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3320/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3321/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003322///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003323bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003324 // Start a transaction at this point that we will rollback if the matching
3325 // fails.
3326 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3327 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003328 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3329 // Fold in immediates if legal for the target.
3330 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003331 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003332 return true;
3333 AddrMode.BaseOffs -= CI->getSExtValue();
3334 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3335 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003336 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003337 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003338 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003339 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003340 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003341 }
3342 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3343 ExtAddrMode BackupAddrMode = AddrMode;
3344 unsigned OldSize = AddrModeInsts.size();
3345
3346 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003347 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003348 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003349 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003350 // to check here.
3351 if (MovedAway)
3352 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003353 // Okay, it's possible to fold this. Check to see if it is actually
3354 // *profitable* to do so. We use a simple cost model to avoid increasing
3355 // register pressure too much.
3356 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003357 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003358 AddrModeInsts.push_back(I);
3359 return true;
3360 }
Stephen Lin837bba12013-07-15 17:55:02 +00003361
Chandler Carruthc8925912013-01-05 02:09:22 +00003362 // It isn't profitable to do this, roll back.
3363 //cerr << "NOT FOLDING: " << *I;
3364 AddrMode = BackupAddrMode;
3365 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003366 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003367 }
3368 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003369 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003370 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003371 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003372 } else if (isa<ConstantPointerNull>(Addr)) {
3373 // Null pointer gets folded without affecting the addressing mode.
3374 return true;
3375 }
3376
3377 // Worse case, the target should support [reg] addressing modes. :)
3378 if (!AddrMode.HasBaseReg) {
3379 AddrMode.HasBaseReg = true;
3380 AddrMode.BaseReg = Addr;
3381 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003382 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003383 return true;
3384 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003385 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003386 }
3387
3388 // If the base register is already taken, see if we can do [r+r].
3389 if (AddrMode.Scale == 0) {
3390 AddrMode.Scale = 1;
3391 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003392 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003393 return true;
3394 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003395 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003396 }
3397 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003398 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003399 return false;
3400}
3401
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003402/// Check to see if all uses of OpVal by the specified inline asm call are due
3403/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003404static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003405 const TargetMachine &TM) {
3406 const Function *F = CI->getParent()->getParent();
3407 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3408 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003409 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003410 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3411 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003412 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3413 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003414
Chandler Carruthc8925912013-01-05 02:09:22 +00003415 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003416 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003417
3418 // If this asm operand is our Value*, and if it isn't an indirect memory
3419 // operand, we can't fold it!
3420 if (OpInfo.CallOperandVal == OpVal &&
3421 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3422 !OpInfo.isIndirect))
3423 return false;
3424 }
3425
3426 return true;
3427}
3428
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003429/// Recursively walk all the uses of I until we find a memory use.
3430/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003431/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003432static bool FindAllMemoryUses(
3433 Instruction *I,
3434 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3435 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003436 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003437 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003438 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003439
Chandler Carruthc8925912013-01-05 02:09:22 +00003440 // If this is an obviously unfoldable instruction, bail out.
3441 if (!MightBeFoldableInst(I))
3442 return true;
3443
3444 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003445 for (Use &U : I->uses()) {
3446 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003447
Chandler Carruthcdf47882014-03-09 03:16:01 +00003448 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3449 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003450 continue;
3451 }
Stephen Lin837bba12013-07-15 17:55:02 +00003452
Chandler Carruthcdf47882014-03-09 03:16:01 +00003453 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3454 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003455 if (opNo == 0) return true; // Storing addr, not into addr.
3456 MemoryUses.push_back(std::make_pair(SI, opNo));
3457 continue;
3458 }
Stephen Lin837bba12013-07-15 17:55:02 +00003459
Chandler Carruthcdf47882014-03-09 03:16:01 +00003460 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003461 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3462 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003463
Chandler Carruthc8925912013-01-05 02:09:22 +00003464 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003465 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003466 return true;
3467 continue;
3468 }
Stephen Lin837bba12013-07-15 17:55:02 +00003469
Eric Christopher11e4df72015-02-26 22:38:43 +00003470 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003471 return true;
3472 }
3473
3474 return false;
3475}
3476
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003477/// Return true if Val is already known to be live at the use site that we're
3478/// folding it into. If so, there is no cost to include it in the addressing
3479/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3480/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003481bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003482 Value *KnownLive2) {
3483 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003484 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003485 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003486
Chandler Carruthc8925912013-01-05 02:09:22 +00003487 // All values other than instructions and arguments (e.g. constants) are live.
3488 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003489
Chandler Carruthc8925912013-01-05 02:09:22 +00003490 // If Val is a constant sized alloca in the entry block, it is live, this is
3491 // true because it is just a reference to the stack/frame pointer, which is
3492 // live for the whole function.
3493 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3494 if (AI->isStaticAlloca())
3495 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003496
Chandler Carruthc8925912013-01-05 02:09:22 +00003497 // Check to see if this value is already used in the memory instruction's
3498 // block. If so, it's already live into the block at the very least, so we
3499 // can reasonably fold it.
3500 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3501}
3502
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003503/// It is possible for the addressing mode of the machine to fold the specified
3504/// instruction into a load or store that ultimately uses it.
3505/// However, the specified instruction has multiple uses.
3506/// Given this, it may actually increase register pressure to fold it
3507/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003508///
3509/// X = ...
3510/// Y = X+1
3511/// use(Y) -> nonload/store
3512/// Z = Y+1
3513/// load Z
3514///
3515/// In this case, Y has multiple uses, and can be folded into the load of Z
3516/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3517/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3518/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3519/// number of computations either.
3520///
3521/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3522/// X was live across 'load Z' for other reasons, we actually *would* want to
3523/// fold the addressing mode in the Z case. This would make Y die earlier.
3524bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003525isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003526 ExtAddrMode &AMAfter) {
3527 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003528
Chandler Carruthc8925912013-01-05 02:09:22 +00003529 // AMBefore is the addressing mode before this instruction was folded into it,
3530 // and AMAfter is the addressing mode after the instruction was folded. Get
3531 // the set of registers referenced by AMAfter and subtract out those
3532 // referenced by AMBefore: this is the set of values which folding in this
3533 // address extends the lifetime of.
3534 //
3535 // Note that there are only two potential values being referenced here,
3536 // BaseReg and ScaleReg (global addresses are always available, as are any
3537 // folded immediates).
3538 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003539
Chandler Carruthc8925912013-01-05 02:09:22 +00003540 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3541 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003542 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003543 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003544 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003545 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003546
3547 // If folding this instruction (and it's subexprs) didn't extend any live
3548 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003549 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003550 return true;
3551
3552 // If all uses of this instruction are ultimately load/store/inlineasm's,
3553 // check to see if their addressing modes will include this instruction. If
3554 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3555 // uses.
3556 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3557 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003558 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003559 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003560
Chandler Carruthc8925912013-01-05 02:09:22 +00003561 // Now that we know that all uses of this instruction are part of a chain of
3562 // computation involving only operations that could theoretically be folded
3563 // into a memory use, loop over each of these uses and see if they could
3564 // *actually* fold the instruction.
3565 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3566 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3567 Instruction *User = MemoryUses[i].first;
3568 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003569
Chandler Carruthc8925912013-01-05 02:09:22 +00003570 // Get the access type of this use. If the use isn't a pointer, we don't
3571 // know what it accesses.
3572 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003573 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3574 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003575 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003576 Type *AddressAccessTy = AddrTy->getElementType();
3577 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003578
Chandler Carruthc8925912013-01-05 02:09:22 +00003579 // Do a match against the root of this address, ignoring profitability. This
3580 // will tell us if the addressing mode for the memory operation will
3581 // *actually* cover the shared instruction.
3582 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003583 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3584 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003585 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003586 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003587 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003588 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003589 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003590 (void)Success; assert(Success && "Couldn't select *anything*?");
3591
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003592 // The match was to check the profitability, the changes made are not
3593 // part of the original matcher. Therefore, they should be dropped
3594 // otherwise the original matcher will not present the right state.
3595 TPT.rollback(LastKnownGood);
3596
Chandler Carruthc8925912013-01-05 02:09:22 +00003597 // If the match didn't cover I, then it won't be shared by it.
3598 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3599 I) == MatchedAddrModeInsts.end())
3600 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003601
Chandler Carruthc8925912013-01-05 02:09:22 +00003602 MatchedAddrModeInsts.clear();
3603 }
Stephen Lin837bba12013-07-15 17:55:02 +00003604
Chandler Carruthc8925912013-01-05 02:09:22 +00003605 return true;
3606}
3607
3608} // end anonymous namespace
3609
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003610/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003611/// different basic block than BB.
3612static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3613 if (Instruction *I = dyn_cast<Instruction>(V))
3614 return I->getParent() != BB;
3615 return false;
3616}
3617
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003618/// Load and Store Instructions often have addressing modes that can do
3619/// significant amounts of computation. As such, instruction selection will try
3620/// to get the load or store to do as much computation as possible for the
3621/// program. The problem is that isel can only see within a single block. As
3622/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003623///
3624/// This method is used to optimize both load/store and inline asms with memory
3625/// operands.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003626bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003627 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003628 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003629
3630 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003631 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003632 SmallVector<Value*, 8> worklist;
3633 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003634 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003635
Owen Anderson8ba5f392010-11-27 08:15:55 +00003636 // Use a worklist to iteratively look through PHI nodes, and ensure that
3637 // the addressing mode obtained from the non-PHI roots of the graph
3638 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003639 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003640 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003641 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003642 SmallVector<Instruction*, 16> AddrModeInsts;
3643 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003644 TypePromotionTransaction TPT;
3645 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3646 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003647 while (!worklist.empty()) {
3648 Value *V = worklist.back();
3649 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003650
Owen Anderson8ba5f392010-11-27 08:15:55 +00003651 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003652 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003653 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003654 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003655 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003656
Owen Anderson8ba5f392010-11-27 08:15:55 +00003657 // For a PHI node, push all of its incoming values.
3658 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003659 for (Value *IncValue : P->incoming_values())
3660 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003661 continue;
3662 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003663
Owen Anderson8ba5f392010-11-27 08:15:55 +00003664 // For non-PHIs, determine the addressing mode being computed.
3665 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003666 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003667 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003668 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003669
3670 // This check is broken into two cases with very similar code to avoid using
3671 // getNumUses() as much as possible. Some values have a lot of uses, so
3672 // calling getNumUses() unconditionally caused a significant compile-time
3673 // regression.
3674 if (!Consensus) {
3675 Consensus = V;
3676 AddrMode = NewAddrMode;
3677 AddrModeInsts = NewAddrModeInsts;
3678 continue;
3679 } else if (NewAddrMode == AddrMode) {
3680 if (!IsNumUsesConsensusValid) {
3681 NumUsesConsensus = Consensus->getNumUses();
3682 IsNumUsesConsensusValid = true;
3683 }
3684
3685 // Ensure that the obtained addressing mode is equivalent to that obtained
3686 // for all other roots of the PHI traversal. Also, when choosing one
3687 // such root as representative, select the one with the most uses in order
3688 // to keep the cost modeling heuristics in AddressingModeMatcher
3689 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003690 unsigned NumUses = V->getNumUses();
3691 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003692 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003693 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003694 AddrModeInsts = NewAddrModeInsts;
3695 }
3696 continue;
3697 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003698
Craig Topperc0196b12014-04-14 00:51:57 +00003699 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003700 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003701 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003702
Owen Anderson8ba5f392010-11-27 08:15:55 +00003703 // If the addressing mode couldn't be determined, or if multiple different
3704 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003705 if (!Consensus) {
3706 TPT.rollback(LastKnownGood);
3707 return false;
3708 }
3709 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003710
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003711 // Check to see if any of the instructions supersumed by this addr mode are
3712 // non-local to I's BB.
3713 bool AnyNonLocal = false;
3714 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003715 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003716 AnyNonLocal = true;
3717 break;
3718 }
3719 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003720
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003721 // If all the instructions matched are already in this BB, don't do anything.
3722 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003723 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003724 return false;
3725 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003726
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003727 // Insert this computation right after this user. Since our caller is
3728 // scanning from the top of the BB to the bottom, reuse of the expr are
3729 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003730 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003731
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003732 // Now that we determined the addressing expression we want to use and know
3733 // that we have to sink it into this block. Check to see if we have already
3734 // done this for some other load/store instr in this block. If so, reuse the
3735 // computation.
3736 Value *&SunkAddr = SunkAddrs[Addr];
3737 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003738 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003739 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003740 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003741 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003742 } else if (AddrSinkUsingGEPs ||
3743 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003744 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3745 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003746 // By default, we use the GEP-based method when AA is used later. This
3747 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3748 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003749 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003750 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003751 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003752
3753 // First, find the pointer.
3754 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3755 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003756 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003757 }
3758
3759 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3760 // We can't add more than one pointer together, nor can we scale a
3761 // pointer (both of which seem meaningless).
3762 if (ResultPtr || AddrMode.Scale != 1)
3763 return false;
3764
3765 ResultPtr = AddrMode.ScaledReg;
3766 AddrMode.Scale = 0;
3767 }
3768
3769 if (AddrMode.BaseGV) {
3770 if (ResultPtr)
3771 return false;
3772
3773 ResultPtr = AddrMode.BaseGV;
3774 }
3775
3776 // If the real base value actually came from an inttoptr, then the matcher
3777 // will look through it and provide only the integer value. In that case,
3778 // use it here.
3779 if (!ResultPtr && AddrMode.BaseReg) {
3780 ResultPtr =
3781 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003782 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003783 } else if (!ResultPtr && AddrMode.Scale == 1) {
3784 ResultPtr =
3785 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3786 AddrMode.Scale = 0;
3787 }
3788
3789 if (!ResultPtr &&
3790 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3791 SunkAddr = Constant::getNullValue(Addr->getType());
3792 } else if (!ResultPtr) {
3793 return false;
3794 } else {
3795 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003796 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3797 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003798
3799 // Start with the base register. Do this first so that subsequent address
3800 // matching finds it last, which will prevent it from trying to match it
3801 // as the scaled value in case it happens to be a mul. That would be
3802 // problematic if we've sunk a different mul for the scale, because then
3803 // we'd end up sinking both muls.
3804 if (AddrMode.BaseReg) {
3805 Value *V = AddrMode.BaseReg;
3806 if (V->getType() != IntPtrTy)
3807 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3808
3809 ResultIndex = V;
3810 }
3811
3812 // Add the scale value.
3813 if (AddrMode.Scale) {
3814 Value *V = AddrMode.ScaledReg;
3815 if (V->getType() == IntPtrTy) {
3816 // done.
3817 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3818 cast<IntegerType>(V->getType())->getBitWidth()) {
3819 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3820 } else {
3821 // It is only safe to sign extend the BaseReg if we know that the math
3822 // required to create it did not overflow before we extend it. Since
3823 // the original IR value was tossed in favor of a constant back when
3824 // the AddrMode was created we need to bail out gracefully if widths
3825 // do not match instead of extending it.
3826 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3827 if (I && (ResultIndex != AddrMode.BaseReg))
3828 I->eraseFromParent();
3829 return false;
3830 }
3831
3832 if (AddrMode.Scale != 1)
3833 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3834 "sunkaddr");
3835 if (ResultIndex)
3836 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3837 else
3838 ResultIndex = V;
3839 }
3840
3841 // Add in the Base Offset if present.
3842 if (AddrMode.BaseOffs) {
3843 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3844 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003845 // We need to add this separately from the scale above to help with
3846 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003847 if (ResultPtr->getType() != I8PtrTy)
3848 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003849 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003850 }
3851
3852 ResultIndex = V;
3853 }
3854
3855 if (!ResultIndex) {
3856 SunkAddr = ResultPtr;
3857 } else {
3858 if (ResultPtr->getType() != I8PtrTy)
3859 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003860 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003861 }
3862
3863 if (SunkAddr->getType() != Addr->getType())
3864 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3865 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003866 } else {
David Greene74e2d492010-01-05 01:27:11 +00003867 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003868 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003869 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003870 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003871
3872 // Start with the base register. Do this first so that subsequent address
3873 // matching finds it last, which will prevent it from trying to match it
3874 // as the scaled value in case it happens to be a mul. That would be
3875 // problematic if we've sunk a different mul for the scale, because then
3876 // we'd end up sinking both muls.
3877 if (AddrMode.BaseReg) {
3878 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003879 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003880 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003881 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003882 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003883 Result = V;
3884 }
3885
3886 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003887 if (AddrMode.Scale) {
3888 Value *V = AddrMode.ScaledReg;
3889 if (V->getType() == IntPtrTy) {
3890 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003891 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003892 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003893 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3894 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003895 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003896 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003897 // It is only safe to sign extend the BaseReg if we know that the math
3898 // required to create it did not overflow before we extend it. Since
3899 // the original IR value was tossed in favor of a constant back when
3900 // the AddrMode was created we need to bail out gracefully if widths
3901 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003902 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003903 if (I && (Result != AddrMode.BaseReg))
3904 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003905 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003906 }
3907 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003908 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3909 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003910 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003911 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003912 else
3913 Result = V;
3914 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003915
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003916 // Add in the BaseGV if present.
3917 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003918 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003919 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003920 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003921 else
3922 Result = V;
3923 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003924
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003925 // Add in the Base Offset if present.
3926 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003927 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003928 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003929 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003930 else
3931 Result = V;
3932 }
3933
Craig Topperc0196b12014-04-14 00:51:57 +00003934 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003935 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003936 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003937 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003938 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003939
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003940 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003941
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003942 // If we have no uses, recursively delete the value and all dead instructions
3943 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003944 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003945 // This can cause recursive deletion, which can invalidate our iterator.
3946 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003947 WeakVH IterHandle(&*CurInstIterator);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003948 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003949
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003950 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003951
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003952 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003953 // If the iterator instruction was recursively deleted, start over at the
3954 // start of the block.
3955 CurInstIterator = BB->begin();
3956 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003957 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003958 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003959 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003960 return true;
3961}
3962
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003963/// If there are any memory operands, use OptimizeMemoryInst to sink their
3964/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003965bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003966 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003967
Eric Christopher11e4df72015-02-26 22:38:43 +00003968 const TargetRegisterInfo *TRI =
3969 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003970 TargetLowering::AsmOperandInfoVector TargetConstraints =
3971 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003972 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003973 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3974 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003975
Evan Cheng1da25002008-02-26 02:42:37 +00003976 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003977 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003978
Eli Friedman666bbe32008-02-26 18:37:49 +00003979 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3980 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003981 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003982 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003983 } else if (OpInfo.Type == InlineAsm::isInput)
3984 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003985 }
3986
3987 return MadeChange;
3988}
3989
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003990/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3991/// sign extensions.
3992static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3993 assert(!Inst->use_empty() && "Input must have at least one use");
3994 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3995 bool IsSExt = isa<SExtInst>(FirstUser);
3996 Type *ExtTy = FirstUser->getType();
3997 for (const User *U : Inst->users()) {
3998 const Instruction *UI = cast<Instruction>(U);
3999 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4000 return false;
4001 Type *CurTy = UI->getType();
4002 // Same input and output types: Same instruction after CSE.
4003 if (CurTy == ExtTy)
4004 continue;
4005
4006 // If IsSExt is true, we are in this situation:
4007 // a = Inst
4008 // b = sext ty1 a to ty2
4009 // c = sext ty1 a to ty3
4010 // Assuming ty2 is shorter than ty3, this could be turned into:
4011 // a = Inst
4012 // b = sext ty1 a to ty2
4013 // c = sext ty2 b to ty3
4014 // However, the last sext is not free.
4015 if (IsSExt)
4016 return false;
4017
4018 // This is a ZExt, maybe this is free to extend from one type to another.
4019 // In that case, we would not account for a different use.
4020 Type *NarrowTy;
4021 Type *LargeTy;
4022 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4023 CurTy->getScalarType()->getIntegerBitWidth()) {
4024 NarrowTy = CurTy;
4025 LargeTy = ExtTy;
4026 } else {
4027 NarrowTy = ExtTy;
4028 LargeTy = CurTy;
4029 }
4030
4031 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4032 return false;
4033 }
4034 // All uses are the same or can be derived from one another for free.
4035 return true;
4036}
4037
4038/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4039/// load instruction.
4040/// If an ext(load) can be formed, it is returned via \p LI for the load
4041/// and \p Inst for the extension.
4042/// Otherwise LI == nullptr and Inst == nullptr.
4043/// When some promotion happened, \p TPT contains the proper state to
4044/// revert them.
4045///
4046/// \return true when promoting was necessary to expose the ext(load)
4047/// opportunity, false otherwise.
4048///
4049/// Example:
4050/// \code
4051/// %ld = load i32* %addr
4052/// %add = add nuw i32 %ld, 4
4053/// %zext = zext i32 %add to i64
4054/// \endcode
4055/// =>
4056/// \code
4057/// %ld = load i32* %addr
4058/// %zext = zext i32 %ld to i64
4059/// %add = add nuw i64 %zext, 4
4060/// \encode
4061/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004062bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004063 LoadInst *&LI, Instruction *&Inst,
4064 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004065 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004066 // Iterate over all the extensions to see if one form an ext(load).
4067 for (auto I : Exts) {
4068 // Check if we directly have ext(load).
4069 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4070 Inst = I;
4071 // No promotion happened here.
4072 return false;
4073 }
4074 // Check whether or not we want to do any promotion.
4075 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4076 continue;
4077 // Get the action to perform the promotion.
4078 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004079 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004080 // Check if we can promote.
4081 if (!TPH)
4082 continue;
4083 // Save the current state.
4084 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4085 TPT.getRestorationPoint();
4086 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004087 unsigned NewCreatedInstsCost = 0;
4088 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004089 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004090 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4091 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004092 assert(PromotedVal &&
4093 "TypePromotionHelper should have filtered out those cases");
4094
4095 // We would be able to merge only one extension in a load.
4096 // Therefore, if we have more than 1 new extension we heuristically
4097 // cut this search path, because it means we degrade the code quality.
4098 // With exactly 2, the transformation is neutral, because we will merge
4099 // one extension but leave one. However, we optimistically keep going,
4100 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004101 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4102 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004103 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004104 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004105 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004106 // The promotion is not profitable, rollback to the previous state.
4107 TPT.rollback(LastKnownGood);
4108 continue;
4109 }
4110 // The promotion is profitable.
4111 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004112 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004113 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004114 // If we have created a new extension, i.e., now we have two
4115 // extensions. We must make sure one of them is merged with
4116 // the load, otherwise we may degrade the code quality.
4117 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4118 // Promotion happened.
4119 return true;
4120 // If this does not help to expose an ext(load) then, rollback.
4121 TPT.rollback(LastKnownGood);
4122 }
4123 // None of the extension can form an ext(load).
4124 LI = nullptr;
4125 Inst = nullptr;
4126 return false;
4127}
4128
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004129/// Move a zext or sext fed by a load into the same basic block as the load,
4130/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4131/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004132/// \p I[in/out] the extension may be modified during the process if some
4133/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004134///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004135bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004136 // Try to promote a chain of computation if it allows to form
4137 // an extended load.
4138 TypePromotionTransaction TPT;
4139 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4140 TPT.getRestorationPoint();
4141 SmallVector<Instruction *, 1> Exts;
4142 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004143 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004144 LoadInst *LI = nullptr;
4145 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004146 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004147 if (!LI || !I) {
4148 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4149 "the code must remain the same");
4150 I = OldExt;
4151 return false;
4152 }
Dan Gohman99429a02009-10-16 20:59:35 +00004153
4154 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004155 // Make the cheap checks first if we did not promote.
4156 // If we promoted, we need to check if it is indeed profitable.
4157 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004158 return false;
4159
Mehdi Amini44ede332015-07-09 02:09:04 +00004160 EVT VT = TLI->getValueType(*DL, I->getType());
4161 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004162
Dan Gohman99429a02009-10-16 20:59:35 +00004163 // If the load has other users and the truncate is not free, this probably
4164 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004165 if (!LI->hasOneUse() && TLI &&
4166 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004167 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4168 I = OldExt;
4169 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004170 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004171 }
Dan Gohman99429a02009-10-16 20:59:35 +00004172
4173 // Check whether the target supports casts folded into loads.
4174 unsigned LType;
4175 if (isa<ZExtInst>(I))
4176 LType = ISD::ZEXTLOAD;
4177 else {
4178 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4179 LType = ISD::SEXTLOAD;
4180 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004181 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004182 I = OldExt;
4183 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004184 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004185 }
Dan Gohman99429a02009-10-16 20:59:35 +00004186
4187 // Move the extend into the same block as the load, so that SelectionDAG
4188 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004189 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004190 I->removeFromParent();
4191 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004192 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004193 return true;
4194}
4195
Sanjay Patelfc580a62015-09-21 23:03:16 +00004196bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004197 BasicBlock *DefBB = I->getParent();
4198
Bob Wilsonff714f92010-09-21 21:44:14 +00004199 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004200 // other uses of the source with result of extension.
4201 Value *Src = I->getOperand(0);
4202 if (Src->hasOneUse())
4203 return false;
4204
Evan Cheng2011df42007-12-13 07:50:36 +00004205 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004206 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004207 return false;
4208
Evan Cheng7bc89422007-12-12 00:51:06 +00004209 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004210 // this block.
4211 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004212 return false;
4213
Evan Chengd3d80172007-12-05 23:58:20 +00004214 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004215 for (User *U : I->users()) {
4216 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004217
4218 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004219 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004220 if (UserBB == DefBB) continue;
4221 DefIsLiveOut = true;
4222 break;
4223 }
4224 if (!DefIsLiveOut)
4225 return false;
4226
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004227 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004228 for (User *U : Src->users()) {
4229 Instruction *UI = cast<Instruction>(U);
4230 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004231 if (UserBB == DefBB) continue;
4232 // Be conservative. We don't want this xform to end up introducing
4233 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004234 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004235 return false;
4236 }
4237
Evan Chengd3d80172007-12-05 23:58:20 +00004238 // InsertedTruncs - Only insert one trunc in each block once.
4239 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4240
4241 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004242 for (Use &U : Src->uses()) {
4243 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004244
4245 // Figure out which BB this ext is used in.
4246 BasicBlock *UserBB = User->getParent();
4247 if (UserBB == DefBB) continue;
4248
4249 // Both src and def are live in this block. Rewrite the use.
4250 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4251
4252 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004253 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004254 assert(InsertPt != UserBB->end());
4255 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004256 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004257 }
4258
4259 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004260 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004261 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004262 MadeChange = true;
4263 }
4264
4265 return MadeChange;
4266}
4267
Geoff Berry5256fca2015-11-20 22:34:39 +00004268// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4269// just after the load if the target can fold this into one extload instruction,
4270// with the hope of eliminating some of the other later "and" instructions using
4271// the loaded value. "and"s that are made trivially redundant by the insertion
4272// of the new "and" are removed by this function, while others (e.g. those whose
4273// path from the load goes through a phi) are left for isel to potentially
4274// remove.
4275//
4276// For example:
4277//
4278// b0:
4279// x = load i32
4280// ...
4281// b1:
4282// y = and x, 0xff
4283// z = use y
4284//
4285// becomes:
4286//
4287// b0:
4288// x = load i32
4289// x' = and x, 0xff
4290// ...
4291// b1:
4292// z = use x'
4293//
4294// whereas:
4295//
4296// b0:
4297// x1 = load i32
4298// ...
4299// b1:
4300// x2 = load i32
4301// ...
4302// b2:
4303// x = phi x1, x2
4304// y = and x, 0xff
4305//
4306// becomes (after a call to optimizeLoadExt for each load):
4307//
4308// b0:
4309// x1 = load i32
4310// x1' = and x1, 0xff
4311// ...
4312// b1:
4313// x2 = load i32
4314// x2' = and x2, 0xff
4315// ...
4316// b2:
4317// x = phi x1', x2'
4318// y = and x, 0xff
4319//
4320
4321bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4322
4323 if (!Load->isSimple() ||
4324 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4325 return false;
4326
4327 // Skip loads we've already transformed or have no reason to transform.
4328 if (Load->hasOneUse()) {
4329 User *LoadUser = *Load->user_begin();
4330 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4331 !dyn_cast<PHINode>(LoadUser))
4332 return false;
4333 }
4334
4335 // Look at all uses of Load, looking through phis, to determine how many bits
4336 // of the loaded value are needed.
4337 SmallVector<Instruction *, 8> WorkList;
4338 SmallPtrSet<Instruction *, 16> Visited;
4339 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4340 for (auto *U : Load->users())
4341 WorkList.push_back(cast<Instruction>(U));
4342
4343 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4344 unsigned BitWidth = LoadResultVT.getSizeInBits();
4345 APInt DemandBits(BitWidth, 0);
4346 APInt WidestAndBits(BitWidth, 0);
4347
4348 while (!WorkList.empty()) {
4349 Instruction *I = WorkList.back();
4350 WorkList.pop_back();
4351
4352 // Break use-def graph loops.
4353 if (!Visited.insert(I).second)
4354 continue;
4355
4356 // For a PHI node, push all of its users.
4357 if (auto *Phi = dyn_cast<PHINode>(I)) {
4358 for (auto *U : Phi->users())
4359 WorkList.push_back(cast<Instruction>(U));
4360 continue;
4361 }
4362
4363 switch (I->getOpcode()) {
4364 case llvm::Instruction::And: {
4365 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4366 if (!AndC)
4367 return false;
4368 APInt AndBits = AndC->getValue();
4369 DemandBits |= AndBits;
4370 // Keep track of the widest and mask we see.
4371 if (AndBits.ugt(WidestAndBits))
4372 WidestAndBits = AndBits;
4373 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4374 AndsToMaybeRemove.push_back(I);
4375 break;
4376 }
4377
4378 case llvm::Instruction::Shl: {
4379 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4380 if (!ShlC)
4381 return false;
4382 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4383 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4384 DemandBits |= ShlDemandBits;
4385 break;
4386 }
4387
4388 case llvm::Instruction::Trunc: {
4389 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4390 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4391 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4392 DemandBits |= TruncBits;
4393 break;
4394 }
4395
4396 default:
4397 return false;
4398 }
4399 }
4400
4401 uint32_t ActiveBits = DemandBits.getActiveBits();
4402 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4403 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4404 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4405 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4406 // followed by an AND.
4407 // TODO: Look into removing this restriction by fixing backends to either
4408 // return false for isLoadExtLegal for i1 or have them select this pattern to
4409 // a single instruction.
4410 //
4411 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4412 // mask, since these are the only ands that will be removed by isel.
4413 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4414 WidestAndBits != DemandBits)
4415 return false;
4416
4417 LLVMContext &Ctx = Load->getType()->getContext();
4418 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4419 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4420
4421 // Reject cases that won't be matched as extloads.
4422 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4423 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4424 return false;
4425
4426 IRBuilder<> Builder(Load->getNextNode());
4427 auto *NewAnd = dyn_cast<Instruction>(
4428 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4429
4430 // Replace all uses of load with new and (except for the use of load in the
4431 // new and itself).
4432 Load->replaceAllUsesWith(NewAnd);
4433 NewAnd->setOperand(0, Load);
4434
4435 // Remove any and instructions that are now redundant.
4436 for (auto *And : AndsToMaybeRemove)
4437 // Check that the and mask is the same as the one we decided to put on the
4438 // new and.
4439 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4440 And->replaceAllUsesWith(NewAnd);
4441 if (&*CurInstIterator == And)
4442 CurInstIterator = std::next(And->getIterator());
4443 And->eraseFromParent();
4444 ++NumAndUses;
4445 }
4446
4447 ++NumAndsAdded;
4448 return true;
4449}
4450
Sanjay Patel69a50a12015-10-19 21:59:12 +00004451/// Check if V (an operand of a select instruction) is an expensive instruction
4452/// that is only used once.
4453static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4454 auto *I = dyn_cast<Instruction>(V);
4455 // If it's safe to speculatively execute, then it should not have side
4456 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004457 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4458 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004459}
4460
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004461/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004462static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
4463 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004464 // FIXME: This should use the same heuristics as IfConversion to determine
4465 // whether a select is better represented as a branch. This requires that
4466 // branch probability metadata is preserved for the select, which is not the
4467 // case currently.
4468
4469 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4470
Sanjay Patel4e652762015-09-28 22:14:51 +00004471 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4472 // comparison condition. If the compare has more than one use, there's
4473 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004474 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004475 return false;
4476
4477 Value *CmpOp0 = Cmp->getOperand(0);
4478 Value *CmpOp1 = Cmp->getOperand(1);
4479
Sanjay Patel4e652762015-09-28 22:14:51 +00004480 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
4481 // on a load from memory. But if the load is used more than once, do not
4482 // change the select to a branch because the load is probably needed
4483 // regardless of whether the branch is taken or not.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004484 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
4485 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
4486 return true;
4487
4488 // If either operand of the select is expensive and only needed on one side
4489 // of the select, we should form a branch.
4490 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4491 sinkSelectOperand(TTI, SI->getFalseValue()))
4492 return true;
4493
4494 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004495}
4496
4497
Nadav Rotem9d832022012-09-02 12:10:19 +00004498/// If we have a SelectInst that will likely profit from branch prediction,
4499/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004500bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00004501 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4502
4503 // Can we convert the 'select' to CF ?
4504 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004505 return false;
4506
Nadav Rotem9d832022012-09-02 12:10:19 +00004507 TargetLowering::SelectSupportKind SelectKind;
4508 if (VectorCond)
4509 SelectKind = TargetLowering::VectorMaskSelect;
4510 else if (SI->getType()->isVectorTy())
4511 SelectKind = TargetLowering::ScalarCondVectorVal;
4512 else
4513 SelectKind = TargetLowering::ScalarValSelect;
4514
4515 // Do we have efficient codegen support for this kind of 'selects' ?
4516 if (TLI->isSelectSupported(SelectKind)) {
4517 // We have efficient codegen support for the select instruction.
4518 // Check if it is profitable to keep this 'select'.
4519 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00004520 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00004521 return false;
4522 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004523
4524 ModifiedDT = true;
4525
Sanjay Patel69a50a12015-10-19 21:59:12 +00004526 // Transform a sequence like this:
4527 // start:
4528 // %cmp = cmp uge i32 %a, %b
4529 // %sel = select i1 %cmp, i32 %c, i32 %d
4530 //
4531 // Into:
4532 // start:
4533 // %cmp = cmp uge i32 %a, %b
4534 // br i1 %cmp, label %select.true, label %select.false
4535 // select.true:
4536 // br label %select.end
4537 // select.false:
4538 // br label %select.end
4539 // select.end:
4540 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4541 //
4542 // In addition, we may sink instructions that produce %c or %d from
4543 // the entry block into the destination(s) of the new branch.
4544 // If the true or false blocks do not contain a sunken instruction, that
4545 // block and its branch may be optimized away. In that case, one side of the
4546 // first branch will point directly to select.end, and the corresponding PHI
4547 // predecessor block will be the start block.
4548
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004549 // First, we split the block containing the select into 2 blocks.
4550 BasicBlock *StartBlock = SI->getParent();
4551 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004552 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004553
Sanjay Patel69a50a12015-10-19 21:59:12 +00004554 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004555 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004556
4557 // These are the new basic blocks for the conditional branch.
4558 // At least one will become an actual new basic block.
4559 BasicBlock *TrueBlock = nullptr;
4560 BasicBlock *FalseBlock = nullptr;
4561
4562 // Sink expensive instructions into the conditional blocks to avoid executing
4563 // them speculatively.
4564 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4565 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4566 EndBlock->getParent(), EndBlock);
4567 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4568 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4569 TrueInst->moveBefore(TrueBranch);
4570 }
4571 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4572 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4573 EndBlock->getParent(), EndBlock);
4574 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4575 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4576 FalseInst->moveBefore(FalseBranch);
4577 }
4578
4579 // If there was nothing to sink, then arbitrarily choose the 'false' side
4580 // for a new input value to the PHI.
4581 if (TrueBlock == FalseBlock) {
4582 assert(TrueBlock == nullptr &&
4583 "Unexpected basic block transform while optimizing select");
4584
4585 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4586 EndBlock->getParent(), EndBlock);
4587 BranchInst::Create(EndBlock, FalseBlock);
4588 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004589
4590 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004591 // If we did not create a new block for one of the 'true' or 'false' paths
4592 // of the condition, it means that side of the branch goes to the end block
4593 // directly and the path originates from the start block from the point of
4594 // view of the new PHI.
4595 if (TrueBlock == nullptr) {
4596 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
4597 TrueBlock = StartBlock;
4598 } else if (FalseBlock == nullptr) {
4599 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4600 FalseBlock = StartBlock;
4601 } else {
4602 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4603 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004604
4605 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004606 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004607 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004608 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4609 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4610
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004611 SI->replaceAllUsesWith(PN);
4612 SI->eraseFromParent();
4613
4614 // Instruct OptimizeBlock to skip to the next block.
4615 CurInstIterator = StartBlock->end();
4616 ++NumSelectsExpanded;
4617 return true;
4618}
4619
Benjamin Kramer573ff362014-03-01 17:24:40 +00004620static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004621 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4622 int SplatElem = -1;
4623 for (unsigned i = 0; i < Mask.size(); ++i) {
4624 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4625 return false;
4626 SplatElem = Mask[i];
4627 }
4628
4629 return true;
4630}
4631
4632/// Some targets have expensive vector shifts if the lanes aren't all the same
4633/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4634/// it's often worth sinking a shufflevector splat down to its use so that
4635/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004636bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004637 BasicBlock *DefBB = SVI->getParent();
4638
4639 // Only do this xform if variable vector shifts are particularly expensive.
4640 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4641 return false;
4642
4643 // We only expect better codegen by sinking a shuffle if we can recognise a
4644 // constant splat.
4645 if (!isBroadcastShuffle(SVI))
4646 return false;
4647
4648 // InsertedShuffles - Only insert a shuffle in each block once.
4649 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4650
4651 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004652 for (User *U : SVI->users()) {
4653 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004654
4655 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004656 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004657 if (UserBB == DefBB) continue;
4658
4659 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004660 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004661
4662 // Everything checks out, sink the shuffle if the user's block doesn't
4663 // already have a copy.
4664 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4665
4666 if (!InsertedShuffle) {
4667 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004668 assert(InsertPt != UserBB->end());
4669 InsertedShuffle =
4670 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4671 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004672 }
4673
Chandler Carruthcdf47882014-03-09 03:16:01 +00004674 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004675 MadeChange = true;
4676 }
4677
4678 // If we removed all uses, nuke the shuffle.
4679 if (SVI->use_empty()) {
4680 SVI->eraseFromParent();
4681 MadeChange = true;
4682 }
4683
4684 return MadeChange;
4685}
4686
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004687bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4688 if (!TLI || !DL)
4689 return false;
4690
4691 Value *Cond = SI->getCondition();
4692 Type *OldType = Cond->getType();
4693 LLVMContext &Context = Cond->getContext();
4694 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4695 unsigned RegWidth = RegType.getSizeInBits();
4696
4697 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4698 return false;
4699
4700 // If the register width is greater than the type width, expand the condition
4701 // of the switch instruction and each case constant to the width of the
4702 // register. By widening the type of the switch condition, subsequent
4703 // comparisons (for case comparisons) will not need to be extended to the
4704 // preferred register width, so we will potentially eliminate N-1 extends,
4705 // where N is the number of cases in the switch.
4706 auto *NewType = Type::getIntNTy(Context, RegWidth);
4707
4708 // Zero-extend the switch condition and case constants unless the switch
4709 // condition is a function argument that is already being sign-extended.
4710 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4711 // everything instead.
4712 Instruction::CastOps ExtType = Instruction::ZExt;
4713 if (auto *Arg = dyn_cast<Argument>(Cond))
4714 if (Arg->hasSExtAttr())
4715 ExtType = Instruction::SExt;
4716
4717 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4718 ExtInst->insertBefore(SI);
4719 SI->setCondition(ExtInst);
4720 for (SwitchInst::CaseIt Case : SI->cases()) {
4721 APInt NarrowConst = Case.getCaseValue()->getValue();
4722 APInt WideConst = (ExtType == Instruction::ZExt) ?
4723 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4724 Case.setValue(ConstantInt::get(Context, WideConst));
4725 }
4726
4727 return true;
4728}
4729
Quentin Colombetc32615d2014-10-31 17:52:53 +00004730namespace {
4731/// \brief Helper class to promote a scalar operation to a vector one.
4732/// This class is used to move downward extractelement transition.
4733/// E.g.,
4734/// a = vector_op <2 x i32>
4735/// b = extractelement <2 x i32> a, i32 0
4736/// c = scalar_op b
4737/// store c
4738///
4739/// =>
4740/// a = vector_op <2 x i32>
4741/// c = vector_op a (equivalent to scalar_op on the related lane)
4742/// * d = extractelement <2 x i32> c, i32 0
4743/// * store d
4744/// Assuming both extractelement and store can be combine, we get rid of the
4745/// transition.
4746class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004747 /// DataLayout associated with the current module.
4748 const DataLayout &DL;
4749
Quentin Colombetc32615d2014-10-31 17:52:53 +00004750 /// Used to perform some checks on the legality of vector operations.
4751 const TargetLowering &TLI;
4752
4753 /// Used to estimated the cost of the promoted chain.
4754 const TargetTransformInfo &TTI;
4755
4756 /// The transition being moved downwards.
4757 Instruction *Transition;
4758 /// The sequence of instructions to be promoted.
4759 SmallVector<Instruction *, 4> InstsToBePromoted;
4760 /// Cost of combining a store and an extract.
4761 unsigned StoreExtractCombineCost;
4762 /// Instruction that will be combined with the transition.
4763 Instruction *CombineInst;
4764
4765 /// \brief The instruction that represents the current end of the transition.
4766 /// Since we are faking the promotion until we reach the end of the chain
4767 /// of computation, we need a way to get the current end of the transition.
4768 Instruction *getEndOfTransition() const {
4769 if (InstsToBePromoted.empty())
4770 return Transition;
4771 return InstsToBePromoted.back();
4772 }
4773
4774 /// \brief Return the index of the original value in the transition.
4775 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4776 /// c, is at index 0.
4777 unsigned getTransitionOriginalValueIdx() const {
4778 assert(isa<ExtractElementInst>(Transition) &&
4779 "Other kind of transitions are not supported yet");
4780 return 0;
4781 }
4782
4783 /// \brief Return the index of the index in the transition.
4784 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4785 /// is at index 1.
4786 unsigned getTransitionIdx() const {
4787 assert(isa<ExtractElementInst>(Transition) &&
4788 "Other kind of transitions are not supported yet");
4789 return 1;
4790 }
4791
4792 /// \brief Get the type of the transition.
4793 /// This is the type of the original value.
4794 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4795 /// transition is <2 x i32>.
4796 Type *getTransitionType() const {
4797 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4798 }
4799
4800 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4801 /// I.e., we have the following sequence:
4802 /// Def = Transition <ty1> a to <ty2>
4803 /// b = ToBePromoted <ty2> Def, ...
4804 /// =>
4805 /// b = ToBePromoted <ty1> a, ...
4806 /// Def = Transition <ty1> ToBePromoted to <ty2>
4807 void promoteImpl(Instruction *ToBePromoted);
4808
4809 /// \brief Check whether or not it is profitable to promote all the
4810 /// instructions enqueued to be promoted.
4811 bool isProfitableToPromote() {
4812 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4813 unsigned Index = isa<ConstantInt>(ValIdx)
4814 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4815 : -1;
4816 Type *PromotedType = getTransitionType();
4817
4818 StoreInst *ST = cast<StoreInst>(CombineInst);
4819 unsigned AS = ST->getPointerAddressSpace();
4820 unsigned Align = ST->getAlignment();
4821 // Check if this store is supported.
4822 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004823 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4824 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004825 // If this is not supported, there is no way we can combine
4826 // the extract with the store.
4827 return false;
4828 }
4829
4830 // The scalar chain of computation has to pay for the transition
4831 // scalar to vector.
4832 // The vector chain has to account for the combining cost.
4833 uint64_t ScalarCost =
4834 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4835 uint64_t VectorCost = StoreExtractCombineCost;
4836 for (const auto &Inst : InstsToBePromoted) {
4837 // Compute the cost.
4838 // By construction, all instructions being promoted are arithmetic ones.
4839 // Moreover, one argument is a constant that can be viewed as a splat
4840 // constant.
4841 Value *Arg0 = Inst->getOperand(0);
4842 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4843 isa<ConstantFP>(Arg0);
4844 TargetTransformInfo::OperandValueKind Arg0OVK =
4845 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4846 : TargetTransformInfo::OK_AnyValue;
4847 TargetTransformInfo::OperandValueKind Arg1OVK =
4848 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4849 : TargetTransformInfo::OK_AnyValue;
4850 ScalarCost += TTI.getArithmeticInstrCost(
4851 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4852 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4853 Arg0OVK, Arg1OVK);
4854 }
4855 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4856 << ScalarCost << "\nVector: " << VectorCost << '\n');
4857 return ScalarCost > VectorCost;
4858 }
4859
4860 /// \brief Generate a constant vector with \p Val with the same
4861 /// number of elements as the transition.
4862 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004863 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004864 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4865 /// otherwise we generate a vector with as many undef as possible:
4866 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4867 /// used at the index of the extract.
4868 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4869 unsigned ExtractIdx = UINT_MAX;
4870 if (!UseSplat) {
4871 // If we cannot determine where the constant must be, we have to
4872 // use a splat constant.
4873 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4874 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4875 ExtractIdx = CstVal->getSExtValue();
4876 else
4877 UseSplat = true;
4878 }
4879
4880 unsigned End = getTransitionType()->getVectorNumElements();
4881 if (UseSplat)
4882 return ConstantVector::getSplat(End, Val);
4883
4884 SmallVector<Constant *, 4> ConstVec;
4885 UndefValue *UndefVal = UndefValue::get(Val->getType());
4886 for (unsigned Idx = 0; Idx != End; ++Idx) {
4887 if (Idx == ExtractIdx)
4888 ConstVec.push_back(Val);
4889 else
4890 ConstVec.push_back(UndefVal);
4891 }
4892 return ConstantVector::get(ConstVec);
4893 }
4894
4895 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4896 /// in \p Use can trigger undefined behavior.
4897 static bool canCauseUndefinedBehavior(const Instruction *Use,
4898 unsigned OperandIdx) {
4899 // This is not safe to introduce undef when the operand is on
4900 // the right hand side of a division-like instruction.
4901 if (OperandIdx != 1)
4902 return false;
4903 switch (Use->getOpcode()) {
4904 default:
4905 return false;
4906 case Instruction::SDiv:
4907 case Instruction::UDiv:
4908 case Instruction::SRem:
4909 case Instruction::URem:
4910 return true;
4911 case Instruction::FDiv:
4912 case Instruction::FRem:
4913 return !Use->hasNoNaNs();
4914 }
4915 llvm_unreachable(nullptr);
4916 }
4917
4918public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004919 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4920 const TargetTransformInfo &TTI, Instruction *Transition,
4921 unsigned CombineCost)
4922 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004923 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4924 assert(Transition && "Do not know how to promote null");
4925 }
4926
4927 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4928 bool canPromote(const Instruction *ToBePromoted) const {
4929 // We could support CastInst too.
4930 return isa<BinaryOperator>(ToBePromoted);
4931 }
4932
4933 /// \brief Check if it is profitable to promote \p ToBePromoted
4934 /// by moving downward the transition through.
4935 bool shouldPromote(const Instruction *ToBePromoted) const {
4936 // Promote only if all the operands can be statically expanded.
4937 // Indeed, we do not want to introduce any new kind of transitions.
4938 for (const Use &U : ToBePromoted->operands()) {
4939 const Value *Val = U.get();
4940 if (Val == getEndOfTransition()) {
4941 // If the use is a division and the transition is on the rhs,
4942 // we cannot promote the operation, otherwise we may create a
4943 // division by zero.
4944 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4945 return false;
4946 continue;
4947 }
4948 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4949 !isa<ConstantFP>(Val))
4950 return false;
4951 }
4952 // Check that the resulting operation is legal.
4953 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4954 if (!ISDOpcode)
4955 return false;
4956 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004957 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004958 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004959 }
4960
4961 /// \brief Check whether or not \p Use can be combined
4962 /// with the transition.
4963 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4964 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4965
4966 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4967 void enqueueForPromotion(Instruction *ToBePromoted) {
4968 InstsToBePromoted.push_back(ToBePromoted);
4969 }
4970
4971 /// \brief Set the instruction that will be combined with the transition.
4972 void recordCombineInstruction(Instruction *ToBeCombined) {
4973 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4974 CombineInst = ToBeCombined;
4975 }
4976
4977 /// \brief Promote all the instructions enqueued for promotion if it is
4978 /// is profitable.
4979 /// \return True if the promotion happened, false otherwise.
4980 bool promote() {
4981 // Check if there is something to promote.
4982 // Right now, if we do not have anything to combine with,
4983 // we assume the promotion is not profitable.
4984 if (InstsToBePromoted.empty() || !CombineInst)
4985 return false;
4986
4987 // Check cost.
4988 if (!StressStoreExtract && !isProfitableToPromote())
4989 return false;
4990
4991 // Promote.
4992 for (auto &ToBePromoted : InstsToBePromoted)
4993 promoteImpl(ToBePromoted);
4994 InstsToBePromoted.clear();
4995 return true;
4996 }
4997};
4998} // End of anonymous namespace.
4999
5000void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5001 // At this point, we know that all the operands of ToBePromoted but Def
5002 // can be statically promoted.
5003 // For Def, we need to use its parameter in ToBePromoted:
5004 // b = ToBePromoted ty1 a
5005 // Def = Transition ty1 b to ty2
5006 // Move the transition down.
5007 // 1. Replace all uses of the promoted operation by the transition.
5008 // = ... b => = ... Def.
5009 assert(ToBePromoted->getType() == Transition->getType() &&
5010 "The type of the result of the transition does not match "
5011 "the final type");
5012 ToBePromoted->replaceAllUsesWith(Transition);
5013 // 2. Update the type of the uses.
5014 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5015 Type *TransitionTy = getTransitionType();
5016 ToBePromoted->mutateType(TransitionTy);
5017 // 3. Update all the operands of the promoted operation with promoted
5018 // operands.
5019 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5020 for (Use &U : ToBePromoted->operands()) {
5021 Value *Val = U.get();
5022 Value *NewVal = nullptr;
5023 if (Val == Transition)
5024 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5025 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5026 isa<ConstantFP>(Val)) {
5027 // Use a splat constant if it is not safe to use undef.
5028 NewVal = getConstantVector(
5029 cast<Constant>(Val),
5030 isa<UndefValue>(Val) ||
5031 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5032 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005033 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5034 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005035 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5036 }
5037 Transition->removeFromParent();
5038 Transition->insertAfter(ToBePromoted);
5039 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5040}
5041
5042/// Some targets can do store(extractelement) with one instruction.
5043/// Try to push the extractelement towards the stores when the target
5044/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005045bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005046 unsigned CombineCost = UINT_MAX;
5047 if (DisableStoreExtract || !TLI ||
5048 (!StressStoreExtract &&
5049 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5050 Inst->getOperand(1), CombineCost)))
5051 return false;
5052
5053 // At this point we know that Inst is a vector to scalar transition.
5054 // Try to move it down the def-use chain, until:
5055 // - We can combine the transition with its single use
5056 // => we got rid of the transition.
5057 // - We escape the current basic block
5058 // => we would need to check that we are moving it at a cheaper place and
5059 // we do not do that for now.
5060 BasicBlock *Parent = Inst->getParent();
5061 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005062 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005063 // If the transition has more than one use, assume this is not going to be
5064 // beneficial.
5065 while (Inst->hasOneUse()) {
5066 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5067 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5068
5069 if (ToBePromoted->getParent() != Parent) {
5070 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5071 << ToBePromoted->getParent()->getName()
5072 << ") than the transition (" << Parent->getName() << ").\n");
5073 return false;
5074 }
5075
5076 if (VPH.canCombine(ToBePromoted)) {
5077 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5078 << "will be combined with: " << *ToBePromoted << '\n');
5079 VPH.recordCombineInstruction(ToBePromoted);
5080 bool Changed = VPH.promote();
5081 NumStoreExtractExposed += Changed;
5082 return Changed;
5083 }
5084
5085 DEBUG(dbgs() << "Try promoting.\n");
5086 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5087 return false;
5088
5089 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5090
5091 VPH.enqueueForPromotion(ToBePromoted);
5092 Inst = ToBePromoted;
5093 }
5094 return false;
5095}
5096
Sanjay Patelfc580a62015-09-21 23:03:16 +00005097bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005098 // Bail out if we inserted the instruction to prevent optimizations from
5099 // stepping on each other's toes.
5100 if (InsertedInsts.count(I))
5101 return false;
5102
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005103 if (PHINode *P = dyn_cast<PHINode>(I)) {
5104 // It is possible for very late stage optimizations (such as SimplifyCFG)
5105 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5106 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005107 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005108 P->replaceAllUsesWith(V);
5109 P->eraseFromParent();
5110 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005111 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005112 }
Chris Lattneree588de2011-01-15 07:29:01 +00005113 return false;
5114 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005115
Chris Lattneree588de2011-01-15 07:29:01 +00005116 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005117 // If the source of the cast is a constant, then this should have
5118 // already been constant folded. The only reason NOT to constant fold
5119 // it is if something (e.g. LSR) was careful to place the constant
5120 // evaluation in a block other than then one that uses it (e.g. to hoist
5121 // the address of globals out of a loop). If this is the case, we don't
5122 // want to forward-subst the cast.
5123 if (isa<Constant>(CI->getOperand(0)))
5124 return false;
5125
Mehdi Amini44ede332015-07-09 02:09:04 +00005126 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005127 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005128
Chris Lattneree588de2011-01-15 07:29:01 +00005129 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005130 /// Sink a zext or sext into its user blocks if the target type doesn't
5131 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005132 if (TLI &&
5133 TLI->getTypeAction(CI->getContext(),
5134 TLI->getValueType(*DL, CI->getType())) ==
5135 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005136 return SinkCast(CI);
5137 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005138 bool MadeChange = moveExtToFormExtLoad(I);
5139 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005140 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005141 }
Chris Lattneree588de2011-01-15 07:29:01 +00005142 return false;
5143 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005144
Chris Lattneree588de2011-01-15 07:29:01 +00005145 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005146 if (!TLI || !TLI->hasMultipleConditionRegisters())
5147 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005148
Chris Lattneree588de2011-01-15 07:29:01 +00005149 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005150 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005151 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005152 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005153 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005154 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5155 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005156 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005157 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005158 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005159
Chris Lattneree588de2011-01-15 07:29:01 +00005160 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005161 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005162 if (TLI) {
5163 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005164 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005165 SI->getOperand(0)->getType(), AS);
5166 }
Chris Lattneree588de2011-01-15 07:29:01 +00005167 return false;
5168 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005169
Yi Jiangd069f632014-04-21 19:34:27 +00005170 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5171
5172 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5173 BinOp->getOpcode() == Instruction::LShr)) {
5174 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5175 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005176 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005177
5178 return false;
5179 }
5180
Chris Lattneree588de2011-01-15 07:29:01 +00005181 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005182 if (GEPI->hasAllZeroIndices()) {
5183 /// The GEP operand must be a pointer, so must its result -> BitCast
5184 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5185 GEPI->getName(), GEPI);
5186 GEPI->replaceAllUsesWith(NC);
5187 GEPI->eraseFromParent();
5188 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005189 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005190 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005191 }
Chris Lattneree588de2011-01-15 07:29:01 +00005192 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005193 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005194
Chris Lattneree588de2011-01-15 07:29:01 +00005195 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005196 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005197
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005198 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005199 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005200
Tim Northoveraeb8e062014-02-19 10:02:43 +00005201 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005202 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005203
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005204 if (auto *Switch = dyn_cast<SwitchInst>(I))
5205 return optimizeSwitchInst(Switch);
5206
Quentin Colombetc32615d2014-10-31 17:52:53 +00005207 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005208 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005209
Chris Lattneree588de2011-01-15 07:29:01 +00005210 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005211}
5212
Chris Lattnerf2836d12007-03-31 04:06:36 +00005213// In this pass we look for GEP and cast instructions that are used
5214// across basic blocks and rewrite them to improve basic-block-at-a-time
5215// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005216bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005217 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005218 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005219
Chris Lattner7a277142011-01-15 07:14:54 +00005220 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005221 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005222 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005223 if (ModifiedDT)
5224 return true;
5225 }
Sanjay Patelfc580a62015-09-21 23:03:16 +00005226 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Benjamin Kramer455fa352012-11-23 19:17:06 +00005227
Chris Lattnerf2836d12007-03-31 04:06:36 +00005228 return MadeChange;
5229}
Devang Patel53771ba2011-08-18 00:50:51 +00005230
5231// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005232// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005233// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005234bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005235 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005236 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005237 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005238 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005239 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005240 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005241 // Leave dbg.values that refer to an alloca alone. These
5242 // instrinsics describe the address of a variable (= the alloca)
5243 // being taken. They should not be moved next to the alloca
5244 // (and to the beginning of the scope), but rather stay close to
5245 // where said address is used.
5246 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005247 PrevNonDbgInst = Insn;
5248 continue;
5249 }
5250
5251 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5252 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005253 // If VI is a phi in a block with an EHPad terminator, we can't insert
5254 // after it.
5255 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5256 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005257 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5258 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005259 if (isa<PHINode>(VI))
5260 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5261 else
5262 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005263 MadeChange = true;
5264 ++NumDbgValueMoved;
5265 }
5266 }
5267 }
5268 return MadeChange;
5269}
Tim Northovercea0abb2014-03-29 08:22:29 +00005270
5271// If there is a sequence that branches based on comparing a single bit
5272// against zero that can be combined into a single instruction, and the
5273// target supports folding these into a single instruction, sink the
5274// mask and compare into the branch uses. Do this before OptimizeBlock ->
5275// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5276// searched for.
5277bool CodeGenPrepare::sinkAndCmp(Function &F) {
5278 if (!EnableAndCmpSinking)
5279 return false;
5280 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5281 return false;
5282 bool MadeChange = false;
5283 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005284 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00005285
5286 // Does this BB end with the following?
5287 // %andVal = and %val, #single-bit-set
5288 // %icmpVal = icmp %andResult, 0
5289 // br i1 %cmpVal label %dest1, label %dest2"
5290 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
5291 if (!Brcc || !Brcc->isConditional())
5292 continue;
5293 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
5294 if (!Cmp || Cmp->getParent() != BB)
5295 continue;
5296 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5297 if (!Zero || !Zero->isZero())
5298 continue;
5299 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
5300 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
5301 continue;
5302 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5303 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5304 continue;
5305 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
5306
5307 // Push the "and; icmp" for any users that are conditional branches.
5308 // Since there can only be one branch use per BB, we don't need to keep
5309 // track of which BBs we insert into.
5310 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
5311 UI != E; ) {
5312 Use &TheUse = *UI;
5313 // Find brcc use.
5314 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
5315 ++UI;
5316 if (!BrccUser || !BrccUser->isConditional())
5317 continue;
5318 BasicBlock *UserBB = BrccUser->getParent();
5319 if (UserBB == BB) continue;
5320 DEBUG(dbgs() << "found Brcc use\n");
5321
5322 // Sink the "and; icmp" to use.
5323 MadeChange = true;
5324 BinaryOperator *NewAnd =
5325 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5326 BrccUser);
5327 CmpInst *NewCmp =
5328 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5329 "", BrccUser);
5330 TheUse = NewCmp;
5331 ++NumAndCmpsMoved;
5332 DEBUG(BrccUser->getParent()->dump());
5333 }
5334 }
5335 return MadeChange;
5336}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005337
Juergen Ributzka194350a2014-12-09 17:32:12 +00005338/// \brief Retrieve the probabilities of a conditional branch. Returns true on
5339/// success, or returns false if no or invalid metadata was found.
5340static bool extractBranchMetadata(BranchInst *BI,
5341 uint64_t &ProbTrue, uint64_t &ProbFalse) {
5342 assert(BI->isConditional() &&
5343 "Looking for probabilities on unconditional branch?");
5344 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
5345 if (!ProfileData || ProfileData->getNumOperands() != 3)
5346 return false;
5347
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005348 const auto *CITrue =
5349 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
5350 const auto *CIFalse =
5351 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00005352 if (!CITrue || !CIFalse)
5353 return false;
5354
5355 ProbTrue = CITrue->getValue().getZExtValue();
5356 ProbFalse = CIFalse->getValue().getZExtValue();
5357
5358 return true;
5359}
5360
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005361/// \brief Scale down both weights to fit into uint32_t.
5362static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5363 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5364 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5365 NewTrue = NewTrue / Scale;
5366 NewFalse = NewFalse / Scale;
5367}
5368
5369/// \brief Some targets prefer to split a conditional branch like:
5370/// \code
5371/// %0 = icmp ne i32 %a, 0
5372/// %1 = icmp ne i32 %b, 0
5373/// %or.cond = or i1 %0, %1
5374/// br i1 %or.cond, label %TrueBB, label %FalseBB
5375/// \endcode
5376/// into multiple branch instructions like:
5377/// \code
5378/// bb1:
5379/// %0 = icmp ne i32 %a, 0
5380/// br i1 %0, label %TrueBB, label %bb2
5381/// bb2:
5382/// %1 = icmp ne i32 %b, 0
5383/// br i1 %1, label %TrueBB, label %FalseBB
5384/// \endcode
5385/// This usually allows instruction selection to do even further optimizations
5386/// and combine the compare with the branch instruction. Currently this is
5387/// applied for targets which have "cheap" jump instructions.
5388///
5389/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5390///
5391bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005392 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005393 return false;
5394
5395 bool MadeChange = false;
5396 for (auto &BB : F) {
5397 // Does this BB end with the following?
5398 // %cond1 = icmp|fcmp|binary instruction ...
5399 // %cond2 = icmp|fcmp|binary instruction ...
5400 // %cond.or = or|and i1 %cond1, cond2
5401 // br i1 %cond.or label %dest1, label %dest2"
5402 BinaryOperator *LogicOp;
5403 BasicBlock *TBB, *FBB;
5404 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5405 continue;
5406
Sanjay Patel42574202015-09-02 19:23:23 +00005407 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5408 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5409 continue;
5410
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005411 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005412 Value *Cond1, *Cond2;
5413 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5414 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005415 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005416 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5417 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005418 Opc = Instruction::Or;
5419 else
5420 continue;
5421
5422 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5423 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5424 continue;
5425
5426 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5427
5428 // Create a new BB.
5429 auto *InsertBefore = std::next(Function::iterator(BB))
5430 .getNodePtrUnchecked();
5431 auto TmpBB = BasicBlock::Create(BB.getContext(),
5432 BB.getName() + ".cond.split",
5433 BB.getParent(), InsertBefore);
5434
5435 // Update original basic block by using the first condition directly by the
5436 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005437 Br1->setCondition(Cond1);
5438 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005439
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005440 // Depending on the conditon we have to either replace the true or the false
5441 // successor of the original branch instruction.
5442 if (Opc == Instruction::And)
5443 Br1->setSuccessor(0, TmpBB);
5444 else
5445 Br1->setSuccessor(1, TmpBB);
5446
5447 // Fill in the new basic block.
5448 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005449 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5450 I->removeFromParent();
5451 I->insertBefore(Br2);
5452 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005453
5454 // Update PHI nodes in both successors. The original BB needs to be
5455 // replaced in one succesor's PHI nodes, because the branch comes now from
5456 // the newly generated BB (NewBB). In the other successor we need to add one
5457 // incoming edge to the PHI nodes, because both branch instructions target
5458 // now the same successor. Depending on the original branch condition
5459 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5460 // we perfrom the correct update for the PHI nodes.
5461 // This doesn't change the successor order of the just created branch
5462 // instruction (or any other instruction).
5463 if (Opc == Instruction::Or)
5464 std::swap(TBB, FBB);
5465
5466 // Replace the old BB with the new BB.
5467 for (auto &I : *TBB) {
5468 PHINode *PN = dyn_cast<PHINode>(&I);
5469 if (!PN)
5470 break;
5471 int i;
5472 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5473 PN->setIncomingBlock(i, TmpBB);
5474 }
5475
5476 // Add another incoming edge form the new BB.
5477 for (auto &I : *FBB) {
5478 PHINode *PN = dyn_cast<PHINode>(&I);
5479 if (!PN)
5480 break;
5481 auto *Val = PN->getIncomingValueForBlock(&BB);
5482 PN->addIncoming(Val, TmpBB);
5483 }
5484
5485 // Update the branch weights (from SelectionDAGBuilder::
5486 // FindMergedConditions).
5487 if (Opc == Instruction::Or) {
5488 // Codegen X | Y as:
5489 // BB1:
5490 // jmp_if_X TBB
5491 // jmp TmpBB
5492 // TmpBB:
5493 // jmp_if_Y TBB
5494 // jmp FBB
5495 //
5496
5497 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5498 // The requirement is that
5499 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5500 // = TrueProb for orignal BB.
5501 // Assuming the orignal weights are A and B, one choice is to set BB1's
5502 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5503 // assumes that
5504 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5505 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5506 // TmpBB, but the math is more complicated.
5507 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005508 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005509 uint64_t NewTrueWeight = TrueWeight;
5510 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5511 scaleWeights(NewTrueWeight, NewFalseWeight);
5512 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5513 .createBranchWeights(TrueWeight, FalseWeight));
5514
5515 NewTrueWeight = TrueWeight;
5516 NewFalseWeight = 2 * FalseWeight;
5517 scaleWeights(NewTrueWeight, NewFalseWeight);
5518 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5519 .createBranchWeights(TrueWeight, FalseWeight));
5520 }
5521 } else {
5522 // Codegen X & Y as:
5523 // BB1:
5524 // jmp_if_X TmpBB
5525 // jmp FBB
5526 // TmpBB:
5527 // jmp_if_Y TBB
5528 // jmp FBB
5529 //
5530 // This requires creation of TmpBB after CurBB.
5531
5532 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5533 // The requirement is that
5534 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5535 // = FalseProb for orignal BB.
5536 // Assuming the orignal weights are A and B, one choice is to set BB1's
5537 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5538 // assumes that
5539 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5540 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005541 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005542 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5543 uint64_t NewFalseWeight = FalseWeight;
5544 scaleWeights(NewTrueWeight, NewFalseWeight);
5545 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5546 .createBranchWeights(TrueWeight, FalseWeight));
5547
5548 NewTrueWeight = 2 * TrueWeight;
5549 NewFalseWeight = FalseWeight;
5550 scaleWeights(NewTrueWeight, NewFalseWeight);
5551 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5552 .createBranchWeights(TrueWeight, FalseWeight));
5553 }
5554 }
5555
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005556 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005557 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005558 ModifiedDT = true;
5559
5560 MadeChange = true;
5561
5562 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5563 TmpBB->dump());
5564 }
5565 return MadeChange;
5566}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005567
5568void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005569 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005570 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5571}