blob: ce6308dd709378d576ba2ce511ecc2ac9461a726 [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.
641 Instruction *ActualRelocatedBase = RelocatedBase;
642 if (RelocatedBase->getType() != Base->getType()) {
643 ActualRelocatedBase =
644 cast<Instruction>(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 Instruction *ReplacementInst = cast<Instruction>(Replacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000649 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000650 // If the newly generated derived pointer's type does not match the original derived
651 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
652 Instruction *ActualReplacement = ReplacementInst;
653 if (ReplacementInst->getType() != ToReplace->getType()) {
654 ActualReplacement =
655 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000656 }
657 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000658 ToReplace->eraseFromParent();
659
660 MadeChange = true;
661 }
662 return MadeChange;
663}
664
665// Turns this:
666//
667// %base = ...
668// %ptr = gep %base + 15
669// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
670// %base' = relocate(%tok, i32 4, i32 4)
671// %ptr' = relocate(%tok, i32 4, i32 5)
672// %val = load %ptr'
673//
674// into this:
675//
676// %base = ...
677// %ptr = gep %base + 15
678// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
679// %base' = gc.relocate(%tok, i32 4, i32 4)
680// %ptr' = gep %base' + 15
681// %val = load %ptr'
682bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
683 bool MadeChange = false;
684 SmallVector<User *, 2> AllRelocateCalls;
685
686 for (auto *U : I.users())
687 if (isGCRelocate(dyn_cast<Instruction>(U)))
688 // Collect all the relocate calls associated with a statepoint
689 AllRelocateCalls.push_back(U);
690
691 // We need atleast one base pointer relocation + one derived pointer
692 // relocation to mangle
693 if (AllRelocateCalls.size() < 2)
694 return false;
695
696 // RelocateInstMap is a mapping from the base relocate instruction to the
697 // corresponding derived relocate instructions
698 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
699 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
700 if (RelocateInstMap.empty())
701 return false;
702
703 for (auto &Item : RelocateInstMap)
704 // Item.first is the RelocatedBase to offset against
705 // Item.second is the vector of Targets to replace
706 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
707 return MadeChange;
708}
709
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000710/// SinkCast - Sink the specified cast instruction into its user blocks
711static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000712 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000713
Chris Lattnerf2836d12007-03-31 04:06:36 +0000714 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000715 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000716
Chris Lattnerf2836d12007-03-31 04:06:36 +0000717 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000718 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000719 UI != E; ) {
720 Use &TheUse = UI.getUse();
721 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000722
Chris Lattnerf2836d12007-03-31 04:06:36 +0000723 // Figure out which BB this cast is used in. For PHI's this is the
724 // appropriate predecessor block.
725 BasicBlock *UserBB = User->getParent();
726 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000727 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000728 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000729
Chris Lattnerf2836d12007-03-31 04:06:36 +0000730 // Preincrement use iterator so we don't invalidate it.
731 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000732
Chris Lattnerf2836d12007-03-31 04:06:36 +0000733 // If this user is in the same block as the cast, don't change the cast.
734 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000735
Chris Lattnerf2836d12007-03-31 04:06:36 +0000736 // If we have already inserted a cast into this block, use it.
737 CastInst *&InsertedCast = InsertedCasts[UserBB];
738
739 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000740 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000741 assert(InsertPt != UserBB->end());
742 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
743 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000744 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000745
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000746 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000747 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000748 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000749 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000750 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000751
Chris Lattnerf2836d12007-03-31 04:06:36 +0000752 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000753 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000754 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000755 MadeChange = true;
756 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000757
Chris Lattnerf2836d12007-03-31 04:06:36 +0000758 return MadeChange;
759}
760
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000761/// If the specified cast instruction is a noop copy (e.g. it's casting from
762/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
763/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000764///
765/// Return true if any changes are made.
766///
Mehdi Amini44ede332015-07-09 02:09:04 +0000767static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
768 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000769 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000770 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
771 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000772
773 // This is an fp<->int conversion?
774 if (SrcVT.isInteger() != DstVT.isInteger())
775 return false;
776
777 // If this is an extension, it will be a zero or sign extension, which
778 // isn't a noop.
779 if (SrcVT.bitsLT(DstVT)) return false;
780
781 // If these values will be promoted, find out what they will be promoted
782 // to. This helps us consider truncates on PPC as noop copies when they
783 // are.
784 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
785 TargetLowering::TypePromoteInteger)
786 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
787 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
788 TargetLowering::TypePromoteInteger)
789 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
790
791 // If, after promotion, these are the same types, this is a noop copy.
792 if (SrcVT != DstVT)
793 return false;
794
795 return SinkCast(CI);
796}
797
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000798/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
799/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000800///
801/// Return true if any changes were made.
802static bool CombineUAddWithOverflow(CmpInst *CI) {
803 Value *A, *B;
804 Instruction *AddI;
805 if (!match(CI,
806 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
807 return false;
808
809 Type *Ty = AddI->getType();
810 if (!isa<IntegerType>(Ty))
811 return false;
812
813 // We don't want to move around uses of condition values this late, so we we
814 // check if it is legal to create the call to the intrinsic in the basic
815 // block containing the icmp:
816
817 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
818 return false;
819
820#ifndef NDEBUG
821 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
822 // for now:
823 if (AddI->hasOneUse())
824 assert(*AddI->user_begin() == CI && "expected!");
825#endif
826
827 Module *M = CI->getParent()->getParent()->getParent();
828 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
829
830 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
831
832 auto *UAddWithOverflow =
833 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
834 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
835 auto *Overflow =
836 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
837
838 CI->replaceAllUsesWith(Overflow);
839 AddI->replaceAllUsesWith(UAdd);
840 CI->eraseFromParent();
841 AddI->eraseFromParent();
842 return true;
843}
844
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000845/// Sink the given CmpInst into user blocks to reduce the number of virtual
846/// registers that must be created and coalesced. This is a clear win except on
847/// targets with multiple condition code registers (PowerPC), where it might
848/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000849///
850/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000851static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000852 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000853
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000854 /// Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000855 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000856
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000857 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000858 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000859 UI != E; ) {
860 Use &TheUse = UI.getUse();
861 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000862
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000863 // Preincrement use iterator so we don't invalidate it.
864 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000865
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000866 // Don't bother for PHI nodes.
867 if (isa<PHINode>(User))
868 continue;
869
870 // Figure out which BB this cmp is used in.
871 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000872
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000873 // If this user is in the same block as the cmp, don't change the cmp.
874 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000875
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000876 // If we have already inserted a cmp into this block, use it.
877 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
878
879 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000880 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000881 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000882 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000883 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
884 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000885 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000886
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000887 // Replace a use of the cmp with a use of the new cmp.
888 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000889 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000890 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000891 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000892
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000893 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000894 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000895 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000896 MadeChange = true;
897 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000898
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000899 return MadeChange;
900}
901
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000902static bool OptimizeCmpExpression(CmpInst *CI) {
903 if (SinkCmpExpression(CI))
904 return true;
905
906 if (CombineUAddWithOverflow(CI))
907 return true;
908
909 return false;
910}
911
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000912/// Check if the candidates could be combined with a shift instruction, which
913/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000914/// 1. Truncate instruction
915/// 2. And instruction and the imm is a mask of the low bits:
916/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000917static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000918 if (!isa<TruncInst>(User)) {
919 if (User->getOpcode() != Instruction::And ||
920 !isa<ConstantInt>(User->getOperand(1)))
921 return false;
922
Quentin Colombetd4f44692014-04-22 01:20:34 +0000923 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000924
Quentin Colombetd4f44692014-04-22 01:20:34 +0000925 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000926 return false;
927 }
928 return true;
929}
930
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000931/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000932static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000933SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
934 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000935 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000936 BasicBlock *UserBB = User->getParent();
937 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
938 TruncInst *TruncI = dyn_cast<TruncInst>(User);
939 bool MadeChange = false;
940
941 for (Value::user_iterator TruncUI = TruncI->user_begin(),
942 TruncE = TruncI->user_end();
943 TruncUI != TruncE;) {
944
945 Use &TruncTheUse = TruncUI.getUse();
946 Instruction *TruncUser = cast<Instruction>(*TruncUI);
947 // Preincrement use iterator so we don't invalidate it.
948
949 ++TruncUI;
950
951 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
952 if (!ISDOpcode)
953 continue;
954
Tim Northovere2239ff2014-07-29 10:20:22 +0000955 // If the use is actually a legal node, there will not be an
956 // implicit truncate.
957 // FIXME: always querying the result type is just an
958 // approximation; some nodes' legality is determined by the
959 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000960 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000961 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000962 continue;
963
964 // Don't bother for PHI nodes.
965 if (isa<PHINode>(TruncUser))
966 continue;
967
968 BasicBlock *TruncUserBB = TruncUser->getParent();
969
970 if (UserBB == TruncUserBB)
971 continue;
972
973 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
974 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
975
976 if (!InsertedShift && !InsertedTrunc) {
977 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000978 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000979 // Sink the shift
980 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000981 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
982 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000983 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000984 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
985 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000986
987 // Sink the trunc
988 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
989 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000990 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000991
992 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000993 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000994
995 MadeChange = true;
996
997 TruncTheUse = InsertedTrunc;
998 }
999 }
1000 return MadeChange;
1001}
1002
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001003/// Sink the shift *right* instruction into user blocks if the uses could
1004/// potentially be combined with this shift instruction and generate BitExtract
1005/// instruction. It will only be applied if the architecture supports BitExtract
1006/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001007/// BB1:
1008/// %x.extract.shift = lshr i64 %arg1, 32
1009/// BB2:
1010/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1011/// ==>
1012///
1013/// BB2:
1014/// %x.extract.shift.1 = lshr i64 %arg1, 32
1015/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1016///
1017/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1018/// instruction.
1019/// Return true if any changes are made.
1020static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001021 const TargetLowering &TLI,
1022 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001023 BasicBlock *DefBB = ShiftI->getParent();
1024
1025 /// Only insert instructions in each block once.
1026 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1027
Mehdi Amini44ede332015-07-09 02:09:04 +00001028 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001029
1030 bool MadeChange = false;
1031 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1032 UI != E;) {
1033 Use &TheUse = UI.getUse();
1034 Instruction *User = cast<Instruction>(*UI);
1035 // Preincrement use iterator so we don't invalidate it.
1036 ++UI;
1037
1038 // Don't bother for PHI nodes.
1039 if (isa<PHINode>(User))
1040 continue;
1041
1042 if (!isExtractBitsCandidateUse(User))
1043 continue;
1044
1045 BasicBlock *UserBB = User->getParent();
1046
1047 if (UserBB == DefBB) {
1048 // If the shift and truncate instruction are in the same BB. The use of
1049 // the truncate(TruncUse) may still introduce another truncate if not
1050 // legal. In this case, we would like to sink both shift and truncate
1051 // instruction to the BB of TruncUse.
1052 // for example:
1053 // BB1:
1054 // i64 shift.result = lshr i64 opnd, imm
1055 // trunc.result = trunc shift.result to i16
1056 //
1057 // BB2:
1058 // ----> We will have an implicit truncate here if the architecture does
1059 // not have i16 compare.
1060 // cmp i16 trunc.result, opnd2
1061 //
1062 if (isa<TruncInst>(User) && shiftIsLegal
1063 // If the type of the truncate is legal, no trucate will be
1064 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001065 &&
1066 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001067 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001068 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001069
1070 continue;
1071 }
1072 // If we have already inserted a shift into this block, use it.
1073 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1074
1075 if (!InsertedShift) {
1076 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001077 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001078
1079 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001080 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1081 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001082 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001083 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1084 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001085
1086 MadeChange = true;
1087 }
1088
1089 // Replace a use of the shift with a use of the new shift.
1090 TheUse = InsertedShift;
1091 }
1092
1093 // If we removed all uses, nuke the shift.
1094 if (ShiftI->use_empty())
1095 ShiftI->eraseFromParent();
1096
1097 return MadeChange;
1098}
1099
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001100// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001101// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1102// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001103// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001104// the appropriate mask bit is set
1105//
1106// %1 = bitcast i8* %addr to i32*
1107// %2 = extractelement <16 x i1> %mask, i32 0
1108// %3 = icmp eq i1 %2, true
1109// br i1 %3, label %cond.load, label %else
1110//
1111//cond.load: ; preds = %0
1112// %4 = getelementptr i32* %1, i32 0
1113// %5 = load i32* %4
1114// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1115// br label %else
1116//
1117//else: ; preds = %0, %cond.load
1118// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1119// %7 = extractelement <16 x i1> %mask, i32 1
1120// %8 = icmp eq i1 %7, true
1121// br i1 %8, label %cond.load1, label %else2
1122//
1123//cond.load1: ; preds = %else
1124// %9 = getelementptr i32* %1, i32 1
1125// %10 = load i32* %9
1126// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1127// br label %else2
1128//
1129//else2: ; preds = %else, %cond.load1
1130// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1131// %12 = extractelement <16 x i1> %mask, i32 2
1132// %13 = icmp eq i1 %12, true
1133// br i1 %13, label %cond.load4, label %else5
1134//
1135static void ScalarizeMaskedLoad(CallInst *CI) {
1136 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001137 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001138 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001139 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001140
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001141 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1142 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001143 assert(VecType && "Unexpected return type of masked load intrinsic");
1144
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001145 Type *EltTy = CI->getType()->getVectorElementType();
1146
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001147 IRBuilder<> Builder(CI->getContext());
1148 Instruction *InsertPt = CI;
1149 BasicBlock *IfBlock = CI->getParent();
1150 BasicBlock *CondBlock = nullptr;
1151 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001152
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001153 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001154 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1155
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001156 // Short-cut if the mask is all-true.
1157 bool IsAllOnesMask = isa<Constant>(Mask) &&
1158 cast<Constant>(Mask)->isAllOnesValue();
1159
1160 if (IsAllOnesMask) {
1161 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1162 CI->replaceAllUsesWith(NewI);
1163 CI->eraseFromParent();
1164 return;
1165 }
1166
1167 // Adjust alignment for the scalar instruction.
1168 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001169 // Bitcast %addr fron i8* to EltTy*
1170 Type *NewPtrType =
1171 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1172 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001173 unsigned VectorWidth = VecType->getNumElements();
1174
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001175 Value *UndefVal = UndefValue::get(VecType);
1176
1177 // The result vector
1178 Value *VResult = UndefVal;
1179
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001180 if (isa<ConstantVector>(Mask)) {
1181 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1182 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1183 continue;
1184 Value *Gep =
1185 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1186 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1187 VResult = Builder.CreateInsertElement(VResult, Load,
1188 Builder.getInt32(Idx));
1189 }
1190 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1191 CI->replaceAllUsesWith(NewI);
1192 CI->eraseFromParent();
1193 return;
1194 }
1195
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001196 PHINode *Phi = nullptr;
1197 Value *PrevPhi = UndefVal;
1198
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001199 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1200
1201 // Fill the "else" block, created in the previous iteration
1202 //
1203 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1204 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1205 // %to_load = icmp eq i1 %mask_1, true
1206 // br i1 %to_load, label %cond.load, label %else
1207 //
1208 if (Idx > 0) {
1209 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1210 Phi->addIncoming(VResult, CondBlock);
1211 Phi->addIncoming(PrevPhi, PrevIfBlock);
1212 PrevPhi = Phi;
1213 VResult = Phi;
1214 }
1215
1216 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1217 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1218 ConstantInt::get(Predicate->getType(), 1));
1219
1220 // Create "cond" block
1221 //
1222 // %EltAddr = getelementptr i32* %1, i32 0
1223 // %Elt = load i32* %EltAddr
1224 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1225 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001226 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001227 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001228
1229 Value *Gep =
1230 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001231 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001232 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1233
1234 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001235 BasicBlock *NewIfBlock =
1236 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001237 Builder.SetInsertPoint(InsertPt);
1238 Instruction *OldBr = IfBlock->getTerminator();
1239 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1240 OldBr->eraseFromParent();
1241 PrevIfBlock = IfBlock;
1242 IfBlock = NewIfBlock;
1243 }
1244
1245 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1246 Phi->addIncoming(VResult, CondBlock);
1247 Phi->addIncoming(PrevPhi, PrevIfBlock);
1248 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1249 CI->replaceAllUsesWith(NewI);
1250 CI->eraseFromParent();
1251}
1252
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001253// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001254// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1255// <16 x i1> %mask)
1256// to a chain of basic blocks, that stores element one-by-one if
1257// the appropriate mask bit is set
1258//
1259// %1 = bitcast i8* %addr to i32*
1260// %2 = extractelement <16 x i1> %mask, i32 0
1261// %3 = icmp eq i1 %2, true
1262// br i1 %3, label %cond.store, label %else
1263//
1264// cond.store: ; preds = %0
1265// %4 = extractelement <16 x i32> %val, i32 0
1266// %5 = getelementptr i32* %1, i32 0
1267// store i32 %4, i32* %5
1268// br label %else
1269//
1270// else: ; preds = %0, %cond.store
1271// %6 = extractelement <16 x i1> %mask, i32 1
1272// %7 = icmp eq i1 %6, true
1273// br i1 %7, label %cond.store1, label %else2
1274//
1275// cond.store1: ; preds = %else
1276// %8 = extractelement <16 x i32> %val, i32 1
1277// %9 = getelementptr i32* %1, i32 1
1278// store i32 %8, i32* %9
1279// br label %else2
1280// . . .
1281static void ScalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001282 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001283 Value *Ptr = CI->getArgOperand(1);
1284 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001285 Value *Mask = CI->getArgOperand(3);
1286
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001287 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001288 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001289 assert(VecType && "Unexpected data type in masked store intrinsic");
1290
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001291 Type *EltTy = VecType->getElementType();
1292
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001293 IRBuilder<> Builder(CI->getContext());
1294 Instruction *InsertPt = CI;
1295 BasicBlock *IfBlock = CI->getParent();
1296 Builder.SetInsertPoint(InsertPt);
1297 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1298
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001299 // Short-cut if the mask is all-true.
1300 bool IsAllOnesMask = isa<Constant>(Mask) &&
1301 cast<Constant>(Mask)->isAllOnesValue();
1302
1303 if (IsAllOnesMask) {
1304 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1305 CI->eraseFromParent();
1306 return;
1307 }
1308
1309 // Adjust alignment for the scalar instruction.
1310 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001311 // Bitcast %addr fron i8* to EltTy*
1312 Type *NewPtrType =
1313 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1314 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001315 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001316
1317 if (isa<ConstantVector>(Mask)) {
1318 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1319 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1320 continue;
1321 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1322 Value *Gep =
1323 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1324 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1325 }
1326 CI->eraseFromParent();
1327 return;
1328 }
1329
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001330 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1331
1332 // Fill the "else" block, created in the previous iteration
1333 //
1334 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1335 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001336 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001337 //
1338 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1339 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1340 ConstantInt::get(Predicate->getType(), 1));
1341
1342 // Create "cond" block
1343 //
1344 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1345 // %EltAddr = getelementptr i32* %1, i32 0
1346 // %store i32 %OneElt, i32* %EltAddr
1347 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001348 BasicBlock *CondBlock =
1349 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001350 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001351
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001352 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001353 Value *Gep =
1354 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001355 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001356
1357 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001358 BasicBlock *NewIfBlock =
1359 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001360 Builder.SetInsertPoint(InsertPt);
1361 Instruction *OldBr = IfBlock->getTerminator();
1362 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1363 OldBr->eraseFromParent();
1364 IfBlock = NewIfBlock;
1365 }
1366 CI->eraseFromParent();
1367}
1368
Elena Demikhovsky09285852015-10-25 15:37:55 +00001369// Translate a masked gather intrinsic like
1370// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1371// <16 x i1> %Mask, <16 x i32> %Src)
1372// to a chain of basic blocks, with loading element one-by-one if
1373// the appropriate mask bit is set
1374//
1375// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1376// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1377// % ToLoad0 = icmp eq i1 % Mask0, true
1378// br i1 % ToLoad0, label %cond.load, label %else
1379//
1380// cond.load:
1381// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1382// % Load0 = load i32, i32* % Ptr0, align 4
1383// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1384// br label %else
1385//
1386// else:
1387// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1388// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1389// % ToLoad1 = icmp eq i1 % Mask1, true
1390// br i1 % ToLoad1, label %cond.load1, label %else2
1391//
1392// cond.load1:
1393// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1394// % Load1 = load i32, i32* % Ptr1, align 4
1395// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1396// br label %else2
1397// . . .
1398// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1399// ret <16 x i32> %Result
1400static void ScalarizeMaskedGather(CallInst *CI) {
1401 Value *Ptrs = CI->getArgOperand(0);
1402 Value *Alignment = CI->getArgOperand(1);
1403 Value *Mask = CI->getArgOperand(2);
1404 Value *Src0 = CI->getArgOperand(3);
1405
1406 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1407
1408 assert(VecType && "Unexpected return type of masked load intrinsic");
1409
1410 IRBuilder<> Builder(CI->getContext());
1411 Instruction *InsertPt = CI;
1412 BasicBlock *IfBlock = CI->getParent();
1413 BasicBlock *CondBlock = nullptr;
1414 BasicBlock *PrevIfBlock = CI->getParent();
1415 Builder.SetInsertPoint(InsertPt);
1416 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1417
1418 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1419
1420 Value *UndefVal = UndefValue::get(VecType);
1421
1422 // The result vector
1423 Value *VResult = UndefVal;
1424 unsigned VectorWidth = VecType->getNumElements();
1425
1426 // Shorten the way if the mask is a vector of constants.
1427 bool IsConstMask = isa<ConstantVector>(Mask);
1428
1429 if (IsConstMask) {
1430 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1431 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1432 continue;
1433 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1434 "Ptr" + Twine(Idx));
1435 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1436 "Load" + Twine(Idx));
1437 VResult = Builder.CreateInsertElement(VResult, Load,
1438 Builder.getInt32(Idx),
1439 "Res" + Twine(Idx));
1440 }
1441 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1442 CI->replaceAllUsesWith(NewI);
1443 CI->eraseFromParent();
1444 return;
1445 }
1446
1447 PHINode *Phi = nullptr;
1448 Value *PrevPhi = UndefVal;
1449
1450 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1451
1452 // Fill the "else" block, created in the previous iteration
1453 //
1454 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1455 // %ToLoad1 = icmp eq i1 %Mask1, true
1456 // br i1 %ToLoad1, label %cond.load, label %else
1457 //
1458 if (Idx > 0) {
1459 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1460 Phi->addIncoming(VResult, CondBlock);
1461 Phi->addIncoming(PrevPhi, PrevIfBlock);
1462 PrevPhi = Phi;
1463 VResult = Phi;
1464 }
1465
1466 Value *Predicate = Builder.CreateExtractElement(Mask,
1467 Builder.getInt32(Idx),
1468 "Mask" + Twine(Idx));
1469 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1470 ConstantInt::get(Predicate->getType(), 1),
1471 "ToLoad" + Twine(Idx));
1472
1473 // Create "cond" block
1474 //
1475 // %EltAddr = getelementptr i32* %1, i32 0
1476 // %Elt = load i32* %EltAddr
1477 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1478 //
1479 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1480 Builder.SetInsertPoint(InsertPt);
1481
1482 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1483 "Ptr" + Twine(Idx));
1484 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1485 "Load" + Twine(Idx));
1486 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1487 "Res" + Twine(Idx));
1488
1489 // Create "else" block, fill it in the next iteration
1490 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1491 Builder.SetInsertPoint(InsertPt);
1492 Instruction *OldBr = IfBlock->getTerminator();
1493 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1494 OldBr->eraseFromParent();
1495 PrevIfBlock = IfBlock;
1496 IfBlock = NewIfBlock;
1497 }
1498
1499 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1500 Phi->addIncoming(VResult, CondBlock);
1501 Phi->addIncoming(PrevPhi, PrevIfBlock);
1502 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1503 CI->replaceAllUsesWith(NewI);
1504 CI->eraseFromParent();
1505}
1506
1507// Translate a masked scatter intrinsic, like
1508// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1509// <16 x i1> %Mask)
1510// to a chain of basic blocks, that stores element one-by-one if
1511// the appropriate mask bit is set.
1512//
1513// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1514// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1515// % ToStore0 = icmp eq i1 % Mask0, true
1516// br i1 %ToStore0, label %cond.store, label %else
1517//
1518// cond.store:
1519// % Elt0 = extractelement <16 x i32> %Src, i32 0
1520// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1521// store i32 %Elt0, i32* % Ptr0, align 4
1522// br label %else
1523//
1524// else:
1525// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1526// % ToStore1 = icmp eq i1 % Mask1, true
1527// br i1 % ToStore1, label %cond.store1, label %else2
1528//
1529// cond.store1:
1530// % Elt1 = extractelement <16 x i32> %Src, i32 1
1531// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1532// store i32 % Elt1, i32* % Ptr1, align 4
1533// br label %else2
1534// . . .
1535static void ScalarizeMaskedScatter(CallInst *CI) {
1536 Value *Src = CI->getArgOperand(0);
1537 Value *Ptrs = CI->getArgOperand(1);
1538 Value *Alignment = CI->getArgOperand(2);
1539 Value *Mask = CI->getArgOperand(3);
1540
1541 assert(isa<VectorType>(Src->getType()) &&
1542 "Unexpected data type in masked scatter intrinsic");
1543 assert(isa<VectorType>(Ptrs->getType()) &&
1544 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1545 "Vector of pointers is expected in masked scatter intrinsic");
1546
1547 IRBuilder<> Builder(CI->getContext());
1548 Instruction *InsertPt = CI;
1549 BasicBlock *IfBlock = CI->getParent();
1550 Builder.SetInsertPoint(InsertPt);
1551 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1552
1553 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1554 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1555
1556 // Shorten the way if the mask is a vector of constants.
1557 bool IsConstMask = isa<ConstantVector>(Mask);
1558
1559 if (IsConstMask) {
1560 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1561 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1562 continue;
1563 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1564 "Elt" + Twine(Idx));
1565 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1566 "Ptr" + Twine(Idx));
1567 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1568 }
1569 CI->eraseFromParent();
1570 return;
1571 }
1572 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1573 // Fill the "else" block, created in the previous iteration
1574 //
1575 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1576 // % ToStore = icmp eq i1 % Mask1, true
1577 // br i1 % ToStore, label %cond.store, label %else
1578 //
1579 Value *Predicate = Builder.CreateExtractElement(Mask,
1580 Builder.getInt32(Idx),
1581 "Mask" + Twine(Idx));
1582 Value *Cmp =
1583 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1584 ConstantInt::get(Predicate->getType(), 1),
1585 "ToStore" + Twine(Idx));
1586
1587 // Create "cond" block
1588 //
1589 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1590 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1591 // %store i32 % Elt1, i32* % Ptr1
1592 //
1593 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1594 Builder.SetInsertPoint(InsertPt);
1595
1596 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1597 "Elt" + Twine(Idx));
1598 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1599 "Ptr" + Twine(Idx));
1600 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1601
1602 // Create "else" block, fill it in the next iteration
1603 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1604 Builder.SetInsertPoint(InsertPt);
1605 Instruction *OldBr = IfBlock->getTerminator();
1606 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1607 OldBr->eraseFromParent();
1608 IfBlock = NewIfBlock;
1609 }
1610 CI->eraseFromParent();
1611}
1612
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001613/// If counting leading or trailing zeros is an expensive operation and a zero
1614/// input is defined, add a check for zero to avoid calling the intrinsic.
1615///
1616/// We want to transform:
1617/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1618///
1619/// into:
1620/// entry:
1621/// %cmpz = icmp eq i64 %A, 0
1622/// br i1 %cmpz, label %cond.end, label %cond.false
1623/// cond.false:
1624/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1625/// br label %cond.end
1626/// cond.end:
1627/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1628///
1629/// If the transform is performed, return true and set ModifiedDT to true.
1630static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1631 const TargetLowering *TLI,
1632 const DataLayout *DL,
1633 bool &ModifiedDT) {
1634 if (!TLI || !DL)
1635 return false;
1636
1637 // If a zero input is undefined, it doesn't make sense to despeculate that.
1638 if (match(CountZeros->getOperand(1), m_One()))
1639 return false;
1640
1641 // If it's cheap to speculate, there's nothing to do.
1642 auto IntrinsicID = CountZeros->getIntrinsicID();
1643 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1644 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1645 return false;
1646
1647 // Only handle legal scalar cases. Anything else requires too much work.
1648 Type *Ty = CountZeros->getType();
1649 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1650 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
1651 return false;
1652
1653 // The intrinsic will be sunk behind a compare against zero and branch.
1654 BasicBlock *StartBlock = CountZeros->getParent();
1655 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1656
1657 // Create another block after the count zero intrinsic. A PHI will be added
1658 // in this block to select the result of the intrinsic or the bit-width
1659 // constant if the input to the intrinsic is zero.
1660 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1661 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1662
1663 // Set up a builder to create a compare, conditional branch, and PHI.
1664 IRBuilder<> Builder(CountZeros->getContext());
1665 Builder.SetInsertPoint(StartBlock->getTerminator());
1666 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1667
1668 // Replace the unconditional branch that was created by the first split with
1669 // a compare against zero and a conditional branch.
1670 Value *Zero = Constant::getNullValue(Ty);
1671 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1672 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1673 StartBlock->getTerminator()->eraseFromParent();
1674
1675 // Create a PHI in the end block to select either the output of the intrinsic
1676 // or the bit width of the operand.
1677 Builder.SetInsertPoint(&EndBlock->front());
1678 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1679 CountZeros->replaceAllUsesWith(PN);
1680 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1681 PN->addIncoming(BitWidth, StartBlock);
1682 PN->addIncoming(CountZeros, CallBlock);
1683
1684 // We are explicitly handling the zero case, so we can set the intrinsic's
1685 // undefined zero argument to 'true'. This will also prevent reprocessing the
1686 // intrinsic; we only despeculate when a zero input is defined.
1687 CountZeros->setArgOperand(1, Builder.getTrue());
1688 ModifiedDT = true;
1689 return true;
1690}
1691
Sanjay Patelfc580a62015-09-21 23:03:16 +00001692bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001693 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001694
Chris Lattner7a277142011-01-15 07:14:54 +00001695 // Lower inline assembly if we can.
1696 // If we found an inline asm expession, and if the target knows how to
1697 // lower it to normal LLVM code, do so now.
1698 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1699 if (TLI->ExpandInlineAsm(CI)) {
1700 // Avoid invalidating the iterator.
1701 CurInstIterator = BB->begin();
1702 // Avoid processing instructions out of order, which could cause
1703 // reuse before a value is defined.
1704 SunkAddrs.clear();
1705 return true;
1706 }
1707 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001708 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001709 return true;
1710 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001711
John Brawn0dbcd652015-03-18 12:01:59 +00001712 // Align the pointer arguments to this call if the target thinks it's a good
1713 // idea
1714 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001715 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001716 for (auto &Arg : CI->arg_operands()) {
1717 // We want to align both objects whose address is used directly and
1718 // objects whose address is used in casts and GEPs, though it only makes
1719 // sense for GEPs if the offset is a multiple of the desired alignment and
1720 // if size - offset meets the size threshold.
1721 if (!Arg->getType()->isPointerTy())
1722 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001723 APInt Offset(DL->getPointerSizeInBits(
1724 cast<PointerType>(Arg->getType())->getAddressSpace()),
1725 0);
1726 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001727 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001728 if ((Offset2 & (PrefAlign-1)) != 0)
1729 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001730 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001731 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1732 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001733 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001734 // Global variables can only be aligned if they are defined in this
1735 // object (i.e. they are uniquely initialized in this object), and
1736 // over-aligning global variables that have an explicit section is
1737 // forbidden.
1738 GlobalVariable *GV;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001739 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1740 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1741 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1742 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001743 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001744 }
1745 // If this is a memcpy (or similar) then we may be able to improve the
1746 // alignment
1747 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001748 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001749 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001750 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001751 if (Align > MI->getAlignment())
1752 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001753 }
1754 }
1755
Eric Christopher4b7948e2010-03-11 02:41:03 +00001756 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001757 if (II) {
1758 switch (II->getIntrinsicID()) {
1759 default: break;
1760 case Intrinsic::objectsize: {
1761 // Lower all uses of llvm.objectsize.*
1762 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1763 Type *ReturnTy = CI->getType();
1764 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001765
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001766 // Substituting this can cause recursive simplifications, which can
1767 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1768 // happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001769 WeakVH IterHandle(&*CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001770
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001771 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001772 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001773
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001774 // If the iterator instruction was recursively deleted, start over at the
1775 // start of the block.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001776 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001777 CurInstIterator = BB->begin();
1778 SunkAddrs.clear();
1779 }
1780 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001781 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001782 case Intrinsic::masked_load: {
1783 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001784 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001785 ScalarizeMaskedLoad(CI);
1786 ModifiedDT = true;
1787 return true;
1788 }
1789 return false;
1790 }
1791 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001792 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001793 ScalarizeMaskedStore(CI);
1794 ModifiedDT = true;
1795 return true;
1796 }
1797 return false;
1798 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001799 case Intrinsic::masked_gather: {
1800 if (!TTI->isLegalMaskedGather(CI->getType())) {
1801 ScalarizeMaskedGather(CI);
1802 ModifiedDT = true;
1803 return true;
1804 }
1805 return false;
1806 }
1807 case Intrinsic::masked_scatter: {
1808 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
1809 ScalarizeMaskedScatter(CI);
1810 ModifiedDT = true;
1811 return true;
1812 }
1813 return false;
1814 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001815 case Intrinsic::aarch64_stlxr:
1816 case Intrinsic::aarch64_stxr: {
1817 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1818 if (!ExtVal || !ExtVal->hasOneUse() ||
1819 ExtVal->getParent() == CI->getParent())
1820 return false;
1821 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1822 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001823 // Mark this instruction as "inserted by CGP", so that other
1824 // optimizations don't touch it.
1825 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001826 return true;
1827 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001828 case Intrinsic::invariant_group_barrier:
1829 II->replaceAllUsesWith(II->getArgOperand(0));
1830 II->eraseFromParent();
1831 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001832
1833 case Intrinsic::cttz:
1834 case Intrinsic::ctlz:
1835 // If counting zeros is expensive, try to avoid it.
1836 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001837 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001838
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001839 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001840 // Unknown address space.
1841 // TODO: Target hook to pick which address space the intrinsic cares
1842 // about?
1843 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001844 SmallVector<Value*, 2> PtrOps;
1845 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001846 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001847 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001848 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001849 return true;
1850 }
Pete Cooper615fd892012-03-13 20:59:56 +00001851 }
1852
Eric Christopher4b7948e2010-03-11 02:41:03 +00001853 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001854 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001855
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001856 // Lower all default uses of _chk calls. This is very similar
1857 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001858 // to fortified library functions (e.g. __memcpy_chk) that have the default
1859 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001860 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001861 if (Value *V = Simplifier.optimizeCall(CI)) {
1862 CI->replaceAllUsesWith(V);
1863 CI->eraseFromParent();
1864 return true;
1865 }
1866 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001867}
Chris Lattner1b93be52011-01-15 07:25:29 +00001868
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001869/// Look for opportunities to duplicate return instructions to the predecessor
1870/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001871/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001872/// bb0:
1873/// %tmp0 = tail call i32 @f0()
1874/// br label %return
1875/// bb1:
1876/// %tmp1 = tail call i32 @f1()
1877/// br label %return
1878/// bb2:
1879/// %tmp2 = tail call i32 @f2()
1880/// br label %return
1881/// return:
1882/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1883/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001884/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001885///
1886/// =>
1887///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001888/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001889/// bb0:
1890/// %tmp0 = tail call i32 @f0()
1891/// ret i32 %tmp0
1892/// bb1:
1893/// %tmp1 = tail call i32 @f1()
1894/// ret i32 %tmp1
1895/// bb2:
1896/// %tmp2 = tail call i32 @f2()
1897/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001898/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001899bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001900 if (!TLI)
1901 return false;
1902
Benjamin Kramer455fa352012-11-23 19:17:06 +00001903 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1904 if (!RI)
1905 return false;
1906
Craig Topperc0196b12014-04-14 00:51:57 +00001907 PHINode *PN = nullptr;
1908 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001909 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001910 if (V) {
1911 BCI = dyn_cast<BitCastInst>(V);
1912 if (BCI)
1913 V = BCI->getOperand(0);
1914
1915 PN = dyn_cast<PHINode>(V);
1916 if (!PN)
1917 return false;
1918 }
Evan Cheng0663f232011-03-21 01:19:09 +00001919
Cameron Zwarich4649f172011-03-24 04:52:10 +00001920 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001921 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001922
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001923 // It's not safe to eliminate the sign / zero extension of the return value.
1924 // See llvm::isInTailCallPosition().
1925 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001926 AttributeSet CallerAttrs = F->getAttributes();
1927 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1928 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001929 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001930
Cameron Zwarich4649f172011-03-24 04:52:10 +00001931 // Make sure there are no instructions between the PHI and return, or that the
1932 // return is the first instruction in the block.
1933 if (PN) {
1934 BasicBlock::iterator BI = BB->begin();
1935 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001936 if (&*BI == BCI)
1937 // Also skip over the bitcast.
1938 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001939 if (&*BI != RI)
1940 return false;
1941 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001942 BasicBlock::iterator BI = BB->begin();
1943 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1944 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001945 return false;
1946 }
Evan Cheng0663f232011-03-21 01:19:09 +00001947
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001948 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1949 /// call.
1950 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001951 if (PN) {
1952 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1953 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1954 // Make sure the phi value is indeed produced by the tail call.
1955 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1956 TLI->mayBeEmittedAsTailCall(CI))
1957 TailCalls.push_back(CI);
1958 }
1959 } else {
1960 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001961 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001962 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001963 continue;
1964
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001965 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001966 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1967 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001968 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1969 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001970 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001971
Cameron Zwarich4649f172011-03-24 04:52:10 +00001972 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001973 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001974 TailCalls.push_back(CI);
1975 }
Evan Cheng0663f232011-03-21 01:19:09 +00001976 }
1977
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001978 bool Changed = false;
1979 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1980 CallInst *CI = TailCalls[i];
1981 CallSite CS(CI);
1982
1983 // Conservatively require the attributes of the call to match those of the
1984 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001985 AttributeSet CalleeAttrs = CS.getAttributes();
1986 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001987 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001988 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001989 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001990 continue;
1991
1992 // Make sure the call instruction is followed by an unconditional branch to
1993 // the return block.
1994 BasicBlock *CallBB = CI->getParent();
1995 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1996 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1997 continue;
1998
1999 // Duplicate the return into CallBB.
2000 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002001 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002002 ++NumRetsDup;
2003 }
2004
2005 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002006 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002007 BB->eraseFromParent();
2008
2009 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002010}
2011
Chris Lattner728f9022008-11-25 07:09:13 +00002012//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002013// Memory Optimization
2014//===----------------------------------------------------------------------===//
2015
Chandler Carruthc8925912013-01-05 02:09:22 +00002016namespace {
2017
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002018/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002019/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002020struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002021 Value *BaseReg;
2022 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002023 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002024 void print(raw_ostream &OS) const;
2025 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002026
Chandler Carruthc8925912013-01-05 02:09:22 +00002027 bool operator==(const ExtAddrMode& O) const {
2028 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2029 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2030 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2031 }
2032};
2033
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002034#ifndef NDEBUG
2035static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2036 AM.print(OS);
2037 return OS;
2038}
2039#endif
2040
Chandler Carruthc8925912013-01-05 02:09:22 +00002041void ExtAddrMode::print(raw_ostream &OS) const {
2042 bool NeedPlus = false;
2043 OS << "[";
2044 if (BaseGV) {
2045 OS << (NeedPlus ? " + " : "")
2046 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002047 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002048 NeedPlus = true;
2049 }
2050
Richard Trieuc0f91212014-05-30 03:15:17 +00002051 if (BaseOffs) {
2052 OS << (NeedPlus ? " + " : "")
2053 << BaseOffs;
2054 NeedPlus = true;
2055 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002056
2057 if (BaseReg) {
2058 OS << (NeedPlus ? " + " : "")
2059 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002060 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002061 NeedPlus = true;
2062 }
2063 if (Scale) {
2064 OS << (NeedPlus ? " + " : "")
2065 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002066 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002067 }
2068
2069 OS << ']';
2070}
2071
2072#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2073void ExtAddrMode::dump() const {
2074 print(dbgs());
2075 dbgs() << '\n';
2076}
2077#endif
2078
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002079/// \brief This class provides transaction based operation on the IR.
2080/// Every change made through this class is recorded in the internal state and
2081/// can be undone (rollback) until commit is called.
2082class TypePromotionTransaction {
2083
2084 /// \brief This represents the common interface of the individual transaction.
2085 /// Each class implements the logic for doing one specific modification on
2086 /// the IR via the TypePromotionTransaction.
2087 class TypePromotionAction {
2088 protected:
2089 /// The Instruction modified.
2090 Instruction *Inst;
2091
2092 public:
2093 /// \brief Constructor of the action.
2094 /// The constructor performs the related action on the IR.
2095 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2096
2097 virtual ~TypePromotionAction() {}
2098
2099 /// \brief Undo the modification done by this action.
2100 /// When this method is called, the IR must be in the same state as it was
2101 /// before this action was applied.
2102 /// \pre Undoing the action works if and only if the IR is in the exact same
2103 /// state as it was directly after this action was applied.
2104 virtual void undo() = 0;
2105
2106 /// \brief Advocate every change made by this action.
2107 /// When the results on the IR of the action are to be kept, it is important
2108 /// to call this function, otherwise hidden information may be kept forever.
2109 virtual void commit() {
2110 // Nothing to be done, this action is not doing anything.
2111 }
2112 };
2113
2114 /// \brief Utility to remember the position of an instruction.
2115 class InsertionHandler {
2116 /// Position of an instruction.
2117 /// Either an instruction:
2118 /// - Is the first in a basic block: BB is used.
2119 /// - Has a previous instructon: PrevInst is used.
2120 union {
2121 Instruction *PrevInst;
2122 BasicBlock *BB;
2123 } Point;
2124 /// Remember whether or not the instruction had a previous instruction.
2125 bool HasPrevInstruction;
2126
2127 public:
2128 /// \brief Record the position of \p Inst.
2129 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002130 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002131 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2132 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002133 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002134 else
2135 Point.BB = Inst->getParent();
2136 }
2137
2138 /// \brief Insert \p Inst at the recorded position.
2139 void insert(Instruction *Inst) {
2140 if (HasPrevInstruction) {
2141 if (Inst->getParent())
2142 Inst->removeFromParent();
2143 Inst->insertAfter(Point.PrevInst);
2144 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002145 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002146 if (Inst->getParent())
2147 Inst->moveBefore(Position);
2148 else
2149 Inst->insertBefore(Position);
2150 }
2151 }
2152 };
2153
2154 /// \brief Move an instruction before another.
2155 class InstructionMoveBefore : public TypePromotionAction {
2156 /// Original position of the instruction.
2157 InsertionHandler Position;
2158
2159 public:
2160 /// \brief Move \p Inst before \p Before.
2161 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2162 : TypePromotionAction(Inst), Position(Inst) {
2163 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2164 Inst->moveBefore(Before);
2165 }
2166
2167 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002168 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002169 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2170 Position.insert(Inst);
2171 }
2172 };
2173
2174 /// \brief Set the operand of an instruction with a new value.
2175 class OperandSetter : public TypePromotionAction {
2176 /// Original operand of the instruction.
2177 Value *Origin;
2178 /// Index of the modified instruction.
2179 unsigned Idx;
2180
2181 public:
2182 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2183 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2184 : TypePromotionAction(Inst), Idx(Idx) {
2185 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2186 << "for:" << *Inst << "\n"
2187 << "with:" << *NewVal << "\n");
2188 Origin = Inst->getOperand(Idx);
2189 Inst->setOperand(Idx, NewVal);
2190 }
2191
2192 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002193 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002194 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2195 << "for: " << *Inst << "\n"
2196 << "with: " << *Origin << "\n");
2197 Inst->setOperand(Idx, Origin);
2198 }
2199 };
2200
2201 /// \brief Hide the operands of an instruction.
2202 /// Do as if this instruction was not using any of its operands.
2203 class OperandsHider : public TypePromotionAction {
2204 /// The list of original operands.
2205 SmallVector<Value *, 4> OriginalValues;
2206
2207 public:
2208 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2209 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2210 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2211 unsigned NumOpnds = Inst->getNumOperands();
2212 OriginalValues.reserve(NumOpnds);
2213 for (unsigned It = 0; It < NumOpnds; ++It) {
2214 // Save the current operand.
2215 Value *Val = Inst->getOperand(It);
2216 OriginalValues.push_back(Val);
2217 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002218 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002219 // that we are not willing to pay.
2220 Inst->setOperand(It, UndefValue::get(Val->getType()));
2221 }
2222 }
2223
2224 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002225 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002226 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2227 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2228 Inst->setOperand(It, OriginalValues[It]);
2229 }
2230 };
2231
2232 /// \brief Build a truncate instruction.
2233 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002234 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002235 public:
2236 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2237 /// result.
2238 /// trunc Opnd to Ty.
2239 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2240 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002241 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2242 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002243 }
2244
Quentin Colombetac55b152014-09-16 22:36:07 +00002245 /// \brief Get the built value.
2246 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002247
2248 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002249 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002250 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2251 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2252 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002253 }
2254 };
2255
2256 /// \brief Build a sign extension instruction.
2257 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002258 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002259 public:
2260 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2261 /// result.
2262 /// sext Opnd to Ty.
2263 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002264 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002265 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002266 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2267 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002268 }
2269
Quentin Colombetac55b152014-09-16 22:36:07 +00002270 /// \brief Get the built value.
2271 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002272
2273 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002274 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002275 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2276 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2277 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002278 }
2279 };
2280
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002281 /// \brief Build a zero extension instruction.
2282 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002283 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002284 public:
2285 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2286 /// result.
2287 /// zext Opnd to Ty.
2288 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002289 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002290 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002291 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2292 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002293 }
2294
Quentin Colombetac55b152014-09-16 22:36:07 +00002295 /// \brief Get the built value.
2296 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002297
2298 /// \brief Remove the built instruction.
2299 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002300 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2301 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2302 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002303 }
2304 };
2305
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002306 /// \brief Mutate an instruction to another type.
2307 class TypeMutator : public TypePromotionAction {
2308 /// Record the original type.
2309 Type *OrigTy;
2310
2311 public:
2312 /// \brief Mutate the type of \p Inst into \p NewTy.
2313 TypeMutator(Instruction *Inst, Type *NewTy)
2314 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2315 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2316 << "\n");
2317 Inst->mutateType(NewTy);
2318 }
2319
2320 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002321 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2323 << "\n");
2324 Inst->mutateType(OrigTy);
2325 }
2326 };
2327
2328 /// \brief Replace the uses of an instruction by another instruction.
2329 class UsesReplacer : public TypePromotionAction {
2330 /// Helper structure to keep track of the replaced uses.
2331 struct InstructionAndIdx {
2332 /// The instruction using the instruction.
2333 Instruction *Inst;
2334 /// The index where this instruction is used for Inst.
2335 unsigned Idx;
2336 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2337 : Inst(Inst), Idx(Idx) {}
2338 };
2339
2340 /// Keep track of the original uses (pair Instruction, Index).
2341 SmallVector<InstructionAndIdx, 4> OriginalUses;
2342 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2343
2344 public:
2345 /// \brief Replace all the use of \p Inst by \p New.
2346 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2347 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2348 << "\n");
2349 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002350 for (Use &U : Inst->uses()) {
2351 Instruction *UserI = cast<Instruction>(U.getUser());
2352 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002353 }
2354 // Now, we can replace the uses.
2355 Inst->replaceAllUsesWith(New);
2356 }
2357
2358 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002359 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002360 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2361 for (use_iterator UseIt = OriginalUses.begin(),
2362 EndIt = OriginalUses.end();
2363 UseIt != EndIt; ++UseIt) {
2364 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2365 }
2366 }
2367 };
2368
2369 /// \brief Remove an instruction from the IR.
2370 class InstructionRemover : public TypePromotionAction {
2371 /// Original position of the instruction.
2372 InsertionHandler Inserter;
2373 /// Helper structure to hide all the link to the instruction. In other
2374 /// words, this helps to do as if the instruction was removed.
2375 OperandsHider Hider;
2376 /// Keep track of the uses replaced, if any.
2377 UsesReplacer *Replacer;
2378
2379 public:
2380 /// \brief Remove all reference of \p Inst and optinally replace all its
2381 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002382 /// \pre If !Inst->use_empty(), then New != nullptr
2383 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002384 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002385 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002386 if (New)
2387 Replacer = new UsesReplacer(Inst, New);
2388 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2389 Inst->removeFromParent();
2390 }
2391
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002392 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002393
2394 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002395 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002396
2397 /// \brief Resurrect the instruction and reassign it to the proper uses if
2398 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002399 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002400 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2401 Inserter.insert(Inst);
2402 if (Replacer)
2403 Replacer->undo();
2404 Hider.undo();
2405 }
2406 };
2407
2408public:
2409 /// Restoration point.
2410 /// The restoration point is a pointer to an action instead of an iterator
2411 /// because the iterator may be invalidated but not the pointer.
2412 typedef const TypePromotionAction *ConstRestorationPt;
2413 /// Advocate every changes made in that transaction.
2414 void commit();
2415 /// Undo all the changes made after the given point.
2416 void rollback(ConstRestorationPt Point);
2417 /// Get the current restoration point.
2418 ConstRestorationPt getRestorationPoint() const;
2419
2420 /// \name API for IR modification with state keeping to support rollback.
2421 /// @{
2422 /// Same as Instruction::setOperand.
2423 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2424 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002425 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002426 /// Same as Value::replaceAllUsesWith.
2427 void replaceAllUsesWith(Instruction *Inst, Value *New);
2428 /// Same as Value::mutateType.
2429 void mutateType(Instruction *Inst, Type *NewTy);
2430 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002431 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002432 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002433 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002434 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002435 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002436 /// Same as Instruction::moveBefore.
2437 void moveBefore(Instruction *Inst, Instruction *Before);
2438 /// @}
2439
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002440private:
2441 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002442 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2443 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002444};
2445
2446void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2447 Value *NewVal) {
2448 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002449 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002450}
2451
2452void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2453 Value *NewVal) {
2454 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002455 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456}
2457
2458void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2459 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002460 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002461}
2462
2463void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002464 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002465}
2466
Quentin Colombetac55b152014-09-16 22:36:07 +00002467Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2468 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002469 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002470 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002471 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002472 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002473}
2474
Quentin Colombetac55b152014-09-16 22:36:07 +00002475Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2476 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002477 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002478 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002479 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002480 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002481}
2482
Quentin Colombetac55b152014-09-16 22:36:07 +00002483Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2484 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002485 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002486 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002487 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002488 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002489}
2490
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002491void TypePromotionTransaction::moveBefore(Instruction *Inst,
2492 Instruction *Before) {
2493 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002494 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002495}
2496
2497TypePromotionTransaction::ConstRestorationPt
2498TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002499 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002500}
2501
2502void TypePromotionTransaction::commit() {
2503 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002504 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002505 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002506 Actions.clear();
2507}
2508
2509void TypePromotionTransaction::rollback(
2510 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002511 while (!Actions.empty() && Point != Actions.back().get()) {
2512 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002513 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002514 }
2515}
2516
Chandler Carruthc8925912013-01-05 02:09:22 +00002517/// \brief A helper class for matching addressing modes.
2518///
2519/// This encapsulates the logic for matching the target-legal addressing modes.
2520class AddressingModeMatcher {
2521 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002522 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002523 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002524 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002525
2526 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2527 /// the memory instruction that we're computing this address for.
2528 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002529 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002530 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002531
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002532 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002533 /// part of the return value of this addressing mode matching stuff.
2534 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002535
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002536 /// The instructions inserted by other CodeGenPrepare optimizations.
2537 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002538 /// A map from the instructions to their type before promotion.
2539 InstrToOrigTy &PromotedInsts;
2540 /// The ongoing transaction where every action should be registered.
2541 TypePromotionTransaction &TPT;
2542
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002543 /// This is set to true when we should not do profitability checks.
2544 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002545 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002546
Eric Christopherd75c00c2015-02-26 22:38:34 +00002547 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002548 const TargetMachine &TM, Type *AT, unsigned AS,
2549 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002550 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002551 InstrToOrigTy &PromotedInsts,
2552 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002553 : AddrModeInsts(AMI), TM(TM),
2554 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2555 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002556 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2557 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2558 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002559 IgnoreProfitability = false;
2560 }
2561public:
Stephen Lin837bba12013-07-15 17:55:02 +00002562
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002563 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002564 /// give an access type of AccessTy. This returns a list of involved
2565 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002566 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002567 /// optimizations.
2568 /// \p PromotedInsts maps the instructions to their type before promotion.
2569 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002570 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002571 Instruction *MemoryInst,
2572 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002573 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002574 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002575 InstrToOrigTy &PromotedInsts,
2576 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002577 ExtAddrMode Result;
2578
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002579 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002580 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002581 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002582 (void)Success; assert(Success && "Couldn't select *anything*?");
2583 return Result;
2584 }
2585private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002586 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2587 bool matchAddr(Value *V, unsigned Depth);
2588 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002589 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002590 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002591 ExtAddrMode &AMBefore,
2592 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002593 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2594 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002595 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002596};
2597
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002598/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002599/// Return true and update AddrMode if this addr mode is legal for the target,
2600/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002601bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002602 unsigned Depth) {
2603 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2604 // mode. Just process that directly.
2605 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002606 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002607
Chandler Carruthc8925912013-01-05 02:09:22 +00002608 // If the scale is 0, it takes nothing to add this.
2609 if (Scale == 0)
2610 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002611
Chandler Carruthc8925912013-01-05 02:09:22 +00002612 // If we already have a scale of this value, we can add to it, otherwise, we
2613 // need an available scale field.
2614 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2615 return false;
2616
2617 ExtAddrMode TestAddrMode = AddrMode;
2618
2619 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2620 // [A+B + A*7] -> [B+A*8].
2621 TestAddrMode.Scale += Scale;
2622 TestAddrMode.ScaledReg = ScaleReg;
2623
2624 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002625 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002626 return false;
2627
2628 // It was legal, so commit it.
2629 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002630
Chandler Carruthc8925912013-01-05 02:09:22 +00002631 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2632 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2633 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002634 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002635 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2636 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2637 TestAddrMode.ScaledReg = AddLHS;
2638 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002639
Chandler Carruthc8925912013-01-05 02:09:22 +00002640 // If this addressing mode is legal, commit it and remember that we folded
2641 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002642 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002643 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2644 AddrMode = TestAddrMode;
2645 return true;
2646 }
2647 }
2648
2649 // Otherwise, not (x+c)*scale, just return what we have.
2650 return true;
2651}
2652
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002653/// This is a little filter, which returns true if an addressing computation
2654/// involving I might be folded into a load/store accessing it.
2655/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002656/// the set of instructions that MatchOperationAddr can.
2657static bool MightBeFoldableInst(Instruction *I) {
2658 switch (I->getOpcode()) {
2659 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002660 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002661 // Don't touch identity bitcasts.
2662 if (I->getType() == I->getOperand(0)->getType())
2663 return false;
2664 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2665 case Instruction::PtrToInt:
2666 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2667 return true;
2668 case Instruction::IntToPtr:
2669 // We know the input is intptr_t, so this is foldable.
2670 return true;
2671 case Instruction::Add:
2672 return true;
2673 case Instruction::Mul:
2674 case Instruction::Shl:
2675 // Can only handle X*C and X << C.
2676 return isa<ConstantInt>(I->getOperand(1));
2677 case Instruction::GetElementPtr:
2678 return true;
2679 default:
2680 return false;
2681 }
2682}
2683
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002684/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2685/// \note \p Val is assumed to be the product of some type promotion.
2686/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2687/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002688static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2689 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002690 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2691 if (!PromotedInst)
2692 return false;
2693 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2694 // If the ISDOpcode is undefined, it was undefined before the promotion.
2695 if (!ISDOpcode)
2696 return true;
2697 // Otherwise, check if the promoted instruction is legal or not.
2698 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002699 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002700}
2701
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002702/// \brief Hepler class to perform type promotion.
2703class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002704 /// \brief Utility function to check whether or not a sign or zero extension
2705 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2706 /// either using the operands of \p Inst or promoting \p Inst.
2707 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002708 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002709 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002710 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002711 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002712 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002713 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002714 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002715 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2716 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002717
2718 /// \brief Utility function to determine if \p OpIdx should be promoted when
2719 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002720 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002721 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002722 }
2723
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002724 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002725 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002726 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002727 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002728 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002729 /// Newly added extensions are inserted in \p Exts.
2730 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002731 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002732 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002733 static Value *promoteOperandForTruncAndAnyExt(
2734 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002735 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002736 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002737 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002738
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002739 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002740 /// operand is promotable and is not a supported trunc or sext.
2741 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002742 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002743 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002744 /// Newly added extensions are inserted in \p Exts.
2745 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002746 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002747 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002748 static Value *promoteOperandForOther(Instruction *Ext,
2749 TypePromotionTransaction &TPT,
2750 InstrToOrigTy &PromotedInsts,
2751 unsigned &CreatedInstsCost,
2752 SmallVectorImpl<Instruction *> *Exts,
2753 SmallVectorImpl<Instruction *> *Truncs,
2754 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002755
2756 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002757 static Value *signExtendOperandForOther(
2758 Instruction *Ext, TypePromotionTransaction &TPT,
2759 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2760 SmallVectorImpl<Instruction *> *Exts,
2761 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2762 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2763 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002764 }
2765
2766 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002767 static Value *zeroExtendOperandForOther(
2768 Instruction *Ext, TypePromotionTransaction &TPT,
2769 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2770 SmallVectorImpl<Instruction *> *Exts,
2771 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2772 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2773 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002774 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002775
2776public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002777 /// Type for the utility function that promotes the operand of Ext.
2778 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002779 InstrToOrigTy &PromotedInsts,
2780 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002781 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002782 SmallVectorImpl<Instruction *> *Truncs,
2783 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002784 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2785 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002786 /// \return NULL if no promotable action is possible with the current
2787 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002788 /// \p InsertedInsts keeps track of all the instructions inserted by the
2789 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002790 /// because we do not want to promote these instructions as CodeGenPrepare
2791 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2792 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002793 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002794 const TargetLowering &TLI,
2795 const InstrToOrigTy &PromotedInsts);
2796};
2797
2798bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002799 Type *ConsideredExtType,
2800 const InstrToOrigTy &PromotedInsts,
2801 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002802 // The promotion helper does not know how to deal with vector types yet.
2803 // To be able to fix that, we would need to fix the places where we
2804 // statically extend, e.g., constants and such.
2805 if (Inst->getType()->isVectorTy())
2806 return false;
2807
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002808 // We can always get through zext.
2809 if (isa<ZExtInst>(Inst))
2810 return true;
2811
2812 // sext(sext) is ok too.
2813 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002814 return true;
2815
2816 // We can get through binary operator, if it is legal. In other words, the
2817 // binary operator must have a nuw or nsw flag.
2818 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2819 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002820 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2821 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002822 return true;
2823
2824 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002825 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002826 if (!isa<TruncInst>(Inst))
2827 return false;
2828
2829 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002830 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002831 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002832 if (!OpndVal->getType()->isIntegerTy() ||
2833 OpndVal->getType()->getIntegerBitWidth() >
2834 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002835 return false;
2836
2837 // If the operand of the truncate is not an instruction, we will not have
2838 // any information on the dropped bits.
2839 // (Actually we could for constant but it is not worth the extra logic).
2840 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2841 if (!Opnd)
2842 return false;
2843
2844 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002845 // I.e., check that trunc just drops extended bits of the same kind of
2846 // the extension.
2847 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002848 const Type *OpndType;
2849 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002850 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2851 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002852 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2853 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002854 else
2855 return false;
2856
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002857 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002858 return Inst->getType()->getIntegerBitWidth() >=
2859 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002860}
2861
2862TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002863 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002864 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002865 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2866 "Unexpected instruction type");
2867 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2868 Type *ExtTy = Ext->getType();
2869 bool IsSExt = isa<SExtInst>(Ext);
2870 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002871 // get through.
2872 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002873 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002874 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002875
2876 // Do not promote if the operand has been added by codegenprepare.
2877 // Otherwise, it means we are undoing an optimization that is likely to be
2878 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002879 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002880 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002881
2882 // SExt or Trunc instructions.
2883 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002884 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2885 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002886 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002887
2888 // Regular instruction.
2889 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002890 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002891 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002892 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002893}
2894
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002895Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002896 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002897 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002898 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002899 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002900 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2901 // get through it and this method should not be called.
2902 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002903 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002904 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002905 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002906 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002907 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002908 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002909 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002910 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2911 TPT.replaceAllUsesWith(SExt, ZExt);
2912 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002913 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002914 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002915 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2916 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002917 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2918 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002919 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002920
2921 // Remove dead code.
2922 if (SExtOpnd->use_empty())
2923 TPT.eraseInstruction(SExtOpnd);
2924
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002925 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002926 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002927 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002928 if (ExtInst) {
2929 if (Exts)
2930 Exts->push_back(ExtInst);
2931 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2932 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002933 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002934 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002935
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002936 // At this point we have: ext ty opnd to ty.
2937 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2938 Value *NextVal = ExtInst->getOperand(0);
2939 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002940 return NextVal;
2941}
2942
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002943Value *TypePromotionHelper::promoteOperandForOther(
2944 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002945 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002946 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002947 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2948 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002949 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002950 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002951 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002952 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002953 if (!ExtOpnd->hasOneUse()) {
2954 // ExtOpnd will be promoted.
2955 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002956 // promoted version.
2957 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002958 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002959 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2960 ITrunc->removeFromParent();
2961 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002962 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002963 if (Truncs)
2964 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002965 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002966
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002967 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002968 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002969 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002970 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002971 }
2972
2973 // Get through the Instruction:
2974 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002975 // 2. Replace the uses of Ext by Inst.
2976 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002977
2978 // Remember the original type of the instruction before promotion.
2979 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002980 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2981 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002982 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002983 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002984 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002985 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002986 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002987 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002988
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002989 DEBUG(dbgs() << "Propagate Ext to operands\n");
2990 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002991 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002992 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2993 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2994 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002995 DEBUG(dbgs() << "No need to propagate\n");
2996 continue;
2997 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002998 // Check if we can statically extend the operand.
2999 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003000 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003001 DEBUG(dbgs() << "Statically extend\n");
3002 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3003 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3004 : Cst->getValue().zext(BitWidth);
3005 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003006 continue;
3007 }
3008 // UndefValue are typed, so we have to statically sign extend them.
3009 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003010 DEBUG(dbgs() << "Statically extend\n");
3011 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003012 continue;
3013 }
3014
3015 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003016 // Check if Ext was reused to extend an operand.
3017 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003018 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003019 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003020 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3021 : TPT.createZExt(Ext, Opnd, Ext->getType());
3022 if (!isa<Instruction>(ValForExtOpnd)) {
3023 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3024 continue;
3025 }
3026 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003027 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003028 if (Exts)
3029 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003030 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003031
3032 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003033 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3034 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003035 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003036 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003037 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003038 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003039 if (ExtForOpnd == Ext) {
3040 DEBUG(dbgs() << "Extension is useless now\n");
3041 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003042 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003043 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003044}
3045
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003046/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003047/// \p NewCost gives the cost of extension instructions created by the
3048/// promotion.
3049/// \p OldCost gives the cost of extension instructions before the promotion
3050/// plus the number of instructions that have been
3051/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003052/// \p PromotedOperand is the value that has been promoted.
3053/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003054bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003055 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3056 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3057 // The cost of the new extensions is greater than the cost of the
3058 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003059 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003060 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003061 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003062 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003063 return true;
3064 // The promotion is neutral but it may help folding the sign extension in
3065 // loads for instance.
3066 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003067 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003068}
3069
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003070/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003071/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003072/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003073/// If \p MovedAway is not NULL, it contains the information of whether or
3074/// not AddrInst has to be folded into the addressing mode on success.
3075/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3076/// because it has been moved away.
3077/// Thus AddrInst must not be added in the matched instructions.
3078/// This state can happen when AddrInst is a sext, since it may be moved away.
3079/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3080/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003081bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003082 unsigned Depth,
3083 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003084 // Avoid exponential behavior on extremely deep expression trees.
3085 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003086
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003087 // By default, all matched instructions stay in place.
3088 if (MovedAway)
3089 *MovedAway = false;
3090
Chandler Carruthc8925912013-01-05 02:09:22 +00003091 switch (Opcode) {
3092 case Instruction::PtrToInt:
3093 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003094 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003095 case Instruction::IntToPtr: {
3096 auto AS = AddrInst->getType()->getPointerAddressSpace();
3097 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003098 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003099 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003100 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003101 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003102 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003103 case Instruction::BitCast:
3104 // BitCast is always a noop, and we can handle it as long as it is
3105 // int->int or pointer->pointer (we don't want int<->fp or something).
3106 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3107 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3108 // Don't touch identity bitcasts. These were probably put here by LSR,
3109 // and we don't want to mess around with them. Assume it knows what it
3110 // is doing.
3111 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003112 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003113 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003114 case Instruction::AddrSpaceCast: {
3115 unsigned SrcAS
3116 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3117 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3118 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003119 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003120 return false;
3121 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003122 case Instruction::Add: {
3123 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3124 ExtAddrMode BackupAddrMode = AddrMode;
3125 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003126 // Start a transaction at this point.
3127 // The LHS may match but not the RHS.
3128 // Therefore, we need a higher level restoration point to undo partially
3129 // matched operation.
3130 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3131 TPT.getRestorationPoint();
3132
Sanjay Patelfc580a62015-09-21 23:03:16 +00003133 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3134 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003135 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003136
Chandler Carruthc8925912013-01-05 02:09:22 +00003137 // Restore the old addr mode info.
3138 AddrMode = BackupAddrMode;
3139 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003140 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003141
Chandler Carruthc8925912013-01-05 02:09:22 +00003142 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003143 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3144 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003145 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003146
Chandler Carruthc8925912013-01-05 02:09:22 +00003147 // Otherwise we definitely can't merge the ADD in.
3148 AddrMode = BackupAddrMode;
3149 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003150 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003151 break;
3152 }
3153 //case Instruction::Or:
3154 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3155 //break;
3156 case Instruction::Mul:
3157 case Instruction::Shl: {
3158 // Can only handle X*C and X << C.
3159 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003160 if (!RHS)
3161 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003162 int64_t Scale = RHS->getSExtValue();
3163 if (Opcode == Instruction::Shl)
3164 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003165
Sanjay Patelfc580a62015-09-21 23:03:16 +00003166 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003167 }
3168 case Instruction::GetElementPtr: {
3169 // Scan the GEP. We check it if it contains constant offsets and at most
3170 // one variable offset.
3171 int VariableOperand = -1;
3172 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003173
Chandler Carruthc8925912013-01-05 02:09:22 +00003174 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003175 gep_type_iterator GTI = gep_type_begin(AddrInst);
3176 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3177 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003178 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003179 unsigned Idx =
3180 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3181 ConstantOffset += SL->getElementOffset(Idx);
3182 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003183 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003184 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3185 ConstantOffset += CI->getSExtValue()*TypeSize;
3186 } else if (TypeSize) { // Scales of zero don't do anything.
3187 // We only allow one variable index at the moment.
3188 if (VariableOperand != -1)
3189 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003190
Chandler Carruthc8925912013-01-05 02:09:22 +00003191 // Remember the variable index.
3192 VariableOperand = i;
3193 VariableScale = TypeSize;
3194 }
3195 }
3196 }
Stephen Lin837bba12013-07-15 17:55:02 +00003197
Chandler Carruthc8925912013-01-05 02:09:22 +00003198 // A common case is for the GEP to only do a constant offset. In this case,
3199 // just add it to the disp field and check validity.
3200 if (VariableOperand == -1) {
3201 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003202 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003203 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003204 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003205 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003206 return true;
3207 }
3208 AddrMode.BaseOffs -= ConstantOffset;
3209 return false;
3210 }
3211
3212 // Save the valid addressing mode in case we can't match.
3213 ExtAddrMode BackupAddrMode = AddrMode;
3214 unsigned OldSize = AddrModeInsts.size();
3215
3216 // See if the scale and offset amount is valid for this target.
3217 AddrMode.BaseOffs += ConstantOffset;
3218
3219 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003220 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003221 // If it couldn't be matched, just stuff the value in a register.
3222 if (AddrMode.HasBaseReg) {
3223 AddrMode = BackupAddrMode;
3224 AddrModeInsts.resize(OldSize);
3225 return false;
3226 }
3227 AddrMode.HasBaseReg = true;
3228 AddrMode.BaseReg = AddrInst->getOperand(0);
3229 }
3230
3231 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003232 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003233 Depth)) {
3234 // If it couldn't be matched, try stuffing the base into a register
3235 // instead of matching it, and retrying the match of the scale.
3236 AddrMode = BackupAddrMode;
3237 AddrModeInsts.resize(OldSize);
3238 if (AddrMode.HasBaseReg)
3239 return false;
3240 AddrMode.HasBaseReg = true;
3241 AddrMode.BaseReg = AddrInst->getOperand(0);
3242 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003243 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003244 VariableScale, Depth)) {
3245 // If even that didn't work, bail.
3246 AddrMode = BackupAddrMode;
3247 AddrModeInsts.resize(OldSize);
3248 return false;
3249 }
3250 }
3251
3252 return true;
3253 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003254 case Instruction::SExt:
3255 case Instruction::ZExt: {
3256 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3257 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003258 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003259
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003260 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003261 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003262 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003263 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003264 if (!TPH)
3265 return false;
3266
3267 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3268 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003269 unsigned CreatedInstsCost = 0;
3270 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003271 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003272 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003273 // SExt has been moved away.
3274 // Thus either it will be rematched later in the recursive calls or it is
3275 // gone. Anyway, we must not fold it into the addressing mode at this point.
3276 // E.g.,
3277 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003278 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003279 // addr = gep base, idx
3280 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003281 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003282 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3283 // addr = gep base, op <- match
3284 if (MovedAway)
3285 *MovedAway = true;
3286
3287 assert(PromotedOperand &&
3288 "TypePromotionHelper should have filtered out those cases");
3289
3290 ExtAddrMode BackupAddrMode = AddrMode;
3291 unsigned OldSize = AddrModeInsts.size();
3292
Sanjay Patelfc580a62015-09-21 23:03:16 +00003293 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003294 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003295 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003296 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003297 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003298 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003299 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003300 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003301 AddrMode = BackupAddrMode;
3302 AddrModeInsts.resize(OldSize);
3303 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3304 TPT.rollback(LastKnownGood);
3305 return false;
3306 }
3307 return true;
3308 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003309 }
3310 return false;
3311}
3312
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003313/// If we can, try to add the value of 'Addr' into the current addressing mode.
3314/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3315/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3316/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003317///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003318bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003319 // Start a transaction at this point that we will rollback if the matching
3320 // fails.
3321 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3322 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003323 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3324 // Fold in immediates if legal for the target.
3325 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003326 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003327 return true;
3328 AddrMode.BaseOffs -= CI->getSExtValue();
3329 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3330 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003331 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003332 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003333 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003334 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003335 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003336 }
3337 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3338 ExtAddrMode BackupAddrMode = AddrMode;
3339 unsigned OldSize = AddrModeInsts.size();
3340
3341 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003342 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003343 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003344 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003345 // to check here.
3346 if (MovedAway)
3347 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003348 // Okay, it's possible to fold this. Check to see if it is actually
3349 // *profitable* to do so. We use a simple cost model to avoid increasing
3350 // register pressure too much.
3351 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003352 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003353 AddrModeInsts.push_back(I);
3354 return true;
3355 }
Stephen Lin837bba12013-07-15 17:55:02 +00003356
Chandler Carruthc8925912013-01-05 02:09:22 +00003357 // It isn't profitable to do this, roll back.
3358 //cerr << "NOT FOLDING: " << *I;
3359 AddrMode = BackupAddrMode;
3360 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003361 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003362 }
3363 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003364 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003365 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003366 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003367 } else if (isa<ConstantPointerNull>(Addr)) {
3368 // Null pointer gets folded without affecting the addressing mode.
3369 return true;
3370 }
3371
3372 // Worse case, the target should support [reg] addressing modes. :)
3373 if (!AddrMode.HasBaseReg) {
3374 AddrMode.HasBaseReg = true;
3375 AddrMode.BaseReg = Addr;
3376 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003377 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003378 return true;
3379 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003380 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003381 }
3382
3383 // If the base register is already taken, see if we can do [r+r].
3384 if (AddrMode.Scale == 0) {
3385 AddrMode.Scale = 1;
3386 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003387 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003388 return true;
3389 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003390 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003391 }
3392 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003393 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003394 return false;
3395}
3396
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003397/// Check to see if all uses of OpVal by the specified inline asm call are due
3398/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003399static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003400 const TargetMachine &TM) {
3401 const Function *F = CI->getParent()->getParent();
3402 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3403 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003404 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003405 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3406 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003407 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3408 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003409
Chandler Carruthc8925912013-01-05 02:09:22 +00003410 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003411 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003412
3413 // If this asm operand is our Value*, and if it isn't an indirect memory
3414 // operand, we can't fold it!
3415 if (OpInfo.CallOperandVal == OpVal &&
3416 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3417 !OpInfo.isIndirect))
3418 return false;
3419 }
3420
3421 return true;
3422}
3423
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003424/// Recursively walk all the uses of I until we find a memory use.
3425/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003426/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003427static bool FindAllMemoryUses(
3428 Instruction *I,
3429 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3430 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003431 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003432 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003433 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003434
Chandler Carruthc8925912013-01-05 02:09:22 +00003435 // If this is an obviously unfoldable instruction, bail out.
3436 if (!MightBeFoldableInst(I))
3437 return true;
3438
3439 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003440 for (Use &U : I->uses()) {
3441 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003442
Chandler Carruthcdf47882014-03-09 03:16:01 +00003443 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3444 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003445 continue;
3446 }
Stephen Lin837bba12013-07-15 17:55:02 +00003447
Chandler Carruthcdf47882014-03-09 03:16:01 +00003448 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3449 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003450 if (opNo == 0) return true; // Storing addr, not into addr.
3451 MemoryUses.push_back(std::make_pair(SI, opNo));
3452 continue;
3453 }
Stephen Lin837bba12013-07-15 17:55:02 +00003454
Chandler Carruthcdf47882014-03-09 03:16:01 +00003455 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003456 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3457 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003458
Chandler Carruthc8925912013-01-05 02:09:22 +00003459 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003460 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003461 return true;
3462 continue;
3463 }
Stephen Lin837bba12013-07-15 17:55:02 +00003464
Eric Christopher11e4df72015-02-26 22:38:43 +00003465 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003466 return true;
3467 }
3468
3469 return false;
3470}
3471
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003472/// Return true if Val is already known to be live at the use site that we're
3473/// folding it into. If so, there is no cost to include it in the addressing
3474/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3475/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003476bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003477 Value *KnownLive2) {
3478 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003479 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003480 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003481
Chandler Carruthc8925912013-01-05 02:09:22 +00003482 // All values other than instructions and arguments (e.g. constants) are live.
3483 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003484
Chandler Carruthc8925912013-01-05 02:09:22 +00003485 // If Val is a constant sized alloca in the entry block, it is live, this is
3486 // true because it is just a reference to the stack/frame pointer, which is
3487 // live for the whole function.
3488 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3489 if (AI->isStaticAlloca())
3490 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003491
Chandler Carruthc8925912013-01-05 02:09:22 +00003492 // Check to see if this value is already used in the memory instruction's
3493 // block. If so, it's already live into the block at the very least, so we
3494 // can reasonably fold it.
3495 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3496}
3497
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003498/// It is possible for the addressing mode of the machine to fold the specified
3499/// instruction into a load or store that ultimately uses it.
3500/// However, the specified instruction has multiple uses.
3501/// Given this, it may actually increase register pressure to fold it
3502/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003503///
3504/// X = ...
3505/// Y = X+1
3506/// use(Y) -> nonload/store
3507/// Z = Y+1
3508/// load Z
3509///
3510/// In this case, Y has multiple uses, and can be folded into the load of Z
3511/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3512/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3513/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3514/// number of computations either.
3515///
3516/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3517/// X was live across 'load Z' for other reasons, we actually *would* want to
3518/// fold the addressing mode in the Z case. This would make Y die earlier.
3519bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003520isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003521 ExtAddrMode &AMAfter) {
3522 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003523
Chandler Carruthc8925912013-01-05 02:09:22 +00003524 // AMBefore is the addressing mode before this instruction was folded into it,
3525 // and AMAfter is the addressing mode after the instruction was folded. Get
3526 // the set of registers referenced by AMAfter and subtract out those
3527 // referenced by AMBefore: this is the set of values which folding in this
3528 // address extends the lifetime of.
3529 //
3530 // Note that there are only two potential values being referenced here,
3531 // BaseReg and ScaleReg (global addresses are always available, as are any
3532 // folded immediates).
3533 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003534
Chandler Carruthc8925912013-01-05 02:09:22 +00003535 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3536 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003537 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003538 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003539 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003540 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003541
3542 // If folding this instruction (and it's subexprs) didn't extend any live
3543 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003544 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003545 return true;
3546
3547 // If all uses of this instruction are ultimately load/store/inlineasm's,
3548 // check to see if their addressing modes will include this instruction. If
3549 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3550 // uses.
3551 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3552 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003553 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003554 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003555
Chandler Carruthc8925912013-01-05 02:09:22 +00003556 // Now that we know that all uses of this instruction are part of a chain of
3557 // computation involving only operations that could theoretically be folded
3558 // into a memory use, loop over each of these uses and see if they could
3559 // *actually* fold the instruction.
3560 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3561 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3562 Instruction *User = MemoryUses[i].first;
3563 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003564
Chandler Carruthc8925912013-01-05 02:09:22 +00003565 // Get the access type of this use. If the use isn't a pointer, we don't
3566 // know what it accesses.
3567 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003568 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3569 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003570 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003571 Type *AddressAccessTy = AddrTy->getElementType();
3572 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003573
Chandler Carruthc8925912013-01-05 02:09:22 +00003574 // Do a match against the root of this address, ignoring profitability. This
3575 // will tell us if the addressing mode for the memory operation will
3576 // *actually* cover the shared instruction.
3577 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003578 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3579 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003580 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003581 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003582 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003583 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003584 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003585 (void)Success; assert(Success && "Couldn't select *anything*?");
3586
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003587 // The match was to check the profitability, the changes made are not
3588 // part of the original matcher. Therefore, they should be dropped
3589 // otherwise the original matcher will not present the right state.
3590 TPT.rollback(LastKnownGood);
3591
Chandler Carruthc8925912013-01-05 02:09:22 +00003592 // If the match didn't cover I, then it won't be shared by it.
3593 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3594 I) == MatchedAddrModeInsts.end())
3595 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003596
Chandler Carruthc8925912013-01-05 02:09:22 +00003597 MatchedAddrModeInsts.clear();
3598 }
Stephen Lin837bba12013-07-15 17:55:02 +00003599
Chandler Carruthc8925912013-01-05 02:09:22 +00003600 return true;
3601}
3602
3603} // end anonymous namespace
3604
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003605/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003606/// different basic block than BB.
3607static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3608 if (Instruction *I = dyn_cast<Instruction>(V))
3609 return I->getParent() != BB;
3610 return false;
3611}
3612
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003613/// Load and Store Instructions often have addressing modes that can do
3614/// significant amounts of computation. As such, instruction selection will try
3615/// to get the load or store to do as much computation as possible for the
3616/// program. The problem is that isel can only see within a single block. As
3617/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003618///
3619/// This method is used to optimize both load/store and inline asms with memory
3620/// operands.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003621bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003622 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003623 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003624
3625 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003626 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003627 SmallVector<Value*, 8> worklist;
3628 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003629 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003630
Owen Anderson8ba5f392010-11-27 08:15:55 +00003631 // Use a worklist to iteratively look through PHI nodes, and ensure that
3632 // the addressing mode obtained from the non-PHI roots of the graph
3633 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003634 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003635 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003636 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003637 SmallVector<Instruction*, 16> AddrModeInsts;
3638 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003639 TypePromotionTransaction TPT;
3640 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3641 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003642 while (!worklist.empty()) {
3643 Value *V = worklist.back();
3644 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003645
Owen Anderson8ba5f392010-11-27 08:15:55 +00003646 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003647 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003648 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003649 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003650 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003651
Owen Anderson8ba5f392010-11-27 08:15:55 +00003652 // For a PHI node, push all of its incoming values.
3653 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003654 for (Value *IncValue : P->incoming_values())
3655 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003656 continue;
3657 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003658
Owen Anderson8ba5f392010-11-27 08:15:55 +00003659 // For non-PHIs, determine the addressing mode being computed.
3660 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003661 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003662 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003663 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003664
3665 // This check is broken into two cases with very similar code to avoid using
3666 // getNumUses() as much as possible. Some values have a lot of uses, so
3667 // calling getNumUses() unconditionally caused a significant compile-time
3668 // regression.
3669 if (!Consensus) {
3670 Consensus = V;
3671 AddrMode = NewAddrMode;
3672 AddrModeInsts = NewAddrModeInsts;
3673 continue;
3674 } else if (NewAddrMode == AddrMode) {
3675 if (!IsNumUsesConsensusValid) {
3676 NumUsesConsensus = Consensus->getNumUses();
3677 IsNumUsesConsensusValid = true;
3678 }
3679
3680 // Ensure that the obtained addressing mode is equivalent to that obtained
3681 // for all other roots of the PHI traversal. Also, when choosing one
3682 // such root as representative, select the one with the most uses in order
3683 // to keep the cost modeling heuristics in AddressingModeMatcher
3684 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003685 unsigned NumUses = V->getNumUses();
3686 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003687 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003688 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003689 AddrModeInsts = NewAddrModeInsts;
3690 }
3691 continue;
3692 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003693
Craig Topperc0196b12014-04-14 00:51:57 +00003694 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003695 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003696 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003697
Owen Anderson8ba5f392010-11-27 08:15:55 +00003698 // If the addressing mode couldn't be determined, or if multiple different
3699 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003700 if (!Consensus) {
3701 TPT.rollback(LastKnownGood);
3702 return false;
3703 }
3704 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003705
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003706 // Check to see if any of the instructions supersumed by this addr mode are
3707 // non-local to I's BB.
3708 bool AnyNonLocal = false;
3709 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003710 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003711 AnyNonLocal = true;
3712 break;
3713 }
3714 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003715
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003716 // If all the instructions matched are already in this BB, don't do anything.
3717 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003718 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003719 return false;
3720 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003721
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003722 // Insert this computation right after this user. Since our caller is
3723 // scanning from the top of the BB to the bottom, reuse of the expr are
3724 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003725 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003726
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003727 // Now that we determined the addressing expression we want to use and know
3728 // that we have to sink it into this block. Check to see if we have already
3729 // done this for some other load/store instr in this block. If so, reuse the
3730 // computation.
3731 Value *&SunkAddr = SunkAddrs[Addr];
3732 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003733 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003734 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003735 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003736 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003737 } else if (AddrSinkUsingGEPs ||
3738 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003739 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3740 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003741 // By default, we use the GEP-based method when AA is used later. This
3742 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3743 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003744 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003745 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003746 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003747
3748 // First, find the pointer.
3749 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3750 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003751 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003752 }
3753
3754 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3755 // We can't add more than one pointer together, nor can we scale a
3756 // pointer (both of which seem meaningless).
3757 if (ResultPtr || AddrMode.Scale != 1)
3758 return false;
3759
3760 ResultPtr = AddrMode.ScaledReg;
3761 AddrMode.Scale = 0;
3762 }
3763
3764 if (AddrMode.BaseGV) {
3765 if (ResultPtr)
3766 return false;
3767
3768 ResultPtr = AddrMode.BaseGV;
3769 }
3770
3771 // If the real base value actually came from an inttoptr, then the matcher
3772 // will look through it and provide only the integer value. In that case,
3773 // use it here.
3774 if (!ResultPtr && AddrMode.BaseReg) {
3775 ResultPtr =
3776 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003777 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003778 } else if (!ResultPtr && AddrMode.Scale == 1) {
3779 ResultPtr =
3780 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3781 AddrMode.Scale = 0;
3782 }
3783
3784 if (!ResultPtr &&
3785 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3786 SunkAddr = Constant::getNullValue(Addr->getType());
3787 } else if (!ResultPtr) {
3788 return false;
3789 } else {
3790 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003791 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3792 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003793
3794 // Start with the base register. Do this first so that subsequent address
3795 // matching finds it last, which will prevent it from trying to match it
3796 // as the scaled value in case it happens to be a mul. That would be
3797 // problematic if we've sunk a different mul for the scale, because then
3798 // we'd end up sinking both muls.
3799 if (AddrMode.BaseReg) {
3800 Value *V = AddrMode.BaseReg;
3801 if (V->getType() != IntPtrTy)
3802 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3803
3804 ResultIndex = V;
3805 }
3806
3807 // Add the scale value.
3808 if (AddrMode.Scale) {
3809 Value *V = AddrMode.ScaledReg;
3810 if (V->getType() == IntPtrTy) {
3811 // done.
3812 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3813 cast<IntegerType>(V->getType())->getBitWidth()) {
3814 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3815 } else {
3816 // It is only safe to sign extend the BaseReg if we know that the math
3817 // required to create it did not overflow before we extend it. Since
3818 // the original IR value was tossed in favor of a constant back when
3819 // the AddrMode was created we need to bail out gracefully if widths
3820 // do not match instead of extending it.
3821 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3822 if (I && (ResultIndex != AddrMode.BaseReg))
3823 I->eraseFromParent();
3824 return false;
3825 }
3826
3827 if (AddrMode.Scale != 1)
3828 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3829 "sunkaddr");
3830 if (ResultIndex)
3831 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3832 else
3833 ResultIndex = V;
3834 }
3835
3836 // Add in the Base Offset if present.
3837 if (AddrMode.BaseOffs) {
3838 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3839 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003840 // We need to add this separately from the scale above to help with
3841 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003842 if (ResultPtr->getType() != I8PtrTy)
3843 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003844 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003845 }
3846
3847 ResultIndex = V;
3848 }
3849
3850 if (!ResultIndex) {
3851 SunkAddr = ResultPtr;
3852 } else {
3853 if (ResultPtr->getType() != I8PtrTy)
3854 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003855 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003856 }
3857
3858 if (SunkAddr->getType() != Addr->getType())
3859 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3860 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003861 } else {
David Greene74e2d492010-01-05 01:27:11 +00003862 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003863 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003864 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003865 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003866
3867 // Start with the base register. Do this first so that subsequent address
3868 // matching finds it last, which will prevent it from trying to match it
3869 // as the scaled value in case it happens to be a mul. That would be
3870 // problematic if we've sunk a different mul for the scale, because then
3871 // we'd end up sinking both muls.
3872 if (AddrMode.BaseReg) {
3873 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003874 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003875 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003876 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003877 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003878 Result = V;
3879 }
3880
3881 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003882 if (AddrMode.Scale) {
3883 Value *V = AddrMode.ScaledReg;
3884 if (V->getType() == IntPtrTy) {
3885 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003886 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003887 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003888 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3889 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003890 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003891 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003892 // It is only safe to sign extend the BaseReg if we know that the math
3893 // required to create it did not overflow before we extend it. Since
3894 // the original IR value was tossed in favor of a constant back when
3895 // the AddrMode was created we need to bail out gracefully if widths
3896 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003897 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003898 if (I && (Result != AddrMode.BaseReg))
3899 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003900 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003901 }
3902 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003903 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3904 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003905 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003906 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003907 else
3908 Result = V;
3909 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003910
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003911 // Add in the BaseGV if present.
3912 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003913 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003914 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003915 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003916 else
3917 Result = V;
3918 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003919
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003920 // Add in the Base Offset if present.
3921 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003922 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003923 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003924 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003925 else
3926 Result = V;
3927 }
3928
Craig Topperc0196b12014-04-14 00:51:57 +00003929 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003930 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003931 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003932 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003933 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003934
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003935 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003936
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003937 // If we have no uses, recursively delete the value and all dead instructions
3938 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003939 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003940 // This can cause recursive deletion, which can invalidate our iterator.
3941 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003942 WeakVH IterHandle(&*CurInstIterator);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003943 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003944
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003945 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003946
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003947 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003948 // If the iterator instruction was recursively deleted, start over at the
3949 // start of the block.
3950 CurInstIterator = BB->begin();
3951 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003952 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003953 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003954 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003955 return true;
3956}
3957
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003958/// If there are any memory operands, use OptimizeMemoryInst to sink their
3959/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003960bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003961 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003962
Eric Christopher11e4df72015-02-26 22:38:43 +00003963 const TargetRegisterInfo *TRI =
3964 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003965 TargetLowering::AsmOperandInfoVector TargetConstraints =
3966 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003967 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003968 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3969 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003970
Evan Cheng1da25002008-02-26 02:42:37 +00003971 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003972 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003973
Eli Friedman666bbe32008-02-26 18:37:49 +00003974 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3975 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003976 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003977 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003978 } else if (OpInfo.Type == InlineAsm::isInput)
3979 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003980 }
3981
3982 return MadeChange;
3983}
3984
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003985/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3986/// sign extensions.
3987static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3988 assert(!Inst->use_empty() && "Input must have at least one use");
3989 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3990 bool IsSExt = isa<SExtInst>(FirstUser);
3991 Type *ExtTy = FirstUser->getType();
3992 for (const User *U : Inst->users()) {
3993 const Instruction *UI = cast<Instruction>(U);
3994 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3995 return false;
3996 Type *CurTy = UI->getType();
3997 // Same input and output types: Same instruction after CSE.
3998 if (CurTy == ExtTy)
3999 continue;
4000
4001 // If IsSExt is true, we are in this situation:
4002 // a = Inst
4003 // b = sext ty1 a to ty2
4004 // c = sext ty1 a to ty3
4005 // Assuming ty2 is shorter than ty3, this could be turned into:
4006 // a = Inst
4007 // b = sext ty1 a to ty2
4008 // c = sext ty2 b to ty3
4009 // However, the last sext is not free.
4010 if (IsSExt)
4011 return false;
4012
4013 // This is a ZExt, maybe this is free to extend from one type to another.
4014 // In that case, we would not account for a different use.
4015 Type *NarrowTy;
4016 Type *LargeTy;
4017 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4018 CurTy->getScalarType()->getIntegerBitWidth()) {
4019 NarrowTy = CurTy;
4020 LargeTy = ExtTy;
4021 } else {
4022 NarrowTy = ExtTy;
4023 LargeTy = CurTy;
4024 }
4025
4026 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4027 return false;
4028 }
4029 // All uses are the same or can be derived from one another for free.
4030 return true;
4031}
4032
4033/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4034/// load instruction.
4035/// If an ext(load) can be formed, it is returned via \p LI for the load
4036/// and \p Inst for the extension.
4037/// Otherwise LI == nullptr and Inst == nullptr.
4038/// When some promotion happened, \p TPT contains the proper state to
4039/// revert them.
4040///
4041/// \return true when promoting was necessary to expose the ext(load)
4042/// opportunity, false otherwise.
4043///
4044/// Example:
4045/// \code
4046/// %ld = load i32* %addr
4047/// %add = add nuw i32 %ld, 4
4048/// %zext = zext i32 %add to i64
4049/// \endcode
4050/// =>
4051/// \code
4052/// %ld = load i32* %addr
4053/// %zext = zext i32 %ld to i64
4054/// %add = add nuw i64 %zext, 4
4055/// \encode
4056/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004057bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004058 LoadInst *&LI, Instruction *&Inst,
4059 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004060 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004061 // Iterate over all the extensions to see if one form an ext(load).
4062 for (auto I : Exts) {
4063 // Check if we directly have ext(load).
4064 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4065 Inst = I;
4066 // No promotion happened here.
4067 return false;
4068 }
4069 // Check whether or not we want to do any promotion.
4070 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4071 continue;
4072 // Get the action to perform the promotion.
4073 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004074 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004075 // Check if we can promote.
4076 if (!TPH)
4077 continue;
4078 // Save the current state.
4079 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4080 TPT.getRestorationPoint();
4081 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004082 unsigned NewCreatedInstsCost = 0;
4083 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004084 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004085 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4086 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004087 assert(PromotedVal &&
4088 "TypePromotionHelper should have filtered out those cases");
4089
4090 // We would be able to merge only one extension in a load.
4091 // Therefore, if we have more than 1 new extension we heuristically
4092 // cut this search path, because it means we degrade the code quality.
4093 // With exactly 2, the transformation is neutral, because we will merge
4094 // one extension but leave one. However, we optimistically keep going,
4095 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004096 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4097 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004098 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004099 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004100 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004101 // The promotion is not profitable, rollback to the previous state.
4102 TPT.rollback(LastKnownGood);
4103 continue;
4104 }
4105 // The promotion is profitable.
4106 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004107 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004108 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004109 // If we have created a new extension, i.e., now we have two
4110 // extensions. We must make sure one of them is merged with
4111 // the load, otherwise we may degrade the code quality.
4112 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4113 // Promotion happened.
4114 return true;
4115 // If this does not help to expose an ext(load) then, rollback.
4116 TPT.rollback(LastKnownGood);
4117 }
4118 // None of the extension can form an ext(load).
4119 LI = nullptr;
4120 Inst = nullptr;
4121 return false;
4122}
4123
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004124/// Move a zext or sext fed by a load into the same basic block as the load,
4125/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4126/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004127/// \p I[in/out] the extension may be modified during the process if some
4128/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004129///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004130bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004131 // Try to promote a chain of computation if it allows to form
4132 // an extended load.
4133 TypePromotionTransaction TPT;
4134 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4135 TPT.getRestorationPoint();
4136 SmallVector<Instruction *, 1> Exts;
4137 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004138 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004139 LoadInst *LI = nullptr;
4140 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004141 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004142 if (!LI || !I) {
4143 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4144 "the code must remain the same");
4145 I = OldExt;
4146 return false;
4147 }
Dan Gohman99429a02009-10-16 20:59:35 +00004148
4149 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004150 // Make the cheap checks first if we did not promote.
4151 // If we promoted, we need to check if it is indeed profitable.
4152 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004153 return false;
4154
Mehdi Amini44ede332015-07-09 02:09:04 +00004155 EVT VT = TLI->getValueType(*DL, I->getType());
4156 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004157
Dan Gohman99429a02009-10-16 20:59:35 +00004158 // If the load has other users and the truncate is not free, this probably
4159 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004160 if (!LI->hasOneUse() && TLI &&
4161 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004162 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4163 I = OldExt;
4164 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004165 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004166 }
Dan Gohman99429a02009-10-16 20:59:35 +00004167
4168 // Check whether the target supports casts folded into loads.
4169 unsigned LType;
4170 if (isa<ZExtInst>(I))
4171 LType = ISD::ZEXTLOAD;
4172 else {
4173 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4174 LType = ISD::SEXTLOAD;
4175 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004176 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004177 I = OldExt;
4178 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004179 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004180 }
Dan Gohman99429a02009-10-16 20:59:35 +00004181
4182 // Move the extend into the same block as the load, so that SelectionDAG
4183 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004184 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004185 I->removeFromParent();
4186 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004187 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004188 return true;
4189}
4190
Sanjay Patelfc580a62015-09-21 23:03:16 +00004191bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004192 BasicBlock *DefBB = I->getParent();
4193
Bob Wilsonff714f92010-09-21 21:44:14 +00004194 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004195 // other uses of the source with result of extension.
4196 Value *Src = I->getOperand(0);
4197 if (Src->hasOneUse())
4198 return false;
4199
Evan Cheng2011df42007-12-13 07:50:36 +00004200 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004201 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004202 return false;
4203
Evan Cheng7bc89422007-12-12 00:51:06 +00004204 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004205 // this block.
4206 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004207 return false;
4208
Evan Chengd3d80172007-12-05 23:58:20 +00004209 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004210 for (User *U : I->users()) {
4211 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004212
4213 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004214 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004215 if (UserBB == DefBB) continue;
4216 DefIsLiveOut = true;
4217 break;
4218 }
4219 if (!DefIsLiveOut)
4220 return false;
4221
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004222 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004223 for (User *U : Src->users()) {
4224 Instruction *UI = cast<Instruction>(U);
4225 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004226 if (UserBB == DefBB) continue;
4227 // Be conservative. We don't want this xform to end up introducing
4228 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004229 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004230 return false;
4231 }
4232
Evan Chengd3d80172007-12-05 23:58:20 +00004233 // InsertedTruncs - Only insert one trunc in each block once.
4234 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4235
4236 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004237 for (Use &U : Src->uses()) {
4238 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004239
4240 // Figure out which BB this ext is used in.
4241 BasicBlock *UserBB = User->getParent();
4242 if (UserBB == DefBB) continue;
4243
4244 // Both src and def are live in this block. Rewrite the use.
4245 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4246
4247 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004248 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004249 assert(InsertPt != UserBB->end());
4250 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004251 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004252 }
4253
4254 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004255 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004256 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004257 MadeChange = true;
4258 }
4259
4260 return MadeChange;
4261}
4262
Geoff Berry5256fca2015-11-20 22:34:39 +00004263// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4264// just after the load if the target can fold this into one extload instruction,
4265// with the hope of eliminating some of the other later "and" instructions using
4266// the loaded value. "and"s that are made trivially redundant by the insertion
4267// of the new "and" are removed by this function, while others (e.g. those whose
4268// path from the load goes through a phi) are left for isel to potentially
4269// remove.
4270//
4271// For example:
4272//
4273// b0:
4274// x = load i32
4275// ...
4276// b1:
4277// y = and x, 0xff
4278// z = use y
4279//
4280// becomes:
4281//
4282// b0:
4283// x = load i32
4284// x' = and x, 0xff
4285// ...
4286// b1:
4287// z = use x'
4288//
4289// whereas:
4290//
4291// b0:
4292// x1 = load i32
4293// ...
4294// b1:
4295// x2 = load i32
4296// ...
4297// b2:
4298// x = phi x1, x2
4299// y = and x, 0xff
4300//
4301// becomes (after a call to optimizeLoadExt for each load):
4302//
4303// b0:
4304// x1 = load i32
4305// x1' = and x1, 0xff
4306// ...
4307// b1:
4308// x2 = load i32
4309// x2' = and x2, 0xff
4310// ...
4311// b2:
4312// x = phi x1', x2'
4313// y = and x, 0xff
4314//
4315
4316bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4317
4318 if (!Load->isSimple() ||
4319 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4320 return false;
4321
4322 // Skip loads we've already transformed or have no reason to transform.
4323 if (Load->hasOneUse()) {
4324 User *LoadUser = *Load->user_begin();
4325 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4326 !dyn_cast<PHINode>(LoadUser))
4327 return false;
4328 }
4329
4330 // Look at all uses of Load, looking through phis, to determine how many bits
4331 // of the loaded value are needed.
4332 SmallVector<Instruction *, 8> WorkList;
4333 SmallPtrSet<Instruction *, 16> Visited;
4334 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4335 for (auto *U : Load->users())
4336 WorkList.push_back(cast<Instruction>(U));
4337
4338 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4339 unsigned BitWidth = LoadResultVT.getSizeInBits();
4340 APInt DemandBits(BitWidth, 0);
4341 APInt WidestAndBits(BitWidth, 0);
4342
4343 while (!WorkList.empty()) {
4344 Instruction *I = WorkList.back();
4345 WorkList.pop_back();
4346
4347 // Break use-def graph loops.
4348 if (!Visited.insert(I).second)
4349 continue;
4350
4351 // For a PHI node, push all of its users.
4352 if (auto *Phi = dyn_cast<PHINode>(I)) {
4353 for (auto *U : Phi->users())
4354 WorkList.push_back(cast<Instruction>(U));
4355 continue;
4356 }
4357
4358 switch (I->getOpcode()) {
4359 case llvm::Instruction::And: {
4360 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4361 if (!AndC)
4362 return false;
4363 APInt AndBits = AndC->getValue();
4364 DemandBits |= AndBits;
4365 // Keep track of the widest and mask we see.
4366 if (AndBits.ugt(WidestAndBits))
4367 WidestAndBits = AndBits;
4368 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4369 AndsToMaybeRemove.push_back(I);
4370 break;
4371 }
4372
4373 case llvm::Instruction::Shl: {
4374 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4375 if (!ShlC)
4376 return false;
4377 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4378 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4379 DemandBits |= ShlDemandBits;
4380 break;
4381 }
4382
4383 case llvm::Instruction::Trunc: {
4384 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4385 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4386 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4387 DemandBits |= TruncBits;
4388 break;
4389 }
4390
4391 default:
4392 return false;
4393 }
4394 }
4395
4396 uint32_t ActiveBits = DemandBits.getActiveBits();
4397 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4398 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4399 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4400 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4401 // followed by an AND.
4402 // TODO: Look into removing this restriction by fixing backends to either
4403 // return false for isLoadExtLegal for i1 or have them select this pattern to
4404 // a single instruction.
4405 //
4406 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4407 // mask, since these are the only ands that will be removed by isel.
4408 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4409 WidestAndBits != DemandBits)
4410 return false;
4411
4412 LLVMContext &Ctx = Load->getType()->getContext();
4413 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4414 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4415
4416 // Reject cases that won't be matched as extloads.
4417 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4418 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4419 return false;
4420
4421 IRBuilder<> Builder(Load->getNextNode());
4422 auto *NewAnd = dyn_cast<Instruction>(
4423 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4424
4425 // Replace all uses of load with new and (except for the use of load in the
4426 // new and itself).
4427 Load->replaceAllUsesWith(NewAnd);
4428 NewAnd->setOperand(0, Load);
4429
4430 // Remove any and instructions that are now redundant.
4431 for (auto *And : AndsToMaybeRemove)
4432 // Check that the and mask is the same as the one we decided to put on the
4433 // new and.
4434 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4435 And->replaceAllUsesWith(NewAnd);
4436 if (&*CurInstIterator == And)
4437 CurInstIterator = std::next(And->getIterator());
4438 And->eraseFromParent();
4439 ++NumAndUses;
4440 }
4441
4442 ++NumAndsAdded;
4443 return true;
4444}
4445
Sanjay Patel69a50a12015-10-19 21:59:12 +00004446/// Check if V (an operand of a select instruction) is an expensive instruction
4447/// that is only used once.
4448static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4449 auto *I = dyn_cast<Instruction>(V);
4450 // If it's safe to speculatively execute, then it should not have side
4451 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004452 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4453 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004454}
4455
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004456/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004457static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
4458 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004459 // FIXME: This should use the same heuristics as IfConversion to determine
4460 // whether a select is better represented as a branch. This requires that
4461 // branch probability metadata is preserved for the select, which is not the
4462 // case currently.
4463
4464 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4465
Sanjay Patel4e652762015-09-28 22:14:51 +00004466 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4467 // comparison condition. If the compare has more than one use, there's
4468 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004469 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004470 return false;
4471
4472 Value *CmpOp0 = Cmp->getOperand(0);
4473 Value *CmpOp1 = Cmp->getOperand(1);
4474
Sanjay Patel4e652762015-09-28 22:14:51 +00004475 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
4476 // on a load from memory. But if the load is used more than once, do not
4477 // change the select to a branch because the load is probably needed
4478 // regardless of whether the branch is taken or not.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004479 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
4480 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
4481 return true;
4482
4483 // If either operand of the select is expensive and only needed on one side
4484 // of the select, we should form a branch.
4485 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4486 sinkSelectOperand(TTI, SI->getFalseValue()))
4487 return true;
4488
4489 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004490}
4491
4492
Nadav Rotem9d832022012-09-02 12:10:19 +00004493/// If we have a SelectInst that will likely profit from branch prediction,
4494/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004495bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00004496 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4497
4498 // Can we convert the 'select' to CF ?
4499 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004500 return false;
4501
Nadav Rotem9d832022012-09-02 12:10:19 +00004502 TargetLowering::SelectSupportKind SelectKind;
4503 if (VectorCond)
4504 SelectKind = TargetLowering::VectorMaskSelect;
4505 else if (SI->getType()->isVectorTy())
4506 SelectKind = TargetLowering::ScalarCondVectorVal;
4507 else
4508 SelectKind = TargetLowering::ScalarValSelect;
4509
4510 // Do we have efficient codegen support for this kind of 'selects' ?
4511 if (TLI->isSelectSupported(SelectKind)) {
4512 // We have efficient codegen support for the select instruction.
4513 // Check if it is profitable to keep this 'select'.
4514 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00004515 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00004516 return false;
4517 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004518
4519 ModifiedDT = true;
4520
Sanjay Patel69a50a12015-10-19 21:59:12 +00004521 // Transform a sequence like this:
4522 // start:
4523 // %cmp = cmp uge i32 %a, %b
4524 // %sel = select i1 %cmp, i32 %c, i32 %d
4525 //
4526 // Into:
4527 // start:
4528 // %cmp = cmp uge i32 %a, %b
4529 // br i1 %cmp, label %select.true, label %select.false
4530 // select.true:
4531 // br label %select.end
4532 // select.false:
4533 // br label %select.end
4534 // select.end:
4535 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4536 //
4537 // In addition, we may sink instructions that produce %c or %d from
4538 // the entry block into the destination(s) of the new branch.
4539 // If the true or false blocks do not contain a sunken instruction, that
4540 // block and its branch may be optimized away. In that case, one side of the
4541 // first branch will point directly to select.end, and the corresponding PHI
4542 // predecessor block will be the start block.
4543
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004544 // First, we split the block containing the select into 2 blocks.
4545 BasicBlock *StartBlock = SI->getParent();
4546 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004547 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004548
Sanjay Patel69a50a12015-10-19 21:59:12 +00004549 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004550 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004551
4552 // These are the new basic blocks for the conditional branch.
4553 // At least one will become an actual new basic block.
4554 BasicBlock *TrueBlock = nullptr;
4555 BasicBlock *FalseBlock = nullptr;
4556
4557 // Sink expensive instructions into the conditional blocks to avoid executing
4558 // them speculatively.
4559 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4560 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4561 EndBlock->getParent(), EndBlock);
4562 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4563 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4564 TrueInst->moveBefore(TrueBranch);
4565 }
4566 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4567 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4568 EndBlock->getParent(), EndBlock);
4569 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4570 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4571 FalseInst->moveBefore(FalseBranch);
4572 }
4573
4574 // If there was nothing to sink, then arbitrarily choose the 'false' side
4575 // for a new input value to the PHI.
4576 if (TrueBlock == FalseBlock) {
4577 assert(TrueBlock == nullptr &&
4578 "Unexpected basic block transform while optimizing select");
4579
4580 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4581 EndBlock->getParent(), EndBlock);
4582 BranchInst::Create(EndBlock, FalseBlock);
4583 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004584
4585 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004586 // If we did not create a new block for one of the 'true' or 'false' paths
4587 // of the condition, it means that side of the branch goes to the end block
4588 // directly and the path originates from the start block from the point of
4589 // view of the new PHI.
4590 if (TrueBlock == nullptr) {
4591 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
4592 TrueBlock = StartBlock;
4593 } else if (FalseBlock == nullptr) {
4594 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4595 FalseBlock = StartBlock;
4596 } else {
4597 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4598 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004599
4600 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004601 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004602 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004603 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4604 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4605
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004606 SI->replaceAllUsesWith(PN);
4607 SI->eraseFromParent();
4608
4609 // Instruct OptimizeBlock to skip to the next block.
4610 CurInstIterator = StartBlock->end();
4611 ++NumSelectsExpanded;
4612 return true;
4613}
4614
Benjamin Kramer573ff362014-03-01 17:24:40 +00004615static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004616 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4617 int SplatElem = -1;
4618 for (unsigned i = 0; i < Mask.size(); ++i) {
4619 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4620 return false;
4621 SplatElem = Mask[i];
4622 }
4623
4624 return true;
4625}
4626
4627/// Some targets have expensive vector shifts if the lanes aren't all the same
4628/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4629/// it's often worth sinking a shufflevector splat down to its use so that
4630/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004631bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004632 BasicBlock *DefBB = SVI->getParent();
4633
4634 // Only do this xform if variable vector shifts are particularly expensive.
4635 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4636 return false;
4637
4638 // We only expect better codegen by sinking a shuffle if we can recognise a
4639 // constant splat.
4640 if (!isBroadcastShuffle(SVI))
4641 return false;
4642
4643 // InsertedShuffles - Only insert a shuffle in each block once.
4644 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4645
4646 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004647 for (User *U : SVI->users()) {
4648 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004649
4650 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004651 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004652 if (UserBB == DefBB) continue;
4653
4654 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004655 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004656
4657 // Everything checks out, sink the shuffle if the user's block doesn't
4658 // already have a copy.
4659 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4660
4661 if (!InsertedShuffle) {
4662 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004663 assert(InsertPt != UserBB->end());
4664 InsertedShuffle =
4665 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4666 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004667 }
4668
Chandler Carruthcdf47882014-03-09 03:16:01 +00004669 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004670 MadeChange = true;
4671 }
4672
4673 // If we removed all uses, nuke the shuffle.
4674 if (SVI->use_empty()) {
4675 SVI->eraseFromParent();
4676 MadeChange = true;
4677 }
4678
4679 return MadeChange;
4680}
4681
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004682bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4683 if (!TLI || !DL)
4684 return false;
4685
4686 Value *Cond = SI->getCondition();
4687 Type *OldType = Cond->getType();
4688 LLVMContext &Context = Cond->getContext();
4689 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4690 unsigned RegWidth = RegType.getSizeInBits();
4691
4692 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4693 return false;
4694
4695 // If the register width is greater than the type width, expand the condition
4696 // of the switch instruction and each case constant to the width of the
4697 // register. By widening the type of the switch condition, subsequent
4698 // comparisons (for case comparisons) will not need to be extended to the
4699 // preferred register width, so we will potentially eliminate N-1 extends,
4700 // where N is the number of cases in the switch.
4701 auto *NewType = Type::getIntNTy(Context, RegWidth);
4702
4703 // Zero-extend the switch condition and case constants unless the switch
4704 // condition is a function argument that is already being sign-extended.
4705 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4706 // everything instead.
4707 Instruction::CastOps ExtType = Instruction::ZExt;
4708 if (auto *Arg = dyn_cast<Argument>(Cond))
4709 if (Arg->hasSExtAttr())
4710 ExtType = Instruction::SExt;
4711
4712 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4713 ExtInst->insertBefore(SI);
4714 SI->setCondition(ExtInst);
4715 for (SwitchInst::CaseIt Case : SI->cases()) {
4716 APInt NarrowConst = Case.getCaseValue()->getValue();
4717 APInt WideConst = (ExtType == Instruction::ZExt) ?
4718 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4719 Case.setValue(ConstantInt::get(Context, WideConst));
4720 }
4721
4722 return true;
4723}
4724
Quentin Colombetc32615d2014-10-31 17:52:53 +00004725namespace {
4726/// \brief Helper class to promote a scalar operation to a vector one.
4727/// This class is used to move downward extractelement transition.
4728/// E.g.,
4729/// a = vector_op <2 x i32>
4730/// b = extractelement <2 x i32> a, i32 0
4731/// c = scalar_op b
4732/// store c
4733///
4734/// =>
4735/// a = vector_op <2 x i32>
4736/// c = vector_op a (equivalent to scalar_op on the related lane)
4737/// * d = extractelement <2 x i32> c, i32 0
4738/// * store d
4739/// Assuming both extractelement and store can be combine, we get rid of the
4740/// transition.
4741class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004742 /// DataLayout associated with the current module.
4743 const DataLayout &DL;
4744
Quentin Colombetc32615d2014-10-31 17:52:53 +00004745 /// Used to perform some checks on the legality of vector operations.
4746 const TargetLowering &TLI;
4747
4748 /// Used to estimated the cost of the promoted chain.
4749 const TargetTransformInfo &TTI;
4750
4751 /// The transition being moved downwards.
4752 Instruction *Transition;
4753 /// The sequence of instructions to be promoted.
4754 SmallVector<Instruction *, 4> InstsToBePromoted;
4755 /// Cost of combining a store and an extract.
4756 unsigned StoreExtractCombineCost;
4757 /// Instruction that will be combined with the transition.
4758 Instruction *CombineInst;
4759
4760 /// \brief The instruction that represents the current end of the transition.
4761 /// Since we are faking the promotion until we reach the end of the chain
4762 /// of computation, we need a way to get the current end of the transition.
4763 Instruction *getEndOfTransition() const {
4764 if (InstsToBePromoted.empty())
4765 return Transition;
4766 return InstsToBePromoted.back();
4767 }
4768
4769 /// \brief Return the index of the original value in the transition.
4770 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4771 /// c, is at index 0.
4772 unsigned getTransitionOriginalValueIdx() const {
4773 assert(isa<ExtractElementInst>(Transition) &&
4774 "Other kind of transitions are not supported yet");
4775 return 0;
4776 }
4777
4778 /// \brief Return the index of the index in the transition.
4779 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4780 /// is at index 1.
4781 unsigned getTransitionIdx() const {
4782 assert(isa<ExtractElementInst>(Transition) &&
4783 "Other kind of transitions are not supported yet");
4784 return 1;
4785 }
4786
4787 /// \brief Get the type of the transition.
4788 /// This is the type of the original value.
4789 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4790 /// transition is <2 x i32>.
4791 Type *getTransitionType() const {
4792 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4793 }
4794
4795 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4796 /// I.e., we have the following sequence:
4797 /// Def = Transition <ty1> a to <ty2>
4798 /// b = ToBePromoted <ty2> Def, ...
4799 /// =>
4800 /// b = ToBePromoted <ty1> a, ...
4801 /// Def = Transition <ty1> ToBePromoted to <ty2>
4802 void promoteImpl(Instruction *ToBePromoted);
4803
4804 /// \brief Check whether or not it is profitable to promote all the
4805 /// instructions enqueued to be promoted.
4806 bool isProfitableToPromote() {
4807 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4808 unsigned Index = isa<ConstantInt>(ValIdx)
4809 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4810 : -1;
4811 Type *PromotedType = getTransitionType();
4812
4813 StoreInst *ST = cast<StoreInst>(CombineInst);
4814 unsigned AS = ST->getPointerAddressSpace();
4815 unsigned Align = ST->getAlignment();
4816 // Check if this store is supported.
4817 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004818 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4819 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004820 // If this is not supported, there is no way we can combine
4821 // the extract with the store.
4822 return false;
4823 }
4824
4825 // The scalar chain of computation has to pay for the transition
4826 // scalar to vector.
4827 // The vector chain has to account for the combining cost.
4828 uint64_t ScalarCost =
4829 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4830 uint64_t VectorCost = StoreExtractCombineCost;
4831 for (const auto &Inst : InstsToBePromoted) {
4832 // Compute the cost.
4833 // By construction, all instructions being promoted are arithmetic ones.
4834 // Moreover, one argument is a constant that can be viewed as a splat
4835 // constant.
4836 Value *Arg0 = Inst->getOperand(0);
4837 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4838 isa<ConstantFP>(Arg0);
4839 TargetTransformInfo::OperandValueKind Arg0OVK =
4840 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4841 : TargetTransformInfo::OK_AnyValue;
4842 TargetTransformInfo::OperandValueKind Arg1OVK =
4843 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4844 : TargetTransformInfo::OK_AnyValue;
4845 ScalarCost += TTI.getArithmeticInstrCost(
4846 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4847 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4848 Arg0OVK, Arg1OVK);
4849 }
4850 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4851 << ScalarCost << "\nVector: " << VectorCost << '\n');
4852 return ScalarCost > VectorCost;
4853 }
4854
4855 /// \brief Generate a constant vector with \p Val with the same
4856 /// number of elements as the transition.
4857 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004858 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004859 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4860 /// otherwise we generate a vector with as many undef as possible:
4861 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4862 /// used at the index of the extract.
4863 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4864 unsigned ExtractIdx = UINT_MAX;
4865 if (!UseSplat) {
4866 // If we cannot determine where the constant must be, we have to
4867 // use a splat constant.
4868 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4869 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4870 ExtractIdx = CstVal->getSExtValue();
4871 else
4872 UseSplat = true;
4873 }
4874
4875 unsigned End = getTransitionType()->getVectorNumElements();
4876 if (UseSplat)
4877 return ConstantVector::getSplat(End, Val);
4878
4879 SmallVector<Constant *, 4> ConstVec;
4880 UndefValue *UndefVal = UndefValue::get(Val->getType());
4881 for (unsigned Idx = 0; Idx != End; ++Idx) {
4882 if (Idx == ExtractIdx)
4883 ConstVec.push_back(Val);
4884 else
4885 ConstVec.push_back(UndefVal);
4886 }
4887 return ConstantVector::get(ConstVec);
4888 }
4889
4890 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4891 /// in \p Use can trigger undefined behavior.
4892 static bool canCauseUndefinedBehavior(const Instruction *Use,
4893 unsigned OperandIdx) {
4894 // This is not safe to introduce undef when the operand is on
4895 // the right hand side of a division-like instruction.
4896 if (OperandIdx != 1)
4897 return false;
4898 switch (Use->getOpcode()) {
4899 default:
4900 return false;
4901 case Instruction::SDiv:
4902 case Instruction::UDiv:
4903 case Instruction::SRem:
4904 case Instruction::URem:
4905 return true;
4906 case Instruction::FDiv:
4907 case Instruction::FRem:
4908 return !Use->hasNoNaNs();
4909 }
4910 llvm_unreachable(nullptr);
4911 }
4912
4913public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004914 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4915 const TargetTransformInfo &TTI, Instruction *Transition,
4916 unsigned CombineCost)
4917 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004918 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4919 assert(Transition && "Do not know how to promote null");
4920 }
4921
4922 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4923 bool canPromote(const Instruction *ToBePromoted) const {
4924 // We could support CastInst too.
4925 return isa<BinaryOperator>(ToBePromoted);
4926 }
4927
4928 /// \brief Check if it is profitable to promote \p ToBePromoted
4929 /// by moving downward the transition through.
4930 bool shouldPromote(const Instruction *ToBePromoted) const {
4931 // Promote only if all the operands can be statically expanded.
4932 // Indeed, we do not want to introduce any new kind of transitions.
4933 for (const Use &U : ToBePromoted->operands()) {
4934 const Value *Val = U.get();
4935 if (Val == getEndOfTransition()) {
4936 // If the use is a division and the transition is on the rhs,
4937 // we cannot promote the operation, otherwise we may create a
4938 // division by zero.
4939 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4940 return false;
4941 continue;
4942 }
4943 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4944 !isa<ConstantFP>(Val))
4945 return false;
4946 }
4947 // Check that the resulting operation is legal.
4948 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4949 if (!ISDOpcode)
4950 return false;
4951 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004952 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004953 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004954 }
4955
4956 /// \brief Check whether or not \p Use can be combined
4957 /// with the transition.
4958 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4959 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4960
4961 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4962 void enqueueForPromotion(Instruction *ToBePromoted) {
4963 InstsToBePromoted.push_back(ToBePromoted);
4964 }
4965
4966 /// \brief Set the instruction that will be combined with the transition.
4967 void recordCombineInstruction(Instruction *ToBeCombined) {
4968 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4969 CombineInst = ToBeCombined;
4970 }
4971
4972 /// \brief Promote all the instructions enqueued for promotion if it is
4973 /// is profitable.
4974 /// \return True if the promotion happened, false otherwise.
4975 bool promote() {
4976 // Check if there is something to promote.
4977 // Right now, if we do not have anything to combine with,
4978 // we assume the promotion is not profitable.
4979 if (InstsToBePromoted.empty() || !CombineInst)
4980 return false;
4981
4982 // Check cost.
4983 if (!StressStoreExtract && !isProfitableToPromote())
4984 return false;
4985
4986 // Promote.
4987 for (auto &ToBePromoted : InstsToBePromoted)
4988 promoteImpl(ToBePromoted);
4989 InstsToBePromoted.clear();
4990 return true;
4991 }
4992};
4993} // End of anonymous namespace.
4994
4995void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4996 // At this point, we know that all the operands of ToBePromoted but Def
4997 // can be statically promoted.
4998 // For Def, we need to use its parameter in ToBePromoted:
4999 // b = ToBePromoted ty1 a
5000 // Def = Transition ty1 b to ty2
5001 // Move the transition down.
5002 // 1. Replace all uses of the promoted operation by the transition.
5003 // = ... b => = ... Def.
5004 assert(ToBePromoted->getType() == Transition->getType() &&
5005 "The type of the result of the transition does not match "
5006 "the final type");
5007 ToBePromoted->replaceAllUsesWith(Transition);
5008 // 2. Update the type of the uses.
5009 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5010 Type *TransitionTy = getTransitionType();
5011 ToBePromoted->mutateType(TransitionTy);
5012 // 3. Update all the operands of the promoted operation with promoted
5013 // operands.
5014 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5015 for (Use &U : ToBePromoted->operands()) {
5016 Value *Val = U.get();
5017 Value *NewVal = nullptr;
5018 if (Val == Transition)
5019 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5020 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5021 isa<ConstantFP>(Val)) {
5022 // Use a splat constant if it is not safe to use undef.
5023 NewVal = getConstantVector(
5024 cast<Constant>(Val),
5025 isa<UndefValue>(Val) ||
5026 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5027 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005028 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5029 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005030 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5031 }
5032 Transition->removeFromParent();
5033 Transition->insertAfter(ToBePromoted);
5034 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5035}
5036
5037/// Some targets can do store(extractelement) with one instruction.
5038/// Try to push the extractelement towards the stores when the target
5039/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005040bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005041 unsigned CombineCost = UINT_MAX;
5042 if (DisableStoreExtract || !TLI ||
5043 (!StressStoreExtract &&
5044 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5045 Inst->getOperand(1), CombineCost)))
5046 return false;
5047
5048 // At this point we know that Inst is a vector to scalar transition.
5049 // Try to move it down the def-use chain, until:
5050 // - We can combine the transition with its single use
5051 // => we got rid of the transition.
5052 // - We escape the current basic block
5053 // => we would need to check that we are moving it at a cheaper place and
5054 // we do not do that for now.
5055 BasicBlock *Parent = Inst->getParent();
5056 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005057 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005058 // If the transition has more than one use, assume this is not going to be
5059 // beneficial.
5060 while (Inst->hasOneUse()) {
5061 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5062 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5063
5064 if (ToBePromoted->getParent() != Parent) {
5065 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5066 << ToBePromoted->getParent()->getName()
5067 << ") than the transition (" << Parent->getName() << ").\n");
5068 return false;
5069 }
5070
5071 if (VPH.canCombine(ToBePromoted)) {
5072 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5073 << "will be combined with: " << *ToBePromoted << '\n');
5074 VPH.recordCombineInstruction(ToBePromoted);
5075 bool Changed = VPH.promote();
5076 NumStoreExtractExposed += Changed;
5077 return Changed;
5078 }
5079
5080 DEBUG(dbgs() << "Try promoting.\n");
5081 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5082 return false;
5083
5084 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5085
5086 VPH.enqueueForPromotion(ToBePromoted);
5087 Inst = ToBePromoted;
5088 }
5089 return false;
5090}
5091
Sanjay Patelfc580a62015-09-21 23:03:16 +00005092bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005093 // Bail out if we inserted the instruction to prevent optimizations from
5094 // stepping on each other's toes.
5095 if (InsertedInsts.count(I))
5096 return false;
5097
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005098 if (PHINode *P = dyn_cast<PHINode>(I)) {
5099 // It is possible for very late stage optimizations (such as SimplifyCFG)
5100 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5101 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005102 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005103 P->replaceAllUsesWith(V);
5104 P->eraseFromParent();
5105 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005106 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005107 }
Chris Lattneree588de2011-01-15 07:29:01 +00005108 return false;
5109 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005110
Chris Lattneree588de2011-01-15 07:29:01 +00005111 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005112 // If the source of the cast is a constant, then this should have
5113 // already been constant folded. The only reason NOT to constant fold
5114 // it is if something (e.g. LSR) was careful to place the constant
5115 // evaluation in a block other than then one that uses it (e.g. to hoist
5116 // the address of globals out of a loop). If this is the case, we don't
5117 // want to forward-subst the cast.
5118 if (isa<Constant>(CI->getOperand(0)))
5119 return false;
5120
Mehdi Amini44ede332015-07-09 02:09:04 +00005121 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005122 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005123
Chris Lattneree588de2011-01-15 07:29:01 +00005124 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005125 /// Sink a zext or sext into its user blocks if the target type doesn't
5126 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005127 if (TLI &&
5128 TLI->getTypeAction(CI->getContext(),
5129 TLI->getValueType(*DL, CI->getType())) ==
5130 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005131 return SinkCast(CI);
5132 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005133 bool MadeChange = moveExtToFormExtLoad(I);
5134 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005135 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005136 }
Chris Lattneree588de2011-01-15 07:29:01 +00005137 return false;
5138 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005139
Chris Lattneree588de2011-01-15 07:29:01 +00005140 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005141 if (!TLI || !TLI->hasMultipleConditionRegisters())
5142 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005143
Chris Lattneree588de2011-01-15 07:29:01 +00005144 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005145 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005146 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005147 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005148 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005149 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5150 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005151 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005152 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005153 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005154
Chris Lattneree588de2011-01-15 07:29:01 +00005155 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005156 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005157 if (TLI) {
5158 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005159 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005160 SI->getOperand(0)->getType(), AS);
5161 }
Chris Lattneree588de2011-01-15 07:29:01 +00005162 return false;
5163 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005164
Yi Jiangd069f632014-04-21 19:34:27 +00005165 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5166
5167 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5168 BinOp->getOpcode() == Instruction::LShr)) {
5169 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5170 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005171 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005172
5173 return false;
5174 }
5175
Chris Lattneree588de2011-01-15 07:29:01 +00005176 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005177 if (GEPI->hasAllZeroIndices()) {
5178 /// The GEP operand must be a pointer, so must its result -> BitCast
5179 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5180 GEPI->getName(), GEPI);
5181 GEPI->replaceAllUsesWith(NC);
5182 GEPI->eraseFromParent();
5183 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005184 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005185 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005186 }
Chris Lattneree588de2011-01-15 07:29:01 +00005187 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005188 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005189
Chris Lattneree588de2011-01-15 07:29:01 +00005190 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005191 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005192
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005193 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005194 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005195
Tim Northoveraeb8e062014-02-19 10:02:43 +00005196 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005197 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005198
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005199 if (auto *Switch = dyn_cast<SwitchInst>(I))
5200 return optimizeSwitchInst(Switch);
5201
Quentin Colombetc32615d2014-10-31 17:52:53 +00005202 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005203 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005204
Chris Lattneree588de2011-01-15 07:29:01 +00005205 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005206}
5207
Chris Lattnerf2836d12007-03-31 04:06:36 +00005208// In this pass we look for GEP and cast instructions that are used
5209// across basic blocks and rewrite them to improve basic-block-at-a-time
5210// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005211bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005212 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005213 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005214
Chris Lattner7a277142011-01-15 07:14:54 +00005215 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005216 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005217 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005218 if (ModifiedDT)
5219 return true;
5220 }
Sanjay Patelfc580a62015-09-21 23:03:16 +00005221 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Benjamin Kramer455fa352012-11-23 19:17:06 +00005222
Chris Lattnerf2836d12007-03-31 04:06:36 +00005223 return MadeChange;
5224}
Devang Patel53771ba2011-08-18 00:50:51 +00005225
5226// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005227// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005228// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005229bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005230 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005231 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005232 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005233 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005234 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005235 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005236 // Leave dbg.values that refer to an alloca alone. These
5237 // instrinsics describe the address of a variable (= the alloca)
5238 // being taken. They should not be moved next to the alloca
5239 // (and to the beginning of the scope), but rather stay close to
5240 // where said address is used.
5241 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005242 PrevNonDbgInst = Insn;
5243 continue;
5244 }
5245
5246 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5247 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
5248 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5249 DVI->removeFromParent();
5250 if (isa<PHINode>(VI))
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005251 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
Devang Patel53771ba2011-08-18 00:50:51 +00005252 else
5253 DVI->insertAfter(VI);
5254 MadeChange = true;
5255 ++NumDbgValueMoved;
5256 }
5257 }
5258 }
5259 return MadeChange;
5260}
Tim Northovercea0abb2014-03-29 08:22:29 +00005261
5262// If there is a sequence that branches based on comparing a single bit
5263// against zero that can be combined into a single instruction, and the
5264// target supports folding these into a single instruction, sink the
5265// mask and compare into the branch uses. Do this before OptimizeBlock ->
5266// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5267// searched for.
5268bool CodeGenPrepare::sinkAndCmp(Function &F) {
5269 if (!EnableAndCmpSinking)
5270 return false;
5271 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5272 return false;
5273 bool MadeChange = false;
5274 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005275 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00005276
5277 // Does this BB end with the following?
5278 // %andVal = and %val, #single-bit-set
5279 // %icmpVal = icmp %andResult, 0
5280 // br i1 %cmpVal label %dest1, label %dest2"
5281 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
5282 if (!Brcc || !Brcc->isConditional())
5283 continue;
5284 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
5285 if (!Cmp || Cmp->getParent() != BB)
5286 continue;
5287 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5288 if (!Zero || !Zero->isZero())
5289 continue;
5290 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
5291 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
5292 continue;
5293 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5294 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5295 continue;
5296 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
5297
5298 // Push the "and; icmp" for any users that are conditional branches.
5299 // Since there can only be one branch use per BB, we don't need to keep
5300 // track of which BBs we insert into.
5301 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
5302 UI != E; ) {
5303 Use &TheUse = *UI;
5304 // Find brcc use.
5305 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
5306 ++UI;
5307 if (!BrccUser || !BrccUser->isConditional())
5308 continue;
5309 BasicBlock *UserBB = BrccUser->getParent();
5310 if (UserBB == BB) continue;
5311 DEBUG(dbgs() << "found Brcc use\n");
5312
5313 // Sink the "and; icmp" to use.
5314 MadeChange = true;
5315 BinaryOperator *NewAnd =
5316 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5317 BrccUser);
5318 CmpInst *NewCmp =
5319 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5320 "", BrccUser);
5321 TheUse = NewCmp;
5322 ++NumAndCmpsMoved;
5323 DEBUG(BrccUser->getParent()->dump());
5324 }
5325 }
5326 return MadeChange;
5327}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005328
Juergen Ributzka194350a2014-12-09 17:32:12 +00005329/// \brief Retrieve the probabilities of a conditional branch. Returns true on
5330/// success, or returns false if no or invalid metadata was found.
5331static bool extractBranchMetadata(BranchInst *BI,
5332 uint64_t &ProbTrue, uint64_t &ProbFalse) {
5333 assert(BI->isConditional() &&
5334 "Looking for probabilities on unconditional branch?");
5335 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
5336 if (!ProfileData || ProfileData->getNumOperands() != 3)
5337 return false;
5338
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005339 const auto *CITrue =
5340 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
5341 const auto *CIFalse =
5342 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00005343 if (!CITrue || !CIFalse)
5344 return false;
5345
5346 ProbTrue = CITrue->getValue().getZExtValue();
5347 ProbFalse = CIFalse->getValue().getZExtValue();
5348
5349 return true;
5350}
5351
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005352/// \brief Scale down both weights to fit into uint32_t.
5353static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5354 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5355 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5356 NewTrue = NewTrue / Scale;
5357 NewFalse = NewFalse / Scale;
5358}
5359
5360/// \brief Some targets prefer to split a conditional branch like:
5361/// \code
5362/// %0 = icmp ne i32 %a, 0
5363/// %1 = icmp ne i32 %b, 0
5364/// %or.cond = or i1 %0, %1
5365/// br i1 %or.cond, label %TrueBB, label %FalseBB
5366/// \endcode
5367/// into multiple branch instructions like:
5368/// \code
5369/// bb1:
5370/// %0 = icmp ne i32 %a, 0
5371/// br i1 %0, label %TrueBB, label %bb2
5372/// bb2:
5373/// %1 = icmp ne i32 %b, 0
5374/// br i1 %1, label %TrueBB, label %FalseBB
5375/// \endcode
5376/// This usually allows instruction selection to do even further optimizations
5377/// and combine the compare with the branch instruction. Currently this is
5378/// applied for targets which have "cheap" jump instructions.
5379///
5380/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5381///
5382bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005383 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005384 return false;
5385
5386 bool MadeChange = false;
5387 for (auto &BB : F) {
5388 // Does this BB end with the following?
5389 // %cond1 = icmp|fcmp|binary instruction ...
5390 // %cond2 = icmp|fcmp|binary instruction ...
5391 // %cond.or = or|and i1 %cond1, cond2
5392 // br i1 %cond.or label %dest1, label %dest2"
5393 BinaryOperator *LogicOp;
5394 BasicBlock *TBB, *FBB;
5395 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5396 continue;
5397
Sanjay Patel42574202015-09-02 19:23:23 +00005398 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5399 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5400 continue;
5401
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005402 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005403 Value *Cond1, *Cond2;
5404 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5405 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005406 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005407 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5408 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005409 Opc = Instruction::Or;
5410 else
5411 continue;
5412
5413 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5414 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5415 continue;
5416
5417 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5418
5419 // Create a new BB.
5420 auto *InsertBefore = std::next(Function::iterator(BB))
5421 .getNodePtrUnchecked();
5422 auto TmpBB = BasicBlock::Create(BB.getContext(),
5423 BB.getName() + ".cond.split",
5424 BB.getParent(), InsertBefore);
5425
5426 // Update original basic block by using the first condition directly by the
5427 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005428 Br1->setCondition(Cond1);
5429 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005430
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005431 // Depending on the conditon we have to either replace the true or the false
5432 // successor of the original branch instruction.
5433 if (Opc == Instruction::And)
5434 Br1->setSuccessor(0, TmpBB);
5435 else
5436 Br1->setSuccessor(1, TmpBB);
5437
5438 // Fill in the new basic block.
5439 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005440 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5441 I->removeFromParent();
5442 I->insertBefore(Br2);
5443 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005444
5445 // Update PHI nodes in both successors. The original BB needs to be
5446 // replaced in one succesor's PHI nodes, because the branch comes now from
5447 // the newly generated BB (NewBB). In the other successor we need to add one
5448 // incoming edge to the PHI nodes, because both branch instructions target
5449 // now the same successor. Depending on the original branch condition
5450 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5451 // we perfrom the correct update for the PHI nodes.
5452 // This doesn't change the successor order of the just created branch
5453 // instruction (or any other instruction).
5454 if (Opc == Instruction::Or)
5455 std::swap(TBB, FBB);
5456
5457 // Replace the old BB with the new BB.
5458 for (auto &I : *TBB) {
5459 PHINode *PN = dyn_cast<PHINode>(&I);
5460 if (!PN)
5461 break;
5462 int i;
5463 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5464 PN->setIncomingBlock(i, TmpBB);
5465 }
5466
5467 // Add another incoming edge form the new BB.
5468 for (auto &I : *FBB) {
5469 PHINode *PN = dyn_cast<PHINode>(&I);
5470 if (!PN)
5471 break;
5472 auto *Val = PN->getIncomingValueForBlock(&BB);
5473 PN->addIncoming(Val, TmpBB);
5474 }
5475
5476 // Update the branch weights (from SelectionDAGBuilder::
5477 // FindMergedConditions).
5478 if (Opc == Instruction::Or) {
5479 // Codegen X | Y as:
5480 // BB1:
5481 // jmp_if_X TBB
5482 // jmp TmpBB
5483 // TmpBB:
5484 // jmp_if_Y TBB
5485 // jmp FBB
5486 //
5487
5488 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5489 // The requirement is that
5490 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5491 // = TrueProb for orignal BB.
5492 // Assuming the orignal weights are A and B, one choice is to set BB1's
5493 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5494 // assumes that
5495 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5496 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5497 // TmpBB, but the math is more complicated.
5498 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005499 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005500 uint64_t NewTrueWeight = TrueWeight;
5501 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5502 scaleWeights(NewTrueWeight, NewFalseWeight);
5503 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5504 .createBranchWeights(TrueWeight, FalseWeight));
5505
5506 NewTrueWeight = TrueWeight;
5507 NewFalseWeight = 2 * FalseWeight;
5508 scaleWeights(NewTrueWeight, NewFalseWeight);
5509 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5510 .createBranchWeights(TrueWeight, FalseWeight));
5511 }
5512 } else {
5513 // Codegen X & Y as:
5514 // BB1:
5515 // jmp_if_X TmpBB
5516 // jmp FBB
5517 // TmpBB:
5518 // jmp_if_Y TBB
5519 // jmp FBB
5520 //
5521 // This requires creation of TmpBB after CurBB.
5522
5523 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5524 // The requirement is that
5525 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5526 // = FalseProb for orignal BB.
5527 // Assuming the orignal weights are A and B, one choice is to set BB1's
5528 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5529 // assumes that
5530 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5531 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005532 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005533 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5534 uint64_t NewFalseWeight = FalseWeight;
5535 scaleWeights(NewTrueWeight, NewFalseWeight);
5536 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5537 .createBranchWeights(TrueWeight, FalseWeight));
5538
5539 NewTrueWeight = 2 * TrueWeight;
5540 NewFalseWeight = FalseWeight;
5541 scaleWeights(NewTrueWeight, NewFalseWeight);
5542 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5543 .createBranchWeights(TrueWeight, FalseWeight));
5544 }
5545 }
5546
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005547 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005548 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005549 ModifiedDT = true;
5550
5551 MadeChange = true;
5552
5553 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5554 TmpBB->dump());
5555 }
5556 return MadeChange;
5557}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005558
5559void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005560 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005561 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5562}