blob: ba68a4ec25272cb96b72014e8c01f52765b42731 [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 {
George Burgess IVd4febd12016-03-22 21:25:08 +0000161 // FIXME: When we can selectively preserve passes, preserve the domtree.
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
Sanjay Patel545a4562016-01-20 18:59:16 +0000615 assert(RelocatedBase->getNextNode() &&
616 "Should always have one since it's not a terminator");
Sanjoy Das3d705e32015-05-11 23:47:30 +0000617
618 // Insert after RelocatedBase
619 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000620 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000621
622 // If gc_relocate does not match the actual type, cast it to the right type.
623 // In theory, there must be a bitcast after gc_relocate if the type does not
624 // match, and we should reuse it to get the derived pointer. But it could be
625 // cases like this:
626 // bb1:
627 // ...
628 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
629 // br label %merge
630 //
631 // bb2:
632 // ...
633 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
634 // br label %merge
635 //
636 // merge:
637 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
638 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
639 //
640 // In this case, we can not find the bitcast any more. So we insert a new bitcast
641 // no matter there is already one or not. In this way, we can handle all cases, and
642 // the extra bitcast should be optimized away in later passes.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000643 Value *ActualRelocatedBase = RelocatedBase;
Sanjoy Das89c54912015-05-11 18:49:34 +0000644 if (RelocatedBase->getType() != Base->getType()) {
645 ActualRelocatedBase =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000646 Builder.CreateBitCast(RelocatedBase, Base->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000647 }
David Blaikie68d535c2015-03-24 22:38:16 +0000648 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000649 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000650 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000651 // If the newly generated derived pointer's type does not match the original derived
652 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
Manuel Jacob5b90b142015-12-19 18:38:42 +0000653 Value *ActualReplacement = Replacement;
654 if (Replacement->getType() != ToReplace->getType()) {
Sanjoy Das89c54912015-05-11 18:49:34 +0000655 ActualReplacement =
Manuel Jacob5b90b142015-12-19 18:38:42 +0000656 Builder.CreateBitCast(Replacement, ToReplace->getType());
Sanjoy Das89c54912015-05-11 18:49:34 +0000657 }
658 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000659 ToReplace->eraseFromParent();
660
661 MadeChange = true;
662 }
663 return MadeChange;
664}
665
666// Turns this:
667//
668// %base = ...
669// %ptr = gep %base + 15
670// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
671// %base' = relocate(%tok, i32 4, i32 4)
672// %ptr' = relocate(%tok, i32 4, i32 5)
673// %val = load %ptr'
674//
675// into this:
676//
677// %base = ...
678// %ptr = gep %base + 15
679// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
680// %base' = gc.relocate(%tok, i32 4, i32 4)
681// %ptr' = gep %base' + 15
682// %val = load %ptr'
683bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
684 bool MadeChange = false;
Manuel Jacob83eefa62016-01-05 04:03:00 +0000685 SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000686
687 for (auto *U : I.users())
Manuel Jacob83eefa62016-01-05 04:03:00 +0000688 if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000689 // Collect all the relocate calls associated with a statepoint
Manuel Jacob83eefa62016-01-05 04:03:00 +0000690 AllRelocateCalls.push_back(Relocate);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000691
692 // We need atleast one base pointer relocation + one derived pointer
693 // relocation to mangle
694 if (AllRelocateCalls.size() < 2)
695 return false;
696
697 // RelocateInstMap is a mapping from the base relocate instruction to the
698 // corresponding derived relocate instructions
Manuel Jacob83eefa62016-01-05 04:03:00 +0000699 DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000700 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
701 if (RelocateInstMap.empty())
702 return false;
703
704 for (auto &Item : RelocateInstMap)
705 // Item.first is the RelocatedBase to offset against
706 // Item.second is the vector of Targets to replace
707 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
708 return MadeChange;
709}
710
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000711/// SinkCast - Sink the specified cast instruction into its user blocks
712static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000713 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000714
Chris Lattnerf2836d12007-03-31 04:06:36 +0000715 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000716 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000717
Chris Lattnerf2836d12007-03-31 04:06:36 +0000718 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000719 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000720 UI != E; ) {
721 Use &TheUse = UI.getUse();
722 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000723
Chris Lattnerf2836d12007-03-31 04:06:36 +0000724 // Figure out which BB this cast is used in. For PHI's this is the
725 // appropriate predecessor block.
726 BasicBlock *UserBB = User->getParent();
727 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000728 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000729 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000730
Chris Lattnerf2836d12007-03-31 04:06:36 +0000731 // Preincrement use iterator so we don't invalidate it.
732 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000733
Andrew Kaylord0430e82015-11-23 19:16:15 +0000734 // If the block selected to receive the cast is an EH pad that does not
735 // allow non-PHI instructions before the terminator, we can't sink the
736 // cast.
737 if (UserBB->getTerminator()->isEHPad())
738 continue;
739
Chris Lattnerf2836d12007-03-31 04:06:36 +0000740 // If this user is in the same block as the cast, don't change the cast.
741 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000742
Chris Lattnerf2836d12007-03-31 04:06:36 +0000743 // If we have already inserted a cast into this block, use it.
744 CastInst *&InsertedCast = InsertedCasts[UserBB];
745
746 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000747 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000748 assert(InsertPt != UserBB->end());
749 InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
750 CI->getType(), "", &*InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000751 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000752
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000753 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000754 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000755 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000756 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000757 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000758
Chris Lattnerf2836d12007-03-31 04:06:36 +0000759 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000760 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000761 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000762 MadeChange = true;
763 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000764
Chris Lattnerf2836d12007-03-31 04:06:36 +0000765 return MadeChange;
766}
767
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000768/// If the specified cast instruction is a noop copy (e.g. it's casting from
769/// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
770/// reduce the number of virtual registers that must be created and coalesced.
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000771///
772/// Return true if any changes are made.
773///
Mehdi Amini44ede332015-07-09 02:09:04 +0000774static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
775 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000776 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000777 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
778 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000779
780 // This is an fp<->int conversion?
781 if (SrcVT.isInteger() != DstVT.isInteger())
782 return false;
783
784 // If this is an extension, it will be a zero or sign extension, which
785 // isn't a noop.
786 if (SrcVT.bitsLT(DstVT)) return false;
787
788 // If these values will be promoted, find out what they will be promoted
789 // to. This helps us consider truncates on PPC as noop copies when they
790 // are.
791 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
792 TargetLowering::TypePromoteInteger)
793 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
794 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
795 TargetLowering::TypePromoteInteger)
796 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
797
798 // If, after promotion, these are the same types, this is a noop copy.
799 if (SrcVT != DstVT)
800 return false;
801
802 return SinkCast(CI);
803}
804
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000805/// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
806/// possible.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000807///
808/// Return true if any changes were made.
809static bool CombineUAddWithOverflow(CmpInst *CI) {
810 Value *A, *B;
811 Instruction *AddI;
812 if (!match(CI,
813 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
814 return false;
815
816 Type *Ty = AddI->getType();
817 if (!isa<IntegerType>(Ty))
818 return false;
819
820 // We don't want to move around uses of condition values this late, so we we
821 // check if it is legal to create the call to the intrinsic in the basic
822 // block containing the icmp:
823
824 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
825 return false;
826
827#ifndef NDEBUG
828 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
829 // for now:
830 if (AddI->hasOneUse())
831 assert(*AddI->user_begin() == CI && "expected!");
832#endif
833
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000834 Module *M = CI->getModule();
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000835 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
836
837 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
838
839 auto *UAddWithOverflow =
840 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
841 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
842 auto *Overflow =
843 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
844
845 CI->replaceAllUsesWith(Overflow);
846 AddI->replaceAllUsesWith(UAdd);
847 CI->eraseFromParent();
848 AddI->eraseFromParent();
849 return true;
850}
851
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000852/// Sink the given CmpInst into user blocks to reduce the number of virtual
853/// registers that must be created and coalesced. This is a clear win except on
854/// targets with multiple condition code registers (PowerPC), where it might
855/// lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000856///
857/// Return true if any changes are made.
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000858static bool SinkCmpExpression(CmpInst *CI, const TargetLowering &TLI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000859 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000860
Peter Zotov0b6d7bc2016-04-03 16:36:17 +0000861 // Avoid sinking soft-FP comparisons, since this can move them into a loop.
862 if (TLI.useSoftFloat() && isa<FCmpInst>(CI))
863 return false;
864
865 // Only insert a cmp in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000866 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000867
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000868 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000869 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000870 UI != E; ) {
871 Use &TheUse = UI.getUse();
872 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000873
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000874 // Preincrement use iterator so we don't invalidate it.
875 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000876
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000877 // Don't bother for PHI nodes.
878 if (isa<PHINode>(User))
879 continue;
880
881 // Figure out which BB this cmp is used in.
882 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000883
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000884 // If this user is in the same block as the cmp, don't change the cmp.
885 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000886
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000887 // If we have already inserted a cmp into this block, use it.
888 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
889
890 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000891 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000892 assert(InsertPt != UserBB->end());
Eric Christopherc1ea1492008-09-24 05:32:41 +0000893 InsertedCmp =
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000894 CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
895 CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000896 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000897
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000898 // Replace a use of the cmp with a use of the new cmp.
899 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000900 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000901 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000902 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000903
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000904 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000905 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000906 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000907 MadeChange = true;
908 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000909
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000910 return MadeChange;
911}
912
Peter Zotovf87e5502016-04-03 17:11:53 +0000913static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
914 if (TLI && SinkCmpExpression(CI, *TLI))
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000915 return true;
916
917 if (CombineUAddWithOverflow(CI))
918 return true;
919
920 return false;
921}
922
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000923/// Check if the candidates could be combined with a shift instruction, which
924/// includes:
Yi Jiangd069f632014-04-21 19:34:27 +0000925/// 1. Truncate instruction
926/// 2. And instruction and the imm is a mask of the low bits:
927/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000928static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000929 if (!isa<TruncInst>(User)) {
930 if (User->getOpcode() != Instruction::And ||
931 !isa<ConstantInt>(User->getOperand(1)))
932 return false;
933
Quentin Colombetd4f44692014-04-22 01:20:34 +0000934 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000935
Quentin Colombetd4f44692014-04-22 01:20:34 +0000936 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000937 return false;
938 }
939 return true;
940}
941
Sanjay Patel4ac6b112015-09-21 22:47:23 +0000942/// Sink both shift and truncate instruction to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000943static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000944SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
945 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000946 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000947 BasicBlock *UserBB = User->getParent();
948 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
949 TruncInst *TruncI = dyn_cast<TruncInst>(User);
950 bool MadeChange = false;
951
952 for (Value::user_iterator TruncUI = TruncI->user_begin(),
953 TruncE = TruncI->user_end();
954 TruncUI != TruncE;) {
955
956 Use &TruncTheUse = TruncUI.getUse();
957 Instruction *TruncUser = cast<Instruction>(*TruncUI);
958 // Preincrement use iterator so we don't invalidate it.
959
960 ++TruncUI;
961
962 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
963 if (!ISDOpcode)
964 continue;
965
Tim Northovere2239ff2014-07-29 10:20:22 +0000966 // If the use is actually a legal node, there will not be an
967 // implicit truncate.
968 // FIXME: always querying the result type is just an
969 // approximation; some nodes' legality is determined by the
970 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000971 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000972 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000973 continue;
974
975 // Don't bother for PHI nodes.
976 if (isa<PHINode>(TruncUser))
977 continue;
978
979 BasicBlock *TruncUserBB = TruncUser->getParent();
980
981 if (UserBB == TruncUserBB)
982 continue;
983
984 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
985 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
986
987 if (!InsertedShift && !InsertedTrunc) {
988 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000989 assert(InsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +0000990 // Sink the shift
991 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000992 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
993 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000994 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +0000995 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
996 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +0000997
998 // Sink the trunc
999 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
1000 TruncInsertPt++;
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001001 assert(TruncInsertPt != TruncUserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001002
1003 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001004 TruncI->getType(), "", &*TruncInsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001005
1006 MadeChange = true;
1007
1008 TruncTheUse = InsertedTrunc;
1009 }
1010 }
1011 return MadeChange;
1012}
1013
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001014/// Sink the shift *right* instruction into user blocks if the uses could
1015/// potentially be combined with this shift instruction and generate BitExtract
1016/// instruction. It will only be applied if the architecture supports BitExtract
1017/// instruction. Here is an example:
Yi Jiangd069f632014-04-21 19:34:27 +00001018/// BB1:
1019/// %x.extract.shift = lshr i64 %arg1, 32
1020/// BB2:
1021/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1022/// ==>
1023///
1024/// BB2:
1025/// %x.extract.shift.1 = lshr i64 %arg1, 32
1026/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1027///
1028/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1029/// instruction.
1030/// Return true if any changes are made.
1031static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001032 const TargetLowering &TLI,
1033 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001034 BasicBlock *DefBB = ShiftI->getParent();
1035
1036 /// Only insert instructions in each block once.
1037 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1038
Mehdi Amini44ede332015-07-09 02:09:04 +00001039 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001040
1041 bool MadeChange = false;
1042 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1043 UI != E;) {
1044 Use &TheUse = UI.getUse();
1045 Instruction *User = cast<Instruction>(*UI);
1046 // Preincrement use iterator so we don't invalidate it.
1047 ++UI;
1048
1049 // Don't bother for PHI nodes.
1050 if (isa<PHINode>(User))
1051 continue;
1052
1053 if (!isExtractBitsCandidateUse(User))
1054 continue;
1055
1056 BasicBlock *UserBB = User->getParent();
1057
1058 if (UserBB == DefBB) {
1059 // If the shift and truncate instruction are in the same BB. The use of
1060 // the truncate(TruncUse) may still introduce another truncate if not
1061 // legal. In this case, we would like to sink both shift and truncate
1062 // instruction to the BB of TruncUse.
1063 // for example:
1064 // BB1:
1065 // i64 shift.result = lshr i64 opnd, imm
1066 // trunc.result = trunc shift.result to i16
1067 //
1068 // BB2:
1069 // ----> We will have an implicit truncate here if the architecture does
1070 // not have i16 compare.
1071 // cmp i16 trunc.result, opnd2
1072 //
1073 if (isa<TruncInst>(User) && shiftIsLegal
1074 // If the type of the truncate is legal, no trucate will be
1075 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001076 &&
1077 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001078 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001079 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001080
1081 continue;
1082 }
1083 // If we have already inserted a shift into this block, use it.
1084 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1085
1086 if (!InsertedShift) {
1087 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001088 assert(InsertPt != UserBB->end());
Yi Jiangd069f632014-04-21 19:34:27 +00001089
1090 if (ShiftI->getOpcode() == Instruction::AShr)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001091 InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
1092 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001093 else
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001094 InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
1095 "", &*InsertPt);
Yi Jiangd069f632014-04-21 19:34:27 +00001096
1097 MadeChange = true;
1098 }
1099
1100 // Replace a use of the shift with a use of the new shift.
1101 TheUse = InsertedShift;
1102 }
1103
1104 // If we removed all uses, nuke the shift.
1105 if (ShiftI->use_empty())
1106 ShiftI->eraseFromParent();
1107
1108 return MadeChange;
1109}
1110
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001111// Translate a masked load intrinsic like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001112// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1113// <16 x i1> %mask, <16 x i32> %passthru)
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001114// to a chain of basic blocks, with loading element one-by-one if
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001115// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001116//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001117// %1 = bitcast i8* %addr to i32*
1118// %2 = extractelement <16 x i1> %mask, i32 0
1119// %3 = icmp eq i1 %2, true
1120// br i1 %3, label %cond.load, label %else
1121//
1122//cond.load: ; preds = %0
1123// %4 = getelementptr i32* %1, i32 0
1124// %5 = load i32* %4
1125// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1126// br label %else
1127//
1128//else: ; preds = %0, %cond.load
1129// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1130// %7 = extractelement <16 x i1> %mask, i32 1
1131// %8 = icmp eq i1 %7, true
1132// br i1 %8, label %cond.load1, label %else2
1133//
1134//cond.load1: ; preds = %else
1135// %9 = getelementptr i32* %1, i32 1
1136// %10 = load i32* %9
1137// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1138// br label %else2
1139//
1140//else2: ; preds = %else, %cond.load1
1141// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1142// %12 = extractelement <16 x i1> %mask, i32 2
1143// %13 = icmp eq i1 %12, true
1144// br i1 %13, label %cond.load4, label %else5
1145//
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001146static void scalarizeMaskedLoad(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001147 Value *Ptr = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001148 Value *Alignment = CI->getArgOperand(1);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001149 Value *Mask = CI->getArgOperand(2);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001150 Value *Src0 = CI->getArgOperand(3);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001151
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001152 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1153 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001154 assert(VecType && "Unexpected return type of masked load intrinsic");
1155
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001156 Type *EltTy = CI->getType()->getVectorElementType();
1157
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001158 IRBuilder<> Builder(CI->getContext());
1159 Instruction *InsertPt = CI;
1160 BasicBlock *IfBlock = CI->getParent();
1161 BasicBlock *CondBlock = nullptr;
1162 BasicBlock *PrevIfBlock = CI->getParent();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001163
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001164 Builder.SetInsertPoint(InsertPt);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001165 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1166
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001167 // Short-cut if the mask is all-true.
1168 bool IsAllOnesMask = isa<Constant>(Mask) &&
1169 cast<Constant>(Mask)->isAllOnesValue();
1170
1171 if (IsAllOnesMask) {
1172 Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
1173 CI->replaceAllUsesWith(NewI);
1174 CI->eraseFromParent();
1175 return;
1176 }
1177
1178 // Adjust alignment for the scalar instruction.
1179 AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001180 // Bitcast %addr fron i8* to EltTy*
1181 Type *NewPtrType =
1182 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1183 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001184 unsigned VectorWidth = VecType->getNumElements();
1185
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001186 Value *UndefVal = UndefValue::get(VecType);
1187
1188 // The result vector
1189 Value *VResult = UndefVal;
1190
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001191 if (isa<ConstantVector>(Mask)) {
1192 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1193 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1194 continue;
1195 Value *Gep =
1196 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1197 LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
1198 VResult = Builder.CreateInsertElement(VResult, Load,
1199 Builder.getInt32(Idx));
1200 }
1201 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1202 CI->replaceAllUsesWith(NewI);
1203 CI->eraseFromParent();
1204 return;
1205 }
1206
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001207 PHINode *Phi = nullptr;
1208 Value *PrevPhi = UndefVal;
1209
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001210 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1211
1212 // Fill the "else" block, created in the previous iteration
1213 //
1214 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1215 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1216 // %to_load = icmp eq i1 %mask_1, true
1217 // br i1 %to_load, label %cond.load, label %else
1218 //
1219 if (Idx > 0) {
1220 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1221 Phi->addIncoming(VResult, CondBlock);
1222 Phi->addIncoming(PrevPhi, PrevIfBlock);
1223 PrevPhi = Phi;
1224 VResult = Phi;
1225 }
1226
1227 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1228 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1229 ConstantInt::get(Predicate->getType(), 1));
1230
1231 // Create "cond" block
1232 //
1233 // %EltAddr = getelementptr i32* %1, i32 0
1234 // %Elt = load i32* %EltAddr
1235 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1236 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001237 CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001238 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001239
1240 Value *Gep =
1241 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky09285852015-10-25 15:37:55 +00001242 LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001243 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1244
1245 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001246 BasicBlock *NewIfBlock =
1247 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001248 Builder.SetInsertPoint(InsertPt);
1249 Instruction *OldBr = IfBlock->getTerminator();
1250 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1251 OldBr->eraseFromParent();
1252 PrevIfBlock = IfBlock;
1253 IfBlock = NewIfBlock;
1254 }
1255
1256 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1257 Phi->addIncoming(VResult, CondBlock);
1258 Phi->addIncoming(PrevPhi, PrevIfBlock);
1259 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1260 CI->replaceAllUsesWith(NewI);
1261 CI->eraseFromParent();
1262}
1263
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001264// Translate a masked store intrinsic, like
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001265// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1266// <16 x i1> %mask)
1267// to a chain of basic blocks, that stores element one-by-one if
1268// the appropriate mask bit is set
1269//
1270// %1 = bitcast i8* %addr to i32*
1271// %2 = extractelement <16 x i1> %mask, i32 0
1272// %3 = icmp eq i1 %2, true
1273// br i1 %3, label %cond.store, label %else
1274//
1275// cond.store: ; preds = %0
1276// %4 = extractelement <16 x i32> %val, i32 0
1277// %5 = getelementptr i32* %1, i32 0
1278// store i32 %4, i32* %5
1279// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001280//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001281// else: ; preds = %0, %cond.store
1282// %6 = extractelement <16 x i1> %mask, i32 1
1283// %7 = icmp eq i1 %6, true
1284// br i1 %7, label %cond.store1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001285//
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001286// cond.store1: ; preds = %else
1287// %8 = extractelement <16 x i32> %val, i32 1
1288// %9 = getelementptr i32* %1, i32 1
1289// store i32 %8, i32* %9
1290// br label %else2
1291// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001292static void scalarizeMaskedStore(CallInst *CI) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001293 Value *Src = CI->getArgOperand(0);
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001294 Value *Ptr = CI->getArgOperand(1);
1295 Value *Alignment = CI->getArgOperand(2);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001296 Value *Mask = CI->getArgOperand(3);
1297
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001298 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001299 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001300 assert(VecType && "Unexpected data type in masked store intrinsic");
1301
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001302 Type *EltTy = VecType->getElementType();
1303
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001304 IRBuilder<> Builder(CI->getContext());
1305 Instruction *InsertPt = CI;
1306 BasicBlock *IfBlock = CI->getParent();
1307 Builder.SetInsertPoint(InsertPt);
1308 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1309
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001310 // Short-cut if the mask is all-true.
1311 bool IsAllOnesMask = isa<Constant>(Mask) &&
1312 cast<Constant>(Mask)->isAllOnesValue();
1313
1314 if (IsAllOnesMask) {
1315 Builder.CreateAlignedStore(Src, Ptr, AlignVal);
1316 CI->eraseFromParent();
1317 return;
1318 }
1319
1320 // Adjust alignment for the scalar instruction.
1321 AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001322 // Bitcast %addr fron i8* to EltTy*
1323 Type *NewPtrType =
1324 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1325 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001326 unsigned VectorWidth = VecType->getNumElements();
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001327
1328 if (isa<ConstantVector>(Mask)) {
1329 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1330 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1331 continue;
1332 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
1333 Value *Gep =
1334 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
1335 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
1336 }
1337 CI->eraseFromParent();
1338 return;
1339 }
1340
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001341 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1342
1343 // Fill the "else" block, created in the previous iteration
1344 //
1345 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1346 // %to_store = icmp eq i1 %mask_1, true
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001347 // br i1 %to_store, label %cond.store, label %else
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001348 //
1349 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1350 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1351 ConstantInt::get(Predicate->getType(), 1));
1352
1353 // Create "cond" block
1354 //
1355 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1356 // %EltAddr = getelementptr i32* %1, i32 0
1357 // %store i32 %OneElt, i32* %EltAddr
1358 //
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001359 BasicBlock *CondBlock =
1360 IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001361 Builder.SetInsertPoint(InsertPt);
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001362
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001363 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001364 Value *Gep =
1365 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky3ad76a12015-10-21 11:50:54 +00001366 Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001367
1368 // Create "else" block, fill it in the next iteration
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00001369 BasicBlock *NewIfBlock =
1370 CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001371 Builder.SetInsertPoint(InsertPt);
1372 Instruction *OldBr = IfBlock->getTerminator();
1373 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1374 OldBr->eraseFromParent();
1375 IfBlock = NewIfBlock;
1376 }
1377 CI->eraseFromParent();
1378}
1379
Elena Demikhovsky09285852015-10-25 15:37:55 +00001380// Translate a masked gather intrinsic like
1381// <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
1382// <16 x i1> %Mask, <16 x i32> %Src)
1383// to a chain of basic blocks, with loading element one-by-one if
1384// the appropriate mask bit is set
Junmo Parkaa9243a2016-01-08 04:20:32 +00001385//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001386// % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
1387// % Mask0 = extractelement <16 x i1> %Mask, i32 0
1388// % ToLoad0 = icmp eq i1 % Mask0, true
1389// br i1 % ToLoad0, label %cond.load, label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001390//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001391// cond.load:
1392// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1393// % Load0 = load i32, i32* % Ptr0, align 4
1394// % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
1395// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001396//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001397// else:
1398// %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
1399// % Mask1 = extractelement <16 x i1> %Mask, i32 1
1400// % ToLoad1 = icmp eq i1 % Mask1, true
1401// br i1 % ToLoad1, label %cond.load1, label %else2
Junmo Parkaa9243a2016-01-08 04:20:32 +00001402//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001403// cond.load1:
1404// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1405// % Load1 = load i32, i32* % Ptr1, align 4
1406// % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
1407// br label %else2
1408// . . .
1409// % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
1410// ret <16 x i32> %Result
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001411static void scalarizeMaskedGather(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001412 Value *Ptrs = CI->getArgOperand(0);
1413 Value *Alignment = CI->getArgOperand(1);
1414 Value *Mask = CI->getArgOperand(2);
1415 Value *Src0 = CI->getArgOperand(3);
1416
1417 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1418
1419 assert(VecType && "Unexpected return type of masked load intrinsic");
1420
1421 IRBuilder<> Builder(CI->getContext());
1422 Instruction *InsertPt = CI;
1423 BasicBlock *IfBlock = CI->getParent();
1424 BasicBlock *CondBlock = nullptr;
1425 BasicBlock *PrevIfBlock = CI->getParent();
1426 Builder.SetInsertPoint(InsertPt);
1427 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1428
1429 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1430
1431 Value *UndefVal = UndefValue::get(VecType);
1432
1433 // The result vector
1434 Value *VResult = UndefVal;
1435 unsigned VectorWidth = VecType->getNumElements();
1436
1437 // Shorten the way if the mask is a vector of constants.
1438 bool IsConstMask = isa<ConstantVector>(Mask);
1439
1440 if (IsConstMask) {
1441 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1442 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1443 continue;
1444 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1445 "Ptr" + Twine(Idx));
1446 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1447 "Load" + Twine(Idx));
1448 VResult = Builder.CreateInsertElement(VResult, Load,
1449 Builder.getInt32(Idx),
1450 "Res" + Twine(Idx));
1451 }
1452 Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
1453 CI->replaceAllUsesWith(NewI);
1454 CI->eraseFromParent();
1455 return;
1456 }
1457
1458 PHINode *Phi = nullptr;
1459 Value *PrevPhi = UndefVal;
1460
1461 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1462
1463 // Fill the "else" block, created in the previous iteration
1464 //
1465 // %Mask1 = extractelement <16 x i1> %Mask, i32 1
1466 // %ToLoad1 = icmp eq i1 %Mask1, true
1467 // br i1 %ToLoad1, label %cond.load, label %else
1468 //
1469 if (Idx > 0) {
1470 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1471 Phi->addIncoming(VResult, CondBlock);
1472 Phi->addIncoming(PrevPhi, PrevIfBlock);
1473 PrevPhi = Phi;
1474 VResult = Phi;
1475 }
1476
1477 Value *Predicate = Builder.CreateExtractElement(Mask,
1478 Builder.getInt32(Idx),
1479 "Mask" + Twine(Idx));
1480 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1481 ConstantInt::get(Predicate->getType(), 1),
1482 "ToLoad" + Twine(Idx));
1483
1484 // Create "cond" block
1485 //
1486 // %EltAddr = getelementptr i32* %1, i32 0
1487 // %Elt = load i32* %EltAddr
1488 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1489 //
1490 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1491 Builder.SetInsertPoint(InsertPt);
1492
1493 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1494 "Ptr" + Twine(Idx));
1495 LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
1496 "Load" + Twine(Idx));
1497 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
1498 "Res" + Twine(Idx));
1499
1500 // Create "else" block, fill it in the next iteration
1501 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1502 Builder.SetInsertPoint(InsertPt);
1503 Instruction *OldBr = IfBlock->getTerminator();
1504 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1505 OldBr->eraseFromParent();
1506 PrevIfBlock = IfBlock;
1507 IfBlock = NewIfBlock;
1508 }
1509
1510 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1511 Phi->addIncoming(VResult, CondBlock);
1512 Phi->addIncoming(PrevPhi, PrevIfBlock);
1513 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1514 CI->replaceAllUsesWith(NewI);
1515 CI->eraseFromParent();
1516}
1517
1518// Translate a masked scatter intrinsic, like
1519// void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
1520// <16 x i1> %Mask)
1521// to a chain of basic blocks, that stores element one-by-one if
1522// the appropriate mask bit is set.
1523//
1524// % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
1525// % Mask0 = extractelement <16 x i1> % Mask, i32 0
1526// % ToStore0 = icmp eq i1 % Mask0, true
1527// br i1 %ToStore0, label %cond.store, label %else
1528//
1529// cond.store:
1530// % Elt0 = extractelement <16 x i32> %Src, i32 0
1531// % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
1532// store i32 %Elt0, i32* % Ptr0, align 4
1533// br label %else
Junmo Parkaa9243a2016-01-08 04:20:32 +00001534//
Elena Demikhovsky09285852015-10-25 15:37:55 +00001535// else:
1536// % Mask1 = extractelement <16 x i1> % Mask, i32 1
1537// % ToStore1 = icmp eq i1 % Mask1, true
1538// br i1 % ToStore1, label %cond.store1, label %else2
1539//
1540// cond.store1:
1541// % Elt1 = extractelement <16 x i32> %Src, i32 1
1542// % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1543// store i32 % Elt1, i32* % Ptr1, align 4
1544// br label %else2
1545// . . .
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001546static void scalarizeMaskedScatter(CallInst *CI) {
Elena Demikhovsky09285852015-10-25 15:37:55 +00001547 Value *Src = CI->getArgOperand(0);
1548 Value *Ptrs = CI->getArgOperand(1);
1549 Value *Alignment = CI->getArgOperand(2);
1550 Value *Mask = CI->getArgOperand(3);
1551
1552 assert(isa<VectorType>(Src->getType()) &&
1553 "Unexpected data type in masked scatter intrinsic");
1554 assert(isa<VectorType>(Ptrs->getType()) &&
1555 isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
1556 "Vector of pointers is expected in masked scatter intrinsic");
1557
1558 IRBuilder<> Builder(CI->getContext());
1559 Instruction *InsertPt = CI;
1560 BasicBlock *IfBlock = CI->getParent();
1561 Builder.SetInsertPoint(InsertPt);
1562 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1563
1564 unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
1565 unsigned VectorWidth = Src->getType()->getVectorNumElements();
1566
1567 // Shorten the way if the mask is a vector of constants.
1568 bool IsConstMask = isa<ConstantVector>(Mask);
1569
1570 if (IsConstMask) {
1571 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1572 if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
1573 continue;
1574 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1575 "Elt" + Twine(Idx));
1576 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1577 "Ptr" + Twine(Idx));
1578 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1579 }
1580 CI->eraseFromParent();
1581 return;
1582 }
1583 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1584 // Fill the "else" block, created in the previous iteration
1585 //
1586 // % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
1587 // % ToStore = icmp eq i1 % Mask1, true
1588 // br i1 % ToStore, label %cond.store, label %else
1589 //
1590 Value *Predicate = Builder.CreateExtractElement(Mask,
1591 Builder.getInt32(Idx),
1592 "Mask" + Twine(Idx));
1593 Value *Cmp =
1594 Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1595 ConstantInt::get(Predicate->getType(), 1),
1596 "ToStore" + Twine(Idx));
1597
1598 // Create "cond" block
1599 //
1600 // % Elt1 = extractelement <16 x i32> %Src, i32 1
1601 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
1602 // %store i32 % Elt1, i32* % Ptr1
1603 //
1604 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1605 Builder.SetInsertPoint(InsertPt);
1606
1607 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
1608 "Elt" + Twine(Idx));
1609 Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
1610 "Ptr" + Twine(Idx));
1611 Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
1612
1613 // Create "else" block, fill it in the next iteration
1614 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1615 Builder.SetInsertPoint(InsertPt);
1616 Instruction *OldBr = IfBlock->getTerminator();
1617 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1618 OldBr->eraseFromParent();
1619 IfBlock = NewIfBlock;
1620 }
1621 CI->eraseFromParent();
1622}
1623
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001624/// If counting leading or trailing zeros is an expensive operation and a zero
1625/// input is defined, add a check for zero to avoid calling the intrinsic.
1626///
1627/// We want to transform:
1628/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
1629///
1630/// into:
1631/// entry:
1632/// %cmpz = icmp eq i64 %A, 0
1633/// br i1 %cmpz, label %cond.end, label %cond.false
1634/// cond.false:
1635/// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
1636/// br label %cond.end
1637/// cond.end:
1638/// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
1639///
1640/// If the transform is performed, return true and set ModifiedDT to true.
1641static bool despeculateCountZeros(IntrinsicInst *CountZeros,
1642 const TargetLowering *TLI,
1643 const DataLayout *DL,
1644 bool &ModifiedDT) {
1645 if (!TLI || !DL)
1646 return false;
1647
1648 // If a zero input is undefined, it doesn't make sense to despeculate that.
1649 if (match(CountZeros->getOperand(1), m_One()))
1650 return false;
1651
1652 // If it's cheap to speculate, there's nothing to do.
1653 auto IntrinsicID = CountZeros->getIntrinsicID();
1654 if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
1655 (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
1656 return false;
1657
1658 // Only handle legal scalar cases. Anything else requires too much work.
1659 Type *Ty = CountZeros->getType();
1660 unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
1661 if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
1662 return false;
1663
1664 // The intrinsic will be sunk behind a compare against zero and branch.
1665 BasicBlock *StartBlock = CountZeros->getParent();
1666 BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
1667
1668 // Create another block after the count zero intrinsic. A PHI will be added
1669 // in this block to select the result of the intrinsic or the bit-width
1670 // constant if the input to the intrinsic is zero.
1671 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
1672 BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
1673
1674 // Set up a builder to create a compare, conditional branch, and PHI.
1675 IRBuilder<> Builder(CountZeros->getContext());
1676 Builder.SetInsertPoint(StartBlock->getTerminator());
1677 Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
1678
1679 // Replace the unconditional branch that was created by the first split with
1680 // a compare against zero and a conditional branch.
1681 Value *Zero = Constant::getNullValue(Ty);
1682 Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
1683 Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
1684 StartBlock->getTerminator()->eraseFromParent();
1685
1686 // Create a PHI in the end block to select either the output of the intrinsic
1687 // or the bit width of the operand.
1688 Builder.SetInsertPoint(&EndBlock->front());
1689 PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
1690 CountZeros->replaceAllUsesWith(PN);
1691 Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
1692 PN->addIncoming(BitWidth, StartBlock);
1693 PN->addIncoming(CountZeros, CallBlock);
1694
1695 // We are explicitly handling the zero case, so we can set the intrinsic's
1696 // undefined zero argument to 'true'. This will also prevent reprocessing the
1697 // intrinsic; we only despeculate when a zero input is defined.
1698 CountZeros->setArgOperand(1, Builder.getTrue());
1699 ModifiedDT = true;
1700 return true;
1701}
1702
Sanjay Patelfc580a62015-09-21 23:03:16 +00001703bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001704 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001705
Chris Lattner7a277142011-01-15 07:14:54 +00001706 // Lower inline assembly if we can.
1707 // If we found an inline asm expession, and if the target knows how to
1708 // lower it to normal LLVM code, do so now.
1709 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1710 if (TLI->ExpandInlineAsm(CI)) {
1711 // Avoid invalidating the iterator.
1712 CurInstIterator = BB->begin();
1713 // Avoid processing instructions out of order, which could cause
1714 // reuse before a value is defined.
1715 SunkAddrs.clear();
1716 return true;
1717 }
1718 // Sink address computing for memory operands into the block.
Sanjay Patelfc580a62015-09-21 23:03:16 +00001719 if (optimizeInlineAsmInst(CI))
Chris Lattner7a277142011-01-15 07:14:54 +00001720 return true;
1721 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001722
John Brawn0dbcd652015-03-18 12:01:59 +00001723 // Align the pointer arguments to this call if the target thinks it's a good
1724 // idea
1725 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001726 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001727 for (auto &Arg : CI->arg_operands()) {
1728 // We want to align both objects whose address is used directly and
1729 // objects whose address is used in casts and GEPs, though it only makes
1730 // sense for GEPs if the offset is a multiple of the desired alignment and
1731 // if size - offset meets the size threshold.
1732 if (!Arg->getType()->isPointerTy())
1733 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001734 APInt Offset(DL->getPointerSizeInBits(
1735 cast<PointerType>(Arg->getType())->getAddressSpace()),
1736 0);
1737 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001738 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001739 if ((Offset2 & (PrefAlign-1)) != 0)
1740 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001741 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001742 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1743 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001744 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001745 // Global variables can only be aligned if they are defined in this
1746 // object (i.e. they are uniquely initialized in this object), and
1747 // over-aligning global variables that have an explicit section is
1748 // forbidden.
1749 GlobalVariable *GV;
James Y Knightac03dca2016-01-15 16:33:06 +00001750 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
1751 GV->getAlignment() < PrefAlign &&
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00001752 DL->getTypeAllocSize(GV->getValueType()) >=
Mehdi Amini4fe37982015-07-07 18:45:17 +00001753 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001754 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001755 }
1756 // If this is a memcpy (or similar) then we may be able to improve the
1757 // alignment
1758 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001759 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001760 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001761 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
Pete Cooper67cf9a72015-11-19 05:56:52 +00001762 if (Align > MI->getAlignment())
1763 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
John Brawn0dbcd652015-03-18 12:01:59 +00001764 }
1765 }
1766
Philip Reamesac115ed2016-03-09 23:13:12 +00001767 // If we have a cold call site, try to sink addressing computation into the
1768 // cold block. This interacts with our handling for loads and stores to
1769 // ensure that we can fold all uses of a potential addressing computation
1770 // into their uses. TODO: generalize this to work over profiling data
1771 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
1772 for (auto &Arg : CI->arg_operands()) {
1773 if (!Arg->getType()->isPointerTy())
1774 continue;
1775 unsigned AS = Arg->getType()->getPointerAddressSpace();
1776 return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
1777 }
Junmo Park6098cbb2016-03-11 07:05:32 +00001778
Eric Christopher4b7948e2010-03-11 02:41:03 +00001779 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001780 if (II) {
1781 switch (II->getIntrinsicID()) {
1782 default: break;
1783 case Intrinsic::objectsize: {
1784 // Lower all uses of llvm.objectsize.*
1785 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1786 Type *ReturnTy = CI->getType();
1787 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001788
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001789 // Substituting this can cause recursive simplifications, which can
1790 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1791 // happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001792 Value *CurValue = &*CurInstIterator;
1793 WeakVH IterHandle(CurValue);
Nadav Rotem465834c2012-07-24 10:51:42 +00001794
Sanjay Patel545a4562016-01-20 18:59:16 +00001795 replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001796
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001797 // If the iterator instruction was recursively deleted, start over at the
1798 // start of the block.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00001799 if (IterHandle != CurValue) {
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001800 CurInstIterator = BB->begin();
1801 SunkAddrs.clear();
1802 }
1803 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001804 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001805 case Intrinsic::masked_load: {
1806 // Scalarize unsupported vector masked load
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001807 if (!TTI->isLegalMaskedLoad(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001808 scalarizeMaskedLoad(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001809 ModifiedDT = true;
1810 return true;
1811 }
1812 return false;
1813 }
1814 case Intrinsic::masked_store: {
Elena Demikhovsky20662e32015-10-19 07:43:38 +00001815 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001816 scalarizeMaskedStore(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001817 ModifiedDT = true;
1818 return true;
1819 }
1820 return false;
1821 }
Elena Demikhovsky09285852015-10-25 15:37:55 +00001822 case Intrinsic::masked_gather: {
1823 if (!TTI->isLegalMaskedGather(CI->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001824 scalarizeMaskedGather(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001825 ModifiedDT = true;
1826 return true;
1827 }
1828 return false;
1829 }
1830 case Intrinsic::masked_scatter: {
1831 if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
Sanjay Patel3388d1f2016-01-22 21:11:47 +00001832 scalarizeMaskedScatter(CI);
Elena Demikhovsky09285852015-10-25 15:37:55 +00001833 ModifiedDT = true;
1834 return true;
1835 }
1836 return false;
1837 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001838 case Intrinsic::aarch64_stlxr:
1839 case Intrinsic::aarch64_stxr: {
1840 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1841 if (!ExtVal || !ExtVal->hasOneUse() ||
1842 ExtVal->getParent() == CI->getParent())
1843 return false;
1844 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1845 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001846 // Mark this instruction as "inserted by CGP", so that other
1847 // optimizations don't touch it.
1848 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001849 return true;
1850 }
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00001851 case Intrinsic::invariant_group_barrier:
1852 II->replaceAllUsesWith(II->getArgOperand(0));
1853 II->eraseFromParent();
1854 return true;
Sanjay Patel4699b8a2015-11-19 16:37:10 +00001855
1856 case Intrinsic::cttz:
1857 case Intrinsic::ctlz:
1858 // If counting zeros is expensive, try to avoid it.
1859 return despeculateCountZeros(II, TLI, DL, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001860 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001861
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001862 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001863 // Unknown address space.
1864 // TODO: Target hook to pick which address space the intrinsic cares
1865 // about?
1866 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001867 SmallVector<Value*, 2> PtrOps;
1868 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001869 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001870 while (!PtrOps.empty())
Sanjay Patelfc580a62015-09-21 23:03:16 +00001871 if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001872 return true;
1873 }
Pete Cooper615fd892012-03-13 20:59:56 +00001874 }
1875
Eric Christopher4b7948e2010-03-11 02:41:03 +00001876 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001877 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001878
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001879 // Lower all default uses of _chk calls. This is very similar
1880 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001881 // to fortified library functions (e.g. __memcpy_chk) that have the default
1882 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001883 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001884 if (Value *V = Simplifier.optimizeCall(CI)) {
1885 CI->replaceAllUsesWith(V);
1886 CI->eraseFromParent();
1887 return true;
1888 }
1889 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001890}
Chris Lattner1b93be52011-01-15 07:25:29 +00001891
Sanjay Patel4ac6b112015-09-21 22:47:23 +00001892/// Look for opportunities to duplicate return instructions to the predecessor
1893/// to enable tail call optimizations. The case it is currently looking for is:
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/// br label %return
1898/// bb1:
1899/// %tmp1 = tail call i32 @f1()
1900/// br label %return
1901/// bb2:
1902/// %tmp2 = tail call i32 @f2()
1903/// br label %return
1904/// return:
1905/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1906/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001907/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001908///
1909/// =>
1910///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001911/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001912/// bb0:
1913/// %tmp0 = tail call i32 @f0()
1914/// ret i32 %tmp0
1915/// bb1:
1916/// %tmp1 = tail call i32 @f1()
1917/// ret i32 %tmp1
1918/// bb2:
1919/// %tmp2 = tail call i32 @f2()
1920/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001921/// @endcode
Sanjay Patelfc580a62015-09-21 23:03:16 +00001922bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001923 if (!TLI)
1924 return false;
1925
Benjamin Kramer455fa352012-11-23 19:17:06 +00001926 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1927 if (!RI)
1928 return false;
1929
Craig Topperc0196b12014-04-14 00:51:57 +00001930 PHINode *PN = nullptr;
1931 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001932 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001933 if (V) {
1934 BCI = dyn_cast<BitCastInst>(V);
1935 if (BCI)
1936 V = BCI->getOperand(0);
1937
1938 PN = dyn_cast<PHINode>(V);
1939 if (!PN)
1940 return false;
1941 }
Evan Cheng0663f232011-03-21 01:19:09 +00001942
Cameron Zwarich4649f172011-03-24 04:52:10 +00001943 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001944 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001945
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001946 // It's not safe to eliminate the sign / zero extension of the return value.
1947 // See llvm::isInTailCallPosition().
1948 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001949 AttributeSet CallerAttrs = F->getAttributes();
1950 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1951 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001952 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001953
Cameron Zwarich4649f172011-03-24 04:52:10 +00001954 // Make sure there are no instructions between the PHI and return, or that the
1955 // return is the first instruction in the block.
1956 if (PN) {
1957 BasicBlock::iterator BI = BB->begin();
1958 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001959 if (&*BI == BCI)
1960 // Also skip over the bitcast.
1961 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001962 if (&*BI != RI)
1963 return false;
1964 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001965 BasicBlock::iterator BI = BB->begin();
1966 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1967 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001968 return false;
1969 }
Evan Cheng0663f232011-03-21 01:19:09 +00001970
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001971 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1972 /// call.
1973 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001974 if (PN) {
1975 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1976 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1977 // Make sure the phi value is indeed produced by the tail call.
1978 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1979 TLI->mayBeEmittedAsTailCall(CI))
1980 TailCalls.push_back(CI);
1981 }
1982 } else {
1983 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001984 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001985 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001986 continue;
1987
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001988 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001989 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1990 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001991 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1992 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001993 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001994
Cameron Zwarich4649f172011-03-24 04:52:10 +00001995 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001996 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001997 TailCalls.push_back(CI);
1998 }
Evan Cheng0663f232011-03-21 01:19:09 +00001999 }
2000
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002001 bool Changed = false;
2002 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
2003 CallInst *CI = TailCalls[i];
2004 CallSite CS(CI);
2005
2006 // Conservatively require the attributes of the call to match those of the
2007 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00002008 AttributeSet CalleeAttrs = CS.getAttributes();
2009 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002010 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00002011 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00002012 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002013 continue;
2014
2015 // Make sure the call instruction is followed by an unconditional branch to
2016 // the return block.
2017 BasicBlock *CallBB = CI->getParent();
2018 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
2019 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
2020 continue;
2021
2022 // Duplicate the return into CallBB.
2023 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00002024 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002025 ++NumRetsDup;
2026 }
2027
2028 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00002029 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00002030 BB->eraseFromParent();
2031
2032 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00002033}
2034
Chris Lattner728f9022008-11-25 07:09:13 +00002035//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00002036// Memory Optimization
2037//===----------------------------------------------------------------------===//
2038
Chandler Carruthc8925912013-01-05 02:09:22 +00002039namespace {
2040
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002041/// This is an extended version of TargetLowering::AddrMode
Chandler Carruthc8925912013-01-05 02:09:22 +00002042/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00002043struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00002044 Value *BaseReg;
2045 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002046 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00002047 void print(raw_ostream &OS) const;
2048 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00002049
Chandler Carruthc8925912013-01-05 02:09:22 +00002050 bool operator==(const ExtAddrMode& O) const {
2051 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
2052 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
2053 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
2054 }
2055};
2056
Eli Friedmanc1f1f852013-09-10 23:09:24 +00002057#ifndef NDEBUG
2058static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
2059 AM.print(OS);
2060 return OS;
2061}
2062#endif
2063
Chandler Carruthc8925912013-01-05 02:09:22 +00002064void ExtAddrMode::print(raw_ostream &OS) const {
2065 bool NeedPlus = false;
2066 OS << "[";
2067 if (BaseGV) {
2068 OS << (NeedPlus ? " + " : "")
2069 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002070 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002071 NeedPlus = true;
2072 }
2073
Richard Trieuc0f91212014-05-30 03:15:17 +00002074 if (BaseOffs) {
2075 OS << (NeedPlus ? " + " : "")
2076 << BaseOffs;
2077 NeedPlus = true;
2078 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002079
2080 if (BaseReg) {
2081 OS << (NeedPlus ? " + " : "")
2082 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002083 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002084 NeedPlus = true;
2085 }
2086 if (Scale) {
2087 OS << (NeedPlus ? " + " : "")
2088 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00002089 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00002090 }
2091
2092 OS << ']';
2093}
2094
2095#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Yaron Kereneb2a2542016-01-29 20:50:44 +00002096LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
Chandler Carruthc8925912013-01-05 02:09:22 +00002097 print(dbgs());
2098 dbgs() << '\n';
2099}
2100#endif
2101
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002102/// \brief This class provides transaction based operation on the IR.
2103/// Every change made through this class is recorded in the internal state and
2104/// can be undone (rollback) until commit is called.
2105class TypePromotionTransaction {
2106
2107 /// \brief This represents the common interface of the individual transaction.
2108 /// Each class implements the logic for doing one specific modification on
2109 /// the IR via the TypePromotionTransaction.
2110 class TypePromotionAction {
2111 protected:
2112 /// The Instruction modified.
2113 Instruction *Inst;
2114
2115 public:
2116 /// \brief Constructor of the action.
2117 /// The constructor performs the related action on the IR.
2118 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
2119
2120 virtual ~TypePromotionAction() {}
2121
2122 /// \brief Undo the modification done by this action.
2123 /// When this method is called, the IR must be in the same state as it was
2124 /// before this action was applied.
2125 /// \pre Undoing the action works if and only if the IR is in the exact same
2126 /// state as it was directly after this action was applied.
2127 virtual void undo() = 0;
2128
2129 /// \brief Advocate every change made by this action.
2130 /// When the results on the IR of the action are to be kept, it is important
2131 /// to call this function, otherwise hidden information may be kept forever.
2132 virtual void commit() {
2133 // Nothing to be done, this action is not doing anything.
2134 }
2135 };
2136
2137 /// \brief Utility to remember the position of an instruction.
2138 class InsertionHandler {
2139 /// Position of an instruction.
2140 /// Either an instruction:
2141 /// - Is the first in a basic block: BB is used.
2142 /// - Has a previous instructon: PrevInst is used.
2143 union {
2144 Instruction *PrevInst;
2145 BasicBlock *BB;
2146 } Point;
2147 /// Remember whether or not the instruction had a previous instruction.
2148 bool HasPrevInstruction;
2149
2150 public:
2151 /// \brief Record the position of \p Inst.
2152 InsertionHandler(Instruction *Inst) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002153 BasicBlock::iterator It = Inst->getIterator();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002154 HasPrevInstruction = (It != (Inst->getParent()->begin()));
2155 if (HasPrevInstruction)
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002156 Point.PrevInst = &*--It;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002157 else
2158 Point.BB = Inst->getParent();
2159 }
2160
2161 /// \brief Insert \p Inst at the recorded position.
2162 void insert(Instruction *Inst) {
2163 if (HasPrevInstruction) {
2164 if (Inst->getParent())
2165 Inst->removeFromParent();
2166 Inst->insertAfter(Point.PrevInst);
2167 } else {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00002168 Instruction *Position = &*Point.BB->getFirstInsertionPt();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002169 if (Inst->getParent())
2170 Inst->moveBefore(Position);
2171 else
2172 Inst->insertBefore(Position);
2173 }
2174 }
2175 };
2176
2177 /// \brief Move an instruction before another.
2178 class InstructionMoveBefore : public TypePromotionAction {
2179 /// Original position of the instruction.
2180 InsertionHandler Position;
2181
2182 public:
2183 /// \brief Move \p Inst before \p Before.
2184 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
2185 : TypePromotionAction(Inst), Position(Inst) {
2186 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
2187 Inst->moveBefore(Before);
2188 }
2189
2190 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00002191 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002192 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
2193 Position.insert(Inst);
2194 }
2195 };
2196
2197 /// \brief Set the operand of an instruction with a new value.
2198 class OperandSetter : public TypePromotionAction {
2199 /// Original operand of the instruction.
2200 Value *Origin;
2201 /// Index of the modified instruction.
2202 unsigned Idx;
2203
2204 public:
2205 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
2206 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
2207 : TypePromotionAction(Inst), Idx(Idx) {
2208 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
2209 << "for:" << *Inst << "\n"
2210 << "with:" << *NewVal << "\n");
2211 Origin = Inst->getOperand(Idx);
2212 Inst->setOperand(Idx, NewVal);
2213 }
2214
2215 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002216 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002217 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
2218 << "for: " << *Inst << "\n"
2219 << "with: " << *Origin << "\n");
2220 Inst->setOperand(Idx, Origin);
2221 }
2222 };
2223
2224 /// \brief Hide the operands of an instruction.
2225 /// Do as if this instruction was not using any of its operands.
2226 class OperandsHider : public TypePromotionAction {
2227 /// The list of original operands.
2228 SmallVector<Value *, 4> OriginalValues;
2229
2230 public:
2231 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
2232 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
2233 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
2234 unsigned NumOpnds = Inst->getNumOperands();
2235 OriginalValues.reserve(NumOpnds);
2236 for (unsigned It = 0; It < NumOpnds; ++It) {
2237 // Save the current operand.
2238 Value *Val = Inst->getOperand(It);
2239 OriginalValues.push_back(Val);
2240 // Set a dummy one.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002241 // We could use OperandSetter here, but that would imply an overhead
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002242 // that we are not willing to pay.
2243 Inst->setOperand(It, UndefValue::get(Val->getType()));
2244 }
2245 }
2246
2247 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00002248 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002249 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
2250 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
2251 Inst->setOperand(It, OriginalValues[It]);
2252 }
2253 };
2254
2255 /// \brief Build a truncate instruction.
2256 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002257 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002258 public:
2259 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
2260 /// result.
2261 /// trunc Opnd to Ty.
2262 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
2263 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002264 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
2265 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002266 }
2267
Quentin Colombetac55b152014-09-16 22:36:07 +00002268 /// \brief Get the built value.
2269 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002270
2271 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002272 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002273 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
2274 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2275 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002276 }
2277 };
2278
2279 /// \brief Build a sign extension instruction.
2280 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002281 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002282 public:
2283 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
2284 /// result.
2285 /// sext Opnd to Ty.
2286 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002287 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002288 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002289 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
2290 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002291 }
2292
Quentin Colombetac55b152014-09-16 22:36:07 +00002293 /// \brief Get the built value.
2294 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002295
2296 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002297 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002298 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
2299 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2300 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002301 }
2302 };
2303
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002304 /// \brief Build a zero extension instruction.
2305 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00002306 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002307 public:
2308 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
2309 /// result.
2310 /// zext Opnd to Ty.
2311 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00002312 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002313 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002314 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
2315 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002316 }
2317
Quentin Colombetac55b152014-09-16 22:36:07 +00002318 /// \brief Get the built value.
2319 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002320
2321 /// \brief Remove the built instruction.
2322 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00002323 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
2324 if (Instruction *IVal = dyn_cast<Instruction>(Val))
2325 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002326 }
2327 };
2328
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002329 /// \brief Mutate an instruction to another type.
2330 class TypeMutator : public TypePromotionAction {
2331 /// Record the original type.
2332 Type *OrigTy;
2333
2334 public:
2335 /// \brief Mutate the type of \p Inst into \p NewTy.
2336 TypeMutator(Instruction *Inst, Type *NewTy)
2337 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
2338 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
2339 << "\n");
2340 Inst->mutateType(NewTy);
2341 }
2342
2343 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00002344 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002345 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
2346 << "\n");
2347 Inst->mutateType(OrigTy);
2348 }
2349 };
2350
2351 /// \brief Replace the uses of an instruction by another instruction.
2352 class UsesReplacer : public TypePromotionAction {
2353 /// Helper structure to keep track of the replaced uses.
2354 struct InstructionAndIdx {
2355 /// The instruction using the instruction.
2356 Instruction *Inst;
2357 /// The index where this instruction is used for Inst.
2358 unsigned Idx;
2359 InstructionAndIdx(Instruction *Inst, unsigned Idx)
2360 : Inst(Inst), Idx(Idx) {}
2361 };
2362
2363 /// Keep track of the original uses (pair Instruction, Index).
2364 SmallVector<InstructionAndIdx, 4> OriginalUses;
2365 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
2366
2367 public:
2368 /// \brief Replace all the use of \p Inst by \p New.
2369 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
2370 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
2371 << "\n");
2372 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002373 for (Use &U : Inst->uses()) {
2374 Instruction *UserI = cast<Instruction>(U.getUser());
2375 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002376 }
2377 // Now, we can replace the uses.
2378 Inst->replaceAllUsesWith(New);
2379 }
2380
2381 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00002382 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002383 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
2384 for (use_iterator UseIt = OriginalUses.begin(),
2385 EndIt = OriginalUses.end();
2386 UseIt != EndIt; ++UseIt) {
2387 UseIt->Inst->setOperand(UseIt->Idx, Inst);
2388 }
2389 }
2390 };
2391
2392 /// \brief Remove an instruction from the IR.
2393 class InstructionRemover : public TypePromotionAction {
2394 /// Original position of the instruction.
2395 InsertionHandler Inserter;
2396 /// Helper structure to hide all the link to the instruction. In other
2397 /// words, this helps to do as if the instruction was removed.
2398 OperandsHider Hider;
2399 /// Keep track of the uses replaced, if any.
2400 UsesReplacer *Replacer;
2401
2402 public:
2403 /// \brief Remove all reference of \p Inst and optinally replace all its
2404 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00002405 /// \pre If !Inst->use_empty(), then New != nullptr
2406 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002407 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00002408 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002409 if (New)
2410 Replacer = new UsesReplacer(Inst, New);
2411 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
2412 Inst->removeFromParent();
2413 }
2414
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00002415 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002416
2417 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00002418 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002419
2420 /// \brief Resurrect the instruction and reassign it to the proper uses if
2421 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00002422 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002423 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
2424 Inserter.insert(Inst);
2425 if (Replacer)
2426 Replacer->undo();
2427 Hider.undo();
2428 }
2429 };
2430
2431public:
2432 /// Restoration point.
2433 /// The restoration point is a pointer to an action instead of an iterator
2434 /// because the iterator may be invalidated but not the pointer.
2435 typedef const TypePromotionAction *ConstRestorationPt;
2436 /// Advocate every changes made in that transaction.
2437 void commit();
2438 /// Undo all the changes made after the given point.
2439 void rollback(ConstRestorationPt Point);
2440 /// Get the current restoration point.
2441 ConstRestorationPt getRestorationPoint() const;
2442
2443 /// \name API for IR modification with state keeping to support rollback.
2444 /// @{
2445 /// Same as Instruction::setOperand.
2446 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2447 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002448 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002449 /// Same as Value::replaceAllUsesWith.
2450 void replaceAllUsesWith(Instruction *Inst, Value *New);
2451 /// Same as Value::mutateType.
2452 void mutateType(Instruction *Inst, Type *NewTy);
2453 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002454 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002455 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002456 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002457 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002458 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002459 /// Same as Instruction::moveBefore.
2460 void moveBefore(Instruction *Inst, Instruction *Before);
2461 /// @}
2462
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002463private:
2464 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002465 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2466 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002467};
2468
2469void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2470 Value *NewVal) {
2471 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002472 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002473}
2474
2475void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2476 Value *NewVal) {
2477 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002478 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002479}
2480
2481void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2482 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002483 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002484}
2485
2486void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002487 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002488}
2489
Quentin Colombetac55b152014-09-16 22:36:07 +00002490Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2491 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002492 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002493 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002494 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002495 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002496}
2497
Quentin Colombetac55b152014-09-16 22:36:07 +00002498Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2499 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002500 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002501 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002502 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002503 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002504}
2505
Quentin Colombetac55b152014-09-16 22:36:07 +00002506Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2507 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002508 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002509 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002510 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002511 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002512}
2513
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002514void TypePromotionTransaction::moveBefore(Instruction *Inst,
2515 Instruction *Before) {
2516 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002517 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002518}
2519
2520TypePromotionTransaction::ConstRestorationPt
2521TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002522 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002523}
2524
2525void TypePromotionTransaction::commit() {
2526 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002527 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002528 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002529 Actions.clear();
2530}
2531
2532void TypePromotionTransaction::rollback(
2533 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002534 while (!Actions.empty() && Point != Actions.back().get()) {
2535 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002536 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002537 }
2538}
2539
Chandler Carruthc8925912013-01-05 02:09:22 +00002540/// \brief A helper class for matching addressing modes.
2541///
2542/// This encapsulates the logic for matching the target-legal addressing modes.
2543class AddressingModeMatcher {
2544 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002545 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002546 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002547 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002548
2549 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2550 /// the memory instruction that we're computing this address for.
2551 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002552 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002553 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002554
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002555 /// This is the addressing mode that we're building up. This is
Chandler Carruthc8925912013-01-05 02:09:22 +00002556 /// part of the return value of this addressing mode matching stuff.
2557 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002558
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002559 /// The instructions inserted by other CodeGenPrepare optimizations.
2560 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002561 /// A map from the instructions to their type before promotion.
2562 InstrToOrigTy &PromotedInsts;
2563 /// The ongoing transaction where every action should be registered.
2564 TypePromotionTransaction &TPT;
2565
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002566 /// This is set to true when we should not do profitability checks.
2567 /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
Chandler Carruthc8925912013-01-05 02:09:22 +00002568 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002569
Eric Christopherd75c00c2015-02-26 22:38:34 +00002570 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002571 const TargetMachine &TM, Type *AT, unsigned AS,
2572 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002573 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002574 InstrToOrigTy &PromotedInsts,
2575 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002576 : AddrModeInsts(AMI), TM(TM),
2577 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2578 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002579 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2580 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2581 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002582 IgnoreProfitability = false;
2583 }
2584public:
Stephen Lin837bba12013-07-15 17:55:02 +00002585
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002586 /// Find the maximal addressing mode that a load/store of V can fold,
Chandler Carruthc8925912013-01-05 02:09:22 +00002587 /// give an access type of AccessTy. This returns a list of involved
2588 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002589 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002590 /// optimizations.
2591 /// \p PromotedInsts maps the instructions to their type before promotion.
2592 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002593 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002594 Instruction *MemoryInst,
2595 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002596 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002597 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002598 InstrToOrigTy &PromotedInsts,
2599 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002600 ExtAddrMode Result;
2601
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002602 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002603 MemoryInst, Result, InsertedInsts,
Sanjay Patelfc580a62015-09-21 23:03:16 +00002604 PromotedInsts, TPT).matchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002605 (void)Success; assert(Success && "Couldn't select *anything*?");
2606 return Result;
2607 }
2608private:
Sanjay Patelfc580a62015-09-21 23:03:16 +00002609 bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2610 bool matchAddr(Value *V, unsigned Depth);
2611 bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002612 bool *MovedAway = nullptr);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002613 bool isProfitableToFoldIntoAddressingMode(Instruction *I,
Chandler Carruthc8925912013-01-05 02:09:22 +00002614 ExtAddrMode &AMBefore,
2615 ExtAddrMode &AMAfter);
Sanjay Patelfc580a62015-09-21 23:03:16 +00002616 bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
2617 bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002618 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002619};
2620
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002621/// Try adding ScaleReg*Scale to the current addressing mode.
Chandler Carruthc8925912013-01-05 02:09:22 +00002622/// Return true and update AddrMode if this addr mode is legal for the target,
2623/// false if not.
Sanjay Patelfc580a62015-09-21 23:03:16 +00002624bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
Chandler Carruthc8925912013-01-05 02:09:22 +00002625 unsigned Depth) {
2626 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2627 // mode. Just process that directly.
2628 if (Scale == 1)
Sanjay Patelfc580a62015-09-21 23:03:16 +00002629 return matchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002630
Chandler Carruthc8925912013-01-05 02:09:22 +00002631 // If the scale is 0, it takes nothing to add this.
2632 if (Scale == 0)
2633 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002634
Chandler Carruthc8925912013-01-05 02:09:22 +00002635 // If we already have a scale of this value, we can add to it, otherwise, we
2636 // need an available scale field.
2637 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2638 return false;
2639
2640 ExtAddrMode TestAddrMode = AddrMode;
2641
2642 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2643 // [A+B + A*7] -> [B+A*8].
2644 TestAddrMode.Scale += Scale;
2645 TestAddrMode.ScaledReg = ScaleReg;
2646
2647 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002648 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002649 return false;
2650
2651 // It was legal, so commit it.
2652 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002653
Chandler Carruthc8925912013-01-05 02:09:22 +00002654 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2655 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2656 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002657 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002658 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2659 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2660 TestAddrMode.ScaledReg = AddLHS;
2661 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002662
Chandler Carruthc8925912013-01-05 02:09:22 +00002663 // If this addressing mode is legal, commit it and remember that we folded
2664 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002665 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002666 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2667 AddrMode = TestAddrMode;
2668 return true;
2669 }
2670 }
2671
2672 // Otherwise, not (x+c)*scale, just return what we have.
2673 return true;
2674}
2675
Sanjay Patel4ac6b112015-09-21 22:47:23 +00002676/// This is a little filter, which returns true if an addressing computation
2677/// involving I might be folded into a load/store accessing it.
2678/// This doesn't need to be perfect, but needs to accept at least
Chandler Carruthc8925912013-01-05 02:09:22 +00002679/// the set of instructions that MatchOperationAddr can.
2680static bool MightBeFoldableInst(Instruction *I) {
2681 switch (I->getOpcode()) {
2682 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002683 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002684 // Don't touch identity bitcasts.
2685 if (I->getType() == I->getOperand(0)->getType())
2686 return false;
2687 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2688 case Instruction::PtrToInt:
2689 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2690 return true;
2691 case Instruction::IntToPtr:
2692 // We know the input is intptr_t, so this is foldable.
2693 return true;
2694 case Instruction::Add:
2695 return true;
2696 case Instruction::Mul:
2697 case Instruction::Shl:
2698 // Can only handle X*C and X << C.
2699 return isa<ConstantInt>(I->getOperand(1));
2700 case Instruction::GetElementPtr:
2701 return true;
2702 default:
2703 return false;
2704 }
2705}
2706
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002707/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2708/// \note \p Val is assumed to be the product of some type promotion.
2709/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2710/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002711static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2712 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002713 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2714 if (!PromotedInst)
2715 return false;
2716 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2717 // If the ISDOpcode is undefined, it was undefined before the promotion.
2718 if (!ISDOpcode)
2719 return true;
2720 // Otherwise, check if the promoted instruction is legal or not.
2721 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002722 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002723}
2724
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002725/// \brief Hepler class to perform type promotion.
2726class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002727 /// \brief Utility function to check whether or not a sign or zero extension
2728 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2729 /// either using the operands of \p Inst or promoting \p Inst.
2730 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002731 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002732 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002733 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002734 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002735 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002736 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002737 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002738 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2739 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002740
2741 /// \brief Utility function to determine if \p OpIdx should be promoted when
2742 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002743 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Rafael Espindola84921b92015-10-24 23:11:13 +00002744 return !(isa<SelectInst>(Inst) && OpIdx == 0);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002745 }
2746
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002747 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002748 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002749 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002750 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002751 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002752 /// Newly added extensions are inserted in \p Exts.
2753 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002754 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002755 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002756 static Value *promoteOperandForTruncAndAnyExt(
2757 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002758 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002759 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002760 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002761
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002762 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002763 /// operand is promotable and is not a supported trunc or sext.
2764 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002765 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002766 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002767 /// Newly added extensions are inserted in \p Exts.
2768 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002769 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002770 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002771 static Value *promoteOperandForOther(Instruction *Ext,
2772 TypePromotionTransaction &TPT,
2773 InstrToOrigTy &PromotedInsts,
2774 unsigned &CreatedInstsCost,
2775 SmallVectorImpl<Instruction *> *Exts,
2776 SmallVectorImpl<Instruction *> *Truncs,
2777 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002778
2779 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002780 static Value *signExtendOperandForOther(
2781 Instruction *Ext, TypePromotionTransaction &TPT,
2782 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2783 SmallVectorImpl<Instruction *> *Exts,
2784 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2785 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2786 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002787 }
2788
2789 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002790 static Value *zeroExtendOperandForOther(
2791 Instruction *Ext, TypePromotionTransaction &TPT,
2792 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2793 SmallVectorImpl<Instruction *> *Exts,
2794 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2795 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2796 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002797 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002798
2799public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002800 /// Type for the utility function that promotes the operand of Ext.
2801 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002802 InstrToOrigTy &PromotedInsts,
2803 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002804 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002805 SmallVectorImpl<Instruction *> *Truncs,
2806 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002807 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2808 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002809 /// \return NULL if no promotable action is possible with the current
2810 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002811 /// \p InsertedInsts keeps track of all the instructions inserted by the
2812 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002813 /// because we do not want to promote these instructions as CodeGenPrepare
2814 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2815 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002816 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002817 const TargetLowering &TLI,
2818 const InstrToOrigTy &PromotedInsts);
2819};
2820
2821bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002822 Type *ConsideredExtType,
2823 const InstrToOrigTy &PromotedInsts,
2824 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002825 // The promotion helper does not know how to deal with vector types yet.
2826 // To be able to fix that, we would need to fix the places where we
2827 // statically extend, e.g., constants and such.
2828 if (Inst->getType()->isVectorTy())
2829 return false;
2830
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002831 // We can always get through zext.
2832 if (isa<ZExtInst>(Inst))
2833 return true;
2834
2835 // sext(sext) is ok too.
2836 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002837 return true;
2838
2839 // We can get through binary operator, if it is legal. In other words, the
2840 // binary operator must have a nuw or nsw flag.
2841 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2842 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002843 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2844 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002845 return true;
2846
2847 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002848 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002849 if (!isa<TruncInst>(Inst))
2850 return false;
2851
2852 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002853 // Check if we can use this operand in the extension.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002854 // If the type is larger than the result type of the extension, we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002855 if (!OpndVal->getType()->isIntegerTy() ||
2856 OpndVal->getType()->getIntegerBitWidth() >
2857 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002858 return false;
2859
2860 // If the operand of the truncate is not an instruction, we will not have
2861 // any information on the dropped bits.
2862 // (Actually we could for constant but it is not worth the extra logic).
2863 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2864 if (!Opnd)
2865 return false;
2866
2867 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002868 // I.e., check that trunc just drops extended bits of the same kind of
2869 // the extension.
2870 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002871 const Type *OpndType;
2872 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002873 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2874 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002875 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2876 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002877 else
2878 return false;
2879
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002880 // #2 check that the truncate just drops extended bits.
Rafael Espindola84921b92015-10-24 23:11:13 +00002881 return Inst->getType()->getIntegerBitWidth() >=
2882 OpndType->getIntegerBitWidth();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002883}
2884
2885TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002886 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002887 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002888 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2889 "Unexpected instruction type");
2890 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2891 Type *ExtTy = Ext->getType();
2892 bool IsSExt = isa<SExtInst>(Ext);
2893 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002894 // get through.
2895 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002896 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002897 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002898
2899 // Do not promote if the operand has been added by codegenprepare.
2900 // Otherwise, it means we are undoing an optimization that is likely to be
2901 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002902 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002903 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002904
2905 // SExt or Trunc instructions.
2906 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002907 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2908 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002909 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002910
2911 // Regular instruction.
2912 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002913 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002914 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002915 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002916}
2917
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002918Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002919 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002920 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002921 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002922 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002923 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2924 // get through it and this method should not be called.
2925 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002926 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002927 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002928 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002929 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002930 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002931 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002932 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002933 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2934 TPT.replaceAllUsesWith(SExt, ZExt);
2935 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002936 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002937 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002938 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2939 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002940 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2941 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002942 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002943
2944 // Remove dead code.
2945 if (SExtOpnd->use_empty())
2946 TPT.eraseInstruction(SExtOpnd);
2947
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002948 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002949 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002950 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002951 if (ExtInst) {
2952 if (Exts)
2953 Exts->push_back(ExtInst);
2954 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2955 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002956 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002957 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002958
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002959 // At this point we have: ext ty opnd to ty.
2960 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2961 Value *NextVal = ExtInst->getOperand(0);
2962 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002963 return NextVal;
2964}
2965
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002966Value *TypePromotionHelper::promoteOperandForOther(
2967 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002968 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002969 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002970 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2971 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002972 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002973 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002974 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002975 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002976 if (!ExtOpnd->hasOneUse()) {
2977 // ExtOpnd will be promoted.
2978 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002979 // promoted version.
2980 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002981 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002982 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2983 ITrunc->removeFromParent();
2984 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002985 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002986 if (Truncs)
2987 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002988 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002989
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002990 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00002991 // Restore the operand of Ext (which has been replaced by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002992 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002993 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002994 }
2995
2996 // Get through the Instruction:
2997 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002998 // 2. Replace the uses of Ext by Inst.
2999 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003000
3001 // Remember the original type of the instruction before promotion.
3002 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003003 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
3004 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003005 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003006 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003007 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003008 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003009 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003010 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003011
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003012 DEBUG(dbgs() << "Propagate Ext to operands\n");
3013 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003014 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003015 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
3016 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
3017 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003018 DEBUG(dbgs() << "No need to propagate\n");
3019 continue;
3020 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003021 // Check if we can statically extend the operand.
3022 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003023 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003024 DEBUG(dbgs() << "Statically extend\n");
3025 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
3026 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
3027 : Cst->getValue().zext(BitWidth);
3028 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003029 continue;
3030 }
3031 // UndefValue are typed, so we have to statically sign extend them.
3032 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003033 DEBUG(dbgs() << "Statically extend\n");
3034 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003035 continue;
3036 }
3037
3038 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003039 // Check if Ext was reused to extend an operand.
3040 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003041 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003042 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00003043 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
3044 : TPT.createZExt(Ext, Opnd, Ext->getType());
3045 if (!isa<Instruction>(ValForExtOpnd)) {
3046 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
3047 continue;
3048 }
3049 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003050 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003051 if (Exts)
3052 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003053 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003054
3055 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003056 TPT.moveBefore(ExtForOpnd, ExtOpnd);
3057 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00003058 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003059 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003060 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003061 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003062 if (ExtForOpnd == Ext) {
3063 DEBUG(dbgs() << "Extension is useless now\n");
3064 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003065 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003066 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003067}
3068
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003069/// Check whether or not promoting an instruction to a wider type is profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003070/// \p NewCost gives the cost of extension instructions created by the
3071/// promotion.
3072/// \p OldCost gives the cost of extension instructions before the promotion
3073/// plus the number of instructions that have been
3074/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00003075/// \p PromotedOperand is the value that has been promoted.
3076/// \return True if the promotion is profitable, false otherwise.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003077bool AddressingModeMatcher::isPromotionProfitable(
Quentin Colombet1b274f92015-03-10 21:48:15 +00003078 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
3079 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
3080 // The cost of the new extensions is greater than the cost of the
3081 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00003082 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003083 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003084 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003085 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00003086 return true;
3087 // The promotion is neutral but it may help folding the sign extension in
3088 // loads for instance.
3089 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00003090 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00003091}
3092
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003093/// Given an instruction or constant expr, see if we can fold the operation
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003094/// into the addressing mode. If so, update the addressing mode and return
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003095/// true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003096/// If \p MovedAway is not NULL, it contains the information of whether or
3097/// not AddrInst has to be folded into the addressing mode on success.
3098/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
3099/// because it has been moved away.
3100/// Thus AddrInst must not be added in the matched instructions.
3101/// This state can happen when AddrInst is a sext, since it may be moved away.
3102/// Therefore, AddrInst may not be valid when MovedAway is true and it must
3103/// not be referenced anymore.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003104bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003105 unsigned Depth,
3106 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003107 // Avoid exponential behavior on extremely deep expression trees.
3108 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003109
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003110 // By default, all matched instructions stay in place.
3111 if (MovedAway)
3112 *MovedAway = false;
3113
Chandler Carruthc8925912013-01-05 02:09:22 +00003114 switch (Opcode) {
3115 case Instruction::PtrToInt:
3116 // PtrToInt is always a noop, as we know that the int type is pointer sized.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003117 return matchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00003118 case Instruction::IntToPtr: {
3119 auto AS = AddrInst->getType()->getPointerAddressSpace();
3120 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00003121 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00003122 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Sanjay Patelfc580a62015-09-21 23:03:16 +00003123 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003124 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00003125 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003126 case Instruction::BitCast:
3127 // BitCast is always a noop, and we can handle it as long as it is
3128 // int->int or pointer->pointer (we don't want int<->fp or something).
3129 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
3130 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
3131 // Don't touch identity bitcasts. These were probably put here by LSR,
3132 // and we don't want to mess around with them. Assume it knows what it
3133 // is doing.
3134 AddrInst->getOperand(0)->getType() != AddrInst->getType())
Sanjay Patelfc580a62015-09-21 23:03:16 +00003135 return matchAddr(AddrInst->getOperand(0), Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003136 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003137 case Instruction::AddrSpaceCast: {
3138 unsigned SrcAS
3139 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
3140 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
3141 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
Sanjay Patelfc580a62015-09-21 23:03:16 +00003142 return matchAddr(AddrInst->getOperand(0), Depth);
Matt Arsenaultf05b0232015-05-26 16:59:43 +00003143 return false;
3144 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003145 case Instruction::Add: {
3146 // Check to see if we can merge in the RHS then the LHS. If so, we win.
3147 ExtAddrMode BackupAddrMode = AddrMode;
3148 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003149 // Start a transaction at this point.
3150 // The LHS may match but not the RHS.
3151 // Therefore, we need a higher level restoration point to undo partially
3152 // matched operation.
3153 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3154 TPT.getRestorationPoint();
3155
Sanjay Patelfc580a62015-09-21 23:03:16 +00003156 if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
3157 matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003158 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003159
Chandler Carruthc8925912013-01-05 02:09:22 +00003160 // Restore the old addr mode info.
3161 AddrMode = BackupAddrMode;
3162 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003163 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00003164
Chandler Carruthc8925912013-01-05 02:09:22 +00003165 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003166 if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
3167 matchAddr(AddrInst->getOperand(1), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003168 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003169
Chandler Carruthc8925912013-01-05 02:09:22 +00003170 // Otherwise we definitely can't merge the ADD in.
3171 AddrMode = BackupAddrMode;
3172 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003173 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003174 break;
3175 }
3176 //case Instruction::Or:
3177 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
3178 //break;
3179 case Instruction::Mul:
3180 case Instruction::Shl: {
3181 // Can only handle X*C and X << C.
3182 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003183 if (!RHS)
3184 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00003185 int64_t Scale = RHS->getSExtValue();
3186 if (Opcode == Instruction::Shl)
3187 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00003188
Sanjay Patelfc580a62015-09-21 23:03:16 +00003189 return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
Chandler Carruthc8925912013-01-05 02:09:22 +00003190 }
3191 case Instruction::GetElementPtr: {
3192 // Scan the GEP. We check it if it contains constant offsets and at most
3193 // one variable offset.
3194 int VariableOperand = -1;
3195 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00003196
Chandler Carruthc8925912013-01-05 02:09:22 +00003197 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00003198 gep_type_iterator GTI = gep_type_begin(AddrInst);
3199 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
3200 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003201 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00003202 unsigned Idx =
3203 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
3204 ConstantOffset += SL->getElementOffset(Idx);
3205 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00003206 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00003207 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
3208 ConstantOffset += CI->getSExtValue()*TypeSize;
3209 } else if (TypeSize) { // Scales of zero don't do anything.
3210 // We only allow one variable index at the moment.
3211 if (VariableOperand != -1)
3212 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003213
Chandler Carruthc8925912013-01-05 02:09:22 +00003214 // Remember the variable index.
3215 VariableOperand = i;
3216 VariableScale = TypeSize;
3217 }
3218 }
3219 }
Stephen Lin837bba12013-07-15 17:55:02 +00003220
Chandler Carruthc8925912013-01-05 02:09:22 +00003221 // A common case is for the GEP to only do a constant offset. In this case,
3222 // just add it to the disp field and check validity.
3223 if (VariableOperand == -1) {
3224 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003225 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003226 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003227 // Check to see if we can fold the base pointer in too.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003228 if (matchAddr(AddrInst->getOperand(0), Depth+1))
Chandler Carruthc8925912013-01-05 02:09:22 +00003229 return true;
3230 }
3231 AddrMode.BaseOffs -= ConstantOffset;
3232 return false;
3233 }
3234
3235 // Save the valid addressing mode in case we can't match.
3236 ExtAddrMode BackupAddrMode = AddrMode;
3237 unsigned OldSize = AddrModeInsts.size();
3238
3239 // See if the scale and offset amount is valid for this target.
3240 AddrMode.BaseOffs += ConstantOffset;
3241
3242 // Match the base operand of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003243 if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003244 // If it couldn't be matched, just stuff the value in a register.
3245 if (AddrMode.HasBaseReg) {
3246 AddrMode = BackupAddrMode;
3247 AddrModeInsts.resize(OldSize);
3248 return false;
3249 }
3250 AddrMode.HasBaseReg = true;
3251 AddrMode.BaseReg = AddrInst->getOperand(0);
3252 }
3253
3254 // Match the remaining variable portion of the GEP.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003255 if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
Chandler Carruthc8925912013-01-05 02:09:22 +00003256 Depth)) {
3257 // If it couldn't be matched, try stuffing the base into a register
3258 // instead of matching it, and retrying the match of the scale.
3259 AddrMode = BackupAddrMode;
3260 AddrModeInsts.resize(OldSize);
3261 if (AddrMode.HasBaseReg)
3262 return false;
3263 AddrMode.HasBaseReg = true;
3264 AddrMode.BaseReg = AddrInst->getOperand(0);
3265 AddrMode.BaseOffs += ConstantOffset;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003266 if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
Chandler Carruthc8925912013-01-05 02:09:22 +00003267 VariableScale, Depth)) {
3268 // If even that didn't work, bail.
3269 AddrMode = BackupAddrMode;
3270 AddrModeInsts.resize(OldSize);
3271 return false;
3272 }
3273 }
3274
3275 return true;
3276 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003277 case Instruction::SExt:
3278 case Instruction::ZExt: {
3279 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
3280 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00003281 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00003282
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003283 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003284 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003285 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003286 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003287 if (!TPH)
3288 return false;
3289
3290 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3291 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00003292 unsigned CreatedInstsCost = 0;
3293 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003294 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00003295 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003296 // SExt has been moved away.
3297 // Thus either it will be rematched later in the recursive calls or it is
3298 // gone. Anyway, we must not fold it into the addressing mode at this point.
3299 // E.g.,
3300 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003301 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003302 // addr = gep base, idx
3303 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00003304 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003305 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
3306 // addr = gep base, op <- match
3307 if (MovedAway)
3308 *MovedAway = true;
3309
3310 assert(PromotedOperand &&
3311 "TypePromotionHelper should have filtered out those cases");
3312
3313 ExtAddrMode BackupAddrMode = AddrMode;
3314 unsigned OldSize = AddrModeInsts.size();
3315
Sanjay Patelfc580a62015-09-21 23:03:16 +00003316 if (!matchAddr(PromotedOperand, Depth) ||
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003317 // The total of the new cost is equal to the cost of the created
Quentin Colombet1b274f92015-03-10 21:48:15 +00003318 // instructions.
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003319 // The total of the old cost is equal to the cost of the extension plus
Quentin Colombet1b274f92015-03-10 21:48:15 +00003320 // what we have saved in the addressing mode.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003321 !isPromotionProfitable(CreatedInstsCost,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003322 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00003323 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003324 AddrMode = BackupAddrMode;
3325 AddrModeInsts.resize(OldSize);
3326 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
3327 TPT.rollback(LastKnownGood);
3328 return false;
3329 }
3330 return true;
3331 }
Chandler Carruthc8925912013-01-05 02:09:22 +00003332 }
3333 return false;
3334}
3335
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003336/// If we can, try to add the value of 'Addr' into the current addressing mode.
3337/// If Addr can't be added to AddrMode this returns false and leaves AddrMode
3338/// unmodified. This assumes that Addr is either a pointer type or intptr_t
3339/// for the target.
Chandler Carruthc8925912013-01-05 02:09:22 +00003340///
Sanjay Patelfc580a62015-09-21 23:03:16 +00003341bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003342 // Start a transaction at this point that we will rollback if the matching
3343 // fails.
3344 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3345 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00003346 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
3347 // Fold in immediates if legal for the target.
3348 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003349 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003350 return true;
3351 AddrMode.BaseOffs -= CI->getSExtValue();
3352 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
3353 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00003354 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003355 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003356 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003357 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00003358 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003359 }
3360 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
3361 ExtAddrMode BackupAddrMode = AddrMode;
3362 unsigned OldSize = AddrModeInsts.size();
3363
3364 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003365 bool MovedAway = false;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003366 if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003367 // This instruction may have been moved away. If so, there is nothing
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003368 // to check here.
3369 if (MovedAway)
3370 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00003371 // Okay, it's possible to fold this. Check to see if it is actually
3372 // *profitable* to do so. We use a simple cost model to avoid increasing
3373 // register pressure too much.
3374 if (I->hasOneUse() ||
Sanjay Patelfc580a62015-09-21 23:03:16 +00003375 isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003376 AddrModeInsts.push_back(I);
3377 return true;
3378 }
Stephen Lin837bba12013-07-15 17:55:02 +00003379
Chandler Carruthc8925912013-01-05 02:09:22 +00003380 // It isn't profitable to do this, roll back.
3381 //cerr << "NOT FOLDING: " << *I;
3382 AddrMode = BackupAddrMode;
3383 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003384 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003385 }
3386 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
Sanjay Patelfc580a62015-09-21 23:03:16 +00003387 if (matchOperationAddr(CE, CE->getOpcode(), Depth))
Chandler Carruthc8925912013-01-05 02:09:22 +00003388 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003389 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003390 } else if (isa<ConstantPointerNull>(Addr)) {
3391 // Null pointer gets folded without affecting the addressing mode.
3392 return true;
3393 }
3394
3395 // Worse case, the target should support [reg] addressing modes. :)
3396 if (!AddrMode.HasBaseReg) {
3397 AddrMode.HasBaseReg = true;
3398 AddrMode.BaseReg = Addr;
3399 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003400 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003401 return true;
3402 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00003403 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003404 }
3405
3406 // If the base register is already taken, see if we can do [r+r].
3407 if (AddrMode.Scale == 0) {
3408 AddrMode.Scale = 1;
3409 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00003410 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00003411 return true;
3412 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00003413 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003414 }
3415 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003416 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00003417 return false;
3418}
3419
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003420/// Check to see if all uses of OpVal by the specified inline asm call are due
3421/// to memory operands. If so, return true, otherwise return false.
Chandler Carruthc8925912013-01-05 02:09:22 +00003422static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00003423 const TargetMachine &TM) {
3424 const Function *F = CI->getParent()->getParent();
3425 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
3426 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00003427 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003428 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
3429 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00003430 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3431 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00003432
Chandler Carruthc8925912013-01-05 02:09:22 +00003433 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00003434 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00003435
3436 // If this asm operand is our Value*, and if it isn't an indirect memory
3437 // operand, we can't fold it!
3438 if (OpInfo.CallOperandVal == OpVal &&
3439 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3440 !OpInfo.isIndirect))
3441 return false;
3442 }
3443
3444 return true;
3445}
3446
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003447/// Recursively walk all the uses of I until we find a memory use.
3448/// If we find an obviously non-foldable instruction, return true.
Chandler Carruthc8925912013-01-05 02:09:22 +00003449/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003450static bool FindAllMemoryUses(
3451 Instruction *I,
3452 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3453 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003454 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003455 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003456 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003457
Chandler Carruthc8925912013-01-05 02:09:22 +00003458 // If this is an obviously unfoldable instruction, bail out.
3459 if (!MightBeFoldableInst(I))
3460 return true;
3461
Philip Reamesac115ed2016-03-09 23:13:12 +00003462 const bool OptSize = I->getFunction()->optForSize();
3463
Chandler Carruthc8925912013-01-05 02:09:22 +00003464 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003465 for (Use &U : I->uses()) {
3466 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003467
Chandler Carruthcdf47882014-03-09 03:16:01 +00003468 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3469 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003470 continue;
3471 }
Stephen Lin837bba12013-07-15 17:55:02 +00003472
Chandler Carruthcdf47882014-03-09 03:16:01 +00003473 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3474 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003475 if (opNo == 0) return true; // Storing addr, not into addr.
3476 MemoryUses.push_back(std::make_pair(SI, opNo));
3477 continue;
3478 }
Stephen Lin837bba12013-07-15 17:55:02 +00003479
Chandler Carruthcdf47882014-03-09 03:16:01 +00003480 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Philip Reamesac115ed2016-03-09 23:13:12 +00003481 // If this is a cold call, we can sink the addressing calculation into
3482 // the cold path. See optimizeCallInst
3483 if (!OptSize && CI->hasFnAttr(Attribute::Cold))
3484 continue;
Junmo Park6098cbb2016-03-11 07:05:32 +00003485
Chandler Carruthc8925912013-01-05 02:09:22 +00003486 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3487 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003488
Chandler Carruthc8925912013-01-05 02:09:22 +00003489 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003490 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003491 return true;
3492 continue;
3493 }
Stephen Lin837bba12013-07-15 17:55:02 +00003494
Eric Christopher11e4df72015-02-26 22:38:43 +00003495 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003496 return true;
3497 }
3498
3499 return false;
3500}
3501
Sanjay Patel9fbe22b2015-10-09 18:01:03 +00003502/// Return true if Val is already known to be live at the use site that we're
3503/// folding it into. If so, there is no cost to include it in the addressing
3504/// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
3505/// instruction already.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003506bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
Chandler Carruthc8925912013-01-05 02:09:22 +00003507 Value *KnownLive2) {
3508 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003509 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003510 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003511
Chandler Carruthc8925912013-01-05 02:09:22 +00003512 // All values other than instructions and arguments (e.g. constants) are live.
3513 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003514
Chandler Carruthc8925912013-01-05 02:09:22 +00003515 // If Val is a constant sized alloca in the entry block, it is live, this is
3516 // true because it is just a reference to the stack/frame pointer, which is
3517 // live for the whole function.
3518 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3519 if (AI->isStaticAlloca())
3520 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003521
Chandler Carruthc8925912013-01-05 02:09:22 +00003522 // Check to see if this value is already used in the memory instruction's
3523 // block. If so, it's already live into the block at the very least, so we
3524 // can reasonably fold it.
3525 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3526}
3527
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003528/// It is possible for the addressing mode of the machine to fold the specified
3529/// instruction into a load or store that ultimately uses it.
3530/// However, the specified instruction has multiple uses.
3531/// Given this, it may actually increase register pressure to fold it
3532/// into the load. For example, consider this code:
Chandler Carruthc8925912013-01-05 02:09:22 +00003533///
3534/// X = ...
3535/// Y = X+1
3536/// use(Y) -> nonload/store
3537/// Z = Y+1
3538/// load Z
3539///
3540/// In this case, Y has multiple uses, and can be folded into the load of Z
3541/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3542/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3543/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3544/// number of computations either.
3545///
3546/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3547/// X was live across 'load Z' for other reasons, we actually *would* want to
3548/// fold the addressing mode in the Z case. This would make Y die earlier.
3549bool AddressingModeMatcher::
Sanjay Patelfc580a62015-09-21 23:03:16 +00003550isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
Chandler Carruthc8925912013-01-05 02:09:22 +00003551 ExtAddrMode &AMAfter) {
3552 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003553
Chandler Carruthc8925912013-01-05 02:09:22 +00003554 // AMBefore is the addressing mode before this instruction was folded into it,
3555 // and AMAfter is the addressing mode after the instruction was folded. Get
3556 // the set of registers referenced by AMAfter and subtract out those
3557 // referenced by AMBefore: this is the set of values which folding in this
3558 // address extends the lifetime of.
3559 //
3560 // Note that there are only two potential values being referenced here,
3561 // BaseReg and ScaleReg (global addresses are always available, as are any
3562 // folded immediates).
3563 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003564
Chandler Carruthc8925912013-01-05 02:09:22 +00003565 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3566 // lifetime wasn't extended by adding this instruction.
Sanjay Patelfc580a62015-09-21 23:03:16 +00003567 if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003568 BaseReg = nullptr;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003569 if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003570 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003571
3572 // If folding this instruction (and it's subexprs) didn't extend any live
3573 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003574 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003575 return true;
3576
Philip Reamesac115ed2016-03-09 23:13:12 +00003577 // If all uses of this instruction can have the address mode sunk into them,
3578 // we can remove the addressing mode and effectively trade one live register
3579 // for another (at worst.) In this context, folding an addressing mode into
Junmo Park6098cbb2016-03-11 07:05:32 +00003580 // the use is just a particularly nice way of sinking it.
Chandler Carruthc8925912013-01-05 02:09:22 +00003581 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3582 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003583 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003584 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003585
Chandler Carruthc8925912013-01-05 02:09:22 +00003586 // Now that we know that all uses of this instruction are part of a chain of
3587 // computation involving only operations that could theoretically be folded
Philip Reamesac115ed2016-03-09 23:13:12 +00003588 // into a memory use, loop over each of these memory operation uses and see
3589 // if they could *actually* fold the instruction. The assumption is that
3590 // addressing modes are cheap and that duplicating the computation involved
3591 // many times is worthwhile, even on a fastpath. For sinking candidates
3592 // (i.e. cold call sites), this serves as a way to prevent excessive code
3593 // growth since most architectures have some reasonable small and fast way to
3594 // compute an effective address. (i.e LEA on x86)
Chandler Carruthc8925912013-01-05 02:09:22 +00003595 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3596 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3597 Instruction *User = MemoryUses[i].first;
3598 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003599
Chandler Carruthc8925912013-01-05 02:09:22 +00003600 // Get the access type of this use. If the use isn't a pointer, we don't
3601 // know what it accesses.
3602 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003603 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3604 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003605 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003606 Type *AddressAccessTy = AddrTy->getElementType();
3607 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003608
Chandler Carruthc8925912013-01-05 02:09:22 +00003609 // Do a match against the root of this address, ignoring profitability. This
3610 // will tell us if the addressing mode for the memory operation will
3611 // *actually* cover the shared instruction.
3612 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003613 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3614 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003615 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003616 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003617 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003618 Matcher.IgnoreProfitability = true;
Sanjay Patelfc580a62015-09-21 23:03:16 +00003619 bool Success = Matcher.matchAddr(Address, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00003620 (void)Success; assert(Success && "Couldn't select *anything*?");
3621
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003622 // The match was to check the profitability, the changes made are not
3623 // part of the original matcher. Therefore, they should be dropped
3624 // otherwise the original matcher will not present the right state.
3625 TPT.rollback(LastKnownGood);
3626
Chandler Carruthc8925912013-01-05 02:09:22 +00003627 // If the match didn't cover I, then it won't be shared by it.
3628 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3629 I) == MatchedAddrModeInsts.end())
3630 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003631
Chandler Carruthc8925912013-01-05 02:09:22 +00003632 MatchedAddrModeInsts.clear();
3633 }
Stephen Lin837bba12013-07-15 17:55:02 +00003634
Chandler Carruthc8925912013-01-05 02:09:22 +00003635 return true;
3636}
3637
3638} // end anonymous namespace
3639
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003640/// Return true if the specified values are defined in a
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003641/// different basic block than BB.
3642static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3643 if (Instruction *I = dyn_cast<Instruction>(V))
3644 return I->getParent() != BB;
3645 return false;
3646}
3647
Philip Reamesac115ed2016-03-09 23:13:12 +00003648/// Sink addressing mode computation immediate before MemoryInst if doing so
3649/// can be done without increasing register pressure. The need for the
3650/// register pressure constraint means this can end up being an all or nothing
3651/// decision for all uses of the same addressing computation.
3652///
Sanjay Patel4ac6b112015-09-21 22:47:23 +00003653/// Load and Store Instructions often have addressing modes that can do
3654/// significant amounts of computation. As such, instruction selection will try
3655/// to get the load or store to do as much computation as possible for the
3656/// program. The problem is that isel can only see within a single block. As
3657/// such, we sink as much legal addressing mode work into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003658///
3659/// This method is used to optimize both load/store and inline asms with memory
Philip Reamesac115ed2016-03-09 23:13:12 +00003660/// operands. It's also used to sink addressing computations feeding into cold
3661/// call sites into their (cold) basic block.
3662///
3663/// The motivation for handling sinking into cold blocks is that doing so can
3664/// both enable other address mode sinking (by satisfying the register pressure
3665/// constraint above), and reduce register pressure globally (by removing the
3666/// addressing mode computation from the fast path entirely.).
Sanjay Patelfc580a62015-09-21 23:03:16 +00003667bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003668 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003669 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003670
3671 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003672 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003673 SmallVector<Value*, 8> worklist;
3674 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003675 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003676
Owen Anderson8ba5f392010-11-27 08:15:55 +00003677 // Use a worklist to iteratively look through PHI nodes, and ensure that
3678 // the addressing mode obtained from the non-PHI roots of the graph
3679 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003680 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003681 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003682 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003683 SmallVector<Instruction*, 16> AddrModeInsts;
3684 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003685 TypePromotionTransaction TPT;
3686 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3687 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003688 while (!worklist.empty()) {
3689 Value *V = worklist.back();
3690 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003691
Owen Anderson8ba5f392010-11-27 08:15:55 +00003692 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003693 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003694 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003695 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003696 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003697
Owen Anderson8ba5f392010-11-27 08:15:55 +00003698 // For a PHI node, push all of its incoming values.
3699 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003700 for (Value *IncValue : P->incoming_values())
3701 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003702 continue;
3703 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003704
Philip Reamesac115ed2016-03-09 23:13:12 +00003705 // For non-PHIs, determine the addressing mode being computed. Note that
3706 // the result may differ depending on what other uses our candidate
3707 // addressing instructions might have.
Owen Anderson8ba5f392010-11-27 08:15:55 +00003708 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003709 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003710 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003711 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003712
3713 // This check is broken into two cases with very similar code to avoid using
3714 // getNumUses() as much as possible. Some values have a lot of uses, so
3715 // calling getNumUses() unconditionally caused a significant compile-time
3716 // regression.
3717 if (!Consensus) {
3718 Consensus = V;
3719 AddrMode = NewAddrMode;
3720 AddrModeInsts = NewAddrModeInsts;
3721 continue;
3722 } else if (NewAddrMode == AddrMode) {
3723 if (!IsNumUsesConsensusValid) {
3724 NumUsesConsensus = Consensus->getNumUses();
3725 IsNumUsesConsensusValid = true;
3726 }
3727
3728 // Ensure that the obtained addressing mode is equivalent to that obtained
3729 // for all other roots of the PHI traversal. Also, when choosing one
3730 // such root as representative, select the one with the most uses in order
3731 // to keep the cost modeling heuristics in AddressingModeMatcher
3732 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003733 unsigned NumUses = V->getNumUses();
3734 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003735 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003736 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003737 AddrModeInsts = NewAddrModeInsts;
3738 }
3739 continue;
3740 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003741
Craig Topperc0196b12014-04-14 00:51:57 +00003742 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003743 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003744 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003745
Owen Anderson8ba5f392010-11-27 08:15:55 +00003746 // If the addressing mode couldn't be determined, or if multiple different
3747 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003748 if (!Consensus) {
3749 TPT.rollback(LastKnownGood);
3750 return false;
3751 }
3752 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003753
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003754 // Check to see if any of the instructions supersumed by this addr mode are
3755 // non-local to I's BB.
3756 bool AnyNonLocal = false;
3757 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003758 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003759 AnyNonLocal = true;
3760 break;
3761 }
3762 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003763
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003764 // If all the instructions matched are already in this BB, don't do anything.
3765 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003766 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003767 return false;
3768 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003769
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003770 // Insert this computation right after this user. Since our caller is
3771 // scanning from the top of the BB to the bottom, reuse of the expr are
3772 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003773 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003774
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003775 // Now that we determined the addressing expression we want to use and know
3776 // that we have to sink it into this block. Check to see if we have already
3777 // done this for some other load/store instr in this block. If so, reuse the
3778 // computation.
3779 Value *&SunkAddr = SunkAddrs[Addr];
3780 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003781 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003782 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003783 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003784 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003785 } else if (AddrSinkUsingGEPs ||
3786 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003787 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3788 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003789 // By default, we use the GEP-based method when AA is used later. This
3790 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3791 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003792 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003793 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003794 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003795
3796 // First, find the pointer.
3797 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3798 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003799 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003800 }
3801
3802 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3803 // We can't add more than one pointer together, nor can we scale a
3804 // pointer (both of which seem meaningless).
3805 if (ResultPtr || AddrMode.Scale != 1)
3806 return false;
3807
3808 ResultPtr = AddrMode.ScaledReg;
3809 AddrMode.Scale = 0;
3810 }
3811
3812 if (AddrMode.BaseGV) {
3813 if (ResultPtr)
3814 return false;
3815
3816 ResultPtr = AddrMode.BaseGV;
3817 }
3818
3819 // If the real base value actually came from an inttoptr, then the matcher
3820 // will look through it and provide only the integer value. In that case,
3821 // use it here.
3822 if (!ResultPtr && AddrMode.BaseReg) {
3823 ResultPtr =
3824 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003825 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003826 } else if (!ResultPtr && AddrMode.Scale == 1) {
3827 ResultPtr =
3828 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3829 AddrMode.Scale = 0;
3830 }
3831
3832 if (!ResultPtr &&
3833 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3834 SunkAddr = Constant::getNullValue(Addr->getType());
3835 } else if (!ResultPtr) {
3836 return false;
3837 } else {
3838 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003839 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3840 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003841
3842 // Start with the base register. Do this first so that subsequent address
3843 // matching finds it last, which will prevent it from trying to match it
3844 // as the scaled value in case it happens to be a mul. That would be
3845 // problematic if we've sunk a different mul for the scale, because then
3846 // we'd end up sinking both muls.
3847 if (AddrMode.BaseReg) {
3848 Value *V = AddrMode.BaseReg;
3849 if (V->getType() != IntPtrTy)
3850 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3851
3852 ResultIndex = V;
3853 }
3854
3855 // Add the scale value.
3856 if (AddrMode.Scale) {
3857 Value *V = AddrMode.ScaledReg;
3858 if (V->getType() == IntPtrTy) {
3859 // done.
3860 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3861 cast<IntegerType>(V->getType())->getBitWidth()) {
3862 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3863 } else {
3864 // It is only safe to sign extend the BaseReg if we know that the math
3865 // required to create it did not overflow before we extend it. Since
3866 // the original IR value was tossed in favor of a constant back when
3867 // the AddrMode was created we need to bail out gracefully if widths
3868 // do not match instead of extending it.
3869 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3870 if (I && (ResultIndex != AddrMode.BaseReg))
3871 I->eraseFromParent();
3872 return false;
3873 }
3874
3875 if (AddrMode.Scale != 1)
3876 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3877 "sunkaddr");
3878 if (ResultIndex)
3879 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3880 else
3881 ResultIndex = V;
3882 }
3883
3884 // Add in the Base Offset if present.
3885 if (AddrMode.BaseOffs) {
3886 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3887 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003888 // We need to add this separately from the scale above to help with
3889 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003890 if (ResultPtr->getType() != I8PtrTy)
3891 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003892 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003893 }
3894
3895 ResultIndex = V;
3896 }
3897
3898 if (!ResultIndex) {
3899 SunkAddr = ResultPtr;
3900 } else {
3901 if (ResultPtr->getType() != I8PtrTy)
3902 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003903 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003904 }
3905
3906 if (SunkAddr->getType() != Addr->getType())
3907 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3908 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003909 } else {
David Greene74e2d492010-01-05 01:27:11 +00003910 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003911 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003912 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003913 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003914
3915 // Start with the base register. Do this first so that subsequent address
3916 // matching finds it last, which will prevent it from trying to match it
3917 // as the scaled value in case it happens to be a mul. That would be
3918 // problematic if we've sunk a different mul for the scale, because then
3919 // we'd end up sinking both muls.
3920 if (AddrMode.BaseReg) {
3921 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003922 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003923 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003924 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003925 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003926 Result = V;
3927 }
3928
3929 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003930 if (AddrMode.Scale) {
3931 Value *V = AddrMode.ScaledReg;
3932 if (V->getType() == IntPtrTy) {
3933 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003934 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003935 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003936 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3937 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003938 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003939 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003940 // It is only safe to sign extend the BaseReg if we know that the math
3941 // required to create it did not overflow before we extend it. Since
3942 // the original IR value was tossed in favor of a constant back when
3943 // the AddrMode was created we need to bail out gracefully if widths
3944 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003945 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003946 if (I && (Result != AddrMode.BaseReg))
3947 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003948 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003949 }
3950 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003951 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3952 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003953 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003954 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003955 else
3956 Result = V;
3957 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003958
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003959 // Add in the BaseGV if present.
3960 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003961 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003962 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003963 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003964 else
3965 Result = V;
3966 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003967
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003968 // Add in the Base Offset if present.
3969 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003970 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003971 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003972 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003973 else
3974 Result = V;
3975 }
3976
Craig Topperc0196b12014-04-14 00:51:57 +00003977 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003978 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003979 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003980 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003981 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003982
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003983 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003984
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003985 // If we have no uses, recursively delete the value and all dead instructions
3986 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003987 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003988 // This can cause recursive deletion, which can invalidate our iterator.
3989 // Use a WeakVH to hold onto it in case this happens.
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00003990 Value *CurValue = &*CurInstIterator;
3991 WeakVH IterHandle(CurValue);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003992 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003993
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003994 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003995
Duncan P. N. Exon Smith7b269642016-02-21 19:37:45 +00003996 if (IterHandle != CurValue) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003997 // If the iterator instruction was recursively deleted, start over at the
3998 // start of the block.
3999 CurInstIterator = BB->begin();
4000 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00004001 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00004002 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00004003 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00004004 return true;
4005}
4006
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004007/// If there are any memory operands, use OptimizeMemoryInst to sink their
4008/// address computing into the block when possible / profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004009bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00004010 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00004011
Eric Christopher11e4df72015-02-26 22:38:43 +00004012 const TargetRegisterInfo *TRI =
4013 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00004014 TargetLowering::AsmOperandInfoVector TargetConstraints =
4015 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004016 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00004017 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
4018 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00004019
Evan Cheng1da25002008-02-26 02:42:37 +00004020 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00004021 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00004022
Eli Friedman666bbe32008-02-26 18:37:49 +00004023 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4024 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00004025 Value *OpVal = CS->getArgOperand(ArgNo++);
Sanjay Patelfc580a62015-09-21 23:03:16 +00004026 MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00004027 } else if (OpInfo.Type == InlineAsm::isInput)
4028 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00004029 }
4030
4031 return MadeChange;
4032}
4033
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004034/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
4035/// sign extensions.
4036static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
4037 assert(!Inst->use_empty() && "Input must have at least one use");
4038 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
4039 bool IsSExt = isa<SExtInst>(FirstUser);
4040 Type *ExtTy = FirstUser->getType();
4041 for (const User *U : Inst->users()) {
4042 const Instruction *UI = cast<Instruction>(U);
4043 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
4044 return false;
4045 Type *CurTy = UI->getType();
4046 // Same input and output types: Same instruction after CSE.
4047 if (CurTy == ExtTy)
4048 continue;
4049
4050 // If IsSExt is true, we are in this situation:
4051 // a = Inst
4052 // b = sext ty1 a to ty2
4053 // c = sext ty1 a to ty3
4054 // Assuming ty2 is shorter than ty3, this could be turned into:
4055 // a = Inst
4056 // b = sext ty1 a to ty2
4057 // c = sext ty2 b to ty3
4058 // However, the last sext is not free.
4059 if (IsSExt)
4060 return false;
4061
4062 // This is a ZExt, maybe this is free to extend from one type to another.
4063 // In that case, we would not account for a different use.
4064 Type *NarrowTy;
4065 Type *LargeTy;
4066 if (ExtTy->getScalarType()->getIntegerBitWidth() >
4067 CurTy->getScalarType()->getIntegerBitWidth()) {
4068 NarrowTy = CurTy;
4069 LargeTy = ExtTy;
4070 } else {
4071 NarrowTy = ExtTy;
4072 LargeTy = CurTy;
4073 }
4074
4075 if (!TLI.isZExtFree(NarrowTy, LargeTy))
4076 return false;
4077 }
4078 // All uses are the same or can be derived from one another for free.
4079 return true;
4080}
4081
4082/// \brief Try to form ExtLd by promoting \p Exts until they reach a
4083/// load instruction.
4084/// If an ext(load) can be formed, it is returned via \p LI for the load
4085/// and \p Inst for the extension.
4086/// Otherwise LI == nullptr and Inst == nullptr.
4087/// When some promotion happened, \p TPT contains the proper state to
4088/// revert them.
4089///
4090/// \return true when promoting was necessary to expose the ext(load)
4091/// opportunity, false otherwise.
4092///
4093/// Example:
4094/// \code
4095/// %ld = load i32* %addr
4096/// %add = add nuw i32 %ld, 4
4097/// %zext = zext i32 %add to i64
4098/// \endcode
4099/// =>
4100/// \code
4101/// %ld = load i32* %addr
4102/// %zext = zext i32 %ld to i64
4103/// %add = add nuw i64 %zext, 4
4104/// \encode
4105/// Thanks to the promotion, we can match zext(load i32*) to i64.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004106bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004107 LoadInst *&LI, Instruction *&Inst,
4108 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00004109 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004110 // Iterate over all the extensions to see if one form an ext(load).
4111 for (auto I : Exts) {
4112 // Check if we directly have ext(load).
4113 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
4114 Inst = I;
4115 // No promotion happened here.
4116 return false;
4117 }
4118 // Check whether or not we want to do any promotion.
4119 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
4120 continue;
4121 // Get the action to perform the promotion.
4122 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004123 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004124 // Check if we can promote.
4125 if (!TPH)
4126 continue;
4127 // Save the current state.
4128 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4129 TPT.getRestorationPoint();
4130 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00004131 unsigned NewCreatedInstsCost = 0;
4132 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004133 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004134 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
4135 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004136 assert(PromotedVal &&
4137 "TypePromotionHelper should have filtered out those cases");
4138
4139 // We would be able to merge only one extension in a load.
4140 // Therefore, if we have more than 1 new extension we heuristically
4141 // cut this search path, because it means we degrade the code quality.
4142 // With exactly 2, the transformation is neutral, because we will merge
4143 // one extension but leave one. However, we optimistically keep going,
4144 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00004145 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
4146 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004147 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00004148 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00004149 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004150 // The promotion is not profitable, rollback to the previous state.
4151 TPT.rollback(LastKnownGood);
4152 continue;
4153 }
4154 // The promotion is profitable.
4155 // Check if it exposes an ext(load).
Sanjay Patelfc580a62015-09-21 23:03:16 +00004156 (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
Quentin Colombet1b274f92015-03-10 21:48:15 +00004157 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004158 // If we have created a new extension, i.e., now we have two
4159 // extensions. We must make sure one of them is merged with
4160 // the load, otherwise we may degrade the code quality.
4161 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
4162 // Promotion happened.
4163 return true;
4164 // If this does not help to expose an ext(load) then, rollback.
4165 TPT.rollback(LastKnownGood);
4166 }
4167 // None of the extension can form an ext(load).
4168 LI = nullptr;
4169 Inst = nullptr;
4170 return false;
4171}
4172
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004173/// Move a zext or sext fed by a load into the same basic block as the load,
4174/// unless conditions are unfavorable. This allows SelectionDAG to fold the
4175/// extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004176/// \p I[in/out] the extension may be modified during the process if some
4177/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00004178///
Sanjay Patelfc580a62015-09-21 23:03:16 +00004179bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004180 // Try to promote a chain of computation if it allows to form
4181 // an extended load.
4182 TypePromotionTransaction TPT;
4183 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
4184 TPT.getRestorationPoint();
4185 SmallVector<Instruction *, 1> Exts;
4186 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00004187 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004188 LoadInst *LI = nullptr;
4189 Instruction *OldExt = I;
Sanjay Patelfc580a62015-09-21 23:03:16 +00004190 bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004191 if (!LI || !I) {
4192 assert(!HasPromoted && !LI && "If we did not match any load instruction "
4193 "the code must remain the same");
4194 I = OldExt;
4195 return false;
4196 }
Dan Gohman99429a02009-10-16 20:59:35 +00004197
4198 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004199 // Make the cheap checks first if we did not promote.
4200 // If we promoted, we need to check if it is indeed profitable.
4201 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00004202 return false;
4203
Mehdi Amini44ede332015-07-09 02:09:04 +00004204 EVT VT = TLI->getValueType(*DL, I->getType());
4205 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004206
Dan Gohman99429a02009-10-16 20:59:35 +00004207 // If the load has other users and the truncate is not free, this probably
4208 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00004209 if (!LI->hasOneUse() && TLI &&
4210 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004211 !TLI->isTruncateFree(I->getType(), LI->getType())) {
4212 I = OldExt;
4213 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004214 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004215 }
Dan Gohman99429a02009-10-16 20:59:35 +00004216
4217 // Check whether the target supports casts folded into loads.
4218 unsigned LType;
4219 if (isa<ZExtInst>(I))
4220 LType = ISD::ZEXTLOAD;
4221 else {
4222 assert(isa<SExtInst>(I) && "Unexpected ext type!");
4223 LType = ISD::SEXTLOAD;
4224 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00004225 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004226 I = OldExt;
4227 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00004228 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004229 }
Dan Gohman99429a02009-10-16 20:59:35 +00004230
4231 // Move the extend into the same block as the load, so that SelectionDAG
4232 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00004233 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00004234 I->removeFromParent();
4235 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00004236 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00004237 return true;
4238}
4239
Sanjay Patelfc580a62015-09-21 23:03:16 +00004240bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
Evan Chengd3d80172007-12-05 23:58:20 +00004241 BasicBlock *DefBB = I->getParent();
4242
Bob Wilsonff714f92010-09-21 21:44:14 +00004243 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00004244 // other uses of the source with result of extension.
4245 Value *Src = I->getOperand(0);
4246 if (Src->hasOneUse())
4247 return false;
4248
Evan Cheng2011df42007-12-13 07:50:36 +00004249 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00004250 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00004251 return false;
4252
Evan Cheng7bc89422007-12-12 00:51:06 +00004253 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00004254 // this block.
4255 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00004256 return false;
4257
Evan Chengd3d80172007-12-05 23:58:20 +00004258 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004259 for (User *U : I->users()) {
4260 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00004261
4262 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004263 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00004264 if (UserBB == DefBB) continue;
4265 DefIsLiveOut = true;
4266 break;
4267 }
4268 if (!DefIsLiveOut)
4269 return false;
4270
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00004271 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004272 for (User *U : Src->users()) {
4273 Instruction *UI = cast<Instruction>(U);
4274 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00004275 if (UserBB == DefBB) continue;
4276 // Be conservative. We don't want this xform to end up introducing
4277 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004278 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00004279 return false;
4280 }
4281
Evan Chengd3d80172007-12-05 23:58:20 +00004282 // InsertedTruncs - Only insert one trunc in each block once.
4283 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
4284
4285 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004286 for (Use &U : Src->uses()) {
4287 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00004288
4289 // Figure out which BB this ext is used in.
4290 BasicBlock *UserBB = User->getParent();
4291 if (UserBB == DefBB) continue;
4292
4293 // Both src and def are live in this block. Rewrite the use.
4294 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
4295
4296 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00004297 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004298 assert(InsertPt != UserBB->end());
4299 InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004300 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00004301 }
4302
4303 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004304 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00004305 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00004306 MadeChange = true;
4307 }
4308
4309 return MadeChange;
4310}
4311
Geoff Berry5256fca2015-11-20 22:34:39 +00004312// Find loads whose uses only use some of the loaded value's bits. Add an "and"
4313// just after the load if the target can fold this into one extload instruction,
4314// with the hope of eliminating some of the other later "and" instructions using
4315// the loaded value. "and"s that are made trivially redundant by the insertion
4316// of the new "and" are removed by this function, while others (e.g. those whose
4317// path from the load goes through a phi) are left for isel to potentially
4318// remove.
4319//
4320// For example:
4321//
4322// b0:
4323// x = load i32
4324// ...
4325// b1:
4326// y = and x, 0xff
4327// z = use y
4328//
4329// becomes:
4330//
4331// b0:
4332// x = load i32
4333// x' = and x, 0xff
4334// ...
4335// b1:
4336// z = use x'
4337//
4338// whereas:
4339//
4340// b0:
4341// x1 = load i32
4342// ...
4343// b1:
4344// x2 = load i32
4345// ...
4346// b2:
4347// x = phi x1, x2
4348// y = and x, 0xff
4349//
4350// becomes (after a call to optimizeLoadExt for each load):
4351//
4352// b0:
4353// x1 = load i32
4354// x1' = and x1, 0xff
4355// ...
4356// b1:
4357// x2 = load i32
4358// x2' = and x2, 0xff
4359// ...
4360// b2:
4361// x = phi x1', x2'
4362// y = and x, 0xff
4363//
4364
4365bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
4366
4367 if (!Load->isSimple() ||
4368 !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
4369 return false;
4370
4371 // Skip loads we've already transformed or have no reason to transform.
4372 if (Load->hasOneUse()) {
4373 User *LoadUser = *Load->user_begin();
4374 if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
4375 !dyn_cast<PHINode>(LoadUser))
4376 return false;
4377 }
4378
4379 // Look at all uses of Load, looking through phis, to determine how many bits
4380 // of the loaded value are needed.
4381 SmallVector<Instruction *, 8> WorkList;
4382 SmallPtrSet<Instruction *, 16> Visited;
4383 SmallVector<Instruction *, 8> AndsToMaybeRemove;
4384 for (auto *U : Load->users())
4385 WorkList.push_back(cast<Instruction>(U));
4386
4387 EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
4388 unsigned BitWidth = LoadResultVT.getSizeInBits();
4389 APInt DemandBits(BitWidth, 0);
4390 APInt WidestAndBits(BitWidth, 0);
4391
4392 while (!WorkList.empty()) {
4393 Instruction *I = WorkList.back();
4394 WorkList.pop_back();
4395
4396 // Break use-def graph loops.
4397 if (!Visited.insert(I).second)
4398 continue;
4399
4400 // For a PHI node, push all of its users.
4401 if (auto *Phi = dyn_cast<PHINode>(I)) {
4402 for (auto *U : Phi->users())
4403 WorkList.push_back(cast<Instruction>(U));
4404 continue;
4405 }
4406
4407 switch (I->getOpcode()) {
4408 case llvm::Instruction::And: {
4409 auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
4410 if (!AndC)
4411 return false;
4412 APInt AndBits = AndC->getValue();
4413 DemandBits |= AndBits;
4414 // Keep track of the widest and mask we see.
4415 if (AndBits.ugt(WidestAndBits))
4416 WidestAndBits = AndBits;
4417 if (AndBits == WidestAndBits && I->getOperand(0) == Load)
4418 AndsToMaybeRemove.push_back(I);
4419 break;
4420 }
4421
4422 case llvm::Instruction::Shl: {
4423 auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
4424 if (!ShlC)
4425 return false;
4426 uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
4427 auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
4428 DemandBits |= ShlDemandBits;
4429 break;
4430 }
4431
4432 case llvm::Instruction::Trunc: {
4433 EVT TruncVT = TLI->getValueType(*DL, I->getType());
4434 unsigned TruncBitWidth = TruncVT.getSizeInBits();
4435 auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
4436 DemandBits |= TruncBits;
4437 break;
4438 }
4439
4440 default:
4441 return false;
4442 }
4443 }
4444
4445 uint32_t ActiveBits = DemandBits.getActiveBits();
4446 // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
4447 // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
4448 // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
4449 // (and (load x) 1) is not matched as a single instruction, rather as a LDR
4450 // followed by an AND.
4451 // TODO: Look into removing this restriction by fixing backends to either
4452 // return false for isLoadExtLegal for i1 or have them select this pattern to
4453 // a single instruction.
4454 //
4455 // Also avoid hoisting if we didn't see any ands with the exact DemandBits
4456 // mask, since these are the only ands that will be removed by isel.
4457 if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
4458 WidestAndBits != DemandBits)
4459 return false;
4460
4461 LLVMContext &Ctx = Load->getType()->getContext();
4462 Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
4463 EVT TruncVT = TLI->getValueType(*DL, TruncTy);
4464
4465 // Reject cases that won't be matched as extloads.
4466 if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
4467 !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
4468 return false;
4469
4470 IRBuilder<> Builder(Load->getNextNode());
4471 auto *NewAnd = dyn_cast<Instruction>(
4472 Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
4473
4474 // Replace all uses of load with new and (except for the use of load in the
4475 // new and itself).
4476 Load->replaceAllUsesWith(NewAnd);
4477 NewAnd->setOperand(0, Load);
4478
4479 // Remove any and instructions that are now redundant.
4480 for (auto *And : AndsToMaybeRemove)
4481 // Check that the and mask is the same as the one we decided to put on the
4482 // new and.
4483 if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
4484 And->replaceAllUsesWith(NewAnd);
4485 if (&*CurInstIterator == And)
4486 CurInstIterator = std::next(And->getIterator());
4487 And->eraseFromParent();
4488 ++NumAndUses;
4489 }
4490
4491 ++NumAndsAdded;
4492 return true;
4493}
4494
Sanjay Patel69a50a12015-10-19 21:59:12 +00004495/// Check if V (an operand of a select instruction) is an expensive instruction
4496/// that is only used once.
4497static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
4498 auto *I = dyn_cast<Instruction>(V);
4499 // If it's safe to speculatively execute, then it should not have side
4500 // effects; therefore, it's safe to sink and possibly *not* execute.
Rafael Espindola84921b92015-10-24 23:11:13 +00004501 return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
4502 TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
Sanjay Patel69a50a12015-10-19 21:59:12 +00004503}
4504
Sanjay Patel4ac6b112015-09-21 22:47:23 +00004505/// Returns true if a SelectInst should be turned into an explicit branch.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004506static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
4507 SelectInst *SI) {
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004508 // FIXME: This should use the same heuristics as IfConversion to determine
4509 // whether a select is better represented as a branch. This requires that
4510 // branch probability metadata is preserved for the select, which is not the
4511 // case currently.
4512
4513 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
4514
Sanjay Patel4e652762015-09-28 22:14:51 +00004515 // If a branch is predictable, an out-of-order CPU can avoid blocking on its
4516 // comparison condition. If the compare has more than one use, there's
4517 // probably another cmov or setcc around, so it's not worth emitting a branch.
Sanjay Patel5e5f0e92015-09-28 21:44:46 +00004518 if (!Cmp || !Cmp->hasOneUse())
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004519 return false;
4520
Sanjay Patel69a50a12015-10-19 21:59:12 +00004521 // If either operand of the select is expensive and only needed on one side
4522 // of the select, we should form a branch.
4523 if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
4524 sinkSelectOperand(TTI, SI->getFalseValue()))
4525 return true;
4526
4527 return false;
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004528}
4529
4530
Nadav Rotem9d832022012-09-02 12:10:19 +00004531/// If we have a SelectInst that will likely profit from branch prediction,
4532/// turn it into a branch.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004533bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00004534 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
4535
4536 // Can we convert the 'select' to CF ?
4537 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004538 return false;
4539
Nadav Rotem9d832022012-09-02 12:10:19 +00004540 TargetLowering::SelectSupportKind SelectKind;
4541 if (VectorCond)
4542 SelectKind = TargetLowering::VectorMaskSelect;
4543 else if (SI->getType()->isVectorTy())
4544 SelectKind = TargetLowering::ScalarCondVectorVal;
4545 else
4546 SelectKind = TargetLowering::ScalarValSelect;
4547
4548 // Do we have efficient codegen support for this kind of 'selects' ?
4549 if (TLI->isSelectSupported(SelectKind)) {
4550 // We have efficient codegen support for the select instruction.
4551 // Check if it is profitable to keep this 'select'.
4552 if (!TLI->isPredictableSelectExpensive() ||
Sanjay Patel69a50a12015-10-19 21:59:12 +00004553 !isFormingBranchFromSelectProfitable(TTI, SI))
Nadav Rotem9d832022012-09-02 12:10:19 +00004554 return false;
4555 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004556
4557 ModifiedDT = true;
4558
Sanjay Patel69a50a12015-10-19 21:59:12 +00004559 // Transform a sequence like this:
4560 // start:
4561 // %cmp = cmp uge i32 %a, %b
4562 // %sel = select i1 %cmp, i32 %c, i32 %d
4563 //
4564 // Into:
4565 // start:
4566 // %cmp = cmp uge i32 %a, %b
4567 // br i1 %cmp, label %select.true, label %select.false
4568 // select.true:
4569 // br label %select.end
4570 // select.false:
4571 // br label %select.end
4572 // select.end:
4573 // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
4574 //
4575 // In addition, we may sink instructions that produce %c or %d from
4576 // the entry block into the destination(s) of the new branch.
4577 // If the true or false blocks do not contain a sunken instruction, that
4578 // block and its branch may be optimized away. In that case, one side of the
4579 // first branch will point directly to select.end, and the corresponding PHI
4580 // predecessor block will be the start block.
4581
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004582 // First, we split the block containing the select into 2 blocks.
4583 BasicBlock *StartBlock = SI->getParent();
4584 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
Sanjay Patel69a50a12015-10-19 21:59:12 +00004585 BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004586
Sanjay Patel69a50a12015-10-19 21:59:12 +00004587 // Delete the unconditional branch that was just created by the split.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004588 StartBlock->getTerminator()->eraseFromParent();
Sanjay Patel69a50a12015-10-19 21:59:12 +00004589
4590 // These are the new basic blocks for the conditional branch.
4591 // At least one will become an actual new basic block.
4592 BasicBlock *TrueBlock = nullptr;
4593 BasicBlock *FalseBlock = nullptr;
4594
4595 // Sink expensive instructions into the conditional blocks to avoid executing
4596 // them speculatively.
4597 if (sinkSelectOperand(TTI, SI->getTrueValue())) {
4598 TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
4599 EndBlock->getParent(), EndBlock);
4600 auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
4601 auto *TrueInst = cast<Instruction>(SI->getTrueValue());
4602 TrueInst->moveBefore(TrueBranch);
4603 }
4604 if (sinkSelectOperand(TTI, SI->getFalseValue())) {
4605 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
4606 EndBlock->getParent(), EndBlock);
4607 auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
4608 auto *FalseInst = cast<Instruction>(SI->getFalseValue());
4609 FalseInst->moveBefore(FalseBranch);
4610 }
4611
4612 // If there was nothing to sink, then arbitrarily choose the 'false' side
4613 // for a new input value to the PHI.
4614 if (TrueBlock == FalseBlock) {
4615 assert(TrueBlock == nullptr &&
4616 "Unexpected basic block transform while optimizing select");
4617
4618 FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
4619 EndBlock->getParent(), EndBlock);
4620 BranchInst::Create(EndBlock, FalseBlock);
4621 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004622
4623 // Insert the real conditional branch based on the original condition.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004624 // If we did not create a new block for one of the 'true' or 'false' paths
4625 // of the condition, it means that side of the branch goes to the end block
4626 // directly and the path originates from the start block from the point of
4627 // view of the new PHI.
4628 if (TrueBlock == nullptr) {
4629 BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
4630 TrueBlock = StartBlock;
4631 } else if (FalseBlock == nullptr) {
4632 BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
4633 FalseBlock = StartBlock;
4634 } else {
4635 BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
4636 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004637
4638 // The select itself is replaced with a PHI Node.
Sanjay Patel69a50a12015-10-19 21:59:12 +00004639 PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004640 PN->takeName(SI);
Sanjay Patel69a50a12015-10-19 21:59:12 +00004641 PN->addIncoming(SI->getTrueValue(), TrueBlock);
4642 PN->addIncoming(SI->getFalseValue(), FalseBlock);
4643
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004644 SI->replaceAllUsesWith(PN);
4645 SI->eraseFromParent();
4646
4647 // Instruct OptimizeBlock to skip to the next block.
4648 CurInstIterator = StartBlock->end();
4649 ++NumSelectsExpanded;
4650 return true;
4651}
4652
Benjamin Kramer573ff362014-03-01 17:24:40 +00004653static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004654 SmallVector<int, 16> Mask(SVI->getShuffleMask());
4655 int SplatElem = -1;
4656 for (unsigned i = 0; i < Mask.size(); ++i) {
4657 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
4658 return false;
4659 SplatElem = Mask[i];
4660 }
4661
4662 return true;
4663}
4664
4665/// Some targets have expensive vector shifts if the lanes aren't all the same
4666/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
4667/// it's often worth sinking a shufflevector splat down to its use so that
4668/// codegen can spot all lanes are identical.
Sanjay Patelfc580a62015-09-21 23:03:16 +00004669bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00004670 BasicBlock *DefBB = SVI->getParent();
4671
4672 // Only do this xform if variable vector shifts are particularly expensive.
4673 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
4674 return false;
4675
4676 // We only expect better codegen by sinking a shuffle if we can recognise a
4677 // constant splat.
4678 if (!isBroadcastShuffle(SVI))
4679 return false;
4680
4681 // InsertedShuffles - Only insert a shuffle in each block once.
4682 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
4683
4684 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00004685 for (User *U : SVI->users()) {
4686 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004687
4688 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004689 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00004690 if (UserBB == DefBB) continue;
4691
4692 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004693 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00004694
4695 // Everything checks out, sink the shuffle if the user's block doesn't
4696 // already have a copy.
4697 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
4698
4699 if (!InsertedShuffle) {
4700 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00004701 assert(InsertPt != UserBB->end());
4702 InsertedShuffle =
4703 new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4704 SVI->getOperand(2), "", &*InsertPt);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004705 }
4706
Chandler Carruthcdf47882014-03-09 03:16:01 +00004707 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00004708 MadeChange = true;
4709 }
4710
4711 // If we removed all uses, nuke the shuffle.
4712 if (SVI->use_empty()) {
4713 SVI->eraseFromParent();
4714 MadeChange = true;
4715 }
4716
4717 return MadeChange;
4718}
4719
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00004720bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
4721 if (!TLI || !DL)
4722 return false;
4723
4724 Value *Cond = SI->getCondition();
4725 Type *OldType = Cond->getType();
4726 LLVMContext &Context = Cond->getContext();
4727 MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
4728 unsigned RegWidth = RegType.getSizeInBits();
4729
4730 if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
4731 return false;
4732
4733 // If the register width is greater than the type width, expand the condition
4734 // of the switch instruction and each case constant to the width of the
4735 // register. By widening the type of the switch condition, subsequent
4736 // comparisons (for case comparisons) will not need to be extended to the
4737 // preferred register width, so we will potentially eliminate N-1 extends,
4738 // where N is the number of cases in the switch.
4739 auto *NewType = Type::getIntNTy(Context, RegWidth);
4740
4741 // Zero-extend the switch condition and case constants unless the switch
4742 // condition is a function argument that is already being sign-extended.
4743 // In that case, we can avoid an unnecessary mask/extension by sign-extending
4744 // everything instead.
4745 Instruction::CastOps ExtType = Instruction::ZExt;
4746 if (auto *Arg = dyn_cast<Argument>(Cond))
4747 if (Arg->hasSExtAttr())
4748 ExtType = Instruction::SExt;
4749
4750 auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
4751 ExtInst->insertBefore(SI);
4752 SI->setCondition(ExtInst);
4753 for (SwitchInst::CaseIt Case : SI->cases()) {
4754 APInt NarrowConst = Case.getCaseValue()->getValue();
4755 APInt WideConst = (ExtType == Instruction::ZExt) ?
4756 NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
4757 Case.setValue(ConstantInt::get(Context, WideConst));
4758 }
4759
4760 return true;
4761}
4762
Quentin Colombetc32615d2014-10-31 17:52:53 +00004763namespace {
4764/// \brief Helper class to promote a scalar operation to a vector one.
4765/// This class is used to move downward extractelement transition.
4766/// E.g.,
4767/// a = vector_op <2 x i32>
4768/// b = extractelement <2 x i32> a, i32 0
4769/// c = scalar_op b
4770/// store c
4771///
4772/// =>
4773/// a = vector_op <2 x i32>
4774/// c = vector_op a (equivalent to scalar_op on the related lane)
4775/// * d = extractelement <2 x i32> c, i32 0
4776/// * store d
4777/// Assuming both extractelement and store can be combine, we get rid of the
4778/// transition.
4779class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004780 /// DataLayout associated with the current module.
4781 const DataLayout &DL;
4782
Quentin Colombetc32615d2014-10-31 17:52:53 +00004783 /// Used to perform some checks on the legality of vector operations.
4784 const TargetLowering &TLI;
4785
4786 /// Used to estimated the cost of the promoted chain.
4787 const TargetTransformInfo &TTI;
4788
4789 /// The transition being moved downwards.
4790 Instruction *Transition;
4791 /// The sequence of instructions to be promoted.
4792 SmallVector<Instruction *, 4> InstsToBePromoted;
4793 /// Cost of combining a store and an extract.
4794 unsigned StoreExtractCombineCost;
4795 /// Instruction that will be combined with the transition.
4796 Instruction *CombineInst;
4797
4798 /// \brief The instruction that represents the current end of the transition.
4799 /// Since we are faking the promotion until we reach the end of the chain
4800 /// of computation, we need a way to get the current end of the transition.
4801 Instruction *getEndOfTransition() const {
4802 if (InstsToBePromoted.empty())
4803 return Transition;
4804 return InstsToBePromoted.back();
4805 }
4806
4807 /// \brief Return the index of the original value in the transition.
4808 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4809 /// c, is at index 0.
4810 unsigned getTransitionOriginalValueIdx() const {
4811 assert(isa<ExtractElementInst>(Transition) &&
4812 "Other kind of transitions are not supported yet");
4813 return 0;
4814 }
4815
4816 /// \brief Return the index of the index in the transition.
4817 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4818 /// is at index 1.
4819 unsigned getTransitionIdx() const {
4820 assert(isa<ExtractElementInst>(Transition) &&
4821 "Other kind of transitions are not supported yet");
4822 return 1;
4823 }
4824
4825 /// \brief Get the type of the transition.
4826 /// This is the type of the original value.
4827 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4828 /// transition is <2 x i32>.
4829 Type *getTransitionType() const {
4830 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4831 }
4832
4833 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4834 /// I.e., we have the following sequence:
4835 /// Def = Transition <ty1> a to <ty2>
4836 /// b = ToBePromoted <ty2> Def, ...
4837 /// =>
4838 /// b = ToBePromoted <ty1> a, ...
4839 /// Def = Transition <ty1> ToBePromoted to <ty2>
4840 void promoteImpl(Instruction *ToBePromoted);
4841
4842 /// \brief Check whether or not it is profitable to promote all the
4843 /// instructions enqueued to be promoted.
4844 bool isProfitableToPromote() {
4845 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4846 unsigned Index = isa<ConstantInt>(ValIdx)
4847 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4848 : -1;
4849 Type *PromotedType = getTransitionType();
4850
4851 StoreInst *ST = cast<StoreInst>(CombineInst);
4852 unsigned AS = ST->getPointerAddressSpace();
4853 unsigned Align = ST->getAlignment();
4854 // Check if this store is supported.
4855 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004856 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4857 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004858 // If this is not supported, there is no way we can combine
4859 // the extract with the store.
4860 return false;
4861 }
4862
4863 // The scalar chain of computation has to pay for the transition
4864 // scalar to vector.
4865 // The vector chain has to account for the combining cost.
4866 uint64_t ScalarCost =
4867 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4868 uint64_t VectorCost = StoreExtractCombineCost;
4869 for (const auto &Inst : InstsToBePromoted) {
4870 // Compute the cost.
4871 // By construction, all instructions being promoted are arithmetic ones.
4872 // Moreover, one argument is a constant that can be viewed as a splat
4873 // constant.
4874 Value *Arg0 = Inst->getOperand(0);
4875 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4876 isa<ConstantFP>(Arg0);
4877 TargetTransformInfo::OperandValueKind Arg0OVK =
4878 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4879 : TargetTransformInfo::OK_AnyValue;
4880 TargetTransformInfo::OperandValueKind Arg1OVK =
4881 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4882 : TargetTransformInfo::OK_AnyValue;
4883 ScalarCost += TTI.getArithmeticInstrCost(
4884 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4885 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4886 Arg0OVK, Arg1OVK);
4887 }
4888 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4889 << ScalarCost << "\nVector: " << VectorCost << '\n');
4890 return ScalarCost > VectorCost;
4891 }
4892
4893 /// \brief Generate a constant vector with \p Val with the same
4894 /// number of elements as the transition.
4895 /// \p UseSplat defines whether or not \p Val should be replicated
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00004896 /// across the whole vector.
Quentin Colombetc32615d2014-10-31 17:52:53 +00004897 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4898 /// otherwise we generate a vector with as many undef as possible:
4899 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4900 /// used at the index of the extract.
4901 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4902 unsigned ExtractIdx = UINT_MAX;
4903 if (!UseSplat) {
4904 // If we cannot determine where the constant must be, we have to
4905 // use a splat constant.
4906 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4907 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4908 ExtractIdx = CstVal->getSExtValue();
4909 else
4910 UseSplat = true;
4911 }
4912
4913 unsigned End = getTransitionType()->getVectorNumElements();
4914 if (UseSplat)
4915 return ConstantVector::getSplat(End, Val);
4916
4917 SmallVector<Constant *, 4> ConstVec;
4918 UndefValue *UndefVal = UndefValue::get(Val->getType());
4919 for (unsigned Idx = 0; Idx != End; ++Idx) {
4920 if (Idx == ExtractIdx)
4921 ConstVec.push_back(Val);
4922 else
4923 ConstVec.push_back(UndefVal);
4924 }
4925 return ConstantVector::get(ConstVec);
4926 }
4927
4928 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4929 /// in \p Use can trigger undefined behavior.
4930 static bool canCauseUndefinedBehavior(const Instruction *Use,
4931 unsigned OperandIdx) {
4932 // This is not safe to introduce undef when the operand is on
4933 // the right hand side of a division-like instruction.
4934 if (OperandIdx != 1)
4935 return false;
4936 switch (Use->getOpcode()) {
4937 default:
4938 return false;
4939 case Instruction::SDiv:
4940 case Instruction::UDiv:
4941 case Instruction::SRem:
4942 case Instruction::URem:
4943 return true;
4944 case Instruction::FDiv:
4945 case Instruction::FRem:
4946 return !Use->hasNoNaNs();
4947 }
4948 llvm_unreachable(nullptr);
4949 }
4950
4951public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004952 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4953 const TargetTransformInfo &TTI, Instruction *Transition,
4954 unsigned CombineCost)
4955 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004956 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4957 assert(Transition && "Do not know how to promote null");
4958 }
4959
4960 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4961 bool canPromote(const Instruction *ToBePromoted) const {
4962 // We could support CastInst too.
4963 return isa<BinaryOperator>(ToBePromoted);
4964 }
4965
4966 /// \brief Check if it is profitable to promote \p ToBePromoted
4967 /// by moving downward the transition through.
4968 bool shouldPromote(const Instruction *ToBePromoted) const {
4969 // Promote only if all the operands can be statically expanded.
4970 // Indeed, we do not want to introduce any new kind of transitions.
4971 for (const Use &U : ToBePromoted->operands()) {
4972 const Value *Val = U.get();
4973 if (Val == getEndOfTransition()) {
4974 // If the use is a division and the transition is on the rhs,
4975 // we cannot promote the operation, otherwise we may create a
4976 // division by zero.
4977 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4978 return false;
4979 continue;
4980 }
4981 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4982 !isa<ConstantFP>(Val))
4983 return false;
4984 }
4985 // Check that the resulting operation is legal.
4986 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4987 if (!ISDOpcode)
4988 return false;
4989 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004990 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004991 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004992 }
4993
4994 /// \brief Check whether or not \p Use can be combined
4995 /// with the transition.
4996 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4997 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4998
4999 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
5000 void enqueueForPromotion(Instruction *ToBePromoted) {
5001 InstsToBePromoted.push_back(ToBePromoted);
5002 }
5003
5004 /// \brief Set the instruction that will be combined with the transition.
5005 void recordCombineInstruction(Instruction *ToBeCombined) {
5006 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
5007 CombineInst = ToBeCombined;
5008 }
5009
5010 /// \brief Promote all the instructions enqueued for promotion if it is
5011 /// is profitable.
5012 /// \return True if the promotion happened, false otherwise.
5013 bool promote() {
5014 // Check if there is something to promote.
5015 // Right now, if we do not have anything to combine with,
5016 // we assume the promotion is not profitable.
5017 if (InstsToBePromoted.empty() || !CombineInst)
5018 return false;
5019
5020 // Check cost.
5021 if (!StressStoreExtract && !isProfitableToPromote())
5022 return false;
5023
5024 // Promote.
5025 for (auto &ToBePromoted : InstsToBePromoted)
5026 promoteImpl(ToBePromoted);
5027 InstsToBePromoted.clear();
5028 return true;
5029 }
5030};
5031} // End of anonymous namespace.
5032
5033void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
5034 // At this point, we know that all the operands of ToBePromoted but Def
5035 // can be statically promoted.
5036 // For Def, we need to use its parameter in ToBePromoted:
5037 // b = ToBePromoted ty1 a
5038 // Def = Transition ty1 b to ty2
5039 // Move the transition down.
5040 // 1. Replace all uses of the promoted operation by the transition.
5041 // = ... b => = ... Def.
5042 assert(ToBePromoted->getType() == Transition->getType() &&
5043 "The type of the result of the transition does not match "
5044 "the final type");
5045 ToBePromoted->replaceAllUsesWith(Transition);
5046 // 2. Update the type of the uses.
5047 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
5048 Type *TransitionTy = getTransitionType();
5049 ToBePromoted->mutateType(TransitionTy);
5050 // 3. Update all the operands of the promoted operation with promoted
5051 // operands.
5052 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
5053 for (Use &U : ToBePromoted->operands()) {
5054 Value *Val = U.get();
5055 Value *NewVal = nullptr;
5056 if (Val == Transition)
5057 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
5058 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
5059 isa<ConstantFP>(Val)) {
5060 // Use a splat constant if it is not safe to use undef.
5061 NewVal = getConstantVector(
5062 cast<Constant>(Val),
5063 isa<UndefValue>(Val) ||
5064 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
5065 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00005066 llvm_unreachable("Did you modified shouldPromote and forgot to update "
5067 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00005068 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
5069 }
5070 Transition->removeFromParent();
5071 Transition->insertAfter(ToBePromoted);
5072 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
5073}
5074
5075/// Some targets can do store(extractelement) with one instruction.
5076/// Try to push the extractelement towards the stores when the target
5077/// has this feature and this is profitable.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005078bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00005079 unsigned CombineCost = UINT_MAX;
5080 if (DisableStoreExtract || !TLI ||
5081 (!StressStoreExtract &&
5082 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
5083 Inst->getOperand(1), CombineCost)))
5084 return false;
5085
5086 // At this point we know that Inst is a vector to scalar transition.
5087 // Try to move it down the def-use chain, until:
5088 // - We can combine the transition with its single use
5089 // => we got rid of the transition.
5090 // - We escape the current basic block
5091 // => we would need to check that we are moving it at a cheaper place and
5092 // we do not do that for now.
5093 BasicBlock *Parent = Inst->getParent();
5094 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00005095 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005096 // If the transition has more than one use, assume this is not going to be
5097 // beneficial.
5098 while (Inst->hasOneUse()) {
5099 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
5100 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
5101
5102 if (ToBePromoted->getParent() != Parent) {
5103 DEBUG(dbgs() << "Instruction to promote is in a different block ("
5104 << ToBePromoted->getParent()->getName()
5105 << ") than the transition (" << Parent->getName() << ").\n");
5106 return false;
5107 }
5108
5109 if (VPH.canCombine(ToBePromoted)) {
5110 DEBUG(dbgs() << "Assume " << *Inst << '\n'
5111 << "will be combined with: " << *ToBePromoted << '\n');
5112 VPH.recordCombineInstruction(ToBePromoted);
5113 bool Changed = VPH.promote();
5114 NumStoreExtractExposed += Changed;
5115 return Changed;
5116 }
5117
5118 DEBUG(dbgs() << "Try promoting.\n");
5119 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
5120 return false;
5121
5122 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
5123
5124 VPH.enqueueForPromotion(ToBePromoted);
5125 Inst = ToBePromoted;
5126 }
5127 return false;
5128}
5129
Sanjay Patelfc580a62015-09-21 23:03:16 +00005130bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00005131 // Bail out if we inserted the instruction to prevent optimizations from
5132 // stepping on each other's toes.
5133 if (InsertedInsts.count(I))
5134 return false;
5135
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005136 if (PHINode *P = dyn_cast<PHINode>(I)) {
5137 // It is possible for very late stage optimizations (such as SimplifyCFG)
5138 // to introduce PHI nodes too late to be cleaned up. If we detect such a
5139 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00005140 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005141 P->replaceAllUsesWith(V);
5142 P->eraseFromParent();
5143 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00005144 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005145 }
Chris Lattneree588de2011-01-15 07:29:01 +00005146 return false;
5147 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005148
Chris Lattneree588de2011-01-15 07:29:01 +00005149 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005150 // If the source of the cast is a constant, then this should have
5151 // already been constant folded. The only reason NOT to constant fold
5152 // it is if something (e.g. LSR) was careful to place the constant
5153 // evaluation in a block other than then one that uses it (e.g. to hoist
5154 // the address of globals out of a loop). If this is the case, we don't
5155 // want to forward-subst the cast.
5156 if (isa<Constant>(CI->getOperand(0)))
5157 return false;
5158
Mehdi Amini44ede332015-07-09 02:09:04 +00005159 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00005160 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005161
Chris Lattneree588de2011-01-15 07:29:01 +00005162 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005163 /// Sink a zext or sext into its user blocks if the target type doesn't
5164 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00005165 if (TLI &&
5166 TLI->getTypeAction(CI->getContext(),
5167 TLI->getValueType(*DL, CI->getType())) ==
5168 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005169 return SinkCast(CI);
5170 } else {
Sanjay Patelfc580a62015-09-21 23:03:16 +00005171 bool MadeChange = moveExtToFormExtLoad(I);
5172 return MadeChange | optimizeExtUses(I);
Manuel Jacoba7c48f92014-03-13 13:36:25 +00005173 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005174 }
Chris Lattneree588de2011-01-15 07:29:01 +00005175 return false;
5176 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005177
Chris Lattneree588de2011-01-15 07:29:01 +00005178 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00005179 if (!TLI || !TLI->hasMultipleConditionRegisters())
Peter Zotovf87e5502016-04-03 17:11:53 +00005180 return OptimizeCmpExpression(CI, TLI);
Nadav Rotem465834c2012-07-24 10:51:42 +00005181
Chris Lattneree588de2011-01-15 07:29:01 +00005182 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005183 stripInvariantGroupMetadata(*LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005184 if (TLI) {
Geoff Berry5256fca2015-11-20 22:34:39 +00005185 bool Modified = optimizeLoadExt(LI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005186 unsigned AS = LI->getPointerAddressSpace();
Geoff Berry5256fca2015-11-20 22:34:39 +00005187 Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
5188 return Modified;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005189 }
Hans Wennborgf3254832012-10-30 11:23:25 +00005190 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00005191 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005192
Chris Lattneree588de2011-01-15 07:29:01 +00005193 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005194 stripInvariantGroupMetadata(*SI);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005195 if (TLI) {
5196 unsigned AS = SI->getPointerAddressSpace();
Sanjay Patelfc580a62015-09-21 23:03:16 +00005197 return optimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00005198 SI->getOperand(0)->getType(), AS);
5199 }
Chris Lattneree588de2011-01-15 07:29:01 +00005200 return false;
5201 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005202
Yi Jiangd069f632014-04-21 19:34:27 +00005203 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
5204
5205 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
5206 BinOp->getOpcode() == Instruction::LShr)) {
5207 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
5208 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00005209 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00005210
5211 return false;
5212 }
5213
Chris Lattneree588de2011-01-15 07:29:01 +00005214 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005215 if (GEPI->hasAllZeroIndices()) {
5216 /// The GEP operand must be a pointer, so must its result -> BitCast
5217 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
5218 GEPI->getName(), GEPI);
5219 GEPI->replaceAllUsesWith(NC);
5220 GEPI->eraseFromParent();
5221 ++NumGEPsElim;
Sanjay Patelfc580a62015-09-21 23:03:16 +00005222 optimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00005223 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00005224 }
Chris Lattneree588de2011-01-15 07:29:01 +00005225 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005226 }
Nadav Rotem465834c2012-07-24 10:51:42 +00005227
Chris Lattneree588de2011-01-15 07:29:01 +00005228 if (CallInst *CI = dyn_cast<CallInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005229 return optimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005230
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005231 if (SelectInst *SI = dyn_cast<SelectInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005232 return optimizeSelectInst(SI);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00005233
Tim Northoveraeb8e062014-02-19 10:02:43 +00005234 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005235 return optimizeShuffleVectorInst(SVI);
Tim Northoveraeb8e062014-02-19 10:02:43 +00005236
Sanjay Patel0ed9aea2015-11-02 23:22:49 +00005237 if (auto *Switch = dyn_cast<SwitchInst>(I))
5238 return optimizeSwitchInst(Switch);
5239
Quentin Colombetc32615d2014-10-31 17:52:53 +00005240 if (isa<ExtractElementInst>(I))
Sanjay Patelfc580a62015-09-21 23:03:16 +00005241 return optimizeExtractElementInst(I);
Quentin Colombetc32615d2014-10-31 17:52:53 +00005242
Chris Lattneree588de2011-01-15 07:29:01 +00005243 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00005244}
5245
James Molloyf01488e2016-01-15 09:20:19 +00005246/// Given an OR instruction, check to see if this is a bitreverse
5247/// idiom. If so, insert the new intrinsic and return true.
5248static bool makeBitReverse(Instruction &I, const DataLayout &DL,
5249 const TargetLowering &TLI) {
5250 if (!I.getType()->isIntegerTy() ||
5251 !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
5252 TLI.getValueType(DL, I.getType(), true)))
5253 return false;
5254
5255 SmallVector<Instruction*, 4> Insts;
5256 if (!recognizeBitReverseOrBSwapIdiom(&I, false, true, Insts))
5257 return false;
5258 Instruction *LastInst = Insts.back();
5259 I.replaceAllUsesWith(LastInst);
5260 RecursivelyDeleteTriviallyDeadInstructions(&I);
5261 return true;
5262}
5263
Chris Lattnerf2836d12007-03-31 04:06:36 +00005264// In this pass we look for GEP and cast instructions that are used
5265// across basic blocks and rewrite them to improve basic-block-at-a-time
5266// selection.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005267bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00005268 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00005269 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00005270
Chris Lattner7a277142011-01-15 07:14:54 +00005271 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005272 while (CurInstIterator != BB.end()) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005273 MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00005274 if (ModifiedDT)
5275 return true;
5276 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00005277
James Molloyf01488e2016-01-15 09:20:19 +00005278 bool MadeBitReverse = true;
5279 while (TLI && MadeBitReverse) {
5280 MadeBitReverse = false;
5281 for (auto &I : reverse(BB)) {
5282 if (makeBitReverse(I, *DL, *TLI)) {
5283 MadeBitReverse = MadeChange = true;
George Burgess IVd4febd12016-03-22 21:25:08 +00005284 ModifiedDT = true;
James Molloyf01488e2016-01-15 09:20:19 +00005285 break;
5286 }
5287 }
5288 }
James Molloy3ef84c42016-01-15 10:36:01 +00005289 MadeChange |= dupRetToEnableTailCallOpts(&BB);
Junmo Park7d6c5f12016-01-28 09:42:39 +00005290
Chris Lattnerf2836d12007-03-31 04:06:36 +00005291 return MadeChange;
5292}
Devang Patel53771ba2011-08-18 00:50:51 +00005293
5294// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00005295// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00005296// find a node corresponding to the value.
Sanjay Patelfc580a62015-09-21 23:03:16 +00005297bool CodeGenPrepare::placeDbgValues(Function &F) {
Devang Patel53771ba2011-08-18 00:50:51 +00005298 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005299 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00005300 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00005301 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005302 Instruction *Insn = &*BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00005303 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00005304 // Leave dbg.values that refer to an alloca alone. These
5305 // instrinsics describe the address of a variable (= the alloca)
5306 // being taken. They should not be moved next to the alloca
5307 // (and to the beginning of the scope), but rather stay close to
5308 // where said address is used.
5309 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00005310 PrevNonDbgInst = Insn;
5311 continue;
5312 }
5313
5314 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
5315 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
Reid Kleckner8de1fe22015-12-08 23:00:03 +00005316 // If VI is a phi in a block with an EHPad terminator, we can't insert
5317 // after it.
5318 if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
5319 continue;
Devang Patel53771ba2011-08-18 00:50:51 +00005320 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
5321 DVI->removeFromParent();
Reid Klecknere18f92b2015-12-08 22:33:23 +00005322 if (isa<PHINode>(VI))
5323 DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
5324 else
5325 DVI->insertAfter(VI);
Devang Patel53771ba2011-08-18 00:50:51 +00005326 MadeChange = true;
5327 ++NumDbgValueMoved;
5328 }
5329 }
5330 }
5331 return MadeChange;
5332}
Tim Northovercea0abb2014-03-29 08:22:29 +00005333
5334// If there is a sequence that branches based on comparing a single bit
5335// against zero that can be combined into a single instruction, and the
5336// target supports folding these into a single instruction, sink the
5337// mask and compare into the branch uses. Do this before OptimizeBlock ->
5338// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
5339// searched for.
5340bool CodeGenPrepare::sinkAndCmp(Function &F) {
5341 if (!EnableAndCmpSinking)
5342 return false;
5343 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
5344 return false;
5345 bool MadeChange = false;
5346 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
Duncan P. N. Exon Smithd83547a2015-10-09 18:44:40 +00005347 BasicBlock *BB = &*I++;
Tim Northovercea0abb2014-03-29 08:22:29 +00005348
5349 // Does this BB end with the following?
5350 // %andVal = and %val, #single-bit-set
5351 // %icmpVal = icmp %andResult, 0
5352 // br i1 %cmpVal label %dest1, label %dest2"
5353 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
5354 if (!Brcc || !Brcc->isConditional())
5355 continue;
5356 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
5357 if (!Cmp || Cmp->getParent() != BB)
5358 continue;
5359 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
5360 if (!Zero || !Zero->isZero())
5361 continue;
5362 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
5363 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
5364 continue;
5365 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
5366 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
5367 continue;
5368 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
5369
5370 // Push the "and; icmp" for any users that are conditional branches.
5371 // Since there can only be one branch use per BB, we don't need to keep
5372 // track of which BBs we insert into.
5373 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
5374 UI != E; ) {
5375 Use &TheUse = *UI;
5376 // Find brcc use.
5377 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
5378 ++UI;
5379 if (!BrccUser || !BrccUser->isConditional())
5380 continue;
5381 BasicBlock *UserBB = BrccUser->getParent();
5382 if (UserBB == BB) continue;
5383 DEBUG(dbgs() << "found Brcc use\n");
5384
5385 // Sink the "and; icmp" to use.
5386 MadeChange = true;
5387 BinaryOperator *NewAnd =
5388 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
5389 BrccUser);
5390 CmpInst *NewCmp =
5391 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
5392 "", BrccUser);
5393 TheUse = NewCmp;
5394 ++NumAndCmpsMoved;
5395 DEBUG(BrccUser->getParent()->dump());
5396 }
5397 }
5398 return MadeChange;
5399}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005400
Juergen Ributzka194350a2014-12-09 17:32:12 +00005401/// \brief Retrieve the probabilities of a conditional branch. Returns true on
5402/// success, or returns false if no or invalid metadata was found.
5403static bool extractBranchMetadata(BranchInst *BI,
5404 uint64_t &ProbTrue, uint64_t &ProbFalse) {
5405 assert(BI->isConditional() &&
5406 "Looking for probabilities on unconditional branch?");
5407 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
5408 if (!ProfileData || ProfileData->getNumOperands() != 3)
5409 return false;
5410
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00005411 const auto *CITrue =
5412 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
5413 const auto *CIFalse =
5414 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00005415 if (!CITrue || !CIFalse)
5416 return false;
5417
5418 ProbTrue = CITrue->getValue().getZExtValue();
5419 ProbFalse = CIFalse->getValue().getZExtValue();
5420
5421 return true;
5422}
5423
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005424/// \brief Scale down both weights to fit into uint32_t.
5425static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
5426 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
5427 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
5428 NewTrue = NewTrue / Scale;
5429 NewFalse = NewFalse / Scale;
5430}
5431
5432/// \brief Some targets prefer to split a conditional branch like:
5433/// \code
5434/// %0 = icmp ne i32 %a, 0
5435/// %1 = icmp ne i32 %b, 0
5436/// %or.cond = or i1 %0, %1
5437/// br i1 %or.cond, label %TrueBB, label %FalseBB
5438/// \endcode
5439/// into multiple branch instructions like:
5440/// \code
5441/// bb1:
5442/// %0 = icmp ne i32 %a, 0
5443/// br i1 %0, label %TrueBB, label %bb2
5444/// bb2:
5445/// %1 = icmp ne i32 %b, 0
5446/// br i1 %1, label %TrueBB, label %FalseBB
5447/// \endcode
5448/// This usually allows instruction selection to do even further optimizations
5449/// and combine the compare with the branch instruction. Currently this is
5450/// applied for targets which have "cheap" jump instructions.
5451///
5452/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
5453///
5454bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00005455 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005456 return false;
5457
5458 bool MadeChange = false;
5459 for (auto &BB : F) {
5460 // Does this BB end with the following?
5461 // %cond1 = icmp|fcmp|binary instruction ...
5462 // %cond2 = icmp|fcmp|binary instruction ...
5463 // %cond.or = or|and i1 %cond1, cond2
5464 // br i1 %cond.or label %dest1, label %dest2"
5465 BinaryOperator *LogicOp;
5466 BasicBlock *TBB, *FBB;
5467 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
5468 continue;
5469
Sanjay Patel42574202015-09-02 19:23:23 +00005470 auto *Br1 = cast<BranchInst>(BB.getTerminator());
5471 if (Br1->getMetadata(LLVMContext::MD_unpredictable))
5472 continue;
5473
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005474 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005475 Value *Cond1, *Cond2;
5476 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
5477 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005478 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005479 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
5480 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005481 Opc = Instruction::Or;
5482 else
5483 continue;
5484
5485 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
5486 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
5487 continue;
5488
5489 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
5490
5491 // Create a new BB.
Duncan P. N. Exon Smitha848c472016-02-21 19:52:15 +00005492 auto TmpBB =
5493 BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
5494 BB.getParent(), BB.getNextNode());
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005495
5496 // Update original basic block by using the first condition directly by the
5497 // branch instruction and removing the no longer needed and/or instruction.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005498 Br1->setCondition(Cond1);
5499 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005500
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005501 // Depending on the conditon we have to either replace the true or the false
5502 // successor of the original branch instruction.
5503 if (Opc == Instruction::And)
5504 Br1->setSuccessor(0, TmpBB);
5505 else
5506 Br1->setSuccessor(1, TmpBB);
5507
5508 // Fill in the new basic block.
5509 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00005510 if (auto *I = dyn_cast<Instruction>(Cond2)) {
5511 I->removeFromParent();
5512 I->insertBefore(Br2);
5513 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005514
5515 // Update PHI nodes in both successors. The original BB needs to be
5516 // replaced in one succesor's PHI nodes, because the branch comes now from
5517 // the newly generated BB (NewBB). In the other successor we need to add one
5518 // incoming edge to the PHI nodes, because both branch instructions target
5519 // now the same successor. Depending on the original branch condition
5520 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
5521 // we perfrom the correct update for the PHI nodes.
5522 // This doesn't change the successor order of the just created branch
5523 // instruction (or any other instruction).
5524 if (Opc == Instruction::Or)
5525 std::swap(TBB, FBB);
5526
5527 // Replace the old BB with the new BB.
5528 for (auto &I : *TBB) {
5529 PHINode *PN = dyn_cast<PHINode>(&I);
5530 if (!PN)
5531 break;
5532 int i;
5533 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
5534 PN->setIncomingBlock(i, TmpBB);
5535 }
5536
5537 // Add another incoming edge form the new BB.
5538 for (auto &I : *FBB) {
5539 PHINode *PN = dyn_cast<PHINode>(&I);
5540 if (!PN)
5541 break;
5542 auto *Val = PN->getIncomingValueForBlock(&BB);
5543 PN->addIncoming(Val, TmpBB);
5544 }
5545
5546 // Update the branch weights (from SelectionDAGBuilder::
5547 // FindMergedConditions).
5548 if (Opc == Instruction::Or) {
5549 // Codegen X | Y as:
5550 // BB1:
5551 // jmp_if_X TBB
5552 // jmp TmpBB
5553 // TmpBB:
5554 // jmp_if_Y TBB
5555 // jmp FBB
5556 //
5557
5558 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
5559 // The requirement is that
5560 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
5561 // = TrueProb for orignal BB.
5562 // Assuming the orignal weights are A and B, one choice is to set BB1's
5563 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
5564 // assumes that
5565 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
5566 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
5567 // TmpBB, but the math is more complicated.
5568 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005569 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005570 uint64_t NewTrueWeight = TrueWeight;
5571 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
5572 scaleWeights(NewTrueWeight, NewFalseWeight);
5573 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5574 .createBranchWeights(TrueWeight, FalseWeight));
5575
5576 NewTrueWeight = TrueWeight;
5577 NewFalseWeight = 2 * FalseWeight;
5578 scaleWeights(NewTrueWeight, NewFalseWeight);
5579 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5580 .createBranchWeights(TrueWeight, FalseWeight));
5581 }
5582 } else {
5583 // Codegen X & Y as:
5584 // BB1:
5585 // jmp_if_X TmpBB
5586 // jmp FBB
5587 // TmpBB:
5588 // jmp_if_Y TBB
5589 // jmp FBB
5590 //
5591 // This requires creation of TmpBB after CurBB.
5592
5593 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
5594 // The requirement is that
5595 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
5596 // = FalseProb for orignal BB.
5597 // Assuming the orignal weights are A and B, one choice is to set BB1's
5598 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
5599 // assumes that
5600 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
5601 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00005602 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005603 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
5604 uint64_t NewFalseWeight = FalseWeight;
5605 scaleWeights(NewTrueWeight, NewFalseWeight);
5606 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
5607 .createBranchWeights(TrueWeight, FalseWeight));
5608
5609 NewTrueWeight = 2 * TrueWeight;
5610 NewFalseWeight = FalseWeight;
5611 scaleWeights(NewTrueWeight, NewFalseWeight);
5612 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
5613 .createBranchWeights(TrueWeight, FalseWeight));
5614 }
5615 }
5616
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005617 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00005618 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00005619 ModifiedDT = true;
5620
5621 MadeChange = true;
5622
5623 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
5624 TmpBB->dump());
5625 }
5626 return MadeChange;
5627}
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005628
5629void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
Piotr Padlewskiea092882015-09-17 20:25:07 +00005630 if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
Piotr Padlewski6c15ec42015-09-15 18:32:14 +00005631 I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
5632}