blob: c8007a524e702acea8defcfee43251e2d8f34943 [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();
Eric Christopher49a7d6c2016-01-04 23:18:58 +0000228 BasicBlock* BB = &*F.begin();
229 while (BB != nullptr) {
230 // bypassSlowDivision may create new BBs, but we don't want to reapply the
231 // optimization to those blocks.
232 BasicBlock* Next = BB->getNextNode();
233 EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
234 BB = Next;
235 }
Preston Gurdcdf540d2012-09-04 18:22:17 +0000236 }
237
238 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000239 // unconditional branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000240 EverMadeChange |= eliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000241
Devang Patel53771ba2011-08-18 00:50:51 +0000242 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000243 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000244 // find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000245 EverMadeChange |= placeDbgValues(F);
Devang Patel53771ba2011-08-18 00:50:51 +0000246
Tim Northovercea0abb2014-03-29 08:22:29 +0000247 // If there is a mask, compare against zero, and branch that can be combined
248 // into a single target instruction, push the mask and compare into branch
249 // users. Do this before OptimizeBlock -> OptimizeInst ->
250 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000251 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000252 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000253 EverMadeChange |= splitBranchCondition(F);
254 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000255
Chris Lattnerc3748562007-04-02 01:35:34 +0000256 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000257 while (MadeChange) {
258 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000259 for (Function::iterator I = F.begin(); I != F.end(); ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000260 BasicBlock *BB = &*I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000261 bool ModifiedDTOnIteration = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +0000262 MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000263
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000264 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000265 if (ModifiedDTOnIteration)
266 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000267 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000268 EverMadeChange |= MadeChange;
269 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000270
271 SunkAddrs.clear();
272
Cameron Zwarich338d3622011-03-11 21:52:04 +0000273 if (!DisableBranchOpts) {
274 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000275 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000276 for (BasicBlock &BB : F) {
277 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
278 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000279 if (!MadeChange) continue;
280
281 for (SmallVectorImpl<BasicBlock*>::iterator
282 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
283 if (pred_begin(*II) == pred_end(*II))
284 WorkList.insert(*II);
285 }
286
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000287 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000288 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000289 while (!WorkList.empty()) {
290 BasicBlock *BB = *WorkList.begin();
291 WorkList.erase(BB);
292 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
293
294 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000295
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000296 for (SmallVectorImpl<BasicBlock*>::iterator
297 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
298 if (pred_begin(*II) == pred_end(*II))
299 WorkList.insert(*II);
300 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000301
Nadav Rotem70409992012-08-14 05:19:07 +0000302 // Merge pairs of basic blocks with unconditional branches, connected by
303 // a single edge.
304 if (EverMadeChange || MadeChange)
Sanjay Patelfc580a62015-09-21 23:03:16 +0000305 MadeChange |= eliminateFallThrough(F);
Nadav Rotem70409992012-08-14 05:19:07 +0000306
Cameron Zwarich338d3622011-03-11 21:52:04 +0000307 EverMadeChange |= MadeChange;
308 }
309
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000310 if (!DisableGCOpts) {
311 SmallVector<Instruction *, 2> Statepoints;
312 for (BasicBlock &BB : F)
313 for (Instruction &I : BB)
314 if (isStatepoint(I))
315 Statepoints.push_back(&I);
316 for (auto &I : Statepoints)
317 EverMadeChange |= simplifyOffsetableRelocate(*I);
318 }
319
Chris Lattnerf2836d12007-03-31 04:06:36 +0000320 return EverMadeChange;
321}
322
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000323/// Merge basic blocks which are connected by a single edge, where one of the
324/// basic blocks has a single successor pointing to the other basic block,
325/// which has a single predecessor.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000326bool CodeGenPrepare::eliminateFallThrough(Function &F) {
Nadav Rotem70409992012-08-14 05:19:07 +0000327 bool Changed = false;
328 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000329 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000330 BasicBlock *BB = &*I++;
Nadav Rotem70409992012-08-14 05:19:07 +0000331 // If the destination block has a single pred, then this is a trivial
332 // edge, just collapse it.
333 BasicBlock *SinglePred = BB->getSinglePredecessor();
334
Evan Cheng64a223a2012-09-28 23:58:57 +0000335 // Don't merge if BB's address is taken.
336 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000337
338 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
339 if (Term && !Term->isConditional()) {
340 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000341 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000342 // Remember if SinglePred was the entry block of the function.
343 // If so, we will need to move BB back to the entry position.
344 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000345 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000346
347 if (isEntry && BB != &BB->getParent()->getEntryBlock())
348 BB->moveBefore(&BB->getParent()->getEntryBlock());
349
350 // We have erased a block. Update the iterator.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000351 I = BB->getIterator();
Nadav Rotem70409992012-08-14 05:19:07 +0000352 }
353 }
354 return Changed;
355}
356
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000357/// Eliminate blocks that contain only PHI nodes, debug info directives, and an
358/// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
359/// edges in ways that are non-optimal for isel. Start by eliminating these
360/// blocks so we can split them the way we want them.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000361bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000362 bool MadeChange = false;
363 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000364 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000365 BasicBlock *BB = &*I++;
Chris Lattnerc3748562007-04-02 01:35:34 +0000366
367 // If this block doesn't end with an uncond branch, ignore it.
368 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
369 if (!BI || !BI->isUnconditional())
370 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000371
Dale Johannesen4026b042009-03-27 01:13:37 +0000372 // If the instruction before the branch (skipping debug info) isn't a phi
373 // node, then other stuff is happening here.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000374 BasicBlock::iterator BBI = BI->getIterator();
Chris Lattnerc3748562007-04-02 01:35:34 +0000375 if (BBI != BB->begin()) {
376 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000377 while (isa<DbgInfoIntrinsic>(BBI)) {
378 if (BBI == BB->begin())
379 break;
380 --BBI;
381 }
382 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
383 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000385
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 // Do not break infinite loops.
387 BasicBlock *DestBB = BI->getSuccessor(0);
388 if (DestBB == BB)
389 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000390
Sanjay Patelfc580a62015-09-21 23:03:16 +0000391 if (!canMergeBlocks(BB, DestBB))
Chris Lattnerc3748562007-04-02 01:35:34 +0000392 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000393
Sanjay Patelfc580a62015-09-21 23:03:16 +0000394 eliminateMostlyEmptyBlock(BB);
Chris Lattnerc3748562007-04-02 01:35:34 +0000395 MadeChange = true;
396 }
397 return MadeChange;
398}
399
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000400/// Return true if we can merge BB into DestBB if there is a single
401/// unconditional branch between them, and BB contains no other non-phi
Chris Lattnerc3748562007-04-02 01:35:34 +0000402/// instructions.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000403bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
Chris Lattnerc3748562007-04-02 01:35:34 +0000404 const BasicBlock *DestBB) const {
405 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
406 // the successor. If there are more complex condition (e.g. preheaders),
407 // don't mess around with them.
408 BasicBlock::const_iterator BBI = BB->begin();
409 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000410 for (const User *U : PN->users()) {
411 const Instruction *UI = cast<Instruction>(U);
412 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000413 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000414 // If User is inside DestBB block and it is a PHINode then check
415 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000416 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000417 if (UI->getParent() == DestBB) {
418 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000419 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
420 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
421 if (Insn && Insn->getParent() == BB &&
422 Insn->getParent() != UPN->getIncomingBlock(I))
423 return false;
424 }
425 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000426 }
427 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000428
Chris Lattnerc3748562007-04-02 01:35:34 +0000429 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
430 // and DestBB may have conflicting incoming values for the block. If so, we
431 // can't merge the block.
432 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
433 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000434
Chris Lattnerc3748562007-04-02 01:35:34 +0000435 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000436 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000437 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
438 // It is faster to get preds from a PHI than with pred_iterator.
439 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
440 BBPreds.insert(BBPN->getIncomingBlock(i));
441 } else {
442 BBPreds.insert(pred_begin(BB), pred_end(BB));
443 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000444
Chris Lattnerc3748562007-04-02 01:35:34 +0000445 // Walk the preds of DestBB.
446 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
447 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
448 if (BBPreds.count(Pred)) { // Common predecessor?
449 BBI = DestBB->begin();
450 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
451 const Value *V1 = PN->getIncomingValueForBlock(Pred);
452 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000453
Chris Lattnerc3748562007-04-02 01:35:34 +0000454 // If V2 is a phi node in BB, look up what the mapped value will be.
455 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
456 if (V2PN->getParent() == BB)
457 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000458
Chris Lattnerc3748562007-04-02 01:35:34 +0000459 // If there is a conflict, bail out.
460 if (V1 != V2) return false;
461 }
462 }
463 }
464
465 return true;
466}
467
468
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000469/// Eliminate a basic block that has only phi's and an unconditional branch in
470/// it.
Sanjay Patelfc580a62015-09-21 23:03:16 +0000471void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000472 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
473 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000474
David Greene74e2d492010-01-05 01:27:11 +0000475 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000476
Chris Lattnerc3748562007-04-02 01:35:34 +0000477 // If the destination block has a single pred, then this is a trivial edge,
478 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000479 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000480 if (SinglePred != DestBB) {
481 // Remember if SinglePred was the entry block of the function. If so, we
482 // will need to move BB back to the entry position.
483 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000484 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000485
Chris Lattner8a172da2008-11-28 19:54:49 +0000486 if (isEntry && BB != &BB->getParent()->getEntryBlock())
487 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000488
David Greene74e2d492010-01-05 01:27:11 +0000489 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000490 return;
491 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000492 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000493
Chris Lattnerc3748562007-04-02 01:35:34 +0000494 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
495 // to handle the new incoming edges it is about to have.
496 PHINode *PN;
497 for (BasicBlock::iterator BBI = DestBB->begin();
498 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
499 // Remove the incoming value for BB, and remember it.
500 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000501
Chris Lattnerc3748562007-04-02 01:35:34 +0000502 // Two options: either the InVal is a phi node defined in BB or it is some
503 // value that dominates BB.
504 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
505 if (InValPhi && InValPhi->getParent() == BB) {
506 // Add all of the input values of the input PHI as inputs of this phi.
507 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
508 PN->addIncoming(InValPhi->getIncomingValue(i),
509 InValPhi->getIncomingBlock(i));
510 } else {
511 // Otherwise, add one instance of the dominating value for each edge that
512 // we will be adding.
513 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
514 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
515 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
516 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000517 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
518 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000519 }
520 }
521 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000522
Chris Lattnerc3748562007-04-02 01:35:34 +0000523 // The PHIs are now updated, change everything that refers to BB to use
524 // DestBB and remove BB.
525 BB->replaceAllUsesWith(DestBB);
526 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000527 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000528
David Greene74e2d492010-01-05 01:27:11 +0000529 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000530}
531
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000532// Computes a map of base pointer relocation instructions to corresponding
533// derived pointer relocation instructions given a vector of all relocate calls
534static void computeBaseDerivedRelocateMap(
Manuel Jacob83eefa62016-01-05 04:03:00 +0000535 const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
536 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
537 &RelocateInstMap) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000538 // Collect information in two maps: one primarily for locating the base object
539 // while filling the second map; the second map is the final structure holding
540 // a mapping between Base and corresponding Derived relocate calls
Manuel Jacob83eefa62016-01-05 04:03:00 +0000541 DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
542 for (auto *ThisRelocate : AllRelocateCalls) {
543 auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
544 ThisRelocate->getDerivedPtrIndex());
545 RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000546 }
547 for (auto &Item : RelocateIdxMap) {
548 std::pair<unsigned, unsigned> Key = Item.first;
549 if (Key.first == Key.second)
550 // Base relocation: nothing to insert
551 continue;
552
Manuel Jacob83eefa62016-01-05 04:03:00 +0000553 GCRelocateInst *I = Item.second;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000554 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000555
556 // We're iterating over RelocateIdxMap so we cannot modify it.
557 auto MaybeBase = RelocateIdxMap.find(BaseKey);
558 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000559 // TODO: We might want to insert a new base object relocate and gep off
560 // that, if there are enough derived object relocates.
561 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000562
563 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000564 }
565}
566
567// Accepts a GEP and extracts the operands into a vector provided they're all
568// small integer constants
569static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
570 SmallVectorImpl<Value *> &OffsetV) {
571 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
572 // Only accept small constant integer operands
573 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
574 if (!Op || Op->getZExtValue() > 20)
575 return false;
576 }
577
578 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
579 OffsetV.push_back(GEP->getOperand(i));
580 return true;
581}
582
583// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
584// replace, computes a replacement, and affects it.
585static bool
Manuel Jacob83eefa62016-01-05 04:03:00 +0000586simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
587 const SmallVectorImpl<GCRelocateInst *> &Targets) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000588 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000589 for (GCRelocateInst *ToReplace : Targets) {
590 assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000591 "Not relocating a derived object of the original base object");
Manuel Jacob83eefa62016-01-05 04:03:00 +0000592 if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000593 // A duplicate relocate call. TODO: coalesce duplicates.
594 continue;
595 }
596
Igor Laevskyf637b4a2015-11-03 18:37:40 +0000597 if (RelocatedBase->getParent() != ToReplace->getParent()) {
598 // Base and derived relocates are in different basic blocks.
599 // In this case transform is only valid when base dominates derived
600 // relocate. However it would be too expensive to check dominance
601 // for each such relocate, so we skip the whole transformation.
602 continue;
603 }
604
Manuel Jacob83eefa62016-01-05 04:03:00 +0000605 Value *Base = ToReplace->getBasePtr();
606 auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000607 if (!Derived || Derived->getPointerOperand() != Base)
608 continue;
609
610 SmallVector<Value *, 2> OffsetV;
611 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
612 continue;
613
614 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000615 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
616
617 // Insert after RelocatedBase
618 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000619 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000620
621 // If gc_relocate does not match the actual type, cast it to the right type.
622 // In theory, there must be a bitcast after gc_relocate if the type does not
623 // match, and we should reuse it to get the derived pointer. But it could be
624 // cases like this:
625 // bb1:
626 // ...
627 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
628 // br label %merge
629 //
630 // bb2:
631 // ...
632 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
633 // br label %merge
634 //
635 // merge:
636 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
637 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
638 //
639 // In this case, we can not find the bitcast any more. So we insert a new bitcast
640 // no matter there is already one or not. In this way, we can handle all cases, and
641 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000642 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000643 if (RelocatedBase->getType() != Base->getType()) {
644 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000645 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000646 }
David Blaikie68d535c2015-03-24 22:38:16 +0000647 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000648 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
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.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000652 Value *ActualReplacement = Replacement;
653 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000654 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000655 Builder.CreateBitCast(Replacement, 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;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000684 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000685
686 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000687 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000688 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000689 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000690
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
Manuel Jacob83eefa62016-01-05 04:03:00 +0000698 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000699 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
Andrew Kaylord0430e82015-11-23 19:16:15 +0000733 // If the block selected to receive the cast is an EH pad that does not
734 // allow non-PHI instructions before the terminator, we can't sink the
735 // cast.
736 if (UserBB->getTerminator()->isEHPad())
737 continue;
738
Chris Lattnerf2836d12007-03-31 04:06:36 +0000739 // If this user is in the same block as the cast, don't change the cast.
740 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000741
Chris Lattnerf2836d12007-03-31 04:06:36 +0000742 // If we have already inserted a cast into this block, use it.
743 CastInst *&InsertedCast = InsertedCasts[UserBB];
744
745 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000746 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000747 assert(InsertPt != UserBB->end());
748 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
749 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000750 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000751
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000752 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000753 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000754 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000755 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000756 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000757
Chris Lattnerf2836d12007-03-31 04:06:36 +0000758 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000759 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000760 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000761 MadeChange = true;
762 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000763
Chris Lattnerf2836d12007-03-31 04:06:36 +0000764 return MadeChange;
765}
766
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000767/// If the specified cast instruction is a noop copy (e.g. it's casting from
768/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
769/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000770///
771/// Return true if any changes are made.
772///
Mehdi Amini44ede332015-07-09 02:09:04 +0000773static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
774 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000775 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000776 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
777 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000778
779 // This is an fp<->int conversion?
780 if (SrcVT.isInteger() != DstVT.isInteger())
781 return false;
782
783 // If this is an extension, it will be a zero or sign extension, which
784 // isn't a noop.
785 if (SrcVT.bitsLT(DstVT)) return false;
786
787 // If these values will be promoted, find out what they will be promoted
788 // to. This helps us consider truncates on PPC as noop copies when they
789 // are.
790 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
791 TargetLowering::TypePromoteInteger)
792 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
793 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
794 TargetLowering::TypePromoteInteger)
795 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
796
797 // If, after promotion, these are the same types, this is a noop copy.
798 if (SrcVT != DstVT)
799 return false;
800
801 return SinkCast(CI);
802}
803
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000804/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
805/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000806///
807/// Return true if any changes were made.
808static bool CombineUAddWithOverflow(CmpInst *CI) {
809 Value *A, *B;
810 Instruction *AddI;
811 if (!match(CI,
812 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
813 return false;
814
815 Type *Ty = AddI->getType();
816 if (!isa<IntegerType>(Ty))
817 return false;
818
819 // We don't want to move around uses of condition values this late, so we we
820 // check if it is legal to create the call to the intrinsic in the basic
821 // block containing the icmp:
822
823 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
824 return false;
825
826#ifndef NDEBUG
827 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
828 // for now:
829 if (AddI->hasOneUse())
830 assert(*AddI->user_begin() == CI && "expected!");
831#endif
832
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000833 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000834 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
835
836 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
837
838 auto *UAddWithOverflow =
839 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
840 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
841 auto *Overflow =
842 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
843
844 CI->replaceAllUsesWith(Overflow);
845 AddI->replaceAllUsesWith(UAdd);
846 CI->eraseFromParent();
847 AddI->eraseFromParent();
848 return true;
849}
850
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000851/// Sink the given CmpInst into user blocks to reduce the number of virtual
852/// registers that must be created and coalesced. This is a clear win except on
853/// targets with multiple condition code registers (PowerPC), where it might
854/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000855///
856/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000857static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000858 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000859
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000860 /// Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000861 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000862
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000863 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000864 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000865 UI != E; ) {
866 Use &TheUse = UI.getUse();
867 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000868
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000869 // Preincrement use iterator so we don't invalidate it.
870 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000871
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000872 // Don't bother for PHI nodes.
873 if (isa<PHINode>(User))
874 continue;
875
876 // Figure out which BB this cmp is used in.
877 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000878
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000879 // If this user is in the same block as the cmp, don't change the cmp.
880 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000881
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000882 // If we have already inserted a cmp into this block, use it.
883 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
884
885 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000886 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000887 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000888 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000889 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
890 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000891 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000892
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000893 // Replace a use of the cmp with a use of the new cmp.
894 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000895 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000896 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000897 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000898
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000899 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000900 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000901 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000902 MadeChange = true;
903 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000904
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000905 return MadeChange;
906}
907
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000908static bool OptimizeCmpExpression(CmpInst *CI) {
909 if (SinkCmpExpression(CI))
910 return true;
911
912 if (CombineUAddWithOverflow(CI))
913 return true;
914
915 return false;
916}
917
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000918/// Check if the candidates could be combined with a shift instruction, which
919/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000920/// 1. Truncate instruction
921/// 2. And instruction and the imm is a mask of the low bits:
922/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000923static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000924 if (!isa<TruncInst>(User)) {
925 if (User->getOpcode() != Instruction::And ||
926 !isa<ConstantInt>(User->getOperand(1)))
927 return false;
928
Quentin Colombetd4f44692014-04-22 01:20:34 +0000929 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000930
Quentin Colombetd4f44692014-04-22 01:20:34 +0000931 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000932 return false;
933 }
934 return true;
935}
936
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000937/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000938static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000939SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
940 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000941 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000942 BasicBlock *UserBB = User->getParent();
943 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
944 TruncInst *TruncI = dyn_cast<TruncInst>(User);
945 bool MadeChange = false;
946
947 for (Value::user_iterator TruncUI = TruncI->user_begin(),
948 TruncE = TruncI->user_end();
949 TruncUI != TruncE;) {
950
951 Use &TruncTheUse = TruncUI.getUse();
952 Instruction *TruncUser = cast<Instruction>(*TruncUI);
953 // Preincrement use iterator so we don't invalidate it.
954
955 ++TruncUI;
956
957 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
958 if (!ISDOpcode)
959 continue;
960
Tim Northovere2239ff2014-07-29 10:20:22 +0000961 // If the use is actually a legal node, there will not be an
962 // implicit truncate.
963 // FIXME: always querying the result type is just an
964 // approximation; some nodes' legality is determined by the
965 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000966 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000967 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000968 continue;
969
970 // Don't bother for PHI nodes.
971 if (isa<PHINode>(TruncUser))
972 continue;
973
974 BasicBlock *TruncUserBB = TruncUser->getParent();
975
976 if (UserBB == TruncUserBB)
977 continue;
978
979 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
980 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
981
982 if (!InsertedShift && !InsertedTrunc) {
983 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000984 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000985 // Sink the shift
986 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000987 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
988 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000989 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000990 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
991 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000992
993 // Sink the trunc
994 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
995 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000996 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000997
998 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000999 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001000
1001 MadeChange = true;
1002
1003 TruncTheUse = InsertedTrunc;
1004 }
1005 }
1006 return MadeChange;
1007}
1008
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001009/// Sink the shift *right* instruction into user blocks if the uses could
1010/// potentially be combined with this shift instruction and generate BitExtract
1011/// instruction. It will only be applied if the architecture supports BitExtract
1012/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001013/// BB1:
1014/// %x.extract.shift = lshr i64 %arg1, 32
1015/// BB2:
1016/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1017/// ==>
1018///
1019/// BB2:
1020/// %x.extract.shift.1 = lshr i64 %arg1, 32
1021/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1022///
1023/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1024/// instruction.
1025/// Return true if any changes are made.
1026static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001027 const TargetLowering &TLI,
1028 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001029 BasicBlock *DefBB = ShiftI->getParent();
1030
1031 /// Only insert instructions in each block once.
1032 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1033
Mehdi Amini44ede332015-07-09 02:09:04 +00001034 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001035
1036 bool MadeChange = false;
1037 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1038 UI != E;) {
1039 Use &TheUse = UI.getUse();
1040 Instruction *User = cast<Instruction>(*UI);
1041 // Preincrement use iterator so we don't invalidate it.
1042 ++UI;
1043
1044 // Don't bother for PHI nodes.
1045 if (isa<PHINode>(User))
1046 continue;
1047
1048 if (!isExtractBitsCandidateUse(User))
1049 continue;
1050
1051 BasicBlock *UserBB = User->getParent();
1052
1053 if (UserBB == DefBB) {
1054 // If the shift and truncate instruction are in the same BB. The use of
1055 // the truncate(TruncUse) may still introduce another truncate if not
1056 // legal. In this case, we would like to sink both shift and truncate
1057 // instruction to the BB of TruncUse.
1058 // for example:
1059 // BB1:
1060 // i64 shift.result = lshr i64 opnd, imm
1061 // trunc.result = trunc shift.result to i16
1062 //
1063 // BB2:
1064 // ----> We will have an implicit truncate here if the architecture does
1065 // not have i16 compare.
1066 // cmp i16 trunc.result, opnd2
1067 //
1068 if (isa<TruncInst>(User) && shiftIsLegal
1069 // If the type of the truncate is legal, no trucate will be
1070 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001071 &&
1072 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001073 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001074 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001075
1076 continue;
1077 }
1078 // If we have already inserted a shift into this block, use it.
1079 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1080
1081 if (!InsertedShift) {
1082 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001083 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001084
1085 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001086 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1087 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001088 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001089 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1090 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001091
1092 MadeChange = true;
1093 }
1094
1095 // Replace a use of the shift with a use of the new shift.
1096 TheUse = InsertedShift;
1097 }
1098
1099 // If we removed all uses, nuke the shift.
1100 if (ShiftI->use_empty())
1101 ShiftI->eraseFromParent();
1102
1103 return MadeChange;
1104}
1105
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001106// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001107// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1108// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001109// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001110// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001111//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001112// %1 = bitcast i8* %addr to i32*
1113// %2 = extractelement <16 x i1> %mask, i32 0
1114// %3 = icmp eq i1 %2, true
1115// br i1 %3, label %cond.load, label %else
1116//
1117//cond.load: ; preds = %0
1118// %4 = getelementptr i32* %1, i32 0
1119// %5 = load i32* %4
1120// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1121// br label %else
1122//
1123//else: ; preds = %0, %cond.load
1124// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1125// %7 = extractelement <16 x i1> %mask, i32 1
1126// %8 = icmp eq i1 %7, true
1127// br i1 %8, label %cond.load1, label %else2
1128//
1129//cond.load1: ; preds = %else
1130// %9 = getelementptr i32* %1, i32 1
1131// %10 = load i32* %9
1132// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1133// br label %else2
1134//
1135//else2: ; preds = %else, %cond.load1
1136// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1137// %12 = extractelement <16 x i1> %mask, i32 2
1138// %13 = icmp eq i1 %12, true
1139// br i1 %13, label %cond.load4, label %else5
1140//
1141static void ScalarizeMaskedLoad(CallInst *CI) {
1142 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001143 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001144 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001145 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001146
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001147 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1148 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001149 assert(VecType && "Unexpected return type of masked load intrinsic");
1150
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001151 Type *EltTy = CI->getType()->getVectorElementType();
1152
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001153 IRBuilder<> Builder(CI->getContext());
1154 Instruction *InsertPt = CI;
1155 BasicBlock *IfBlock = CI->getParent();
1156 BasicBlock *CondBlock = nullptr;
1157 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001158
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001159 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001160 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1161
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001162 // Short-cut if the mask is all-true.
1163 bool IsAllOnesMask = isa<Constant>(Mask) &&
1164 cast<Constant>(Mask)->isAllOnesValue();
1165
1166 if (IsAllOnesMask) {
1167 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1168 CI->replaceAllUsesWith(NewI);
1169 CI->eraseFromParent();
1170 return;
1171 }
1172
1173 // Adjust alignment for the scalar instruction.
1174 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001175 // Bitcast %addr fron i8* to EltTy*
1176 Type *NewPtrType =
1177 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1178 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001179 unsigned VectorWidth = VecType->getNumElements();
1180
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001181 Value *UndefVal = UndefValue::get(VecType);
1182
1183 // The result vector
1184 Value *VResult = UndefVal;
1185
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001186 if (isa<ConstantVector>(Mask)) {
1187 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1188 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1189 continue;
1190 Value *Gep =
1191 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1192 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1193 VResult = Builder.CreateInsertElement(VResult, Load,
1194 Builder.getInt32(Idx));
1195 }
1196 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1197 CI->replaceAllUsesWith(NewI);
1198 CI->eraseFromParent();
1199 return;
1200 }
1201
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001202 PHINode *Phi = nullptr;
1203 Value *PrevPhi = UndefVal;
1204
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001205 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1206
1207 // Fill the "else" block, created in the previous iteration
1208 //
1209 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1210 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1211 // %to_load = icmp eq i1 %mask_1, true
1212 // br i1 %to_load, label %cond.load, label %else
1213 //
1214 if (Idx > 0) {
1215 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1216 Phi->addIncoming(VResult, CondBlock);
1217 Phi->addIncoming(PrevPhi, PrevIfBlock);
1218 PrevPhi = Phi;
1219 VResult = Phi;
1220 }
1221
1222 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1223 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1224 ConstantInt::get(Predicate->getType(), 1));
1225
1226 // Create "cond" block
1227 //
1228 // %EltAddr = getelementptr i32* %1, i32 0
1229 // %Elt = load i32* %EltAddr
1230 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1231 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001232 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001233 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001234
1235 Value *Gep =
1236 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001237 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001238 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1239
1240 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001241 BasicBlock *NewIfBlock =
1242 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001243 Builder.SetInsertPoint(InsertPt);
1244 Instruction *OldBr = IfBlock->getTerminator();
1245 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1246 OldBr->eraseFromParent();
1247 PrevIfBlock = IfBlock;
1248 IfBlock = NewIfBlock;
1249 }
1250
1251 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1252 Phi->addIncoming(VResult, CondBlock);
1253 Phi->addIncoming(PrevPhi, PrevIfBlock);
1254 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1255 CI->replaceAllUsesWith(NewI);
1256 CI->eraseFromParent();
1257}
1258
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001259// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001260// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1261// <16 x i1> %mask)
1262// to a chain of basic blocks, that stores element one-by-one if
1263// the appropriate mask bit is set
1264//
1265// %1 = bitcast i8* %addr to i32*
1266// %2 = extractelement <16 x i1> %mask, i32 0
1267// %3 = icmp eq i1 %2, true
1268// br i1 %3, label %cond.store, label %else
1269//
1270// cond.store: ; preds = %0
1271// %4 = extractelement <16 x i32> %val, i32 0
1272// %5 = getelementptr i32* %1, i32 0
1273// store i32 %4, i32* %5
1274// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001275//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001276// else: ; preds = %0, %cond.store
1277// %6 = extractelement <16 x i1> %mask, i32 1
1278// %7 = icmp eq i1 %6, true
1279// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001280//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001281// cond.store1: ; preds = %else
1282// %8 = extractelement <16 x i32> %val, i32 1
1283// %9 = getelementptr i32* %1, i32 1
1284// store i32 %8, i32* %9
1285// br label %else2
1286// . . .
1287static void ScalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001288 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001289 Value *Ptr = CI->getArgOperand(1);
1290 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001291 Value *Mask = CI->getArgOperand(3);
1292
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001293 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001294 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001295 assert(VecType && "Unexpected data type in masked store intrinsic");
1296
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001297 Type *EltTy = VecType->getElementType();
1298
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001299 IRBuilder<> Builder(CI->getContext());
1300 Instruction *InsertPt = CI;
1301 BasicBlock *IfBlock = CI->getParent();
1302 Builder.SetInsertPoint(InsertPt);
1303 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1304
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001305 // Short-cut if the mask is all-true.
1306 bool IsAllOnesMask = isa<Constant>(Mask) &&
1307 cast<Constant>(Mask)->isAllOnesValue();
1308
1309 if (IsAllOnesMask) {
1310 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1311 CI->eraseFromParent();
1312 return;
1313 }
1314
1315 // Adjust alignment for the scalar instruction.
1316 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001317 // Bitcast %addr fron i8* to EltTy*
1318 Type *NewPtrType =
1319 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1320 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001321 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001322
1323 if (isa<ConstantVector>(Mask)) {
1324 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1325 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1326 continue;
1327 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1328 Value *Gep =
1329 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1330 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1331 }
1332 CI->eraseFromParent();
1333 return;
1334 }
1335
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001336 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1337
1338 // Fill the "else" block, created in the previous iteration
1339 //
1340 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1341 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001342 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001343 //
1344 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1345 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1346 ConstantInt::get(Predicate->getType(), 1));
1347
1348 // Create "cond" block
1349 //
1350 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1351 // %EltAddr = getelementptr i32* %1, i32 0
1352 // %store i32 %OneElt, i32* %EltAddr
1353 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001354 BasicBlock *CondBlock =
1355 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001356 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001357
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001358 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001359 Value *Gep =
1360 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001361 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001362
1363 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001364 BasicBlock *NewIfBlock =
1365 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001366 Builder.SetInsertPoint(InsertPt);
1367 Instruction *OldBr = IfBlock->getTerminator();
1368 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1369 OldBr->eraseFromParent();
1370 IfBlock = NewIfBlock;
1371 }
1372 CI->eraseFromParent();
1373}
1374
Elena Demikhovsky09285852015-10-25 15:37:55 +00001375// Translate a masked gather intrinsic like
1376// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1377// <16 x i1> %Mask, <16 x i32> %Src)
1378// to a chain of basic blocks, with loading element one-by-one if
1379// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001380//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001381// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1382// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1383// % ToLoad0 = icmp eq i1 % Mask0, true
1384// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001385//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001386// cond.load:
1387// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1388// % Load0 = load i32, i32* % Ptr0, align 4
1389// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1390// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001391//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001392// else:
1393// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1394// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1395// % ToLoad1 = icmp eq i1 % Mask1, true
1396// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001397//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001398// cond.load1:
1399// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1400// % Load1 = load i32, i32* % Ptr1, align 4
1401// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1402// br label %else2
1403// . . .
1404// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1405// ret <16 x i32> %Result
1406static void ScalarizeMaskedGather(CallInst *CI) {
1407 Value *Ptrs = CI->getArgOperand(0);
1408 Value *Alignment = CI->getArgOperand(1);
1409 Value *Mask = CI->getArgOperand(2);
1410 Value *Src0 = CI->getArgOperand(3);
1411
1412 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1413
1414 assert(VecType && "Unexpected return type of masked load intrinsic");
1415
1416 IRBuilder<> Builder(CI->getContext());
1417 Instruction *InsertPt = CI;
1418 BasicBlock *IfBlock = CI->getParent();
1419 BasicBlock *CondBlock = nullptr;
1420 BasicBlock *PrevIfBlock = CI->getParent();
1421 Builder.SetInsertPoint(InsertPt);
1422 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1423
1424 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1425
1426 Value *UndefVal = UndefValue::get(VecType);
1427
1428 // The result vector
1429 Value *VResult = UndefVal;
1430 unsigned VectorWidth = VecType->getNumElements();
1431
1432 // Shorten the way if the mask is a vector of constants.
1433 bool IsConstMask = isa<ConstantVector>(Mask);
1434
1435 if (IsConstMask) {
1436 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1437 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1438 continue;
1439 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1440 "Ptr" + Twine(Idx));
1441 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1442 "Load" + Twine(Idx));
1443 VResult = Builder.CreateInsertElement(VResult, Load,
1444 Builder.getInt32(Idx),
1445 "Res" + Twine(Idx));
1446 }
1447 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1448 CI->replaceAllUsesWith(NewI);
1449 CI->eraseFromParent();
1450 return;
1451 }
1452
1453 PHINode *Phi = nullptr;
1454 Value *PrevPhi = UndefVal;
1455
1456 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1457
1458 // Fill the "else" block, created in the previous iteration
1459 //
1460 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1461 // %ToLoad1 = icmp eq i1 %Mask1, true
1462 // br i1 %ToLoad1, label %cond.load, label %else
1463 //
1464 if (Idx > 0) {
1465 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1466 Phi->addIncoming(VResult, CondBlock);
1467 Phi->addIncoming(PrevPhi, PrevIfBlock);
1468 PrevPhi = Phi;
1469 VResult = Phi;
1470 }
1471
1472 Value *Predicate = Builder.CreateExtractElement(Mask,
1473 Builder.getInt32(Idx),
1474 "Mask" + Twine(Idx));
1475 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1476 ConstantInt::get(Predicate->getType(), 1),
1477 "ToLoad" + Twine(Idx));
1478
1479 // Create "cond" block
1480 //
1481 // %EltAddr = getelementptr i32* %1, i32 0
1482 // %Elt = load i32* %EltAddr
1483 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1484 //
1485 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1486 Builder.SetInsertPoint(InsertPt);
1487
1488 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1489 "Ptr" + Twine(Idx));
1490 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1491 "Load" + Twine(Idx));
1492 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1493 "Res" + Twine(Idx));
1494
1495 // Create "else" block, fill it in the next iteration
1496 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1497 Builder.SetInsertPoint(InsertPt);
1498 Instruction *OldBr = IfBlock->getTerminator();
1499 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1500 OldBr->eraseFromParent();
1501 PrevIfBlock = IfBlock;
1502 IfBlock = NewIfBlock;
1503 }
1504
1505 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1506 Phi->addIncoming(VResult, CondBlock);
1507 Phi->addIncoming(PrevPhi, PrevIfBlock);
1508 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1509 CI->replaceAllUsesWith(NewI);
1510 CI->eraseFromParent();
1511}
1512
1513// Translate a masked scatter intrinsic, like
1514// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1515// <16 x i1> %Mask)
1516// to a chain of basic blocks, that stores element one-by-one if
1517// the appropriate mask bit is set.
1518//
1519// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1520// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1521// % ToStore0 = icmp eq i1 % Mask0, true
1522// br i1 %ToStore0, label %cond.store, label %else
1523//
1524// cond.store:
1525// % Elt0 = extractelement <16 x i32> %Src, i32 0
1526// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1527// store i32 %Elt0, i32* % Ptr0, align 4
1528// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001529//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001530// else:
1531// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1532// % ToStore1 = icmp eq i1 % Mask1, true
1533// br i1 % ToStore1, label %cond.store1, label %else2
1534//
1535// cond.store1:
1536// % Elt1 = extractelement <16 x i32> %Src, i32 1
1537// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1538// store i32 % Elt1, i32* % Ptr1, align 4
1539// br label %else2
1540// . . .
1541static void ScalarizeMaskedScatter(CallInst *CI) {
1542 Value *Src = CI->getArgOperand(0);
1543 Value *Ptrs = CI->getArgOperand(1);
1544 Value *Alignment = CI->getArgOperand(2);
1545 Value *Mask = CI->getArgOperand(3);
1546
1547 assert(isa<VectorType>(Src->getType()) &&
1548 "Unexpected data type in masked scatter intrinsic");
1549 assert(isa<VectorType>(Ptrs->getType()) &&
1550 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1551 "Vector of pointers is expected in masked scatter intrinsic");
1552
1553 IRBuilder<> Builder(CI->getContext());
1554 Instruction *InsertPt = CI;
1555 BasicBlock *IfBlock = CI->getParent();
1556 Builder.SetInsertPoint(InsertPt);
1557 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1558
1559 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1560 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1561
1562 // Shorten the way if the mask is a vector of constants.
1563 bool IsConstMask = isa<ConstantVector>(Mask);
1564
1565 if (IsConstMask) {
1566 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1567 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1568 continue;
1569 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1570 "Elt" + Twine(Idx));
1571 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1572 "Ptr" + Twine(Idx));
1573 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1574 }
1575 CI->eraseFromParent();
1576 return;
1577 }
1578 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1579 // Fill the "else" block, created in the previous iteration
1580 //
1581 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1582 // % ToStore = icmp eq i1 % Mask1, true
1583 // br i1 % ToStore, label %cond.store, label %else
1584 //
1585 Value *Predicate = Builder.CreateExtractElement(Mask,
1586 Builder.getInt32(Idx),
1587 "Mask" + Twine(Idx));
1588 Value *Cmp =
1589 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1590 ConstantInt::get(Predicate->getType(), 1),
1591 "ToStore" + Twine(Idx));
1592
1593 // Create "cond" block
1594 //
1595 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1596 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1597 // %store i32 % Elt1, i32* % Ptr1
1598 //
1599 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1600 Builder.SetInsertPoint(InsertPt);
1601
1602 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1603 "Elt" + Twine(Idx));
1604 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1605 "Ptr" + Twine(Idx));
1606 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1607
1608 // Create "else" block, fill it in the next iteration
1609 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1610 Builder.SetInsertPoint(InsertPt);
1611 Instruction *OldBr = IfBlock->getTerminator();
1612 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1613 OldBr->eraseFromParent();
1614 IfBlock = NewIfBlock;
1615 }
1616 CI->eraseFromParent();
1617}
1618
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001619/// If counting leading or trailing zeros is an expensive operation and a zero
1620/// input is defined, add a check for zero to avoid calling the intrinsic.
1621///
1622/// We want to transform:
1623/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1624///
1625/// into:
1626/// entry:
1627/// %cmpz = icmp eq i64 %A, 0
1628/// br i1 %cmpz, label %cond.end, label %cond.false
1629/// cond.false:
1630/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1631/// br label %cond.end
1632/// cond.end:
1633/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1634///
1635/// If the transform is performed, return true and set ModifiedDT to true.
1636static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1637 const TargetLowering *TLI,
1638 const DataLayout *DL,
1639 bool &ModifiedDT) {
1640 if (!TLI || !DL)
1641 return false;
1642
1643 // If a zero input is undefined, it doesn't make sense to despeculate that.
1644 if (match(CountZeros->getOperand(1), m_One()))
1645 return false;
1646
1647 // If it's cheap to speculate, there's nothing to do.
1648 auto IntrinsicID = CountZeros->getIntrinsicID();
1649 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1650 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1651 return false;
1652
1653 // Only handle legal scalar cases. Anything else requires too much work.
1654 Type *Ty = CountZeros->getType();
1655 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1656 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
1657 return false;
1658
1659 // The intrinsic will be sunk behind a compare against zero and branch.
1660 BasicBlock *StartBlock = CountZeros->getParent();
1661 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1662
1663 // Create another block after the count zero intrinsic. A PHI will be added
1664 // in this block to select the result of the intrinsic or the bit-width
1665 // constant if the input to the intrinsic is zero.
1666 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1667 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1668
1669 // Set up a builder to create a compare, conditional branch, and PHI.
1670 IRBuilder<> Builder(CountZeros->getContext());
1671 Builder.SetInsertPoint(StartBlock->getTerminator());
1672 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1673
1674 // Replace the unconditional branch that was created by the first split with
1675 // a compare against zero and a conditional branch.
1676 Value *Zero = Constant::getNullValue(Ty);
1677 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1678 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1679 StartBlock->getTerminator()->eraseFromParent();
1680
1681 // Create a PHI in the end block to select either the output of the intrinsic
1682 // or the bit width of the operand.
1683 Builder.SetInsertPoint(&EndBlock->front());
1684 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1685 CountZeros->replaceAllUsesWith(PN);
1686 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1687 PN->addIncoming(BitWidth, StartBlock);
1688 PN->addIncoming(CountZeros, CallBlock);
1689
1690 // We are explicitly handling the zero case, so we can set the intrinsic's
1691 // undefined zero argument to 'true'. This will also prevent reprocessing the
1692 // intrinsic; we only despeculate when a zero input is defined.
1693 CountZeros->setArgOperand(1, Builder.getTrue());
1694 ModifiedDT = true;
1695 return true;
1696}
1697
Sanjay Patelfc580a62015-09-21 23:03:16 +00001698bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001699 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001700
Chris Lattner7a277142011-01-15 07:14:54 +00001701 // Lower inline assembly if we can.
1702 // If we found an inline asm expession, and if the target knows how to
1703 // lower it to normal LLVM code, do so now.
1704 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1705 if (TLI->ExpandInlineAsm(CI)) {
1706 // Avoid invalidating the iterator.
1707 CurInstIterator = BB->begin();
1708 // Avoid processing instructions out of order, which could cause
1709 // reuse before a value is defined.
1710 SunkAddrs.clear();
1711 return true;
1712 }
1713 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001714 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001715 return true;
1716 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001717
John Brawn0dbcd652015-03-18 12:01:59 +00001718 // Align the pointer arguments to this call if the target thinks it's a good
1719 // idea
1720 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001721 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001722 for (auto &Arg : CI->arg_operands()) {
1723 // We want to align both objects whose address is used directly and
1724 // objects whose address is used in casts and GEPs, though it only makes
1725 // sense for GEPs if the offset is a multiple of the desired alignment and
1726 // if size - offset meets the size threshold.
1727 if (!Arg->getType()->isPointerTy())
1728 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001729 APInt Offset(DL->getPointerSizeInBits(
1730 cast<PointerType>(Arg->getType())->getAddressSpace()),
1731 0);
1732 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001733 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001734 if ((Offset2 & (PrefAlign-1)) != 0)
1735 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001736 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001737 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1738 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001739 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001740 // Global variables can only be aligned if they are defined in this
1741 // object (i.e. they are uniquely initialized in this object), and
1742 // over-aligning global variables that have an explicit section is
1743 // forbidden.
1744 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001745 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
1746 GV->getAlignment() < PrefAlign &&
Mehdi Amini4fe37982015-07-07 18:45:17 +00001747 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1748 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001749 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001750 }
1751 // If this is a memcpy (or similar) then we may be able to improve the
1752 // alignment
1753 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001754 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001755 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001756 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001757 if (Align > MI->getAlignment())
1758 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001759 }
1760 }
1761
Eric Christopher4b7948e2010-03-11 02:41:03 +00001762 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001763 if (II) {
1764 switch (II->getIntrinsicID()) {
1765 default: break;
1766 case Intrinsic::objectsize: {
1767 // Lower all uses of llvm.objectsize.*
1768 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1769 Type *ReturnTy = CI->getType();
1770 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001771
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001772 // Substituting this can cause recursive simplifications, which can
1773 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1774 // happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001775 WeakVH IterHandle(&*CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001776
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001777 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001778 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001779
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001780 // If the iterator instruction was recursively deleted, start over at the
1781 // start of the block.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001782 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001783 CurInstIterator = BB->begin();
1784 SunkAddrs.clear();
1785 }
1786 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001787 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001788 case Intrinsic::masked_load: {
1789 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001790 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001791 ScalarizeMaskedLoad(CI);
1792 ModifiedDT = true;
1793 return true;
1794 }
1795 return false;
1796 }
1797 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001798 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001799 ScalarizeMaskedStore(CI);
1800 ModifiedDT = true;
1801 return true;
1802 }
1803 return false;
1804 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001805 case Intrinsic::masked_gather: {
1806 if (!TTI->isLegalMaskedGather(CI->getType())) {
1807 ScalarizeMaskedGather(CI);
1808 ModifiedDT = true;
1809 return true;
1810 }
1811 return false;
1812 }
1813 case Intrinsic::masked_scatter: {
1814 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
1815 ScalarizeMaskedScatter(CI);
1816 ModifiedDT = true;
1817 return true;
1818 }
1819 return false;
1820 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001821 case Intrinsic::aarch64_stlxr:
1822 case Intrinsic::aarch64_stxr: {
1823 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1824 if (!ExtVal || !ExtVal->hasOneUse() ||
1825 ExtVal->getParent() == CI->getParent())
1826 return false;
1827 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1828 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001829 // Mark this instruction as "inserted by CGP", so that other
1830 // optimizations don't touch it.
1831 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001832 return true;
1833 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001834 case Intrinsic::invariant_group_barrier:
1835 II->replaceAllUsesWith(II->getArgOperand(0));
1836 II->eraseFromParent();
1837 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001838
1839 case Intrinsic::cttz:
1840 case Intrinsic::ctlz:
1841 // If counting zeros is expensive, try to avoid it.
1842 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001843 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001844
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001845 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001846 // Unknown address space.
1847 // TODO: Target hook to pick which address space the intrinsic cares
1848 // about?
1849 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001850 SmallVector<Value*, 2> PtrOps;
1851 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001852 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001853 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001854 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001855 return true;
1856 }
Pete Cooper615fd892012-03-13 20:59:56 +00001857 }
1858
Eric Christopher4b7948e2010-03-11 02:41:03 +00001859 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001860 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001861
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001862 // Lower all default uses of _chk calls. This is very similar
1863 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001864 // to fortified library functions (e.g. __memcpy_chk) that have the default
1865 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001866 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001867 if (Value *V = Simplifier.optimizeCall(CI)) {
1868 CI->replaceAllUsesWith(V);
1869 CI->eraseFromParent();
1870 return true;
1871 }
1872 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001873}
Chris Lattner1b93be52011-01-15 07:25:29 +00001874
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001875/// Look for opportunities to duplicate return instructions to the predecessor
1876/// to enable tail call optimizations. The case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001877/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001878/// bb0:
1879/// %tmp0 = tail call i32 @f0()
1880/// br label %return
1881/// bb1:
1882/// %tmp1 = tail call i32 @f1()
1883/// br label %return
1884/// bb2:
1885/// %tmp2 = tail call i32 @f2()
1886/// br label %return
1887/// return:
1888/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1889/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001890/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001891///
1892/// =>
1893///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001894/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001895/// bb0:
1896/// %tmp0 = tail call i32 @f0()
1897/// ret i32 %tmp0
1898/// bb1:
1899/// %tmp1 = tail call i32 @f1()
1900/// ret i32 %tmp1
1901/// bb2:
1902/// %tmp2 = tail call i32 @f2()
1903/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001904/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001905bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001906 if (!TLI)
1907 return false;
1908
Benjamin Kramer455fa352012-11-23 19:17:06 +00001909 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1910 if (!RI)
1911 return false;
1912
Craig Topperc0196b12014-04-14 00:51:57 +00001913 PHINode *PN = nullptr;
1914 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001915 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001916 if (V) {
1917 BCI = dyn_cast<BitCastInst>(V);
1918 if (BCI)
1919 V = BCI->getOperand(0);
1920
1921 PN = dyn_cast<PHINode>(V);
1922 if (!PN)
1923 return false;
1924 }
Evan Cheng0663f232011-03-21 01:19:09 +00001925
Cameron Zwarich4649f172011-03-24 04:52:10 +00001926 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001927 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001928
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001929 // It's not safe to eliminate the sign / zero extension of the return value.
1930 // See llvm::isInTailCallPosition().
1931 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001932 AttributeSet CallerAttrs = F->getAttributes();
1933 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1934 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001935 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001936
Cameron Zwarich4649f172011-03-24 04:52:10 +00001937 // Make sure there are no instructions between the PHI and return, or that the
1938 // return is the first instruction in the block.
1939 if (PN) {
1940 BasicBlock::iterator BI = BB->begin();
1941 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001942 if (&*BI == BCI)
1943 // Also skip over the bitcast.
1944 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001945 if (&*BI != RI)
1946 return false;
1947 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001948 BasicBlock::iterator BI = BB->begin();
1949 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1950 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001951 return false;
1952 }
Evan Cheng0663f232011-03-21 01:19:09 +00001953
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001954 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1955 /// call.
1956 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001957 if (PN) {
1958 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1959 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1960 // Make sure the phi value is indeed produced by the tail call.
1961 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1962 TLI->mayBeEmittedAsTailCall(CI))
1963 TailCalls.push_back(CI);
1964 }
1965 } else {
1966 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001967 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001968 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001969 continue;
1970
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001971 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001972 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1973 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001974 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1975 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001976 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001977
Cameron Zwarich4649f172011-03-24 04:52:10 +00001978 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001979 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001980 TailCalls.push_back(CI);
1981 }
Evan Cheng0663f232011-03-21 01:19:09 +00001982 }
1983
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001984 bool Changed = false;
1985 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1986 CallInst *CI = TailCalls[i];
1987 CallSite CS(CI);
1988
1989 // Conservatively require the attributes of the call to match those of the
1990 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001991 AttributeSet CalleeAttrs = CS.getAttributes();
1992 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001993 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001994 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001995 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001996 continue;
1997
1998 // Make sure the call instruction is followed by an unconditional branch to
1999 // the return block.
2000 BasicBlock *CallBB = CI->getParent();
2001 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2002 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2003 continue;
2004
2005 // Duplicate the return into CallBB.
2006 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002007 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002008 ++NumRetsDup;
2009 }
2010
2011 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002012 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002013 BB->eraseFromParent();
2014
2015 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002016}
2017
Chris Lattner728f9022008-11-25 07:09:13 +00002018//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002019// Memory Optimization
2020//===----------------------------------------------------------------------===//
2021
Chandler Carruthc8925912013-01-05 02:09:22 +00002022namespace {
2023
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002024/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002025/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002026struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002027 Value *BaseReg;
2028 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002029 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002030 void print(raw_ostream &OS) const;
2031 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002032
Chandler Carruthc8925912013-01-05 02:09:22 +00002033 bool operator==(const ExtAddrMode& O) const {
2034 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2035 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2036 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2037 }
2038};
2039
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002040#ifndef NDEBUG
2041static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2042 AM.print(OS);
2043 return OS;
2044}
2045#endif
2046
Chandler Carruthc8925912013-01-05 02:09:22 +00002047void ExtAddrMode::print(raw_ostream &OS) const {
2048 bool NeedPlus = false;
2049 OS << "[";
2050 if (BaseGV) {
2051 OS << (NeedPlus ? " + " : "")
2052 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002053 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002054 NeedPlus = true;
2055 }
2056
Richard Trieuc0f91212014-05-30 03:15:17 +00002057 if (BaseOffs) {
2058 OS << (NeedPlus ? " + " : "")
2059 << BaseOffs;
2060 NeedPlus = true;
2061 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002062
2063 if (BaseReg) {
2064 OS << (NeedPlus ? " + " : "")
2065 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002066 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002067 NeedPlus = true;
2068 }
2069 if (Scale) {
2070 OS << (NeedPlus ? " + " : "")
2071 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002072 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002073 }
2074
2075 OS << ']';
2076}
2077
2078#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2079void ExtAddrMode::dump() const {
2080 print(dbgs());
2081 dbgs() << '\n';
2082}
2083#endif
2084
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002085/// \brief This class provides transaction based operation on the IR.
2086/// Every change made through this class is recorded in the internal state and
2087/// can be undone (rollback) until commit is called.
2088class TypePromotionTransaction {
2089
2090 /// \brief This represents the common interface of the individual transaction.
2091 /// Each class implements the logic for doing one specific modification on
2092 /// the IR via the TypePromotionTransaction.
2093 class TypePromotionAction {
2094 protected:
2095 /// The Instruction modified.
2096 Instruction *Inst;
2097
2098 public:
2099 /// \brief Constructor of the action.
2100 /// The constructor performs the related action on the IR.
2101 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2102
2103 virtual ~TypePromotionAction() {}
2104
2105 /// \brief Undo the modification done by this action.
2106 /// When this method is called, the IR must be in the same state as it was
2107 /// before this action was applied.
2108 /// \pre Undoing the action works if and only if the IR is in the exact same
2109 /// state as it was directly after this action was applied.
2110 virtual void undo() = 0;
2111
2112 /// \brief Advocate every change made by this action.
2113 /// When the results on the IR of the action are to be kept, it is important
2114 /// to call this function, otherwise hidden information may be kept forever.
2115 virtual void commit() {
2116 // Nothing to be done, this action is not doing anything.
2117 }
2118 };
2119
2120 /// \brief Utility to remember the position of an instruction.
2121 class InsertionHandler {
2122 /// Position of an instruction.
2123 /// Either an instruction:
2124 /// - Is the first in a basic block: BB is used.
2125 /// - Has a previous instructon: PrevInst is used.
2126 union {
2127 Instruction *PrevInst;
2128 BasicBlock *BB;
2129 } Point;
2130 /// Remember whether or not the instruction had a previous instruction.
2131 bool HasPrevInstruction;
2132
2133 public:
2134 /// \brief Record the position of \p Inst.
2135 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002136 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002137 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2138 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002139 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002140 else
2141 Point.BB = Inst->getParent();
2142 }
2143
2144 /// \brief Insert \p Inst at the recorded position.
2145 void insert(Instruction *Inst) {
2146 if (HasPrevInstruction) {
2147 if (Inst->getParent())
2148 Inst->removeFromParent();
2149 Inst->insertAfter(Point.PrevInst);
2150 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002151 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002152 if (Inst->getParent())
2153 Inst->moveBefore(Position);
2154 else
2155 Inst->insertBefore(Position);
2156 }
2157 }
2158 };
2159
2160 /// \brief Move an instruction before another.
2161 class InstructionMoveBefore : public TypePromotionAction {
2162 /// Original position of the instruction.
2163 InsertionHandler Position;
2164
2165 public:
2166 /// \brief Move \p Inst before \p Before.
2167 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2168 : TypePromotionAction(Inst), Position(Inst) {
2169 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2170 Inst->moveBefore(Before);
2171 }
2172
2173 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002174 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002175 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2176 Position.insert(Inst);
2177 }
2178 };
2179
2180 /// \brief Set the operand of an instruction with a new value.
2181 class OperandSetter : public TypePromotionAction {
2182 /// Original operand of the instruction.
2183 Value *Origin;
2184 /// Index of the modified instruction.
2185 unsigned Idx;
2186
2187 public:
2188 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2189 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2190 : TypePromotionAction(Inst), Idx(Idx) {
2191 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2192 << "for:" << *Inst << "\n"
2193 << "with:" << *NewVal << "\n");
2194 Origin = Inst->getOperand(Idx);
2195 Inst->setOperand(Idx, NewVal);
2196 }
2197
2198 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002199 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002200 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2201 << "for: " << *Inst << "\n"
2202 << "with: " << *Origin << "\n");
2203 Inst->setOperand(Idx, Origin);
2204 }
2205 };
2206
2207 /// \brief Hide the operands of an instruction.
2208 /// Do as if this instruction was not using any of its operands.
2209 class OperandsHider : public TypePromotionAction {
2210 /// The list of original operands.
2211 SmallVector<Value *, 4> OriginalValues;
2212
2213 public:
2214 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2215 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2216 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2217 unsigned NumOpnds = Inst->getNumOperands();
2218 OriginalValues.reserve(NumOpnds);
2219 for (unsigned It = 0; It < NumOpnds; ++It) {
2220 // Save the current operand.
2221 Value *Val = Inst->getOperand(It);
2222 OriginalValues.push_back(Val);
2223 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002224 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002225 // that we are not willing to pay.
2226 Inst->setOperand(It, UndefValue::get(Val->getType()));
2227 }
2228 }
2229
2230 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002231 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002232 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2233 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2234 Inst->setOperand(It, OriginalValues[It]);
2235 }
2236 };
2237
2238 /// \brief Build a truncate instruction.
2239 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002240 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002241 public:
2242 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2243 /// result.
2244 /// trunc Opnd to Ty.
2245 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2246 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002247 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2248 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002249 }
2250
Quentin Colombetac55b152014-09-16 22:36:07 +00002251 /// \brief Get the built value.
2252 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002253
2254 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002255 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002256 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2257 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2258 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002259 }
2260 };
2261
2262 /// \brief Build a sign extension instruction.
2263 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002264 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002265 public:
2266 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2267 /// result.
2268 /// sext Opnd to Ty.
2269 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002270 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002271 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002272 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2273 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002274 }
2275
Quentin Colombetac55b152014-09-16 22:36:07 +00002276 /// \brief Get the built value.
2277 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002278
2279 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002280 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002281 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2282 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2283 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002284 }
2285 };
2286
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002287 /// \brief Build a zero extension instruction.
2288 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002289 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002290 public:
2291 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2292 /// result.
2293 /// zext Opnd to Ty.
2294 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002295 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002296 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002297 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2298 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002299 }
2300
Quentin Colombetac55b152014-09-16 22:36:07 +00002301 /// \brief Get the built value.
2302 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002303
2304 /// \brief Remove the built instruction.
2305 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002306 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2307 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2308 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002309 }
2310 };
2311
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002312 /// \brief Mutate an instruction to another type.
2313 class TypeMutator : public TypePromotionAction {
2314 /// Record the original type.
2315 Type *OrigTy;
2316
2317 public:
2318 /// \brief Mutate the type of \p Inst into \p NewTy.
2319 TypeMutator(Instruction *Inst, Type *NewTy)
2320 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2321 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2322 << "\n");
2323 Inst->mutateType(NewTy);
2324 }
2325
2326 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002327 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002328 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2329 << "\n");
2330 Inst->mutateType(OrigTy);
2331 }
2332 };
2333
2334 /// \brief Replace the uses of an instruction by another instruction.
2335 class UsesReplacer : public TypePromotionAction {
2336 /// Helper structure to keep track of the replaced uses.
2337 struct InstructionAndIdx {
2338 /// The instruction using the instruction.
2339 Instruction *Inst;
2340 /// The index where this instruction is used for Inst.
2341 unsigned Idx;
2342 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2343 : Inst(Inst), Idx(Idx) {}
2344 };
2345
2346 /// Keep track of the original uses (pair Instruction, Index).
2347 SmallVector<InstructionAndIdx, 4> OriginalUses;
2348 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2349
2350 public:
2351 /// \brief Replace all the use of \p Inst by \p New.
2352 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2353 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2354 << "\n");
2355 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002356 for (Use &U : Inst->uses()) {
2357 Instruction *UserI = cast<Instruction>(U.getUser());
2358 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002359 }
2360 // Now, we can replace the uses.
2361 Inst->replaceAllUsesWith(New);
2362 }
2363
2364 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002365 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002366 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2367 for (use_iterator UseIt = OriginalUses.begin(),
2368 EndIt = OriginalUses.end();
2369 UseIt != EndIt; ++UseIt) {
2370 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2371 }
2372 }
2373 };
2374
2375 /// \brief Remove an instruction from the IR.
2376 class InstructionRemover : public TypePromotionAction {
2377 /// Original position of the instruction.
2378 InsertionHandler Inserter;
2379 /// Helper structure to hide all the link to the instruction. In other
2380 /// words, this helps to do as if the instruction was removed.
2381 OperandsHider Hider;
2382 /// Keep track of the uses replaced, if any.
2383 UsesReplacer *Replacer;
2384
2385 public:
2386 /// \brief Remove all reference of \p Inst and optinally replace all its
2387 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002388 /// \pre If !Inst->use_empty(), then New != nullptr
2389 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002390 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002391 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002392 if (New)
2393 Replacer = new UsesReplacer(Inst, New);
2394 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2395 Inst->removeFromParent();
2396 }
2397
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002398 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002399
2400 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002401 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002402
2403 /// \brief Resurrect the instruction and reassign it to the proper uses if
2404 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002405 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002406 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2407 Inserter.insert(Inst);
2408 if (Replacer)
2409 Replacer->undo();
2410 Hider.undo();
2411 }
2412 };
2413
2414public:
2415 /// Restoration point.
2416 /// The restoration point is a pointer to an action instead of an iterator
2417 /// because the iterator may be invalidated but not the pointer.
2418 typedef const TypePromotionAction *ConstRestorationPt;
2419 /// Advocate every changes made in that transaction.
2420 void commit();
2421 /// Undo all the changes made after the given point.
2422 void rollback(ConstRestorationPt Point);
2423 /// Get the current restoration point.
2424 ConstRestorationPt getRestorationPoint() const;
2425
2426 /// \name API for IR modification with state keeping to support rollback.
2427 /// @{
2428 /// Same as Instruction::setOperand.
2429 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2430 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002431 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002432 /// Same as Value::replaceAllUsesWith.
2433 void replaceAllUsesWith(Instruction *Inst, Value *New);
2434 /// Same as Value::mutateType.
2435 void mutateType(Instruction *Inst, Type *NewTy);
2436 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002437 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002438 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002439 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002440 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002441 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002442 /// Same as Instruction::moveBefore.
2443 void moveBefore(Instruction *Inst, Instruction *Before);
2444 /// @}
2445
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002446private:
2447 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002448 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2449 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002450};
2451
2452void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2453 Value *NewVal) {
2454 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002455 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456}
2457
2458void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2459 Value *NewVal) {
2460 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002461 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002462}
2463
2464void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2465 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002466 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002467}
2468
2469void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002470 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002471}
2472
Quentin Colombetac55b152014-09-16 22:36:07 +00002473Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2474 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002475 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002476 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002477 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002478 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002479}
2480
Quentin Colombetac55b152014-09-16 22:36:07 +00002481Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2482 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002483 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002484 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002485 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002486 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002487}
2488
Quentin Colombetac55b152014-09-16 22:36:07 +00002489Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2490 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002491 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002492 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002493 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002494 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002495}
2496
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002497void TypePromotionTransaction::moveBefore(Instruction *Inst,
2498 Instruction *Before) {
2499 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002500 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002501}
2502
2503TypePromotionTransaction::ConstRestorationPt
2504TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002505 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002506}
2507
2508void TypePromotionTransaction::commit() {
2509 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002510 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002511 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002512 Actions.clear();
2513}
2514
2515void TypePromotionTransaction::rollback(
2516 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002517 while (!Actions.empty() && Point != Actions.back().get()) {
2518 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002519 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002520 }
2521}
2522
Chandler Carruthc8925912013-01-05 02:09:22 +00002523/// \brief A helper class for matching addressing modes.
2524///
2525/// This encapsulates the logic for matching the target-legal addressing modes.
2526class AddressingModeMatcher {
2527 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002528 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002529 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002530 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002531
2532 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2533 /// the memory instruction that we're computing this address for.
2534 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002535 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002536 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002537
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002538 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002539 /// part of the return value of this addressing mode matching stuff.
2540 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002541
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002542 /// The instructions inserted by other CodeGenPrepare optimizations.
2543 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002544 /// A map from the instructions to their type before promotion.
2545 InstrToOrigTy &PromotedInsts;
2546 /// The ongoing transaction where every action should be registered.
2547 TypePromotionTransaction &TPT;
2548
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002549 /// This is set to true when we should not do profitability checks.
2550 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002551 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002552
Eric Christopherd75c00c2015-02-26 22:38:34 +00002553 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002554 const TargetMachine &TM, Type *AT, unsigned AS,
2555 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002556 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002557 InstrToOrigTy &PromotedInsts,
2558 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002559 : AddrModeInsts(AMI), TM(TM),
2560 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2561 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002562 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2563 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2564 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002565 IgnoreProfitability = false;
2566 }
2567public:
Stephen Lin837bba12013-07-15 17:55:02 +00002568
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002569 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002570 /// give an access type of AccessTy. This returns a list of involved
2571 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002572 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002573 /// optimizations.
2574 /// \p PromotedInsts maps the instructions to their type before promotion.
2575 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002576 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002577 Instruction *MemoryInst,
2578 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002579 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002580 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002581 InstrToOrigTy &PromotedInsts,
2582 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002583 ExtAddrMode Result;
2584
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002585 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002586 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002587 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002588 (void)Success; assert(Success && "Couldn't select *anything*?");
2589 return Result;
2590 }
2591private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002592 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2593 bool matchAddr(Value *V, unsigned Depth);
2594 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002595 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002596 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002597 ExtAddrMode &AMBefore,
2598 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002599 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2600 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002601 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002602};
2603
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002604/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002605/// Return true and update AddrMode if this addr mode is legal for the target,
2606/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002607bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002608 unsigned Depth) {
2609 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2610 // mode. Just process that directly.
2611 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002612 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002613
Chandler Carruthc8925912013-01-05 02:09:22 +00002614 // If the scale is 0, it takes nothing to add this.
2615 if (Scale == 0)
2616 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002617
Chandler Carruthc8925912013-01-05 02:09:22 +00002618 // If we already have a scale of this value, we can add to it, otherwise, we
2619 // need an available scale field.
2620 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2621 return false;
2622
2623 ExtAddrMode TestAddrMode = AddrMode;
2624
2625 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2626 // [A+B + A*7] -> [B+A*8].
2627 TestAddrMode.Scale += Scale;
2628 TestAddrMode.ScaledReg = ScaleReg;
2629
2630 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002631 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002632 return false;
2633
2634 // It was legal, so commit it.
2635 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002636
Chandler Carruthc8925912013-01-05 02:09:22 +00002637 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2638 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2639 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002640 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002641 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2642 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2643 TestAddrMode.ScaledReg = AddLHS;
2644 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002645
Chandler Carruthc8925912013-01-05 02:09:22 +00002646 // If this addressing mode is legal, commit it and remember that we folded
2647 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002648 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002649 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2650 AddrMode = TestAddrMode;
2651 return true;
2652 }
2653 }
2654
2655 // Otherwise, not (x+c)*scale, just return what we have.
2656 return true;
2657}
2658
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002659/// This is a little filter, which returns true if an addressing computation
2660/// involving I might be folded into a load/store accessing it.
2661/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002662/// the set of instructions that MatchOperationAddr can.
2663static bool MightBeFoldableInst(Instruction *I) {
2664 switch (I->getOpcode()) {
2665 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002666 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002667 // Don't touch identity bitcasts.
2668 if (I->getType() == I->getOperand(0)->getType())
2669 return false;
2670 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2671 case Instruction::PtrToInt:
2672 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2673 return true;
2674 case Instruction::IntToPtr:
2675 // We know the input is intptr_t, so this is foldable.
2676 return true;
2677 case Instruction::Add:
2678 return true;
2679 case Instruction::Mul:
2680 case Instruction::Shl:
2681 // Can only handle X*C and X << C.
2682 return isa<ConstantInt>(I->getOperand(1));
2683 case Instruction::GetElementPtr:
2684 return true;
2685 default:
2686 return false;
2687 }
2688}
2689
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002690/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2691/// \note \p Val is assumed to be the product of some type promotion.
2692/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2693/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002694static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2695 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002696 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2697 if (!PromotedInst)
2698 return false;
2699 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2700 // If the ISDOpcode is undefined, it was undefined before the promotion.
2701 if (!ISDOpcode)
2702 return true;
2703 // Otherwise, check if the promoted instruction is legal or not.
2704 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002705 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002706}
2707
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002708/// \brief Hepler class to perform type promotion.
2709class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002710 /// \brief Utility function to check whether or not a sign or zero extension
2711 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2712 /// either using the operands of \p Inst or promoting \p Inst.
2713 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002714 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002715 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002716 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002717 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002718 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002719 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002720 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002721 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2722 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002723
2724 /// \brief Utility function to determine if \p OpIdx should be promoted when
2725 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002726 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002727 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002728 }
2729
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002730 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002731 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002732 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002733 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002734 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002735 /// Newly added extensions are inserted in \p Exts.
2736 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002737 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002738 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002739 static Value *promoteOperandForTruncAndAnyExt(
2740 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002741 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002742 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002743 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002744
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002745 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002746 /// operand is promotable and is not a supported trunc or sext.
2747 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002748 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002749 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002750 /// Newly added extensions are inserted in \p Exts.
2751 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002752 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002753 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002754 static Value *promoteOperandForOther(Instruction *Ext,
2755 TypePromotionTransaction &TPT,
2756 InstrToOrigTy &PromotedInsts,
2757 unsigned &CreatedInstsCost,
2758 SmallVectorImpl<Instruction *> *Exts,
2759 SmallVectorImpl<Instruction *> *Truncs,
2760 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002761
2762 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002763 static Value *signExtendOperandForOther(
2764 Instruction *Ext, TypePromotionTransaction &TPT,
2765 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2766 SmallVectorImpl<Instruction *> *Exts,
2767 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2768 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2769 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002770 }
2771
2772 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002773 static Value *zeroExtendOperandForOther(
2774 Instruction *Ext, TypePromotionTransaction &TPT,
2775 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2776 SmallVectorImpl<Instruction *> *Exts,
2777 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2778 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2779 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002780 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002781
2782public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002783 /// Type for the utility function that promotes the operand of Ext.
2784 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002785 InstrToOrigTy &PromotedInsts,
2786 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002787 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002788 SmallVectorImpl<Instruction *> *Truncs,
2789 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002790 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2791 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002792 /// \return NULL if no promotable action is possible with the current
2793 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002794 /// \p InsertedInsts keeps track of all the instructions inserted by the
2795 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002796 /// because we do not want to promote these instructions as CodeGenPrepare
2797 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2798 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002799 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002800 const TargetLowering &TLI,
2801 const InstrToOrigTy &PromotedInsts);
2802};
2803
2804bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002805 Type *ConsideredExtType,
2806 const InstrToOrigTy &PromotedInsts,
2807 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002808 // The promotion helper does not know how to deal with vector types yet.
2809 // To be able to fix that, we would need to fix the places where we
2810 // statically extend, e.g., constants and such.
2811 if (Inst->getType()->isVectorTy())
2812 return false;
2813
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002814 // We can always get through zext.
2815 if (isa<ZExtInst>(Inst))
2816 return true;
2817
2818 // sext(sext) is ok too.
2819 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002820 return true;
2821
2822 // We can get through binary operator, if it is legal. In other words, the
2823 // binary operator must have a nuw or nsw flag.
2824 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2825 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002826 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2827 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002828 return true;
2829
2830 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002831 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002832 if (!isa<TruncInst>(Inst))
2833 return false;
2834
2835 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002836 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002837 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002838 if (!OpndVal->getType()->isIntegerTy() ||
2839 OpndVal->getType()->getIntegerBitWidth() >
2840 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002841 return false;
2842
2843 // If the operand of the truncate is not an instruction, we will not have
2844 // any information on the dropped bits.
2845 // (Actually we could for constant but it is not worth the extra logic).
2846 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2847 if (!Opnd)
2848 return false;
2849
2850 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002851 // I.e., check that trunc just drops extended bits of the same kind of
2852 // the extension.
2853 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002854 const Type *OpndType;
2855 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002856 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2857 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002858 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2859 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002860 else
2861 return false;
2862
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002863 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002864 return Inst->getType()->getIntegerBitWidth() >=
2865 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002866}
2867
2868TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002869 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002870 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002871 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2872 "Unexpected instruction type");
2873 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2874 Type *ExtTy = Ext->getType();
2875 bool IsSExt = isa<SExtInst>(Ext);
2876 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002877 // get through.
2878 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002879 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002880 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002881
2882 // Do not promote if the operand has been added by codegenprepare.
2883 // Otherwise, it means we are undoing an optimization that is likely to be
2884 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002885 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002886 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002887
2888 // SExt or Trunc instructions.
2889 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002890 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2891 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002892 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002893
2894 // Regular instruction.
2895 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002896 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002897 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002898 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002899}
2900
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002901Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002902 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002903 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002904 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002905 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002906 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2907 // get through it and this method should not be called.
2908 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002909 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002910 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002911 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002912 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002913 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002914 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002915 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002916 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2917 TPT.replaceAllUsesWith(SExt, ZExt);
2918 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002919 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002920 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002921 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2922 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002923 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2924 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002925 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002926
2927 // Remove dead code.
2928 if (SExtOpnd->use_empty())
2929 TPT.eraseInstruction(SExtOpnd);
2930
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002931 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002932 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002933 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002934 if (ExtInst) {
2935 if (Exts)
2936 Exts->push_back(ExtInst);
2937 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2938 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002939 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002940 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002941
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002942 // At this point we have: ext ty opnd to ty.
2943 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2944 Value *NextVal = ExtInst->getOperand(0);
2945 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002946 return NextVal;
2947}
2948
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002949Value *TypePromotionHelper::promoteOperandForOther(
2950 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002951 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002952 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002953 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2954 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002955 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002956 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002957 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002958 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002959 if (!ExtOpnd->hasOneUse()) {
2960 // ExtOpnd will be promoted.
2961 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002962 // promoted version.
2963 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002964 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002965 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2966 ITrunc->removeFromParent();
2967 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002968 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002969 if (Truncs)
2970 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002971 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002972
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002973 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002974 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002975 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002976 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002977 }
2978
2979 // Get through the Instruction:
2980 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002981 // 2. Replace the uses of Ext by Inst.
2982 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002983
2984 // Remember the original type of the instruction before promotion.
2985 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002986 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2987 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002988 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002989 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002990 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002991 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002992 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002993 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002994
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002995 DEBUG(dbgs() << "Propagate Ext to operands\n");
2996 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002997 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002998 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2999 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3000 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003001 DEBUG(dbgs() << "No need to propagate\n");
3002 continue;
3003 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003004 // Check if we can statically extend the operand.
3005 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003006 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003007 DEBUG(dbgs() << "Statically extend\n");
3008 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3009 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3010 : Cst->getValue().zext(BitWidth);
3011 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003012 continue;
3013 }
3014 // UndefValue are typed, so we have to statically sign extend them.
3015 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003016 DEBUG(dbgs() << "Statically extend\n");
3017 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003018 continue;
3019 }
3020
3021 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003022 // Check if Ext was reused to extend an operand.
3023 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003024 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003025 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003026 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3027 : TPT.createZExt(Ext, Opnd, Ext->getType());
3028 if (!isa<Instruction>(ValForExtOpnd)) {
3029 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3030 continue;
3031 }
3032 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003033 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003034 if (Exts)
3035 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003036 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003037
3038 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003039 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3040 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003041 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003042 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003043 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003044 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003045 if (ExtForOpnd == Ext) {
3046 DEBUG(dbgs() << "Extension is useless now\n");
3047 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003048 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003049 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003050}
3051
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003052/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003053/// \p NewCost gives the cost of extension instructions created by the
3054/// promotion.
3055/// \p OldCost gives the cost of extension instructions before the promotion
3056/// plus the number of instructions that have been
3057/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003058/// \p PromotedOperand is the value that has been promoted.
3059/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003060bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003061 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3062 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3063 // The cost of the new extensions is greater than the cost of the
3064 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003065 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003066 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003067 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003068 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003069 return true;
3070 // The promotion is neutral but it may help folding the sign extension in
3071 // loads for instance.
3072 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003073 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003074}
3075
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003076/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003077/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003078/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003079/// If \p MovedAway is not NULL, it contains the information of whether or
3080/// not AddrInst has to be folded into the addressing mode on success.
3081/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3082/// because it has been moved away.
3083/// Thus AddrInst must not be added in the matched instructions.
3084/// This state can happen when AddrInst is a sext, since it may be moved away.
3085/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3086/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003087bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003088 unsigned Depth,
3089 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003090 // Avoid exponential behavior on extremely deep expression trees.
3091 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003092
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003093 // By default, all matched instructions stay in place.
3094 if (MovedAway)
3095 *MovedAway = false;
3096
Chandler Carruthc8925912013-01-05 02:09:22 +00003097 switch (Opcode) {
3098 case Instruction::PtrToInt:
3099 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003100 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003101 case Instruction::IntToPtr: {
3102 auto AS = AddrInst->getType()->getPointerAddressSpace();
3103 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003104 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003105 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003106 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003107 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003108 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003109 case Instruction::BitCast:
3110 // BitCast is always a noop, and we can handle it as long as it is
3111 // int->int or pointer->pointer (we don't want int<->fp or something).
3112 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3113 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3114 // Don't touch identity bitcasts. These were probably put here by LSR,
3115 // and we don't want to mess around with them. Assume it knows what it
3116 // is doing.
3117 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003118 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003119 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003120 case Instruction::AddrSpaceCast: {
3121 unsigned SrcAS
3122 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3123 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3124 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003125 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003126 return false;
3127 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003128 case Instruction::Add: {
3129 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3130 ExtAddrMode BackupAddrMode = AddrMode;
3131 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003132 // Start a transaction at this point.
3133 // The LHS may match but not the RHS.
3134 // Therefore, we need a higher level restoration point to undo partially
3135 // matched operation.
3136 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3137 TPT.getRestorationPoint();
3138
Sanjay Patelfc580a62015-09-21 23:03:16 +00003139 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3140 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003141 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003142
Chandler Carruthc8925912013-01-05 02:09:22 +00003143 // Restore the old addr mode info.
3144 AddrMode = BackupAddrMode;
3145 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003146 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003147
Chandler Carruthc8925912013-01-05 02:09:22 +00003148 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003149 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3150 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003151 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003152
Chandler Carruthc8925912013-01-05 02:09:22 +00003153 // Otherwise we definitely can't merge the ADD in.
3154 AddrMode = BackupAddrMode;
3155 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003156 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003157 break;
3158 }
3159 //case Instruction::Or:
3160 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3161 //break;
3162 case Instruction::Mul:
3163 case Instruction::Shl: {
3164 // Can only handle X*C and X << C.
3165 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003166 if (!RHS)
3167 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003168 int64_t Scale = RHS->getSExtValue();
3169 if (Opcode == Instruction::Shl)
3170 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003171
Sanjay Patelfc580a62015-09-21 23:03:16 +00003172 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003173 }
3174 case Instruction::GetElementPtr: {
3175 // Scan the GEP. We check it if it contains constant offsets and at most
3176 // one variable offset.
3177 int VariableOperand = -1;
3178 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003179
Chandler Carruthc8925912013-01-05 02:09:22 +00003180 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003181 gep_type_iterator GTI = gep_type_begin(AddrInst);
3182 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3183 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003184 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003185 unsigned Idx =
3186 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3187 ConstantOffset += SL->getElementOffset(Idx);
3188 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003189 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003190 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3191 ConstantOffset += CI->getSExtValue()*TypeSize;
3192 } else if (TypeSize) { // Scales of zero don't do anything.
3193 // We only allow one variable index at the moment.
3194 if (VariableOperand != -1)
3195 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003196
Chandler Carruthc8925912013-01-05 02:09:22 +00003197 // Remember the variable index.
3198 VariableOperand = i;
3199 VariableScale = TypeSize;
3200 }
3201 }
3202 }
Stephen Lin837bba12013-07-15 17:55:02 +00003203
Chandler Carruthc8925912013-01-05 02:09:22 +00003204 // A common case is for the GEP to only do a constant offset. In this case,
3205 // just add it to the disp field and check validity.
3206 if (VariableOperand == -1) {
3207 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003208 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003209 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003210 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003211 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003212 return true;
3213 }
3214 AddrMode.BaseOffs -= ConstantOffset;
3215 return false;
3216 }
3217
3218 // Save the valid addressing mode in case we can't match.
3219 ExtAddrMode BackupAddrMode = AddrMode;
3220 unsigned OldSize = AddrModeInsts.size();
3221
3222 // See if the scale and offset amount is valid for this target.
3223 AddrMode.BaseOffs += ConstantOffset;
3224
3225 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003226 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003227 // If it couldn't be matched, just stuff the value in a register.
3228 if (AddrMode.HasBaseReg) {
3229 AddrMode = BackupAddrMode;
3230 AddrModeInsts.resize(OldSize);
3231 return false;
3232 }
3233 AddrMode.HasBaseReg = true;
3234 AddrMode.BaseReg = AddrInst->getOperand(0);
3235 }
3236
3237 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003238 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003239 Depth)) {
3240 // If it couldn't be matched, try stuffing the base into a register
3241 // instead of matching it, and retrying the match of the scale.
3242 AddrMode = BackupAddrMode;
3243 AddrModeInsts.resize(OldSize);
3244 if (AddrMode.HasBaseReg)
3245 return false;
3246 AddrMode.HasBaseReg = true;
3247 AddrMode.BaseReg = AddrInst->getOperand(0);
3248 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003249 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003250 VariableScale, Depth)) {
3251 // If even that didn't work, bail.
3252 AddrMode = BackupAddrMode;
3253 AddrModeInsts.resize(OldSize);
3254 return false;
3255 }
3256 }
3257
3258 return true;
3259 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003260 case Instruction::SExt:
3261 case Instruction::ZExt: {
3262 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3263 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003264 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003265
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003266 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003267 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003268 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003269 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003270 if (!TPH)
3271 return false;
3272
3273 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3274 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003275 unsigned CreatedInstsCost = 0;
3276 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003277 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003278 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003279 // SExt has been moved away.
3280 // Thus either it will be rematched later in the recursive calls or it is
3281 // gone. Anyway, we must not fold it into the addressing mode at this point.
3282 // E.g.,
3283 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003284 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003285 // addr = gep base, idx
3286 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003287 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003288 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3289 // addr = gep base, op <- match
3290 if (MovedAway)
3291 *MovedAway = true;
3292
3293 assert(PromotedOperand &&
3294 "TypePromotionHelper should have filtered out those cases");
3295
3296 ExtAddrMode BackupAddrMode = AddrMode;
3297 unsigned OldSize = AddrModeInsts.size();
3298
Sanjay Patelfc580a62015-09-21 23:03:16 +00003299 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003300 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003301 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003302 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003303 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003304 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003305 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003306 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003307 AddrMode = BackupAddrMode;
3308 AddrModeInsts.resize(OldSize);
3309 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3310 TPT.rollback(LastKnownGood);
3311 return false;
3312 }
3313 return true;
3314 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003315 }
3316 return false;
3317}
3318
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003319/// If we can, try to add the value of 'Addr' into the current addressing mode.
3320/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3321/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3322/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003323///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003324bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003325 // Start a transaction at this point that we will rollback if the matching
3326 // fails.
3327 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3328 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003329 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3330 // Fold in immediates if legal for the target.
3331 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003332 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003333 return true;
3334 AddrMode.BaseOffs -= CI->getSExtValue();
3335 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3336 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003337 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003338 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003339 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003340 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003341 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003342 }
3343 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3344 ExtAddrMode BackupAddrMode = AddrMode;
3345 unsigned OldSize = AddrModeInsts.size();
3346
3347 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003348 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003349 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003350 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003351 // to check here.
3352 if (MovedAway)
3353 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003354 // Okay, it's possible to fold this. Check to see if it is actually
3355 // *profitable* to do so. We use a simple cost model to avoid increasing
3356 // register pressure too much.
3357 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003358 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003359 AddrModeInsts.push_back(I);
3360 return true;
3361 }
Stephen Lin837bba12013-07-15 17:55:02 +00003362
Chandler Carruthc8925912013-01-05 02:09:22 +00003363 // It isn't profitable to do this, roll back.
3364 //cerr << "NOT FOLDING: " << *I;
3365 AddrMode = BackupAddrMode;
3366 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003367 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003368 }
3369 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003370 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003371 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003372 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003373 } else if (isa<ConstantPointerNull>(Addr)) {
3374 // Null pointer gets folded without affecting the addressing mode.
3375 return true;
3376 }
3377
3378 // Worse case, the target should support [reg] addressing modes. :)
3379 if (!AddrMode.HasBaseReg) {
3380 AddrMode.HasBaseReg = true;
3381 AddrMode.BaseReg = Addr;
3382 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003383 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003384 return true;
3385 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003386 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003387 }
3388
3389 // If the base register is already taken, see if we can do [r+r].
3390 if (AddrMode.Scale == 0) {
3391 AddrMode.Scale = 1;
3392 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003393 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003394 return true;
3395 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003396 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003397 }
3398 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003399 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003400 return false;
3401}
3402
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003403/// Check to see if all uses of OpVal by the specified inline asm call are due
3404/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003405static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003406 const TargetMachine &TM) {
3407 const Function *F = CI->getParent()->getParent();
3408 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3409 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003410 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003411 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3412 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003413 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3414 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003415
Chandler Carruthc8925912013-01-05 02:09:22 +00003416 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003417 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003418
3419 // If this asm operand is our Value*, and if it isn't an indirect memory
3420 // operand, we can't fold it!
3421 if (OpInfo.CallOperandVal == OpVal &&
3422 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3423 !OpInfo.isIndirect))
3424 return false;
3425 }
3426
3427 return true;
3428}
3429
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003430/// Recursively walk all the uses of I until we find a memory use.
3431/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003432/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003433static bool FindAllMemoryUses(
3434 Instruction *I,
3435 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3436 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003437 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003438 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003439 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003440
Chandler Carruthc8925912013-01-05 02:09:22 +00003441 // If this is an obviously unfoldable instruction, bail out.
3442 if (!MightBeFoldableInst(I))
3443 return true;
3444
3445 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003446 for (Use &U : I->uses()) {
3447 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003448
Chandler Carruthcdf47882014-03-09 03:16:01 +00003449 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3450 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003451 continue;
3452 }
Stephen Lin837bba12013-07-15 17:55:02 +00003453
Chandler Carruthcdf47882014-03-09 03:16:01 +00003454 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3455 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003456 if (opNo == 0) return true; // Storing addr, not into addr.
3457 MemoryUses.push_back(std::make_pair(SI, opNo));
3458 continue;
3459 }
Stephen Lin837bba12013-07-15 17:55:02 +00003460
Chandler Carruthcdf47882014-03-09 03:16:01 +00003461 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003462 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3463 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003464
Chandler Carruthc8925912013-01-05 02:09:22 +00003465 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003466 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003467 return true;
3468 continue;
3469 }
Stephen Lin837bba12013-07-15 17:55:02 +00003470
Eric Christopher11e4df72015-02-26 22:38:43 +00003471 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003472 return true;
3473 }
3474
3475 return false;
3476}
3477
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003478/// Return true if Val is already known to be live at the use site that we're
3479/// folding it into. If so, there is no cost to include it in the addressing
3480/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3481/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003482bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003483 Value *KnownLive2) {
3484 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003485 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003486 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003487
Chandler Carruthc8925912013-01-05 02:09:22 +00003488 // All values other than instructions and arguments (e.g. constants) are live.
3489 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003490
Chandler Carruthc8925912013-01-05 02:09:22 +00003491 // If Val is a constant sized alloca in the entry block, it is live, this is
3492 // true because it is just a reference to the stack/frame pointer, which is
3493 // live for the whole function.
3494 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3495 if (AI->isStaticAlloca())
3496 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003497
Chandler Carruthc8925912013-01-05 02:09:22 +00003498 // Check to see if this value is already used in the memory instruction's
3499 // block. If so, it's already live into the block at the very least, so we
3500 // can reasonably fold it.
3501 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3502}
3503
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003504/// It is possible for the addressing mode of the machine to fold the specified
3505/// instruction into a load or store that ultimately uses it.
3506/// However, the specified instruction has multiple uses.
3507/// Given this, it may actually increase register pressure to fold it
3508/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003509///
3510/// X = ...
3511/// Y = X+1
3512/// use(Y) -> nonload/store
3513/// Z = Y+1
3514/// load Z
3515///
3516/// In this case, Y has multiple uses, and can be folded into the load of Z
3517/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3518/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3519/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3520/// number of computations either.
3521///
3522/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3523/// X was live across 'load Z' for other reasons, we actually *would* want to
3524/// fold the addressing mode in the Z case. This would make Y die earlier.
3525bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003526isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003527 ExtAddrMode &AMAfter) {
3528 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003529
Chandler Carruthc8925912013-01-05 02:09:22 +00003530 // AMBefore is the addressing mode before this instruction was folded into it,
3531 // and AMAfter is the addressing mode after the instruction was folded. Get
3532 // the set of registers referenced by AMAfter and subtract out those
3533 // referenced by AMBefore: this is the set of values which folding in this
3534 // address extends the lifetime of.
3535 //
3536 // Note that there are only two potential values being referenced here,
3537 // BaseReg and ScaleReg (global addresses are always available, as are any
3538 // folded immediates).
3539 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003540
Chandler Carruthc8925912013-01-05 02:09:22 +00003541 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3542 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003543 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003544 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003545 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003546 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003547
3548 // If folding this instruction (and it's subexprs) didn't extend any live
3549 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003550 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003551 return true;
3552
3553 // If all uses of this instruction are ultimately load/store/inlineasm's,
3554 // check to see if their addressing modes will include this instruction. If
3555 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3556 // uses.
3557 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3558 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003559 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003560 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003561
Chandler Carruthc8925912013-01-05 02:09:22 +00003562 // Now that we know that all uses of this instruction are part of a chain of
3563 // computation involving only operations that could theoretically be folded
3564 // into a memory use, loop over each of these uses and see if they could
3565 // *actually* fold the instruction.
3566 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3567 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3568 Instruction *User = MemoryUses[i].first;
3569 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003570
Chandler Carruthc8925912013-01-05 02:09:22 +00003571 // Get the access type of this use. If the use isn't a pointer, we don't
3572 // know what it accesses.
3573 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003574 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3575 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003576 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003577 Type *AddressAccessTy = AddrTy->getElementType();
3578 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003579
Chandler Carruthc8925912013-01-05 02:09:22 +00003580 // Do a match against the root of this address, ignoring profitability. This
3581 // will tell us if the addressing mode for the memory operation will
3582 // *actually* cover the shared instruction.
3583 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003584 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3585 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003586 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003587 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003588 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003589 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003590 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003591 (void)Success; assert(Success && "Couldn't select *anything*?");
3592
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003593 // The match was to check the profitability, the changes made are not
3594 // part of the original matcher. Therefore, they should be dropped
3595 // otherwise the original matcher will not present the right state.
3596 TPT.rollback(LastKnownGood);
3597
Chandler Carruthc8925912013-01-05 02:09:22 +00003598 // If the match didn't cover I, then it won't be shared by it.
3599 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3600 I) == MatchedAddrModeInsts.end())
3601 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003602
Chandler Carruthc8925912013-01-05 02:09:22 +00003603 MatchedAddrModeInsts.clear();
3604 }
Stephen Lin837bba12013-07-15 17:55:02 +00003605
Chandler Carruthc8925912013-01-05 02:09:22 +00003606 return true;
3607}
3608
3609} // end anonymous namespace
3610
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003611/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003612/// different basic block than BB.
3613static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3614 if (Instruction *I = dyn_cast<Instruction>(V))
3615 return I->getParent() != BB;
3616 return false;
3617}
3618
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003619/// Load and Store Instructions often have addressing modes that can do
3620/// significant amounts of computation. As such, instruction selection will try
3621/// to get the load or store to do as much computation as possible for the
3622/// program. The problem is that isel can only see within a single block. As
3623/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003624///
3625/// This method is used to optimize both load/store and inline asms with memory
3626/// operands.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003627bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003628 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003629 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003630
3631 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003632 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003633 SmallVector<Value*, 8> worklist;
3634 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003635 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003636
Owen Anderson8ba5f392010-11-27 08:15:55 +00003637 // Use a worklist to iteratively look through PHI nodes, and ensure that
3638 // the addressing mode obtained from the non-PHI roots of the graph
3639 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003640 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003641 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003642 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003643 SmallVector<Instruction*, 16> AddrModeInsts;
3644 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003645 TypePromotionTransaction TPT;
3646 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3647 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003648 while (!worklist.empty()) {
3649 Value *V = worklist.back();
3650 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003651
Owen Anderson8ba5f392010-11-27 08:15:55 +00003652 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003653 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003654 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003655 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003656 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003657
Owen Anderson8ba5f392010-11-27 08:15:55 +00003658 // For a PHI node, push all of its incoming values.
3659 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003660 for (Value *IncValue : P->incoming_values())
3661 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003662 continue;
3663 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003664
Owen Anderson8ba5f392010-11-27 08:15:55 +00003665 // For non-PHIs, determine the addressing mode being computed.
3666 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003667 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003668 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003669 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003670
3671 // This check is broken into two cases with very similar code to avoid using
3672 // getNumUses() as much as possible. Some values have a lot of uses, so
3673 // calling getNumUses() unconditionally caused a significant compile-time
3674 // regression.
3675 if (!Consensus) {
3676 Consensus = V;
3677 AddrMode = NewAddrMode;
3678 AddrModeInsts = NewAddrModeInsts;
3679 continue;
3680 } else if (NewAddrMode == AddrMode) {
3681 if (!IsNumUsesConsensusValid) {
3682 NumUsesConsensus = Consensus->getNumUses();
3683 IsNumUsesConsensusValid = true;
3684 }
3685
3686 // Ensure that the obtained addressing mode is equivalent to that obtained
3687 // for all other roots of the PHI traversal. Also, when choosing one
3688 // such root as representative, select the one with the most uses in order
3689 // to keep the cost modeling heuristics in AddressingModeMatcher
3690 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003691 unsigned NumUses = V->getNumUses();
3692 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003693 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003694 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003695 AddrModeInsts = NewAddrModeInsts;
3696 }
3697 continue;
3698 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003699
Craig Topperc0196b12014-04-14 00:51:57 +00003700 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003701 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003702 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003703
Owen Anderson8ba5f392010-11-27 08:15:55 +00003704 // If the addressing mode couldn't be determined, or if multiple different
3705 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003706 if (!Consensus) {
3707 TPT.rollback(LastKnownGood);
3708 return false;
3709 }
3710 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003711
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003712 // Check to see if any of the instructions supersumed by this addr mode are
3713 // non-local to I's BB.
3714 bool AnyNonLocal = false;
3715 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003716 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003717 AnyNonLocal = true;
3718 break;
3719 }
3720 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003721
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003722 // If all the instructions matched are already in this BB, don't do anything.
3723 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003724 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003725 return false;
3726 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003727
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003728 // Insert this computation right after this user. Since our caller is
3729 // scanning from the top of the BB to the bottom, reuse of the expr are
3730 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003731 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003732
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003733 // Now that we determined the addressing expression we want to use and know
3734 // that we have to sink it into this block. Check to see if we have already
3735 // done this for some other load/store instr in this block. If so, reuse the
3736 // computation.
3737 Value *&SunkAddr = SunkAddrs[Addr];
3738 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003739 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003740 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003741 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003742 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003743 } else if (AddrSinkUsingGEPs ||
3744 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003745 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3746 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003747 // By default, we use the GEP-based method when AA is used later. This
3748 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3749 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003750 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003751 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003752 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003753
3754 // First, find the pointer.
3755 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3756 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003757 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003758 }
3759
3760 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3761 // We can't add more than one pointer together, nor can we scale a
3762 // pointer (both of which seem meaningless).
3763 if (ResultPtr || AddrMode.Scale != 1)
3764 return false;
3765
3766 ResultPtr = AddrMode.ScaledReg;
3767 AddrMode.Scale = 0;
3768 }
3769
3770 if (AddrMode.BaseGV) {
3771 if (ResultPtr)
3772 return false;
3773
3774 ResultPtr = AddrMode.BaseGV;
3775 }
3776
3777 // If the real base value actually came from an inttoptr, then the matcher
3778 // will look through it and provide only the integer value. In that case,
3779 // use it here.
3780 if (!ResultPtr && AddrMode.BaseReg) {
3781 ResultPtr =
3782 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003783 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003784 } else if (!ResultPtr && AddrMode.Scale == 1) {
3785 ResultPtr =
3786 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3787 AddrMode.Scale = 0;
3788 }
3789
3790 if (!ResultPtr &&
3791 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3792 SunkAddr = Constant::getNullValue(Addr->getType());
3793 } else if (!ResultPtr) {
3794 return false;
3795 } else {
3796 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003797 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3798 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003799
3800 // Start with the base register. Do this first so that subsequent address
3801 // matching finds it last, which will prevent it from trying to match it
3802 // as the scaled value in case it happens to be a mul. That would be
3803 // problematic if we've sunk a different mul for the scale, because then
3804 // we'd end up sinking both muls.
3805 if (AddrMode.BaseReg) {
3806 Value *V = AddrMode.BaseReg;
3807 if (V->getType() != IntPtrTy)
3808 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3809
3810 ResultIndex = V;
3811 }
3812
3813 // Add the scale value.
3814 if (AddrMode.Scale) {
3815 Value *V = AddrMode.ScaledReg;
3816 if (V->getType() == IntPtrTy) {
3817 // done.
3818 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3819 cast<IntegerType>(V->getType())->getBitWidth()) {
3820 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3821 } else {
3822 // It is only safe to sign extend the BaseReg if we know that the math
3823 // required to create it did not overflow before we extend it. Since
3824 // the original IR value was tossed in favor of a constant back when
3825 // the AddrMode was created we need to bail out gracefully if widths
3826 // do not match instead of extending it.
3827 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3828 if (I && (ResultIndex != AddrMode.BaseReg))
3829 I->eraseFromParent();
3830 return false;
3831 }
3832
3833 if (AddrMode.Scale != 1)
3834 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3835 "sunkaddr");
3836 if (ResultIndex)
3837 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3838 else
3839 ResultIndex = V;
3840 }
3841
3842 // Add in the Base Offset if present.
3843 if (AddrMode.BaseOffs) {
3844 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3845 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003846 // We need to add this separately from the scale above to help with
3847 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003848 if (ResultPtr->getType() != I8PtrTy)
3849 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003850 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003851 }
3852
3853 ResultIndex = V;
3854 }
3855
3856 if (!ResultIndex) {
3857 SunkAddr = ResultPtr;
3858 } else {
3859 if (ResultPtr->getType() != I8PtrTy)
3860 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003861 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003862 }
3863
3864 if (SunkAddr->getType() != Addr->getType())
3865 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3866 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003867 } else {
David Greene74e2d492010-01-05 01:27:11 +00003868 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003869 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003870 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003871 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003872
3873 // Start with the base register. Do this first so that subsequent address
3874 // matching finds it last, which will prevent it from trying to match it
3875 // as the scaled value in case it happens to be a mul. That would be
3876 // problematic if we've sunk a different mul for the scale, because then
3877 // we'd end up sinking both muls.
3878 if (AddrMode.BaseReg) {
3879 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003880 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003881 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003882 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003883 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003884 Result = V;
3885 }
3886
3887 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003888 if (AddrMode.Scale) {
3889 Value *V = AddrMode.ScaledReg;
3890 if (V->getType() == IntPtrTy) {
3891 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003892 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003893 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003894 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3895 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003896 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003897 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003898 // It is only safe to sign extend the BaseReg if we know that the math
3899 // required to create it did not overflow before we extend it. Since
3900 // the original IR value was tossed in favor of a constant back when
3901 // the AddrMode was created we need to bail out gracefully if widths
3902 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003903 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003904 if (I && (Result != AddrMode.BaseReg))
3905 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003906 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003907 }
3908 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003909 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3910 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003911 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003912 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003913 else
3914 Result = V;
3915 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003916
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003917 // Add in the BaseGV if present.
3918 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003919 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003920 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003921 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003922 else
3923 Result = V;
3924 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003925
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003926 // Add in the Base Offset if present.
3927 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003928 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003929 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003930 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003931 else
3932 Result = V;
3933 }
3934
Craig Topperc0196b12014-04-14 00:51:57 +00003935 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003936 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003937 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003938 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003939 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003940
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003941 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003942
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003943 // If we have no uses, recursively delete the value and all dead instructions
3944 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003945 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003946 // This can cause recursive deletion, which can invalidate our iterator.
3947 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003948 WeakVH IterHandle(&*CurInstIterator);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003949 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003950
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003951 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003952
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00003953 if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003954 // If the iterator instruction was recursively deleted, start over at the
3955 // start of the block.
3956 CurInstIterator = BB->begin();
3957 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003958 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003959 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003960 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003961 return true;
3962}
3963
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003964/// If there are any memory operands, use OptimizeMemoryInst to sink their
3965/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003966bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003967 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003968
Eric Christopher11e4df72015-02-26 22:38:43 +00003969 const TargetRegisterInfo *TRI =
3970 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003971 TargetLowering::AsmOperandInfoVector TargetConstraints =
3972 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003973 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003974 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3975 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003976
Evan Cheng1da25002008-02-26 02:42:37 +00003977 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003978 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003979
Eli Friedman666bbe32008-02-26 18:37:49 +00003980 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3981 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003982 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00003983 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003984 } else if (OpInfo.Type == InlineAsm::isInput)
3985 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003986 }
3987
3988 return MadeChange;
3989}
3990
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003991/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3992/// sign extensions.
3993static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3994 assert(!Inst->use_empty() && "Input must have at least one use");
3995 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3996 bool IsSExt = isa<SExtInst>(FirstUser);
3997 Type *ExtTy = FirstUser->getType();
3998 for (const User *U : Inst->users()) {
3999 const Instruction *UI = cast<Instruction>(U);
4000 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4001 return false;
4002 Type *CurTy = UI->getType();
4003 // Same input and output types: Same instruction after CSE.
4004 if (CurTy == ExtTy)
4005 continue;
4006
4007 // If IsSExt is true, we are in this situation:
4008 // a = Inst
4009 // b = sext ty1 a to ty2
4010 // c = sext ty1 a to ty3
4011 // Assuming ty2 is shorter than ty3, this could be turned into:
4012 // a = Inst
4013 // b = sext ty1 a to ty2
4014 // c = sext ty2 b to ty3
4015 // However, the last sext is not free.
4016 if (IsSExt)
4017 return false;
4018
4019 // This is a ZExt, maybe this is free to extend from one type to another.
4020 // In that case, we would not account for a different use.
4021 Type *NarrowTy;
4022 Type *LargeTy;
4023 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4024 CurTy->getScalarType()->getIntegerBitWidth()) {
4025 NarrowTy = CurTy;
4026 LargeTy = ExtTy;
4027 } else {
4028 NarrowTy = ExtTy;
4029 LargeTy = CurTy;
4030 }
4031
4032 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4033 return false;
4034 }
4035 // All uses are the same or can be derived from one another for free.
4036 return true;
4037}
4038
4039/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4040/// load instruction.
4041/// If an ext(load) can be formed, it is returned via \p LI for the load
4042/// and \p Inst for the extension.
4043/// Otherwise LI == nullptr and Inst == nullptr.
4044/// When some promotion happened, \p TPT contains the proper state to
4045/// revert them.
4046///
4047/// \return true when promoting was necessary to expose the ext(load)
4048/// opportunity, false otherwise.
4049///
4050/// Example:
4051/// \code
4052/// %ld = load i32* %addr
4053/// %add = add nuw i32 %ld, 4
4054/// %zext = zext i32 %add to i64
4055/// \endcode
4056/// =>
4057/// \code
4058/// %ld = load i32* %addr
4059/// %zext = zext i32 %ld to i64
4060/// %add = add nuw i64 %zext, 4
4061/// \encode
4062/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004063bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004064 LoadInst *&LI, Instruction *&Inst,
4065 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004066 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004067 // Iterate over all the extensions to see if one form an ext(load).
4068 for (auto I : Exts) {
4069 // Check if we directly have ext(load).
4070 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4071 Inst = I;
4072 // No promotion happened here.
4073 return false;
4074 }
4075 // Check whether or not we want to do any promotion.
4076 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4077 continue;
4078 // Get the action to perform the promotion.
4079 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004080 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004081 // Check if we can promote.
4082 if (!TPH)
4083 continue;
4084 // Save the current state.
4085 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4086 TPT.getRestorationPoint();
4087 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004088 unsigned NewCreatedInstsCost = 0;
4089 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004090 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004091 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4092 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004093 assert(PromotedVal &&
4094 "TypePromotionHelper should have filtered out those cases");
4095
4096 // We would be able to merge only one extension in a load.
4097 // Therefore, if we have more than 1 new extension we heuristically
4098 // cut this search path, because it means we degrade the code quality.
4099 // With exactly 2, the transformation is neutral, because we will merge
4100 // one extension but leave one. However, we optimistically keep going,
4101 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004102 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4103 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004104 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004105 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004106 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004107 // The promotion is not profitable, rollback to the previous state.
4108 TPT.rollback(LastKnownGood);
4109 continue;
4110 }
4111 // The promotion is profitable.
4112 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004113 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004114 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004115 // If we have created a new extension, i.e., now we have two
4116 // extensions. We must make sure one of them is merged with
4117 // the load, otherwise we may degrade the code quality.
4118 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4119 // Promotion happened.
4120 return true;
4121 // If this does not help to expose an ext(load) then, rollback.
4122 TPT.rollback(LastKnownGood);
4123 }
4124 // None of the extension can form an ext(load).
4125 LI = nullptr;
4126 Inst = nullptr;
4127 return false;
4128}
4129
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004130/// Move a zext or sext fed by a load into the same basic block as the load,
4131/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4132/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004133/// \p I[in/out] the extension may be modified during the process if some
4134/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004135///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004136bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004137 // Try to promote a chain of computation if it allows to form
4138 // an extended load.
4139 TypePromotionTransaction TPT;
4140 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4141 TPT.getRestorationPoint();
4142 SmallVector<Instruction *, 1> Exts;
4143 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004144 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004145 LoadInst *LI = nullptr;
4146 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004147 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004148 if (!LI || !I) {
4149 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4150 "the code must remain the same");
4151 I = OldExt;
4152 return false;
4153 }
Dan Gohman99429a02009-10-16 20:59:35 +00004154
4155 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004156 // Make the cheap checks first if we did not promote.
4157 // If we promoted, we need to check if it is indeed profitable.
4158 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004159 return false;
4160
Mehdi Amini44ede332015-07-09 02:09:04 +00004161 EVT VT = TLI->getValueType(*DL, I->getType());
4162 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004163
Dan Gohman99429a02009-10-16 20:59:35 +00004164 // If the load has other users and the truncate is not free, this probably
4165 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004166 if (!LI->hasOneUse() && TLI &&
4167 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004168 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4169 I = OldExt;
4170 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004171 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004172 }
Dan Gohman99429a02009-10-16 20:59:35 +00004173
4174 // Check whether the target supports casts folded into loads.
4175 unsigned LType;
4176 if (isa<ZExtInst>(I))
4177 LType = ISD::ZEXTLOAD;
4178 else {
4179 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4180 LType = ISD::SEXTLOAD;
4181 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004182 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004183 I = OldExt;
4184 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004185 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004186 }
Dan Gohman99429a02009-10-16 20:59:35 +00004187
4188 // Move the extend into the same block as the load, so that SelectionDAG
4189 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004190 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004191 I->removeFromParent();
4192 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004193 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004194 return true;
4195}
4196
Sanjay Patelfc580a62015-09-21 23:03:16 +00004197bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004198 BasicBlock *DefBB = I->getParent();
4199
Bob Wilsonff714f92010-09-21 21:44:14 +00004200 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004201 // other uses of the source with result of extension.
4202 Value *Src = I->getOperand(0);
4203 if (Src->hasOneUse())
4204 return false;
4205
Evan Cheng2011df42007-12-13 07:50:36 +00004206 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004207 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004208 return false;
4209
Evan Cheng7bc89422007-12-12 00:51:06 +00004210 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004211 // this block.
4212 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004213 return false;
4214
Evan Chengd3d80172007-12-05 23:58:20 +00004215 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004216 for (User *U : I->users()) {
4217 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004218
4219 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004220 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004221 if (UserBB == DefBB) continue;
4222 DefIsLiveOut = true;
4223 break;
4224 }
4225 if (!DefIsLiveOut)
4226 return false;
4227
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004228 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004229 for (User *U : Src->users()) {
4230 Instruction *UI = cast<Instruction>(U);
4231 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004232 if (UserBB == DefBB) continue;
4233 // Be conservative. We don't want this xform to end up introducing
4234 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004235 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004236 return false;
4237 }
4238
Evan Chengd3d80172007-12-05 23:58:20 +00004239 // InsertedTruncs - Only insert one trunc in each block once.
4240 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4241
4242 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004243 for (Use &U : Src->uses()) {
4244 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004245
4246 // Figure out which BB this ext is used in.
4247 BasicBlock *UserBB = User->getParent();
4248 if (UserBB == DefBB) continue;
4249
4250 // Both src and def are live in this block. Rewrite the use.
4251 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4252
4253 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004254 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004255 assert(InsertPt != UserBB->end());
4256 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004257 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004258 }
4259
4260 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004261 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004262 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004263 MadeChange = true;
4264 }
4265
4266 return MadeChange;
4267}
4268
Geoff Berry5256fca2015-11-20 22:34:39 +00004269// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4270// just after the load if the target can fold this into one extload instruction,
4271// with the hope of eliminating some of the other later "and" instructions using
4272// the loaded value. "and"s that are made trivially redundant by the insertion
4273// of the new "and" are removed by this function, while others (e.g. those whose
4274// path from the load goes through a phi) are left for isel to potentially
4275// remove.
4276//
4277// For example:
4278//
4279// b0:
4280// x = load i32
4281// ...
4282// b1:
4283// y = and x, 0xff
4284// z = use y
4285//
4286// becomes:
4287//
4288// b0:
4289// x = load i32
4290// x' = and x, 0xff
4291// ...
4292// b1:
4293// z = use x'
4294//
4295// whereas:
4296//
4297// b0:
4298// x1 = load i32
4299// ...
4300// b1:
4301// x2 = load i32
4302// ...
4303// b2:
4304// x = phi x1, x2
4305// y = and x, 0xff
4306//
4307// becomes (after a call to optimizeLoadExt for each load):
4308//
4309// b0:
4310// x1 = load i32
4311// x1' = and x1, 0xff
4312// ...
4313// b1:
4314// x2 = load i32
4315// x2' = and x2, 0xff
4316// ...
4317// b2:
4318// x = phi x1', x2'
4319// y = and x, 0xff
4320//
4321
4322bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4323
4324 if (!Load->isSimple() ||
4325 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4326 return false;
4327
4328 // Skip loads we've already transformed or have no reason to transform.
4329 if (Load->hasOneUse()) {
4330 User *LoadUser = *Load->user_begin();
4331 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4332 !dyn_cast<PHINode>(LoadUser))
4333 return false;
4334 }
4335
4336 // Look at all uses of Load, looking through phis, to determine how many bits
4337 // of the loaded value are needed.
4338 SmallVector<Instruction *, 8> WorkList;
4339 SmallPtrSet<Instruction *, 16> Visited;
4340 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4341 for (auto *U : Load->users())
4342 WorkList.push_back(cast<Instruction>(U));
4343
4344 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4345 unsigned BitWidth = LoadResultVT.getSizeInBits();
4346 APInt DemandBits(BitWidth, 0);
4347 APInt WidestAndBits(BitWidth, 0);
4348
4349 while (!WorkList.empty()) {
4350 Instruction *I = WorkList.back();
4351 WorkList.pop_back();
4352
4353 // Break use-def graph loops.
4354 if (!Visited.insert(I).second)
4355 continue;
4356
4357 // For a PHI node, push all of its users.
4358 if (auto *Phi = dyn_cast<PHINode>(I)) {
4359 for (auto *U : Phi->users())
4360 WorkList.push_back(cast<Instruction>(U));
4361 continue;
4362 }
4363
4364 switch (I->getOpcode()) {
4365 case llvm::Instruction::And: {
4366 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4367 if (!AndC)
4368 return false;
4369 APInt AndBits = AndC->getValue();
4370 DemandBits |= AndBits;
4371 // Keep track of the widest and mask we see.
4372 if (AndBits.ugt(WidestAndBits))
4373 WidestAndBits = AndBits;
4374 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4375 AndsToMaybeRemove.push_back(I);
4376 break;
4377 }
4378
4379 case llvm::Instruction::Shl: {
4380 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4381 if (!ShlC)
4382 return false;
4383 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4384 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4385 DemandBits |= ShlDemandBits;
4386 break;
4387 }
4388
4389 case llvm::Instruction::Trunc: {
4390 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4391 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4392 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4393 DemandBits |= TruncBits;
4394 break;
4395 }
4396
4397 default:
4398 return false;
4399 }
4400 }
4401
4402 uint32_t ActiveBits = DemandBits.getActiveBits();
4403 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4404 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4405 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4406 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4407 // followed by an AND.
4408 // TODO: Look into removing this restriction by fixing backends to either
4409 // return false for isLoadExtLegal for i1 or have them select this pattern to
4410 // a single instruction.
4411 //
4412 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4413 // mask, since these are the only ands that will be removed by isel.
4414 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4415 WidestAndBits != DemandBits)
4416 return false;
4417
4418 LLVMContext &Ctx = Load->getType()->getContext();
4419 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4420 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4421
4422 // Reject cases that won't be matched as extloads.
4423 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4424 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4425 return false;
4426
4427 IRBuilder<> Builder(Load->getNextNode());
4428 auto *NewAnd = dyn_cast<Instruction>(
4429 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4430
4431 // Replace all uses of load with new and (except for the use of load in the
4432 // new and itself).
4433 Load->replaceAllUsesWith(NewAnd);
4434 NewAnd->setOperand(0, Load);
4435
4436 // Remove any and instructions that are now redundant.
4437 for (auto *And : AndsToMaybeRemove)
4438 // Check that the and mask is the same as the one we decided to put on the
4439 // new and.
4440 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4441 And->replaceAllUsesWith(NewAnd);
4442 if (&*CurInstIterator == And)
4443 CurInstIterator = std::next(And->getIterator());
4444 And->eraseFromParent();
4445 ++NumAndUses;
4446 }
4447
4448 ++NumAndsAdded;
4449 return true;
4450}
4451
Sanjay Patel69a50a12015-10-19 21:59:12 +00004452/// Check if V (an operand of a select instruction) is an expensive instruction
4453/// that is only used once.
4454static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4455 auto *I = dyn_cast<Instruction>(V);
4456 // If it's safe to speculatively execute, then it should not have side
4457 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004458 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4459 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004460}
4461
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004462/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004463static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
4464 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004465 // FIXME: This should use the same heuristics as IfConversion to determine
4466 // whether a select is better represented as a branch. This requires that
4467 // branch probability metadata is preserved for the select, which is not the
4468 // case currently.
4469
4470 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4471
Sanjay Patel4e652762015-09-28 22:14:51 +00004472 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4473 // comparison condition. If the compare has more than one use, there's
4474 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004475 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004476 return false;
4477
4478 Value *CmpOp0 = Cmp->getOperand(0);
4479 Value *CmpOp1 = Cmp->getOperand(1);
4480
Sanjay Patel4e652762015-09-28 22:14:51 +00004481 // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
4482 // on a load from memory. But if the load is used more than once, do not
4483 // change the select to a branch because the load is probably needed
4484 // regardless of whether the branch is taken or not.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004485 if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
4486 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
4487 return true;
4488
4489 // If either operand of the select is expensive and only needed on one side
4490 // of the select, we should form a branch.
4491 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4492 sinkSelectOperand(TTI, SI->getFalseValue()))
4493 return true;
4494
4495 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004496}
4497
4498
Nadav Rotem9d832022012-09-02 12:10:19 +00004499/// If we have a SelectInst that will likely profit from branch prediction,
4500/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004501bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00004502 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4503
4504 // Can we convert the 'select' to CF ?
4505 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004506 return false;
4507
Nadav Rotem9d832022012-09-02 12:10:19 +00004508 TargetLowering::SelectSupportKind SelectKind;
4509 if (VectorCond)
4510 SelectKind = TargetLowering::VectorMaskSelect;
4511 else if (SI->getType()->isVectorTy())
4512 SelectKind = TargetLowering::ScalarCondVectorVal;
4513 else
4514 SelectKind = TargetLowering::ScalarValSelect;
4515
4516 // Do we have efficient codegen support for this kind of 'selects' ?
4517 if (TLI->isSelectSupported(SelectKind)) {
4518 // We have efficient codegen support for the select instruction.
4519 // Check if it is profitable to keep this 'select'.
4520 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00004521 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00004522 return false;
4523 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004524
4525 ModifiedDT = true;
4526
Sanjay Patel69a50a12015-10-19 21:59:12 +00004527 // Transform a sequence like this:
4528 // start:
4529 // %cmp = cmp uge i32 %a, %b
4530 // %sel = select i1 %cmp, i32 %c, i32 %d
4531 //
4532 // Into:
4533 // start:
4534 // %cmp = cmp uge i32 %a, %b
4535 // br i1 %cmp, label %select.true, label %select.false
4536 // select.true:
4537 // br label %select.end
4538 // select.false:
4539 // br label %select.end
4540 // select.end:
4541 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4542 //
4543 // In addition, we may sink instructions that produce %c or %d from
4544 // the entry block into the destination(s) of the new branch.
4545 // If the true or false blocks do not contain a sunken instruction, that
4546 // block and its branch may be optimized away. In that case, one side of the
4547 // first branch will point directly to select.end, and the corresponding PHI
4548 // predecessor block will be the start block.
4549
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004550 // First, we split the block containing the select into 2 blocks.
4551 BasicBlock *StartBlock = SI->getParent();
4552 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004553 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004554
Sanjay Patel69a50a12015-10-19 21:59:12 +00004555 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004556 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004557
4558 // These are the new basic blocks for the conditional branch.
4559 // At least one will become an actual new basic block.
4560 BasicBlock *TrueBlock = nullptr;
4561 BasicBlock *FalseBlock = nullptr;
4562
4563 // Sink expensive instructions into the conditional blocks to avoid executing
4564 // them speculatively.
4565 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4566 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4567 EndBlock->getParent(), EndBlock);
4568 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4569 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4570 TrueInst->moveBefore(TrueBranch);
4571 }
4572 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4573 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4574 EndBlock->getParent(), EndBlock);
4575 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4576 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4577 FalseInst->moveBefore(FalseBranch);
4578 }
4579
4580 // If there was nothing to sink, then arbitrarily choose the 'false' side
4581 // for a new input value to the PHI.
4582 if (TrueBlock == FalseBlock) {
4583 assert(TrueBlock == nullptr &&
4584 "Unexpected basic block transform while optimizing select");
4585
4586 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4587 EndBlock->getParent(), EndBlock);
4588 BranchInst::Create(EndBlock, FalseBlock);
4589 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004590
4591 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004592 // If we did not create a new block for one of the 'true' or 'false' paths
4593 // of the condition, it means that side of the branch goes to the end block
4594 // directly and the path originates from the start block from the point of
4595 // view of the new PHI.
4596 if (TrueBlock == nullptr) {
4597 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
4598 TrueBlock = StartBlock;
4599 } else if (FalseBlock == nullptr) {
4600 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4601 FalseBlock = StartBlock;
4602 } else {
4603 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4604 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004605
4606 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004607 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004608 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004609 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4610 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4611
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004612 SI->replaceAllUsesWith(PN);
4613 SI->eraseFromParent();
4614
4615 // Instruct OptimizeBlock to skip to the next block.
4616 CurInstIterator = StartBlock->end();
4617 ++NumSelectsExpanded;
4618 return true;
4619}
4620
Benjamin Kramer573ff362014-03-01 17:24:40 +00004621static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004622 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4623 int SplatElem = -1;
4624 for (unsigned i = 0; i < Mask.size(); ++i) {
4625 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4626 return false;
4627 SplatElem = Mask[i];
4628 }
4629
4630 return true;
4631}
4632
4633/// Some targets have expensive vector shifts if the lanes aren't all the same
4634/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4635/// it's often worth sinking a shufflevector splat down to its use so that
4636/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004637bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004638 BasicBlock *DefBB = SVI->getParent();
4639
4640 // Only do this xform if variable vector shifts are particularly expensive.
4641 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4642 return false;
4643
4644 // We only expect better codegen by sinking a shuffle if we can recognise a
4645 // constant splat.
4646 if (!isBroadcastShuffle(SVI))
4647 return false;
4648
4649 // InsertedShuffles - Only insert a shuffle in each block once.
4650 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4651
4652 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004653 for (User *U : SVI->users()) {
4654 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004655
4656 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004657 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004658 if (UserBB == DefBB) continue;
4659
4660 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004661 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004662
4663 // Everything checks out, sink the shuffle if the user's block doesn't
4664 // already have a copy.
4665 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4666
4667 if (!InsertedShuffle) {
4668 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004669 assert(InsertPt != UserBB->end());
4670 InsertedShuffle =
4671 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4672 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004673 }
4674
Chandler Carruthcdf47882014-03-09 03:16:01 +00004675 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004676 MadeChange = true;
4677 }
4678
4679 // If we removed all uses, nuke the shuffle.
4680 if (SVI->use_empty()) {
4681 SVI->eraseFromParent();
4682 MadeChange = true;
4683 }
4684
4685 return MadeChange;
4686}
4687
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004688bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4689 if (!TLI || !DL)
4690 return false;
4691
4692 Value *Cond = SI->getCondition();
4693 Type *OldType = Cond->getType();
4694 LLVMContext &Context = Cond->getContext();
4695 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4696 unsigned RegWidth = RegType.getSizeInBits();
4697
4698 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4699 return false;
4700
4701 // If the register width is greater than the type width, expand the condition
4702 // of the switch instruction and each case constant to the width of the
4703 // register. By widening the type of the switch condition, subsequent
4704 // comparisons (for case comparisons) will not need to be extended to the
4705 // preferred register width, so we will potentially eliminate N-1 extends,
4706 // where N is the number of cases in the switch.
4707 auto *NewType = Type::getIntNTy(Context, RegWidth);
4708
4709 // Zero-extend the switch condition and case constants unless the switch
4710 // condition is a function argument that is already being sign-extended.
4711 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4712 // everything instead.
4713 Instruction::CastOps ExtType = Instruction::ZExt;
4714 if (auto *Arg = dyn_cast<Argument>(Cond))
4715 if (Arg->hasSExtAttr())
4716 ExtType = Instruction::SExt;
4717
4718 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4719 ExtInst->insertBefore(SI);
4720 SI->setCondition(ExtInst);
4721 for (SwitchInst::CaseIt Case : SI->cases()) {
4722 APInt NarrowConst = Case.getCaseValue()->getValue();
4723 APInt WideConst = (ExtType == Instruction::ZExt) ?
4724 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4725 Case.setValue(ConstantInt::get(Context, WideConst));
4726 }
4727
4728 return true;
4729}
4730
Quentin Colombetc32615d2014-10-31 17:52:53 +00004731namespace {
4732/// \brief Helper class to promote a scalar operation to a vector one.
4733/// This class is used to move downward extractelement transition.
4734/// E.g.,
4735/// a = vector_op <2 x i32>
4736/// b = extractelement <2 x i32> a, i32 0
4737/// c = scalar_op b
4738/// store c
4739///
4740/// =>
4741/// a = vector_op <2 x i32>
4742/// c = vector_op a (equivalent to scalar_op on the related lane)
4743/// * d = extractelement <2 x i32> c, i32 0
4744/// * store d
4745/// Assuming both extractelement and store can be combine, we get rid of the
4746/// transition.
4747class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004748 /// DataLayout associated with the current module.
4749 const DataLayout &DL;
4750
Quentin Colombetc32615d2014-10-31 17:52:53 +00004751 /// Used to perform some checks on the legality of vector operations.
4752 const TargetLowering &TLI;
4753
4754 /// Used to estimated the cost of the promoted chain.
4755 const TargetTransformInfo &TTI;
4756
4757 /// The transition being moved downwards.
4758 Instruction *Transition;
4759 /// The sequence of instructions to be promoted.
4760 SmallVector<Instruction *, 4> InstsToBePromoted;
4761 /// Cost of combining a store and an extract.
4762 unsigned StoreExtractCombineCost;
4763 /// Instruction that will be combined with the transition.
4764 Instruction *CombineInst;
4765
4766 /// \brief The instruction that represents the current end of the transition.
4767 /// Since we are faking the promotion until we reach the end of the chain
4768 /// of computation, we need a way to get the current end of the transition.
4769 Instruction *getEndOfTransition() const {
4770 if (InstsToBePromoted.empty())
4771 return Transition;
4772 return InstsToBePromoted.back();
4773 }
4774
4775 /// \brief Return the index of the original value in the transition.
4776 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4777 /// c, is at index 0.
4778 unsigned getTransitionOriginalValueIdx() const {
4779 assert(isa<ExtractElementInst>(Transition) &&
4780 "Other kind of transitions are not supported yet");
4781 return 0;
4782 }
4783
4784 /// \brief Return the index of the index in the transition.
4785 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4786 /// is at index 1.
4787 unsigned getTransitionIdx() const {
4788 assert(isa<ExtractElementInst>(Transition) &&
4789 "Other kind of transitions are not supported yet");
4790 return 1;
4791 }
4792
4793 /// \brief Get the type of the transition.
4794 /// This is the type of the original value.
4795 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4796 /// transition is <2 x i32>.
4797 Type *getTransitionType() const {
4798 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4799 }
4800
4801 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4802 /// I.e., we have the following sequence:
4803 /// Def = Transition <ty1> a to <ty2>
4804 /// b = ToBePromoted <ty2> Def, ...
4805 /// =>
4806 /// b = ToBePromoted <ty1> a, ...
4807 /// Def = Transition <ty1> ToBePromoted to <ty2>
4808 void promoteImpl(Instruction *ToBePromoted);
4809
4810 /// \brief Check whether or not it is profitable to promote all the
4811 /// instructions enqueued to be promoted.
4812 bool isProfitableToPromote() {
4813 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4814 unsigned Index = isa<ConstantInt>(ValIdx)
4815 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4816 : -1;
4817 Type *PromotedType = getTransitionType();
4818
4819 StoreInst *ST = cast<StoreInst>(CombineInst);
4820 unsigned AS = ST->getPointerAddressSpace();
4821 unsigned Align = ST->getAlignment();
4822 // Check if this store is supported.
4823 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004824 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4825 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004826 // If this is not supported, there is no way we can combine
4827 // the extract with the store.
4828 return false;
4829 }
4830
4831 // The scalar chain of computation has to pay for the transition
4832 // scalar to vector.
4833 // The vector chain has to account for the combining cost.
4834 uint64_t ScalarCost =
4835 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4836 uint64_t VectorCost = StoreExtractCombineCost;
4837 for (const auto &Inst : InstsToBePromoted) {
4838 // Compute the cost.
4839 // By construction, all instructions being promoted are arithmetic ones.
4840 // Moreover, one argument is a constant that can be viewed as a splat
4841 // constant.
4842 Value *Arg0 = Inst->getOperand(0);
4843 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4844 isa<ConstantFP>(Arg0);
4845 TargetTransformInfo::OperandValueKind Arg0OVK =
4846 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4847 : TargetTransformInfo::OK_AnyValue;
4848 TargetTransformInfo::OperandValueKind Arg1OVK =
4849 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4850 : TargetTransformInfo::OK_AnyValue;
4851 ScalarCost += TTI.getArithmeticInstrCost(
4852 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4853 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4854 Arg0OVK, Arg1OVK);
4855 }
4856 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4857 << ScalarCost << "\nVector: " << VectorCost << '\n');
4858 return ScalarCost > VectorCost;
4859 }
4860
4861 /// \brief Generate a constant vector with \p Val with the same
4862 /// number of elements as the transition.
4863 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004864 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004865 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4866 /// otherwise we generate a vector with as many undef as possible:
4867 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4868 /// used at the index of the extract.
4869 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4870 unsigned ExtractIdx = UINT_MAX;
4871 if (!UseSplat) {
4872 // If we cannot determine where the constant must be, we have to
4873 // use a splat constant.
4874 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4875 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4876 ExtractIdx = CstVal->getSExtValue();
4877 else
4878 UseSplat = true;
4879 }
4880
4881 unsigned End = getTransitionType()->getVectorNumElements();
4882 if (UseSplat)
4883 return ConstantVector::getSplat(End, Val);
4884
4885 SmallVector<Constant *, 4> ConstVec;
4886 UndefValue *UndefVal = UndefValue::get(Val->getType());
4887 for (unsigned Idx = 0; Idx != End; ++Idx) {
4888 if (Idx == ExtractIdx)
4889 ConstVec.push_back(Val);
4890 else
4891 ConstVec.push_back(UndefVal);
4892 }
4893 return ConstantVector::get(ConstVec);
4894 }
4895
4896 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4897 /// in \p Use can trigger undefined behavior.
4898 static bool canCauseUndefinedBehavior(const Instruction *Use,
4899 unsigned OperandIdx) {
4900 // This is not safe to introduce undef when the operand is on
4901 // the right hand side of a division-like instruction.
4902 if (OperandIdx != 1)
4903 return false;
4904 switch (Use->getOpcode()) {
4905 default:
4906 return false;
4907 case Instruction::SDiv:
4908 case Instruction::UDiv:
4909 case Instruction::SRem:
4910 case Instruction::URem:
4911 return true;
4912 case Instruction::FDiv:
4913 case Instruction::FRem:
4914 return !Use->hasNoNaNs();
4915 }
4916 llvm_unreachable(nullptr);
4917 }
4918
4919public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004920 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4921 const TargetTransformInfo &TTI, Instruction *Transition,
4922 unsigned CombineCost)
4923 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004924 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4925 assert(Transition && "Do not know how to promote null");
4926 }
4927
4928 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4929 bool canPromote(const Instruction *ToBePromoted) const {
4930 // We could support CastInst too.
4931 return isa<BinaryOperator>(ToBePromoted);
4932 }
4933
4934 /// \brief Check if it is profitable to promote \p ToBePromoted
4935 /// by moving downward the transition through.
4936 bool shouldPromote(const Instruction *ToBePromoted) const {
4937 // Promote only if all the operands can be statically expanded.
4938 // Indeed, we do not want to introduce any new kind of transitions.
4939 for (const Use &U : ToBePromoted->operands()) {
4940 const Value *Val = U.get();
4941 if (Val == getEndOfTransition()) {
4942 // If the use is a division and the transition is on the rhs,
4943 // we cannot promote the operation, otherwise we may create a
4944 // division by zero.
4945 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4946 return false;
4947 continue;
4948 }
4949 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4950 !isa<ConstantFP>(Val))
4951 return false;
4952 }
4953 // Check that the resulting operation is legal.
4954 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4955 if (!ISDOpcode)
4956 return false;
4957 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004958 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004959 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004960 }
4961
4962 /// \brief Check whether or not \p Use can be combined
4963 /// with the transition.
4964 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4965 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4966
4967 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4968 void enqueueForPromotion(Instruction *ToBePromoted) {
4969 InstsToBePromoted.push_back(ToBePromoted);
4970 }
4971
4972 /// \brief Set the instruction that will be combined with the transition.
4973 void recordCombineInstruction(Instruction *ToBeCombined) {
4974 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4975 CombineInst = ToBeCombined;
4976 }
4977
4978 /// \brief Promote all the instructions enqueued for promotion if it is
4979 /// is profitable.
4980 /// \return True if the promotion happened, false otherwise.
4981 bool promote() {
4982 // Check if there is something to promote.
4983 // Right now, if we do not have anything to combine with,
4984 // we assume the promotion is not profitable.
4985 if (InstsToBePromoted.empty() || !CombineInst)
4986 return false;
4987
4988 // Check cost.
4989 if (!StressStoreExtract && !isProfitableToPromote())
4990 return false;
4991
4992 // Promote.
4993 for (auto &ToBePromoted : InstsToBePromoted)
4994 promoteImpl(ToBePromoted);
4995 InstsToBePromoted.clear();
4996 return true;
4997 }
4998};
4999} // End of anonymous namespace.
5000
5001void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5002 // At this point, we know that all the operands of ToBePromoted but Def
5003 // can be statically promoted.
5004 // For Def, we need to use its parameter in ToBePromoted:
5005 // b = ToBePromoted ty1 a
5006 // Def = Transition ty1 b to ty2
5007 // Move the transition down.
5008 // 1. Replace all uses of the promoted operation by the transition.
5009 // = ... b => = ... Def.
5010 assert(ToBePromoted->getType() == Transition->getType() &&
5011 "The type of the result of the transition does not match "
5012 "the final type");
5013 ToBePromoted->replaceAllUsesWith(Transition);
5014 // 2. Update the type of the uses.
5015 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5016 Type *TransitionTy = getTransitionType();
5017 ToBePromoted->mutateType(TransitionTy);
5018 // 3. Update all the operands of the promoted operation with promoted
5019 // operands.
5020 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5021 for (Use &U : ToBePromoted->operands()) {
5022 Value *Val = U.get();
5023 Value *NewVal = nullptr;
5024 if (Val == Transition)
5025 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5026 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5027 isa<ConstantFP>(Val)) {
5028 // Use a splat constant if it is not safe to use undef.
5029 NewVal = getConstantVector(
5030 cast<Constant>(Val),
5031 isa<UndefValue>(Val) ||
5032 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5033 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005034 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5035 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005036 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5037 }
5038 Transition->removeFromParent();
5039 Transition->insertAfter(ToBePromoted);
5040 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5041}
5042
5043/// Some targets can do store(extractelement) with one instruction.
5044/// Try to push the extractelement towards the stores when the target
5045/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005046bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005047 unsigned CombineCost = UINT_MAX;
5048 if (DisableStoreExtract || !TLI ||
5049 (!StressStoreExtract &&
5050 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5051 Inst->getOperand(1), CombineCost)))
5052 return false;
5053
5054 // At this point we know that Inst is a vector to scalar transition.
5055 // Try to move it down the def-use chain, until:
5056 // - We can combine the transition with its single use
5057 // => we got rid of the transition.
5058 // - We escape the current basic block
5059 // => we would need to check that we are moving it at a cheaper place and
5060 // we do not do that for now.
5061 BasicBlock *Parent = Inst->getParent();
5062 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005063 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005064 // If the transition has more than one use, assume this is not going to be
5065 // beneficial.
5066 while (Inst->hasOneUse()) {
5067 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5068 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5069
5070 if (ToBePromoted->getParent() != Parent) {
5071 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5072 << ToBePromoted->getParent()->getName()
5073 << ") than the transition (" << Parent->getName() << ").\n");
5074 return false;
5075 }
5076
5077 if (VPH.canCombine(ToBePromoted)) {
5078 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5079 << "will be combined with: " << *ToBePromoted << '\n');
5080 VPH.recordCombineInstruction(ToBePromoted);
5081 bool Changed = VPH.promote();
5082 NumStoreExtractExposed += Changed;
5083 return Changed;
5084 }
5085
5086 DEBUG(dbgs() << "Try promoting.\n");
5087 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5088 return false;
5089
5090 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5091
5092 VPH.enqueueForPromotion(ToBePromoted);
5093 Inst = ToBePromoted;
5094 }
5095 return false;
5096}
5097
Sanjay Patelfc580a62015-09-21 23:03:16 +00005098bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005099 // Bail out if we inserted the instruction to prevent optimizations from
5100 // stepping on each other's toes.
5101 if (InsertedInsts.count(I))
5102 return false;
5103
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005104 if (PHINode *P = dyn_cast<PHINode>(I)) {
5105 // It is possible for very late stage optimizations (such as SimplifyCFG)
5106 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5107 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005108 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005109 P->replaceAllUsesWith(V);
5110 P->eraseFromParent();
5111 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005112 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005113 }
Chris Lattneree588de2011-01-15 07:29:01 +00005114 return false;
5115 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005116
Chris Lattneree588de2011-01-15 07:29:01 +00005117 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005118 // If the source of the cast is a constant, then this should have
5119 // already been constant folded. The only reason NOT to constant fold
5120 // it is if something (e.g. LSR) was careful to place the constant
5121 // evaluation in a block other than then one that uses it (e.g. to hoist
5122 // the address of globals out of a loop). If this is the case, we don't
5123 // want to forward-subst the cast.
5124 if (isa<Constant>(CI->getOperand(0)))
5125 return false;
5126
Mehdi Amini44ede332015-07-09 02:09:04 +00005127 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005128 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005129
Chris Lattneree588de2011-01-15 07:29:01 +00005130 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005131 /// Sink a zext or sext into its user blocks if the target type doesn't
5132 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005133 if (TLI &&
5134 TLI->getTypeAction(CI->getContext(),
5135 TLI->getValueType(*DL, CI->getType())) ==
5136 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005137 return SinkCast(CI);
5138 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005139 bool MadeChange = moveExtToFormExtLoad(I);
5140 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005141 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005142 }
Chris Lattneree588de2011-01-15 07:29:01 +00005143 return false;
5144 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005145
Chris Lattneree588de2011-01-15 07:29:01 +00005146 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005147 if (!TLI || !TLI->hasMultipleConditionRegisters())
5148 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005149
Chris Lattneree588de2011-01-15 07:29:01 +00005150 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005151 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005152 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005153 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005154 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005155 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5156 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005157 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005158 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005159 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005160
Chris Lattneree588de2011-01-15 07:29:01 +00005161 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005162 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005163 if (TLI) {
5164 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005165 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005166 SI->getOperand(0)->getType(), AS);
5167 }
Chris Lattneree588de2011-01-15 07:29:01 +00005168 return false;
5169 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005170
Yi Jiangd069f632014-04-21 19:34:27 +00005171 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5172
5173 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5174 BinOp->getOpcode() == Instruction::LShr)) {
5175 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5176 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005177 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005178
5179 return false;
5180 }
5181
Chris Lattneree588de2011-01-15 07:29:01 +00005182 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005183 if (GEPI->hasAllZeroIndices()) {
5184 /// The GEP operand must be a pointer, so must its result -> BitCast
5185 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5186 GEPI->getName(), GEPI);
5187 GEPI->replaceAllUsesWith(NC);
5188 GEPI->eraseFromParent();
5189 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005190 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005191 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005192 }
Chris Lattneree588de2011-01-15 07:29:01 +00005193 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005194 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005195
Chris Lattneree588de2011-01-15 07:29:01 +00005196 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005197 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005198
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005199 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005200 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005201
Tim Northoveraeb8e062014-02-19 10:02:43 +00005202 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005203 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005204
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005205 if (auto *Switch = dyn_cast<SwitchInst>(I))
5206 return optimizeSwitchInst(Switch);
5207
Quentin Colombetc32615d2014-10-31 17:52:53 +00005208 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005209 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005210
Chris Lattneree588de2011-01-15 07:29:01 +00005211 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005212}
5213
James Molloyf01488e2016-01-15 09:20:19 +00005214/// Given an OR instruction, check to see if this is a bitreverse
5215/// idiom. If so, insert the new intrinsic and return true.
5216static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5217 const TargetLowering &TLI) {
5218 if (!I.getType()->isIntegerTy() ||
5219 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5220 TLI.getValueType(DL, I.getType(), true)))
5221 return false;
5222
5223 SmallVector<Instruction*, 4> Insts;
5224 if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
5225 return false;
5226 Instruction *LastInst = Insts.back();
5227 I.replaceAllUsesWith(LastInst);
5228 RecursivelyDeleteTriviallyDeadInstructions(&I);
5229 return true;
5230}
5231
Chris Lattnerf2836d12007-03-31 04:06:36 +00005232// In this pass we look for GEP and cast instructions that are used
5233// across basic blocks and rewrite them to improve basic-block-at-a-time
5234// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005235bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005236 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005237 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005238
Chris Lattner7a277142011-01-15 07:14:54 +00005239 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005240 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005241 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005242 if (ModifiedDT)
5243 return true;
5244 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005245
James Molloyf01488e2016-01-15 09:20:19 +00005246 bool MadeBitReverse = true;
5247 while (TLI && MadeBitReverse) {
5248 MadeBitReverse = false;
5249 for (auto &I : reverse(BB)) {
5250 if (makeBitReverse(I, *DL, *TLI)) {
5251 MadeBitReverse = MadeChange = true;
5252 break;
5253 }
5254 }
5255 }
James Molloy3ef84c42016-01-15 10:36:01 +00005256 MadeChange |= dupRetToEnableTailCallOpts(&BB);
James Molloyf01488e2016-01-15 09:20:19 +00005257
Chris Lattnerf2836d12007-03-31 04:06:36 +00005258 return MadeChange;
5259}
Devang Patel53771ba2011-08-18 00:50:51 +00005260
5261// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005262// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005263// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005264bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005265 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005266 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005267 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005268 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005269 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005270 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005271 // Leave dbg.values that refer to an alloca alone. These
5272 // instrinsics describe the address of a variable (= the alloca)
5273 // being taken. They should not be moved next to the alloca
5274 // (and to the beginning of the scope), but rather stay close to
5275 // where said address is used.
5276 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005277 PrevNonDbgInst = Insn;
5278 continue;
5279 }
5280
5281 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5282 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005283 // If VI is a phi in a block with an EHPad terminator, we can't insert
5284 // after it.
5285 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5286 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005287 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5288 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005289 if (isa<PHINode>(VI))
5290 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5291 else
5292 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005293 MadeChange = true;
5294 ++NumDbgValueMoved;
5295 }
5296 }
5297 }
5298 return MadeChange;
5299}
Tim Northovercea0abb2014-03-29 08:22:29 +00005300
5301// If there is a sequence that branches based on comparing a single bit
5302// against zero that can be combined into a single instruction, and the
5303// target supports folding these into a single instruction, sink the
5304// mask and compare into the branch uses. Do this before OptimizeBlock ->
5305// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5306// searched for.
5307bool CodeGenPrepare::sinkAndCmp(Function &F) {
5308 if (!EnableAndCmpSinking)
5309 return false;
5310 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5311 return false;
5312 bool MadeChange = false;
5313 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005314 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00005315
5316 // Does this BB end with the following?
5317 // %andVal = and %val, #single-bit-set
5318 // %icmpVal = icmp %andResult, 0
5319 // br i1 %cmpVal label %dest1, label %dest2"
5320 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
5321 if (!Brcc || !Brcc->isConditional())
5322 continue;
5323 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
5324 if (!Cmp || Cmp->getParent() != BB)
5325 continue;
5326 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5327 if (!Zero || !Zero->isZero())
5328 continue;
5329 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
5330 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
5331 continue;
5332 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5333 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5334 continue;
5335 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
5336
5337 // Push the "and; icmp" for any users that are conditional branches.
5338 // Since there can only be one branch use per BB, we don't need to keep
5339 // track of which BBs we insert into.
5340 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
5341 UI != E; ) {
5342 Use &TheUse = *UI;
5343 // Find brcc use.
5344 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
5345 ++UI;
5346 if (!BrccUser || !BrccUser->isConditional())
5347 continue;
5348 BasicBlock *UserBB = BrccUser->getParent();
5349 if (UserBB == BB) continue;
5350 DEBUG(dbgs() << "found Brcc use\n");
5351
5352 // Sink the "and; icmp" to use.
5353 MadeChange = true;
5354 BinaryOperator *NewAnd =
5355 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5356 BrccUser);
5357 CmpInst *NewCmp =
5358 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5359 "", BrccUser);
5360 TheUse = NewCmp;
5361 ++NumAndCmpsMoved;
5362 DEBUG(BrccUser->getParent()->dump());
5363 }
5364 }
5365 return MadeChange;
5366}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005367
Juergen Ributzka194350a2014-12-09 17:32:12 +00005368/// \brief Retrieve the probabilities of a conditional branch. Returns true on
5369/// success, or returns false if no or invalid metadata was found.
5370static bool extractBranchMetadata(BranchInst *BI,
5371 uint64_t &ProbTrue, uint64_t &ProbFalse) {
5372 assert(BI->isConditional() &&
5373 "Looking for probabilities on unconditional branch?");
5374 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
5375 if (!ProfileData || ProfileData->getNumOperands() != 3)
5376 return false;
5377
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005378 const auto *CITrue =
5379 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
5380 const auto *CIFalse =
5381 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00005382 if (!CITrue || !CIFalse)
5383 return false;
5384
5385 ProbTrue = CITrue->getValue().getZExtValue();
5386 ProbFalse = CIFalse->getValue().getZExtValue();
5387
5388 return true;
5389}
5390
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005391/// \brief Scale down both weights to fit into uint32_t.
5392static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5393 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5394 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5395 NewTrue = NewTrue / Scale;
5396 NewFalse = NewFalse / Scale;
5397}
5398
5399/// \brief Some targets prefer to split a conditional branch like:
5400/// \code
5401/// %0 = icmp ne i32 %a, 0
5402/// %1 = icmp ne i32 %b, 0
5403/// %or.cond = or i1 %0, %1
5404/// br i1 %or.cond, label %TrueBB, label %FalseBB
5405/// \endcode
5406/// into multiple branch instructions like:
5407/// \code
5408/// bb1:
5409/// %0 = icmp ne i32 %a, 0
5410/// br i1 %0, label %TrueBB, label %bb2
5411/// bb2:
5412/// %1 = icmp ne i32 %b, 0
5413/// br i1 %1, label %TrueBB, label %FalseBB
5414/// \endcode
5415/// This usually allows instruction selection to do even further optimizations
5416/// and combine the compare with the branch instruction. Currently this is
5417/// applied for targets which have "cheap" jump instructions.
5418///
5419/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5420///
5421bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005422 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005423 return false;
5424
5425 bool MadeChange = false;
5426 for (auto &BB : F) {
5427 // Does this BB end with the following?
5428 // %cond1 = icmp|fcmp|binary instruction ...
5429 // %cond2 = icmp|fcmp|binary instruction ...
5430 // %cond.or = or|and i1 %cond1, cond2
5431 // br i1 %cond.or label %dest1, label %dest2"
5432 BinaryOperator *LogicOp;
5433 BasicBlock *TBB, *FBB;
5434 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5435 continue;
5436
Sanjay Patel42574202015-09-02 19:23:23 +00005437 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5438 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5439 continue;
5440
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005441 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005442 Value *Cond1, *Cond2;
5443 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5444 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005445 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005446 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5447 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005448 Opc = Instruction::Or;
5449 else
5450 continue;
5451
5452 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5453 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5454 continue;
5455
5456 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5457
5458 // Create a new BB.
5459 auto *InsertBefore = std::next(Function::iterator(BB))
5460 .getNodePtrUnchecked();
5461 auto TmpBB = BasicBlock::Create(BB.getContext(),
5462 BB.getName() + ".cond.split",
5463 BB.getParent(), InsertBefore);
5464
5465 // Update original basic block by using the first condition directly by the
5466 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005467 Br1->setCondition(Cond1);
5468 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005469
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005470 // Depending on the conditon we have to either replace the true or the false
5471 // successor of the original branch instruction.
5472 if (Opc == Instruction::And)
5473 Br1->setSuccessor(0, TmpBB);
5474 else
5475 Br1->setSuccessor(1, TmpBB);
5476
5477 // Fill in the new basic block.
5478 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005479 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5480 I->removeFromParent();
5481 I->insertBefore(Br2);
5482 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005483
5484 // Update PHI nodes in both successors. The original BB needs to be
5485 // replaced in one succesor's PHI nodes, because the branch comes now from
5486 // the newly generated BB (NewBB). In the other successor we need to add one
5487 // incoming edge to the PHI nodes, because both branch instructions target
5488 // now the same successor. Depending on the original branch condition
5489 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5490 // we perfrom the correct update for the PHI nodes.
5491 // This doesn't change the successor order of the just created branch
5492 // instruction (or any other instruction).
5493 if (Opc == Instruction::Or)
5494 std::swap(TBB, FBB);
5495
5496 // Replace the old BB with the new BB.
5497 for (auto &I : *TBB) {
5498 PHINode *PN = dyn_cast<PHINode>(&I);
5499 if (!PN)
5500 break;
5501 int i;
5502 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5503 PN->setIncomingBlock(i, TmpBB);
5504 }
5505
5506 // Add another incoming edge form the new BB.
5507 for (auto &I : *FBB) {
5508 PHINode *PN = dyn_cast<PHINode>(&I);
5509 if (!PN)
5510 break;
5511 auto *Val = PN->getIncomingValueForBlock(&BB);
5512 PN->addIncoming(Val, TmpBB);
5513 }
5514
5515 // Update the branch weights (from SelectionDAGBuilder::
5516 // FindMergedConditions).
5517 if (Opc == Instruction::Or) {
5518 // Codegen X | Y as:
5519 // BB1:
5520 // jmp_if_X TBB
5521 // jmp TmpBB
5522 // TmpBB:
5523 // jmp_if_Y TBB
5524 // jmp FBB
5525 //
5526
5527 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5528 // The requirement is that
5529 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5530 // = TrueProb for orignal BB.
5531 // Assuming the orignal weights are A and B, one choice is to set BB1's
5532 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5533 // assumes that
5534 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5535 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5536 // TmpBB, but the math is more complicated.
5537 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005538 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005539 uint64_t NewTrueWeight = TrueWeight;
5540 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5541 scaleWeights(NewTrueWeight, NewFalseWeight);
5542 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5543 .createBranchWeights(TrueWeight, FalseWeight));
5544
5545 NewTrueWeight = TrueWeight;
5546 NewFalseWeight = 2 * FalseWeight;
5547 scaleWeights(NewTrueWeight, NewFalseWeight);
5548 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5549 .createBranchWeights(TrueWeight, FalseWeight));
5550 }
5551 } else {
5552 // Codegen X & Y as:
5553 // BB1:
5554 // jmp_if_X TmpBB
5555 // jmp FBB
5556 // TmpBB:
5557 // jmp_if_Y TBB
5558 // jmp FBB
5559 //
5560 // This requires creation of TmpBB after CurBB.
5561
5562 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5563 // The requirement is that
5564 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5565 // = FalseProb for orignal BB.
5566 // Assuming the orignal weights are A and B, one choice is to set BB1's
5567 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5568 // assumes that
5569 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5570 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005571 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005572 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5573 uint64_t NewFalseWeight = FalseWeight;
5574 scaleWeights(NewTrueWeight, NewFalseWeight);
5575 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5576 .createBranchWeights(TrueWeight, FalseWeight));
5577
5578 NewTrueWeight = 2 * TrueWeight;
5579 NewFalseWeight = FalseWeight;
5580 scaleWeights(NewTrueWeight, NewFalseWeight);
5581 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5582 .createBranchWeights(TrueWeight, FalseWeight));
5583 }
5584 }
5585
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005586 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005587 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005588 ModifiedDT = true;
5589
5590 MadeChange = true;
5591
5592 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5593 TmpBB->dump());
5594 }
5595 return MadeChange;
5596}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005597
5598void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005599 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005600 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5601}