blob: 6e7f525736d07ad1e61c8c8d3e3e2bbef41e0566 [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"
Chandler Carruth219b89b2014-03-04 11:01:28 +000023#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000027#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/IRBuilder.h"
31#include "llvm/IR/InlineAsm.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/IntrinsicInst.h"
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +000034#include "llvm/IR/MDBuilder.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000035#include "llvm/IR/PatternMatch.h"
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000036#include "llvm/IR/Statepoint.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000038#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000039#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000040#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000041#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000043#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000044#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000047#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000048#include "llvm/Transforms/Utils/Local.h"
Ahmed Bougachae03bef72015-01-12 17:22:43 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000050using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000051using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000052
Chandler Carruth1b9dde02014-04-22 02:02:50 +000053#define DEBUG_TYPE "codegenprepare"
54
Cameron Zwarichced753f2011-01-05 17:27:27 +000055STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000056STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
57STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000058STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
59 "sunken Cmps");
60STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
61 "of sunken Casts");
62STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
63 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000064STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
65STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
66STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000067STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000068STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000069STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Quentin Colombetc32615d2014-10-31 17:52:53 +000070STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000071
Cameron Zwarich338d3622011-03-11 21:52:04 +000072static cl::opt<bool> DisableBranchOpts(
73 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
74 cl::desc("Disable branch optimizations in CodeGenPrepare"));
75
Ramkumar Ramachandradba73292015-01-14 23:27:07 +000076static cl::opt<bool>
77 DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
78 cl::desc("Disable GC optimizations in CodeGenPrepare"));
79
Benjamin Kramer3d38c172012-05-06 14:25:16 +000080static cl::opt<bool> DisableSelectToBranch(
81 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
82 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000083
Hal Finkelc3998302014-04-12 00:59:48 +000084static cl::opt<bool> AddrSinkUsingGEPs(
85 "addr-sink-using-gep", cl::Hidden, cl::init(false),
86 cl::desc("Address sinking in CGP using GEPs."));
87
Tim Northovercea0abb2014-03-29 08:22:29 +000088static cl::opt<bool> EnableAndCmpSinking(
89 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
90 cl::desc("Enable sinkinig and/cmp into branches."));
91
Quentin Colombetc32615d2014-10-31 17:52:53 +000092static cl::opt<bool> DisableStoreExtract(
93 "disable-cgp-store-extract", cl::Hidden, cl::init(false),
94 cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
95
96static cl::opt<bool> StressStoreExtract(
97 "stress-cgp-store-extract", cl::Hidden, cl::init(false),
98 cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
99
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000100static cl::opt<bool> DisableExtLdPromotion(
101 "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
102 cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
103 "CodeGenPrepare"));
104
105static cl::opt<bool> StressExtLdPromotion(
106 "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
107 cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
108 "optimization in CodeGenPrepare"));
109
Eric Christopherc1ea1492008-09-24 05:32:41 +0000110namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000111typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +0000112typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
Quentin Colombetf5485bb2014-11-13 01:44:51 +0000113typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000114class TypePromotionTransaction;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000115
Chris Lattner2dd09db2009-09-02 06:11:42 +0000116 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000117 /// TLI - Keep a pointer of a TargetLowering to consult for determining
118 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000119 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000120 const TargetLowering *TLI;
Quentin Colombetc32615d2014-10-31 17:52:53 +0000121 const TargetTransformInfo *TTI;
Chad Rosierc24b86f2011-12-01 03:08:23 +0000122 const TargetLibraryInfo *TLInfo;
Nadav Rotem465834c2012-07-24 10:51:42 +0000123
Chris Lattner7a277142011-01-15 07:14:54 +0000124 /// CurInstIterator - As we scan instructions optimizing them, this is the
125 /// next instruction to optimize. Xforms that can invalidate this should
126 /// update it.
127 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +0000128
Evan Cheng0663f232011-03-21 01:19:09 +0000129 /// Keeps track of non-local addresses that have been sunk into a block.
130 /// This allows us to avoid inserting duplicate code for blocks with
131 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000132 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000133
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000134 /// Keeps track of all instructions inserted for the current function.
135 SetOfInstrs InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000136 /// Keeps track of the type of the related instruction before their
137 /// promotion for the current function.
138 InstrToOrigTy PromotedInsts;
139
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000140 /// ModifiedDT - If CFG is modified in anyway.
Devang Patel8f606d72011-03-24 15:35:25 +0000141 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000142
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000143 /// OptSize - True if optimizing for size.
144 bool OptSize;
145
Mehdi Amini4fe37982015-07-07 18:45:17 +0000146 /// DataLayout for the Function being processed.
147 const DataLayout *DL;
148
Chris Lattnerf2836d12007-03-31 04:06:36 +0000149 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000150 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000151 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
Mehdi Amini4fe37982015-07-07 18:45:17 +0000152 : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000153 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
154 }
Craig Topper4584cd52014-03-07 09:26:03 +0000155 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000156
Craig Topper4584cd52014-03-07 09:26:03 +0000157 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000158
Craig Topper4584cd52014-03-07 09:26:03 +0000159 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000160 AU.addPreserved<DominatorTreeWrapperPass>();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000161 AU.addRequired<TargetLibraryInfoWrapperPass>();
Chandler Carruth705b1852015-01-31 03:43:40 +0000162 AU.addRequired<TargetTransformInfoWrapperPass>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000163 }
164
Chris Lattnerf2836d12007-03-31 04:06:36 +0000165 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000166 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000167 bool EliminateMostlyEmptyBlocks(Function &F);
168 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
169 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000170 bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
171 bool OptimizeInst(Instruction *I, bool& ModifiedDT);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +0000172 bool OptimizeMemoryInst(Instruction *I, Value *Addr,
173 Type *AccessTy, unsigned AS);
Chris Lattner7a277142011-01-15 07:14:54 +0000174 bool OptimizeInlineAsmInst(CallInst *CS);
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000175 bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000176 bool MoveExtToFormExtLoad(Instruction *&I);
Evan Chengd3d80172007-12-05 23:58:20 +0000177 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000178 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000179 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Quentin Colombetc32615d2014-10-31 17:52:53 +0000180 bool OptimizeExtractElementInst(Instruction *Inst);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000181 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000182 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000183 bool sinkAndCmp(Function &F);
Quentin Colombetfc2201e2014-12-17 01:36:17 +0000184 bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
185 Instruction *&Inst,
186 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +0000187 unsigned CreatedInstCost);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000188 bool splitBranchCondition(Function &F);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000189 bool simplifyOffsetableRelocate(Instruction &I);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000190 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000191}
Devang Patel09f162c2007-05-01 21:15:47 +0000192
Devang Patel8c78a0b2007-05-03 01:11:54 +0000193char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000194INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
195 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000196
Bill Wendling7a639ea2013-06-19 21:07:11 +0000197FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
198 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000199}
200
Chris Lattnerf2836d12007-03-31 04:06:36 +0000201bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000202 if (skipOptnoneFunction(F))
203 return false;
204
Mehdi Amini4fe37982015-07-07 18:45:17 +0000205 DL = &F.getParent()->getDataLayout();
206
Chris Lattnerf2836d12007-03-31 04:06:36 +0000207 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000208 // Clear per function information.
Ahmed Bougachaf3299142015-06-17 20:44:32 +0000209 InsertedInsts.clear();
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000210 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000211
Devang Patel8f606d72011-03-24 15:35:25 +0000212 ModifiedDT = false;
Eric Christopherd9134482014-08-04 21:25:23 +0000213 if (TM)
Eric Christopherfccff372015-01-27 01:01:38 +0000214 TLI = TM->getSubtargetImpl(F)->getTargetLowering();
Chandler Carruthb98f63d2015-01-15 10:41:28 +0000215 TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
Chandler Carruthfdb9c572015-02-01 12:01:35 +0000216 TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
Sanjay Patel924879a2015-08-04 15:49:57 +0000217 // FIXME: Use Function::optForSize().
Duncan P. N. Exon Smith70eb9c52015-02-14 01:44:41 +0000218 OptSize = F.hasFnAttribute(Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000219
Preston Gurdcdf540d2012-09-04 18:22:17 +0000220 /// This optimization identifies DIV instructions that can be
221 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000222 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000223 const DenseMap<unsigned int, unsigned int> &BypassWidths =
224 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000225 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000226 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000227 }
228
229 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000230 // unconditional branch.
231 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000232
Devang Patel53771ba2011-08-18 00:50:51 +0000233 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000234 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000235 // find a node corresponding to the value.
236 EverMadeChange |= PlaceDbgValues(F);
237
Tim Northovercea0abb2014-03-29 08:22:29 +0000238 // If there is a mask, compare against zero, and branch that can be combined
239 // into a single target instruction, push the mask and compare into branch
240 // users. Do this before OptimizeBlock -> OptimizeInst ->
241 // OptimizeCmpExpression, which perturbs the pattern being searched for.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000242 if (!DisableBranchOpts) {
Tim Northovercea0abb2014-03-29 08:22:29 +0000243 EverMadeChange |= sinkAndCmp(F);
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +0000244 EverMadeChange |= splitBranchCondition(F);
245 }
Tim Northovercea0abb2014-03-29 08:22:29 +0000246
Chris Lattnerc3748562007-04-02 01:35:34 +0000247 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000248 while (MadeChange) {
249 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000250 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000251 BasicBlock *BB = I++;
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000252 bool ModifiedDTOnIteration = false;
253 MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000254
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000255 // Restart BB iteration if the dominator tree of the Function was changed
Elena Demikhovsky87700a72014-12-28 08:54:45 +0000256 if (ModifiedDTOnIteration)
257 break;
Evan Cheng0663f232011-03-21 01:19:09 +0000258 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000259 EverMadeChange |= MadeChange;
260 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000261
262 SunkAddrs.clear();
263
Cameron Zwarich338d3622011-03-11 21:52:04 +0000264 if (!DisableBranchOpts) {
265 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000266 SmallPtrSet<BasicBlock*, 8> WorkList;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +0000267 for (BasicBlock &BB : F) {
268 SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
269 MadeChange |= ConstantFoldTerminator(&BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000270 if (!MadeChange) continue;
271
272 for (SmallVectorImpl<BasicBlock*>::iterator
273 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
274 if (pred_begin(*II) == pred_end(*II))
275 WorkList.insert(*II);
276 }
277
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000278 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000279 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000280 while (!WorkList.empty()) {
281 BasicBlock *BB = *WorkList.begin();
282 WorkList.erase(BB);
283 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
284
285 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000286
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000287 for (SmallVectorImpl<BasicBlock*>::iterator
288 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
289 if (pred_begin(*II) == pred_end(*II))
290 WorkList.insert(*II);
291 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000292
Nadav Rotem70409992012-08-14 05:19:07 +0000293 // Merge pairs of basic blocks with unconditional branches, connected by
294 // a single edge.
295 if (EverMadeChange || MadeChange)
296 MadeChange |= EliminateFallThrough(F);
297
Cameron Zwarich338d3622011-03-11 21:52:04 +0000298 EverMadeChange |= MadeChange;
299 }
300
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000301 if (!DisableGCOpts) {
302 SmallVector<Instruction *, 2> Statepoints;
303 for (BasicBlock &BB : F)
304 for (Instruction &I : BB)
305 if (isStatepoint(I))
306 Statepoints.push_back(&I);
307 for (auto &I : Statepoints)
308 EverMadeChange |= simplifyOffsetableRelocate(*I);
309 }
310
Chris Lattnerf2836d12007-03-31 04:06:36 +0000311 return EverMadeChange;
312}
313
Nadav Rotem70409992012-08-14 05:19:07 +0000314/// EliminateFallThrough - Merge basic blocks which are connected
315/// by a single edge, where one of the basic blocks has a single successor
316/// pointing to the other basic block, which has a single predecessor.
317bool CodeGenPrepare::EliminateFallThrough(Function &F) {
318 bool Changed = false;
319 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000320 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000321 BasicBlock *BB = I++;
322 // If the destination block has a single pred, then this is a trivial
323 // edge, just collapse it.
324 BasicBlock *SinglePred = BB->getSinglePredecessor();
325
Evan Cheng64a223a2012-09-28 23:58:57 +0000326 // Don't merge if BB's address is taken.
327 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000328
329 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
330 if (Term && !Term->isConditional()) {
331 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000332 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000333 // Remember if SinglePred was the entry block of the function.
334 // If so, we will need to move BB back to the entry position.
335 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000336 MergeBasicBlockIntoOnlyPred(BB, nullptr);
Nadav Rotem70409992012-08-14 05:19:07 +0000337
338 if (isEntry && BB != &BB->getParent()->getEntryBlock())
339 BB->moveBefore(&BB->getParent()->getEntryBlock());
340
341 // We have erased a block. Update the iterator.
342 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000343 }
344 }
345 return Changed;
346}
347
Dale Johannesen4026b042009-03-27 01:13:37 +0000348/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
349/// debug info directives, and an unconditional branch. Passes before isel
350/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
351/// isel. Start by eliminating these blocks so we can split them the way we
352/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000353bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
354 bool MadeChange = false;
355 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000356 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000357 BasicBlock *BB = I++;
358
359 // If this block doesn't end with an uncond branch, ignore it.
360 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
361 if (!BI || !BI->isUnconditional())
362 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000363
Dale Johannesen4026b042009-03-27 01:13:37 +0000364 // If the instruction before the branch (skipping debug info) isn't a phi
365 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000366 BasicBlock::iterator BBI = BI;
367 if (BBI != BB->begin()) {
368 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000369 while (isa<DbgInfoIntrinsic>(BBI)) {
370 if (BBI == BB->begin())
371 break;
372 --BBI;
373 }
374 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
375 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000376 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000377
Chris Lattnerc3748562007-04-02 01:35:34 +0000378 // Do not break infinite loops.
379 BasicBlock *DestBB = BI->getSuccessor(0);
380 if (DestBB == BB)
381 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000382
Chris Lattnerc3748562007-04-02 01:35:34 +0000383 if (!CanMergeBlocks(BB, DestBB))
384 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000385
Chris Lattnerc3748562007-04-02 01:35:34 +0000386 EliminateMostlyEmptyBlock(BB);
387 MadeChange = true;
388 }
389 return MadeChange;
390}
391
392/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
393/// single uncond branch between them, and BB contains no other non-phi
394/// instructions.
395bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
396 const BasicBlock *DestBB) const {
397 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
398 // the successor. If there are more complex condition (e.g. preheaders),
399 // don't mess around with them.
400 BasicBlock::const_iterator BBI = BB->begin();
401 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000402 for (const User *U : PN->users()) {
403 const Instruction *UI = cast<Instruction>(U);
404 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000405 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000406 // If User is inside DestBB block and it is a PHINode then check
407 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000408 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000409 if (UI->getParent() == DestBB) {
410 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000411 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
412 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
413 if (Insn && Insn->getParent() == BB &&
414 Insn->getParent() != UPN->getIncomingBlock(I))
415 return false;
416 }
417 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000418 }
419 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000420
Chris Lattnerc3748562007-04-02 01:35:34 +0000421 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
422 // and DestBB may have conflicting incoming values for the block. If so, we
423 // can't merge the block.
424 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
425 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000426
Chris Lattnerc3748562007-04-02 01:35:34 +0000427 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000428 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000429 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
430 // It is faster to get preds from a PHI than with pred_iterator.
431 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
432 BBPreds.insert(BBPN->getIncomingBlock(i));
433 } else {
434 BBPreds.insert(pred_begin(BB), pred_end(BB));
435 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000436
Chris Lattnerc3748562007-04-02 01:35:34 +0000437 // Walk the preds of DestBB.
438 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
439 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
440 if (BBPreds.count(Pred)) { // Common predecessor?
441 BBI = DestBB->begin();
442 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
443 const Value *V1 = PN->getIncomingValueForBlock(Pred);
444 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000445
Chris Lattnerc3748562007-04-02 01:35:34 +0000446 // If V2 is a phi node in BB, look up what the mapped value will be.
447 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
448 if (V2PN->getParent() == BB)
449 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000450
Chris Lattnerc3748562007-04-02 01:35:34 +0000451 // If there is a conflict, bail out.
452 if (V1 != V2) return false;
453 }
454 }
455 }
456
457 return true;
458}
459
460
461/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
462/// an unconditional branch in it.
463void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
464 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
465 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000466
David Greene74e2d492010-01-05 01:27:11 +0000467 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000468
Chris Lattnerc3748562007-04-02 01:35:34 +0000469 // If the destination block has a single pred, then this is a trivial edge,
470 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000471 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000472 if (SinglePred != DestBB) {
473 // Remember if SinglePred was the entry block of the function. If so, we
474 // will need to move BB back to the entry position.
475 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Quentin Colombet7bdd50d2015-03-18 23:17:28 +0000476 MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
Chris Lattner4059f432008-11-27 19:29:14 +0000477
Chris Lattner8a172da2008-11-28 19:54:49 +0000478 if (isEntry && BB != &BB->getParent()->getEntryBlock())
479 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000480
David Greene74e2d492010-01-05 01:27:11 +0000481 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000482 return;
483 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000484 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000485
Chris Lattnerc3748562007-04-02 01:35:34 +0000486 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
487 // to handle the new incoming edges it is about to have.
488 PHINode *PN;
489 for (BasicBlock::iterator BBI = DestBB->begin();
490 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
491 // Remove the incoming value for BB, and remember it.
492 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000493
Chris Lattnerc3748562007-04-02 01:35:34 +0000494 // Two options: either the InVal is a phi node defined in BB or it is some
495 // value that dominates BB.
496 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
497 if (InValPhi && InValPhi->getParent() == BB) {
498 // Add all of the input values of the input PHI as inputs of this phi.
499 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
500 PN->addIncoming(InValPhi->getIncomingValue(i),
501 InValPhi->getIncomingBlock(i));
502 } else {
503 // Otherwise, add one instance of the dominating value for each edge that
504 // we will be adding.
505 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
506 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
507 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
508 } else {
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000509 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
510 PN->addIncoming(InVal, *PI);
Chris Lattnerc3748562007-04-02 01:35:34 +0000511 }
512 }
513 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000514
Chris Lattnerc3748562007-04-02 01:35:34 +0000515 // The PHIs are now updated, change everything that refers to BB to use
516 // DestBB and remove BB.
517 BB->replaceAllUsesWith(DestBB);
518 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000519 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000520
David Greene74e2d492010-01-05 01:27:11 +0000521 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000522}
523
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000524// Computes a map of base pointer relocation instructions to corresponding
525// derived pointer relocation instructions given a vector of all relocate calls
526static void computeBaseDerivedRelocateMap(
527 const SmallVectorImpl<User *> &AllRelocateCalls,
528 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
529 RelocateInstMap) {
530 // Collect information in two maps: one primarily for locating the base object
531 // while filling the second map; the second map is the final structure holding
532 // a mapping between Base and corresponding Derived relocate calls
533 DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
534 for (auto &U : AllRelocateCalls) {
535 GCRelocateOperands ThisRelocate(U);
536 IntrinsicInst *I = cast<IntrinsicInst>(U);
Sanjoy Das499d7032015-05-06 02:36:26 +0000537 auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
538 ThisRelocate.getDerivedPtrIndex());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000539 RelocateIdxMap.insert(std::make_pair(K, I));
540 }
541 for (auto &Item : RelocateIdxMap) {
542 std::pair<unsigned, unsigned> Key = Item.first;
543 if (Key.first == Key.second)
544 // Base relocation: nothing to insert
545 continue;
546
547 IntrinsicInst *I = Item.second;
548 auto BaseKey = std::make_pair(Key.first, Key.first);
Sanjoy Dasb8186762015-02-27 02:24:16 +0000549
550 // We're iterating over RelocateIdxMap so we cannot modify it.
551 auto MaybeBase = RelocateIdxMap.find(BaseKey);
552 if (MaybeBase == RelocateIdxMap.end())
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000553 // TODO: We might want to insert a new base object relocate and gep off
554 // that, if there are enough derived object relocates.
555 continue;
Sanjoy Dasb8186762015-02-27 02:24:16 +0000556
557 RelocateInstMap[MaybeBase->second].push_back(I);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000558 }
559}
560
561// Accepts a GEP and extracts the operands into a vector provided they're all
562// small integer constants
563static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
564 SmallVectorImpl<Value *> &OffsetV) {
565 for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
566 // Only accept small constant integer operands
567 auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
568 if (!Op || Op->getZExtValue() > 20)
569 return false;
570 }
571
572 for (unsigned i = 1; i < GEP->getNumOperands(); i++)
573 OffsetV.push_back(GEP->getOperand(i));
574 return true;
575}
576
577// Takes a RelocatedBase (base pointer relocation instruction) and Targets to
578// replace, computes a replacement, and affects it.
579static bool
580simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
581 const SmallVectorImpl<IntrinsicInst *> &Targets) {
582 bool MadeChange = false;
583 for (auto &ToReplace : Targets) {
584 GCRelocateOperands MasterRelocate(RelocatedBase);
585 GCRelocateOperands ThisRelocate(ToReplace);
586
Sanjoy Das499d7032015-05-06 02:36:26 +0000587 assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000588 "Not relocating a derived object of the original base object");
Sanjoy Das499d7032015-05-06 02:36:26 +0000589 if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000590 // A duplicate relocate call. TODO: coalesce duplicates.
591 continue;
592 }
593
Sanjoy Das499d7032015-05-06 02:36:26 +0000594 Value *Base = ThisRelocate.getBasePtr();
595 auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000596 if (!Derived || Derived->getPointerOperand() != Base)
597 continue;
598
599 SmallVector<Value *, 2> OffsetV;
600 if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
601 continue;
602
603 // Create a Builder and replace the target callsite with a gep
Sanjoy Das3d705e32015-05-11 23:47:30 +0000604 assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
605
606 // Insert after RelocatedBase
607 IRBuilder<> Builder(RelocatedBase->getNextNode());
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000608 Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
Sanjoy Das89c54912015-05-11 18:49:34 +0000609
610 // If gc_relocate does not match the actual type, cast it to the right type.
611 // In theory, there must be a bitcast after gc_relocate if the type does not
612 // match, and we should reuse it to get the derived pointer. But it could be
613 // cases like this:
614 // bb1:
615 // ...
616 // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
617 // br label %merge
618 //
619 // bb2:
620 // ...
621 // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
622 // br label %merge
623 //
624 // merge:
625 // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
626 // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
627 //
628 // In this case, we can not find the bitcast any more. So we insert a new bitcast
629 // no matter there is already one or not. In this way, we can handle all cases, and
630 // the extra bitcast should be optimized away in later passes.
631 Instruction *ActualRelocatedBase = RelocatedBase;
632 if (RelocatedBase->getType() != Base->getType()) {
633 ActualRelocatedBase =
634 cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000635 }
David Blaikie68d535c2015-03-24 22:38:16 +0000636 Value *Replacement = Builder.CreateGEP(
Sanjoy Das89c54912015-05-11 18:49:34 +0000637 Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000638 Instruction *ReplacementInst = cast<Instruction>(Replacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000639 Replacement->takeName(ToReplace);
Sanjoy Das89c54912015-05-11 18:49:34 +0000640 // If the newly generated derived pointer's type does not match the original derived
641 // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
642 Instruction *ActualReplacement = ReplacementInst;
643 if (ReplacementInst->getType() != ToReplace->getType()) {
644 ActualReplacement =
645 cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
Sanjoy Das89c54912015-05-11 18:49:34 +0000646 }
647 ToReplace->replaceAllUsesWith(ActualReplacement);
Ramkumar Ramachandradba73292015-01-14 23:27:07 +0000648 ToReplace->eraseFromParent();
649
650 MadeChange = true;
651 }
652 return MadeChange;
653}
654
655// Turns this:
656//
657// %base = ...
658// %ptr = gep %base + 15
659// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
660// %base' = relocate(%tok, i32 4, i32 4)
661// %ptr' = relocate(%tok, i32 4, i32 5)
662// %val = load %ptr'
663//
664// into this:
665//
666// %base = ...
667// %ptr = gep %base + 15
668// %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
669// %base' = gc.relocate(%tok, i32 4, i32 4)
670// %ptr' = gep %base' + 15
671// %val = load %ptr'
672bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
673 bool MadeChange = false;
674 SmallVector<User *, 2> AllRelocateCalls;
675
676 for (auto *U : I.users())
677 if (isGCRelocate(dyn_cast<Instruction>(U)))
678 // Collect all the relocate calls associated with a statepoint
679 AllRelocateCalls.push_back(U);
680
681 // We need atleast one base pointer relocation + one derived pointer
682 // relocation to mangle
683 if (AllRelocateCalls.size() < 2)
684 return false;
685
686 // RelocateInstMap is a mapping from the base relocate instruction to the
687 // corresponding derived relocate instructions
688 DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
689 computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
690 if (RelocateInstMap.empty())
691 return false;
692
693 for (auto &Item : RelocateInstMap)
694 // Item.first is the RelocatedBase to offset against
695 // Item.second is the vector of Targets to replace
696 MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
697 return MadeChange;
698}
699
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000700/// SinkCast - Sink the specified cast instruction into its user blocks
701static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000702 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000703
Chris Lattnerf2836d12007-03-31 04:06:36 +0000704 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000705 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000706
Chris Lattnerf2836d12007-03-31 04:06:36 +0000707 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000708 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000709 UI != E; ) {
710 Use &TheUse = UI.getUse();
711 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000712
Chris Lattnerf2836d12007-03-31 04:06:36 +0000713 // Figure out which BB this cast is used in. For PHI's this is the
714 // appropriate predecessor block.
715 BasicBlock *UserBB = User->getParent();
716 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000717 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000718 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000719
Chris Lattnerf2836d12007-03-31 04:06:36 +0000720 // Preincrement use iterator so we don't invalidate it.
721 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000722
Chris Lattnerf2836d12007-03-31 04:06:36 +0000723 // If this user is in the same block as the cast, don't change the cast.
724 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000725
Chris Lattnerf2836d12007-03-31 04:06:36 +0000726 // If we have already inserted a cast into this block, use it.
727 CastInst *&InsertedCast = InsertedCasts[UserBB];
728
729 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000730 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000731 InsertedCast =
732 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000733 InsertPt);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000734 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000735
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000736 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000737 TheUse = InsertedCast;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000738 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000739 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000740 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000741
Chris Lattnerf2836d12007-03-31 04:06:36 +0000742 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000743 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000744 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000745 MadeChange = true;
746 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000747
Chris Lattnerf2836d12007-03-31 04:06:36 +0000748 return MadeChange;
749}
750
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000751/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
752/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
753/// sink it into user blocks to reduce the number of virtual
754/// registers that must be created and coalesced.
755///
756/// Return true if any changes are made.
757///
Mehdi Amini44ede332015-07-09 02:09:04 +0000758static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
759 const DataLayout &DL) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000760 // If this is a noop copy,
Mehdi Amini44ede332015-07-09 02:09:04 +0000761 EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
762 EVT DstVT = TLI.getValueType(DL, CI->getType());
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000763
764 // This is an fp<->int conversion?
765 if (SrcVT.isInteger() != DstVT.isInteger())
766 return false;
767
768 // If this is an extension, it will be a zero or sign extension, which
769 // isn't a noop.
770 if (SrcVT.bitsLT(DstVT)) return false;
771
772 // If these values will be promoted, find out what they will be promoted
773 // to. This helps us consider truncates on PPC as noop copies when they
774 // are.
775 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
776 TargetLowering::TypePromoteInteger)
777 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
778 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
779 TargetLowering::TypePromoteInteger)
780 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
781
782 // If, after promotion, these are the same types, this is a noop copy.
783 if (SrcVT != DstVT)
784 return false;
785
786 return SinkCast(CI);
787}
788
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000789/// CombineUAddWithOverflow - try to combine CI into a call to the
790/// llvm.uadd.with.overflow intrinsic if possible.
791///
792/// Return true if any changes were made.
793static bool CombineUAddWithOverflow(CmpInst *CI) {
794 Value *A, *B;
795 Instruction *AddI;
796 if (!match(CI,
797 m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
798 return false;
799
800 Type *Ty = AddI->getType();
801 if (!isa<IntegerType>(Ty))
802 return false;
803
804 // We don't want to move around uses of condition values this late, so we we
805 // check if it is legal to create the call to the intrinsic in the basic
806 // block containing the icmp:
807
808 if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
809 return false;
810
811#ifndef NDEBUG
812 // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
813 // for now:
814 if (AddI->hasOneUse())
815 assert(*AddI->user_begin() == CI && "expected!");
816#endif
817
818 Module *M = CI->getParent()->getParent()->getParent();
819 Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
820
821 auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
822
823 auto *UAddWithOverflow =
824 CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
825 auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
826 auto *Overflow =
827 ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
828
829 CI->replaceAllUsesWith(Overflow);
830 AddI->replaceAllUsesWith(UAdd);
831 CI->eraseFromParent();
832 AddI->eraseFromParent();
833 return true;
834}
835
836/// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000837/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000838/// a clear win except on targets with multiple condition code registers
839/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000840///
841/// Return true if any changes are made.
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000842static bool SinkCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000843 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000844
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000845 /// InsertedCmp - Only insert a cmp in each block once.
846 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000847
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000848 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000849 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000850 UI != E; ) {
851 Use &TheUse = UI.getUse();
852 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000853
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000854 // Preincrement use iterator so we don't invalidate it.
855 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000856
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000857 // Don't bother for PHI nodes.
858 if (isa<PHINode>(User))
859 continue;
860
861 // Figure out which BB this cmp is used in.
862 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000863
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000864 // If this user is in the same block as the cmp, don't change the cmp.
865 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000866
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000867 // If we have already inserted a cmp into this block, use it.
868 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
869
870 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000871 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000872 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000873 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000874 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000875 CI->getOperand(1), "", InsertPt);
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000876 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000877
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000878 // Replace a use of the cmp with a use of the new cmp.
879 TheUse = InsertedCmp;
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000880 MadeChange = true;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000881 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000882 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000883
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000884 // If we removed all uses, nuke the cmp.
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000885 if (CI->use_empty()) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000886 CI->eraseFromParent();
Benjamin Kramerb4bf14c2015-04-10 22:25:36 +0000887 MadeChange = true;
888 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000889
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000890 return MadeChange;
891}
892
Sanjoy Dasb6c59142015-04-10 21:07:09 +0000893static bool OptimizeCmpExpression(CmpInst *CI) {
894 if (SinkCmpExpression(CI))
895 return true;
896
897 if (CombineUAddWithOverflow(CI))
898 return true;
899
900 return false;
901}
902
Yi Jiangd069f632014-04-21 19:34:27 +0000903/// isExtractBitsCandidateUse - Check if the candidates could
904/// be combined with shift instruction, which includes:
905/// 1. Truncate instruction
906/// 2. And instruction and the imm is a mask of the low bits:
907/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000908static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000909 if (!isa<TruncInst>(User)) {
910 if (User->getOpcode() != Instruction::And ||
911 !isa<ConstantInt>(User->getOperand(1)))
912 return false;
913
Quentin Colombetd4f44692014-04-22 01:20:34 +0000914 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000915
Quentin Colombetd4f44692014-04-22 01:20:34 +0000916 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000917 return false;
918 }
919 return true;
920}
921
922/// SinkShiftAndTruncate - sink both shift and truncate instruction
923/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000924static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000925SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
926 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
Mehdi Amini44ede332015-07-09 02:09:04 +0000927 const TargetLowering &TLI, const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +0000928 BasicBlock *UserBB = User->getParent();
929 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
930 TruncInst *TruncI = dyn_cast<TruncInst>(User);
931 bool MadeChange = false;
932
933 for (Value::user_iterator TruncUI = TruncI->user_begin(),
934 TruncE = TruncI->user_end();
935 TruncUI != TruncE;) {
936
937 Use &TruncTheUse = TruncUI.getUse();
938 Instruction *TruncUser = cast<Instruction>(*TruncUI);
939 // Preincrement use iterator so we don't invalidate it.
940
941 ++TruncUI;
942
943 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
944 if (!ISDOpcode)
945 continue;
946
Tim Northovere2239ff2014-07-29 10:20:22 +0000947 // If the use is actually a legal node, there will not be an
948 // implicit truncate.
949 // FIXME: always querying the result type is just an
950 // approximation; some nodes' legality is determined by the
951 // operand or other means. There's no good way to find out though.
Ahmed Bougacha0788d492014-11-12 22:16:55 +0000952 if (TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +0000953 ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
Yi Jiangd069f632014-04-21 19:34:27 +0000954 continue;
955
956 // Don't bother for PHI nodes.
957 if (isa<PHINode>(TruncUser))
958 continue;
959
960 BasicBlock *TruncUserBB = TruncUser->getParent();
961
962 if (UserBB == TruncUserBB)
963 continue;
964
965 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
966 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
967
968 if (!InsertedShift && !InsertedTrunc) {
969 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
970 // Sink the shift
971 if (ShiftI->getOpcode() == Instruction::AShr)
972 InsertedShift =
973 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
974 else
975 InsertedShift =
976 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
977
978 // Sink the trunc
979 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
980 TruncInsertPt++;
981
982 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
983 TruncI->getType(), "", TruncInsertPt);
984
985 MadeChange = true;
986
987 TruncTheUse = InsertedTrunc;
988 }
989 }
990 return MadeChange;
991}
992
993/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
994/// the uses could potentially be combined with this shift instruction and
995/// generate BitExtract instruction. It will only be applied if the architecture
996/// supports BitExtract instruction. Here is an example:
997/// BB1:
998/// %x.extract.shift = lshr i64 %arg1, 32
999/// BB2:
1000/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
1001/// ==>
1002///
1003/// BB2:
1004/// %x.extract.shift.1 = lshr i64 %arg1, 32
1005/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1006///
1007/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1008/// instruction.
1009/// Return true if any changes are made.
1010static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
Mehdi Amini44ede332015-07-09 02:09:04 +00001011 const TargetLowering &TLI,
1012 const DataLayout &DL) {
Yi Jiangd069f632014-04-21 19:34:27 +00001013 BasicBlock *DefBB = ShiftI->getParent();
1014
1015 /// Only insert instructions in each block once.
1016 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1017
Mehdi Amini44ede332015-07-09 02:09:04 +00001018 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
Yi Jiangd069f632014-04-21 19:34:27 +00001019
1020 bool MadeChange = false;
1021 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1022 UI != E;) {
1023 Use &TheUse = UI.getUse();
1024 Instruction *User = cast<Instruction>(*UI);
1025 // Preincrement use iterator so we don't invalidate it.
1026 ++UI;
1027
1028 // Don't bother for PHI nodes.
1029 if (isa<PHINode>(User))
1030 continue;
1031
1032 if (!isExtractBitsCandidateUse(User))
1033 continue;
1034
1035 BasicBlock *UserBB = User->getParent();
1036
1037 if (UserBB == DefBB) {
1038 // If the shift and truncate instruction are in the same BB. The use of
1039 // the truncate(TruncUse) may still introduce another truncate if not
1040 // legal. In this case, we would like to sink both shift and truncate
1041 // instruction to the BB of TruncUse.
1042 // for example:
1043 // BB1:
1044 // i64 shift.result = lshr i64 opnd, imm
1045 // trunc.result = trunc shift.result to i16
1046 //
1047 // BB2:
1048 // ----> We will have an implicit truncate here if the architecture does
1049 // not have i16 compare.
1050 // cmp i16 trunc.result, opnd2
1051 //
1052 if (isa<TruncInst>(User) && shiftIsLegal
1053 // If the type of the truncate is legal, no trucate will be
1054 // introduced in other basic blocks.
Mehdi Amini44ede332015-07-09 02:09:04 +00001055 &&
1056 (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
Yi Jiangd069f632014-04-21 19:34:27 +00001057 MadeChange =
Mehdi Amini44ede332015-07-09 02:09:04 +00001058 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
Yi Jiangd069f632014-04-21 19:34:27 +00001059
1060 continue;
1061 }
1062 // If we have already inserted a shift into this block, use it.
1063 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
1064
1065 if (!InsertedShift) {
1066 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1067
1068 if (ShiftI->getOpcode() == Instruction::AShr)
1069 InsertedShift =
1070 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
1071 else
1072 InsertedShift =
1073 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
1074
1075 MadeChange = true;
1076 }
1077
1078 // Replace a use of the shift with a use of the new shift.
1079 TheUse = InsertedShift;
1080 }
1081
1082 // If we removed all uses, nuke the shift.
1083 if (ShiftI->use_empty())
1084 ShiftI->eraseFromParent();
1085
1086 return MadeChange;
1087}
1088
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001089// ScalarizeMaskedLoad() translates masked load intrinsic, like
1090// <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
1091// <16 x i1> %mask, <16 x i32> %passthru)
1092// to a chain of basic blocks, whith loading element one-by-one if
1093// the appropriate mask bit is set
1094//
1095// %1 = bitcast i8* %addr to i32*
1096// %2 = extractelement <16 x i1> %mask, i32 0
1097// %3 = icmp eq i1 %2, true
1098// br i1 %3, label %cond.load, label %else
1099//
1100//cond.load: ; preds = %0
1101// %4 = getelementptr i32* %1, i32 0
1102// %5 = load i32* %4
1103// %6 = insertelement <16 x i32> undef, i32 %5, i32 0
1104// br label %else
1105//
1106//else: ; preds = %0, %cond.load
1107// %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
1108// %7 = extractelement <16 x i1> %mask, i32 1
1109// %8 = icmp eq i1 %7, true
1110// br i1 %8, label %cond.load1, label %else2
1111//
1112//cond.load1: ; preds = %else
1113// %9 = getelementptr i32* %1, i32 1
1114// %10 = load i32* %9
1115// %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
1116// br label %else2
1117//
1118//else2: ; preds = %else, %cond.load1
1119// %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1120// %12 = extractelement <16 x i1> %mask, i32 2
1121// %13 = icmp eq i1 %12, true
1122// br i1 %13, label %cond.load4, label %else5
1123//
1124static void ScalarizeMaskedLoad(CallInst *CI) {
1125 Value *Ptr = CI->getArgOperand(0);
1126 Value *Src0 = CI->getArgOperand(3);
1127 Value *Mask = CI->getArgOperand(2);
1128 VectorType *VecType = dyn_cast<VectorType>(CI->getType());
1129 Type *EltTy = VecType->getElementType();
1130
1131 assert(VecType && "Unexpected return type of masked load intrinsic");
1132
1133 IRBuilder<> Builder(CI->getContext());
1134 Instruction *InsertPt = CI;
1135 BasicBlock *IfBlock = CI->getParent();
1136 BasicBlock *CondBlock = nullptr;
1137 BasicBlock *PrevIfBlock = CI->getParent();
1138 Builder.SetInsertPoint(InsertPt);
1139
1140 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1141
1142 // Bitcast %addr fron i8* to EltTy*
1143 Type *NewPtrType =
1144 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1145 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1146 Value *UndefVal = UndefValue::get(VecType);
1147
1148 // The result vector
1149 Value *VResult = UndefVal;
1150
1151 PHINode *Phi = nullptr;
1152 Value *PrevPhi = UndefVal;
1153
1154 unsigned VectorWidth = VecType->getNumElements();
1155 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1156
1157 // Fill the "else" block, created in the previous iteration
1158 //
1159 // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
1160 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1161 // %to_load = icmp eq i1 %mask_1, true
1162 // br i1 %to_load, label %cond.load, label %else
1163 //
1164 if (Idx > 0) {
1165 Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
1166 Phi->addIncoming(VResult, CondBlock);
1167 Phi->addIncoming(PrevPhi, PrevIfBlock);
1168 PrevPhi = Phi;
1169 VResult = Phi;
1170 }
1171
1172 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1173 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1174 ConstantInt::get(Predicate->getType(), 1));
1175
1176 // Create "cond" block
1177 //
1178 // %EltAddr = getelementptr i32* %1, i32 0
1179 // %Elt = load i32* %EltAddr
1180 // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
1181 //
1182 CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
1183 Builder.SetInsertPoint(InsertPt);
David Blaikieaa41cd52015-04-03 21:33:42 +00001184
1185 Value *Gep =
1186 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001187 LoadInst* Load = Builder.CreateLoad(Gep, false);
1188 VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
1189
1190 // Create "else" block, fill it in the next iteration
1191 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1192 Builder.SetInsertPoint(InsertPt);
1193 Instruction *OldBr = IfBlock->getTerminator();
1194 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1195 OldBr->eraseFromParent();
1196 PrevIfBlock = IfBlock;
1197 IfBlock = NewIfBlock;
1198 }
1199
1200 Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
1201 Phi->addIncoming(VResult, CondBlock);
1202 Phi->addIncoming(PrevPhi, PrevIfBlock);
1203 Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
1204 CI->replaceAllUsesWith(NewI);
1205 CI->eraseFromParent();
1206}
1207
1208// ScalarizeMaskedStore() translates masked store intrinsic, like
1209// void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
1210// <16 x i1> %mask)
1211// to a chain of basic blocks, that stores element one-by-one if
1212// the appropriate mask bit is set
1213//
1214// %1 = bitcast i8* %addr to i32*
1215// %2 = extractelement <16 x i1> %mask, i32 0
1216// %3 = icmp eq i1 %2, true
1217// br i1 %3, label %cond.store, label %else
1218//
1219// cond.store: ; preds = %0
1220// %4 = extractelement <16 x i32> %val, i32 0
1221// %5 = getelementptr i32* %1, i32 0
1222// store i32 %4, i32* %5
1223// br label %else
1224//
1225// else: ; preds = %0, %cond.store
1226// %6 = extractelement <16 x i1> %mask, i32 1
1227// %7 = icmp eq i1 %6, true
1228// br i1 %7, label %cond.store1, label %else2
1229//
1230// cond.store1: ; preds = %else
1231// %8 = extractelement <16 x i32> %val, i32 1
1232// %9 = getelementptr i32* %1, i32 1
1233// store i32 %8, i32* %9
1234// br label %else2
1235// . . .
1236static void ScalarizeMaskedStore(CallInst *CI) {
1237 Value *Ptr = CI->getArgOperand(1);
1238 Value *Src = CI->getArgOperand(0);
1239 Value *Mask = CI->getArgOperand(3);
1240
1241 VectorType *VecType = dyn_cast<VectorType>(Src->getType());
1242 Type *EltTy = VecType->getElementType();
1243
1244 assert(VecType && "Unexpected data type in masked store intrinsic");
1245
1246 IRBuilder<> Builder(CI->getContext());
1247 Instruction *InsertPt = CI;
1248 BasicBlock *IfBlock = CI->getParent();
1249 Builder.SetInsertPoint(InsertPt);
1250 Builder.SetCurrentDebugLocation(CI->getDebugLoc());
1251
1252 // Bitcast %addr fron i8* to EltTy*
1253 Type *NewPtrType =
1254 EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
1255 Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
1256
1257 unsigned VectorWidth = VecType->getNumElements();
1258 for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
1259
1260 // Fill the "else" block, created in the previous iteration
1261 //
1262 // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
1263 // %to_store = icmp eq i1 %mask_1, true
1264 // br i1 %to_load, label %cond.store, label %else
1265 //
1266 Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
1267 Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
1268 ConstantInt::get(Predicate->getType(), 1));
1269
1270 // Create "cond" block
1271 //
1272 // %OneElt = extractelement <16 x i32> %Src, i32 Idx
1273 // %EltAddr = getelementptr i32* %1, i32 0
1274 // %store i32 %OneElt, i32* %EltAddr
1275 //
1276 BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
1277 Builder.SetInsertPoint(InsertPt);
1278
1279 Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
David Blaikieaa41cd52015-04-03 21:33:42 +00001280 Value *Gep =
1281 Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001282 Builder.CreateStore(OneElt, Gep);
1283
1284 // Create "else" block, fill it in the next iteration
1285 BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
1286 Builder.SetInsertPoint(InsertPt);
1287 Instruction *OldBr = IfBlock->getTerminator();
1288 BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
1289 OldBr->eraseFromParent();
1290 IfBlock = NewIfBlock;
1291 }
1292 CI->eraseFromParent();
1293}
1294
1295bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
Chris Lattner7a277142011-01-15 07:14:54 +00001296 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001297
Chris Lattner7a277142011-01-15 07:14:54 +00001298 // Lower inline assembly if we can.
1299 // If we found an inline asm expession, and if the target knows how to
1300 // lower it to normal LLVM code, do so now.
1301 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1302 if (TLI->ExpandInlineAsm(CI)) {
1303 // Avoid invalidating the iterator.
1304 CurInstIterator = BB->begin();
1305 // Avoid processing instructions out of order, which could cause
1306 // reuse before a value is defined.
1307 SunkAddrs.clear();
1308 return true;
1309 }
1310 // Sink address computing for memory operands into the block.
1311 if (OptimizeInlineAsmInst(CI))
1312 return true;
1313 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001314
John Brawn0dbcd652015-03-18 12:01:59 +00001315 // Align the pointer arguments to this call if the target thinks it's a good
1316 // idea
1317 unsigned MinSize, PrefAlign;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001318 if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
John Brawn0dbcd652015-03-18 12:01:59 +00001319 for (auto &Arg : CI->arg_operands()) {
1320 // We want to align both objects whose address is used directly and
1321 // objects whose address is used in casts and GEPs, though it only makes
1322 // sense for GEPs if the offset is a multiple of the desired alignment and
1323 // if size - offset meets the size threshold.
1324 if (!Arg->getType()->isPointerTy())
1325 continue;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001326 APInt Offset(DL->getPointerSizeInBits(
1327 cast<PointerType>(Arg->getType())->getAddressSpace()),
1328 0);
1329 Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
John Brawn0dbcd652015-03-18 12:01:59 +00001330 uint64_t Offset2 = Offset.getLimitedValue();
John Brawne8fd6c82015-04-13 10:47:39 +00001331 if ((Offset2 & (PrefAlign-1)) != 0)
1332 continue;
John Brawn0dbcd652015-03-18 12:01:59 +00001333 AllocaInst *AI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001334 if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
1335 DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
John Brawn0dbcd652015-03-18 12:01:59 +00001336 AI->setAlignment(PrefAlign);
John Brawne8fd6c82015-04-13 10:47:39 +00001337 // Global variables can only be aligned if they are defined in this
1338 // object (i.e. they are uniquely initialized in this object), and
1339 // over-aligning global variables that have an explicit section is
1340 // forbidden.
1341 GlobalVariable *GV;
Mehdi Amini4fe37982015-07-07 18:45:17 +00001342 if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
1343 !GV->hasSection() && GV->getAlignment() < PrefAlign &&
1344 DL->getTypeAllocSize(GV->getType()->getElementType()) >=
1345 MinSize + Offset2)
John Brawne8fd6c82015-04-13 10:47:39 +00001346 GV->setAlignment(PrefAlign);
John Brawn0dbcd652015-03-18 12:01:59 +00001347 }
1348 // If this is a memcpy (or similar) then we may be able to improve the
1349 // alignment
1350 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00001351 unsigned Align = getKnownAlignment(MI->getDest(), *DL);
John Brawn0dbcd652015-03-18 12:01:59 +00001352 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
Mehdi Amini4fe37982015-07-07 18:45:17 +00001353 Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
John Brawn0dbcd652015-03-18 12:01:59 +00001354 if (Align > MI->getAlignment())
1355 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
1356 }
1357 }
1358
Eric Christopher4b7948e2010-03-11 02:41:03 +00001359 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001360 if (II) {
1361 switch (II->getIntrinsicID()) {
1362 default: break;
1363 case Intrinsic::objectsize: {
1364 // Lower all uses of llvm.objectsize.*
1365 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
1366 Type *ReturnTy = CI->getType();
1367 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
Nadav Rotem465834c2012-07-24 10:51:42 +00001368
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001369 // Substituting this can cause recursive simplifications, which can
1370 // invalidate our iterator. Use a WeakVH to hold onto it in case this
1371 // happens.
1372 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +00001373
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001374 replaceAndRecursivelySimplify(CI, RetVal,
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00001375 TLInfo, nullptr);
Chris Lattner1b93be52011-01-15 07:25:29 +00001376
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001377 // If the iterator instruction was recursively deleted, start over at the
1378 // start of the block.
1379 if (IterHandle != CurInstIterator) {
1380 CurInstIterator = BB->begin();
1381 SunkAddrs.clear();
1382 }
1383 return true;
Chris Lattner86d56c62011-01-18 20:53:04 +00001384 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001385 case Intrinsic::masked_load: {
1386 // Scalarize unsupported vector masked load
1387 if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
1388 ScalarizeMaskedLoad(CI);
1389 ModifiedDT = true;
1390 return true;
1391 }
1392 return false;
1393 }
1394 case Intrinsic::masked_store: {
1395 if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
1396 ScalarizeMaskedStore(CI);
1397 ModifiedDT = true;
1398 return true;
1399 }
1400 return false;
1401 }
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001402 case Intrinsic::aarch64_stlxr:
1403 case Intrinsic::aarch64_stxr: {
1404 ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
1405 if (!ExtVal || !ExtVal->hasOneUse() ||
1406 ExtVal->getParent() == CI->getParent())
1407 return false;
1408 // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
1409 ExtVal->moveBefore(CI);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00001410 // Mark this instruction as "inserted by CGP", so that other
1411 // optimizations don't touch it.
1412 InsertedInsts.insert(ExtVal);
Ahmed Bougacha236f9042015-05-22 21:37:17 +00001413 return true;
1414 }
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001415 }
Eric Christopher4b7948e2010-03-11 02:41:03 +00001416
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001417 if (TLI) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001418 // Unknown address space.
1419 // TODO: Target hook to pick which address space the intrinsic cares
1420 // about?
1421 unsigned AddrSpace = ~0u;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001422 SmallVector<Value*, 2> PtrOps;
1423 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001424 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001425 while (!PtrOps.empty())
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00001426 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00001427 return true;
1428 }
Pete Cooper615fd892012-03-13 20:59:56 +00001429 }
1430
Eric Christopher4b7948e2010-03-11 02:41:03 +00001431 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +00001432 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +00001433
Benjamin Kramer7b88a492010-03-12 09:27:41 +00001434 // Lower all default uses of _chk calls. This is very similar
1435 // to what InstCombineCalls does, but here we are only lowering calls
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001436 // to fortified library functions (e.g. __memcpy_chk) that have the default
1437 // "don't know" as the objectsize. Anything else should be left alone.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001438 FortifiedLibCallSimplifier Simplifier(TLInfo, true);
Ahmed Bougachae03bef72015-01-12 17:22:43 +00001439 if (Value *V = Simplifier.optimizeCall(CI)) {
1440 CI->replaceAllUsesWith(V);
1441 CI->eraseFromParent();
1442 return true;
1443 }
1444 return false;
Eric Christopher4b7948e2010-03-11 02:41:03 +00001445}
Chris Lattner1b93be52011-01-15 07:25:29 +00001446
Evan Cheng0663f232011-03-21 01:19:09 +00001447/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
1448/// instructions to the predecessor to enable tail call optimizations. The
1449/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001450/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001451/// bb0:
1452/// %tmp0 = tail call i32 @f0()
1453/// br label %return
1454/// bb1:
1455/// %tmp1 = tail call i32 @f1()
1456/// br label %return
1457/// bb2:
1458/// %tmp2 = tail call i32 @f2()
1459/// br label %return
1460/// return:
1461/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
1462/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001463/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +00001464///
1465/// =>
1466///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001467/// @code
Evan Cheng0663f232011-03-21 01:19:09 +00001468/// bb0:
1469/// %tmp0 = tail call i32 @f0()
1470/// ret i32 %tmp0
1471/// bb1:
1472/// %tmp1 = tail call i32 @f1()
1473/// ret i32 %tmp1
1474/// bb2:
1475/// %tmp2 = tail call i32 @f2()
1476/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +00001477/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +00001478bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +00001479 if (!TLI)
1480 return false;
1481
Benjamin Kramer455fa352012-11-23 19:17:06 +00001482 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
1483 if (!RI)
1484 return false;
1485
Craig Topperc0196b12014-04-14 00:51:57 +00001486 PHINode *PN = nullptr;
1487 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +00001488 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +00001489 if (V) {
1490 BCI = dyn_cast<BitCastInst>(V);
1491 if (BCI)
1492 V = BCI->getOperand(0);
1493
1494 PN = dyn_cast<PHINode>(V);
1495 if (!PN)
1496 return false;
1497 }
Evan Cheng0663f232011-03-21 01:19:09 +00001498
Cameron Zwarich4649f172011-03-24 04:52:10 +00001499 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001500 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001501
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001502 // It's not safe to eliminate the sign / zero extension of the return value.
1503 // See llvm::isInTailCallPosition().
1504 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +00001505 AttributeSet CallerAttrs = F->getAttributes();
1506 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
1507 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001508 return false;
Evan Cheng0663f232011-03-21 01:19:09 +00001509
Cameron Zwarich4649f172011-03-24 04:52:10 +00001510 // Make sure there are no instructions between the PHI and return, or that the
1511 // return is the first instruction in the block.
1512 if (PN) {
1513 BasicBlock::iterator BI = BB->begin();
1514 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +00001515 if (&*BI == BCI)
1516 // Also skip over the bitcast.
1517 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001518 if (&*BI != RI)
1519 return false;
1520 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001521 BasicBlock::iterator BI = BB->begin();
1522 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
1523 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001524 return false;
1525 }
Evan Cheng0663f232011-03-21 01:19:09 +00001526
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001527 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
1528 /// call.
1529 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +00001530 if (PN) {
1531 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
1532 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
1533 // Make sure the phi value is indeed produced by the tail call.
1534 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
1535 TLI->mayBeEmittedAsTailCall(CI))
1536 TailCalls.push_back(CI);
1537 }
1538 } else {
1539 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001540 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
David Blaikie70573dc2014-11-19 07:49:26 +00001541 if (!VisitedBBs.insert(*PI).second)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001542 continue;
1543
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00001544 BasicBlock::InstListType &InstList = (*PI)->getInstList();
Cameron Zwarich4649f172011-03-24 04:52:10 +00001545 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1546 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001547 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1548 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +00001549 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +00001550
Cameron Zwarich4649f172011-03-24 04:52:10 +00001551 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +00001552 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +00001553 TailCalls.push_back(CI);
1554 }
Evan Cheng0663f232011-03-21 01:19:09 +00001555 }
1556
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001557 bool Changed = false;
1558 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1559 CallInst *CI = TailCalls[i];
1560 CallSite CS(CI);
1561
1562 // Conservatively require the attributes of the call to match those of the
1563 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001564 AttributeSet CalleeAttrs = CS.getAttributes();
1565 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001566 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001567 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001568 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001569 continue;
1570
1571 // Make sure the call instruction is followed by an unconditional branch to
1572 // the return block.
1573 BasicBlock *CallBB = CI->getParent();
1574 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1575 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1576 continue;
1577
1578 // Duplicate the return into CallBB.
1579 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001580 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001581 ++NumRetsDup;
1582 }
1583
1584 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001585 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001586 BB->eraseFromParent();
1587
1588 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001589}
1590
Chris Lattner728f9022008-11-25 07:09:13 +00001591//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001592// Memory Optimization
1593//===----------------------------------------------------------------------===//
1594
Chandler Carruthc8925912013-01-05 02:09:22 +00001595namespace {
1596
1597/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1598/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001599struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001600 Value *BaseReg;
1601 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001602 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001603 void print(raw_ostream &OS) const;
1604 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001605
Chandler Carruthc8925912013-01-05 02:09:22 +00001606 bool operator==(const ExtAddrMode& O) const {
1607 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1608 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1609 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1610 }
1611};
1612
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001613#ifndef NDEBUG
1614static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1615 AM.print(OS);
1616 return OS;
1617}
1618#endif
1619
Chandler Carruthc8925912013-01-05 02:09:22 +00001620void ExtAddrMode::print(raw_ostream &OS) const {
1621 bool NeedPlus = false;
1622 OS << "[";
1623 if (BaseGV) {
1624 OS << (NeedPlus ? " + " : "")
1625 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001626 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001627 NeedPlus = true;
1628 }
1629
Richard Trieuc0f91212014-05-30 03:15:17 +00001630 if (BaseOffs) {
1631 OS << (NeedPlus ? " + " : "")
1632 << BaseOffs;
1633 NeedPlus = true;
1634 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001635
1636 if (BaseReg) {
1637 OS << (NeedPlus ? " + " : "")
1638 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001639 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001640 NeedPlus = true;
1641 }
1642 if (Scale) {
1643 OS << (NeedPlus ? " + " : "")
1644 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001645 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001646 }
1647
1648 OS << ']';
1649}
1650
1651#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1652void ExtAddrMode::dump() const {
1653 print(dbgs());
1654 dbgs() << '\n';
1655}
1656#endif
1657
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001658/// \brief This class provides transaction based operation on the IR.
1659/// Every change made through this class is recorded in the internal state and
1660/// can be undone (rollback) until commit is called.
1661class TypePromotionTransaction {
1662
1663 /// \brief This represents the common interface of the individual transaction.
1664 /// Each class implements the logic for doing one specific modification on
1665 /// the IR via the TypePromotionTransaction.
1666 class TypePromotionAction {
1667 protected:
1668 /// The Instruction modified.
1669 Instruction *Inst;
1670
1671 public:
1672 /// \brief Constructor of the action.
1673 /// The constructor performs the related action on the IR.
1674 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1675
1676 virtual ~TypePromotionAction() {}
1677
1678 /// \brief Undo the modification done by this action.
1679 /// When this method is called, the IR must be in the same state as it was
1680 /// before this action was applied.
1681 /// \pre Undoing the action works if and only if the IR is in the exact same
1682 /// state as it was directly after this action was applied.
1683 virtual void undo() = 0;
1684
1685 /// \brief Advocate every change made by this action.
1686 /// When the results on the IR of the action are to be kept, it is important
1687 /// to call this function, otherwise hidden information may be kept forever.
1688 virtual void commit() {
1689 // Nothing to be done, this action is not doing anything.
1690 }
1691 };
1692
1693 /// \brief Utility to remember the position of an instruction.
1694 class InsertionHandler {
1695 /// Position of an instruction.
1696 /// Either an instruction:
1697 /// - Is the first in a basic block: BB is used.
1698 /// - Has a previous instructon: PrevInst is used.
1699 union {
1700 Instruction *PrevInst;
1701 BasicBlock *BB;
1702 } Point;
1703 /// Remember whether or not the instruction had a previous instruction.
1704 bool HasPrevInstruction;
1705
1706 public:
1707 /// \brief Record the position of \p Inst.
1708 InsertionHandler(Instruction *Inst) {
1709 BasicBlock::iterator It = Inst;
1710 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1711 if (HasPrevInstruction)
1712 Point.PrevInst = --It;
1713 else
1714 Point.BB = Inst->getParent();
1715 }
1716
1717 /// \brief Insert \p Inst at the recorded position.
1718 void insert(Instruction *Inst) {
1719 if (HasPrevInstruction) {
1720 if (Inst->getParent())
1721 Inst->removeFromParent();
1722 Inst->insertAfter(Point.PrevInst);
1723 } else {
1724 Instruction *Position = Point.BB->getFirstInsertionPt();
1725 if (Inst->getParent())
1726 Inst->moveBefore(Position);
1727 else
1728 Inst->insertBefore(Position);
1729 }
1730 }
1731 };
1732
1733 /// \brief Move an instruction before another.
1734 class InstructionMoveBefore : public TypePromotionAction {
1735 /// Original position of the instruction.
1736 InsertionHandler Position;
1737
1738 public:
1739 /// \brief Move \p Inst before \p Before.
1740 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1741 : TypePromotionAction(Inst), Position(Inst) {
1742 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1743 Inst->moveBefore(Before);
1744 }
1745
1746 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001747 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001748 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1749 Position.insert(Inst);
1750 }
1751 };
1752
1753 /// \brief Set the operand of an instruction with a new value.
1754 class OperandSetter : public TypePromotionAction {
1755 /// Original operand of the instruction.
1756 Value *Origin;
1757 /// Index of the modified instruction.
1758 unsigned Idx;
1759
1760 public:
1761 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1762 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1763 : TypePromotionAction(Inst), Idx(Idx) {
1764 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1765 << "for:" << *Inst << "\n"
1766 << "with:" << *NewVal << "\n");
1767 Origin = Inst->getOperand(Idx);
1768 Inst->setOperand(Idx, NewVal);
1769 }
1770
1771 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001772 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001773 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1774 << "for: " << *Inst << "\n"
1775 << "with: " << *Origin << "\n");
1776 Inst->setOperand(Idx, Origin);
1777 }
1778 };
1779
1780 /// \brief Hide the operands of an instruction.
1781 /// Do as if this instruction was not using any of its operands.
1782 class OperandsHider : public TypePromotionAction {
1783 /// The list of original operands.
1784 SmallVector<Value *, 4> OriginalValues;
1785
1786 public:
1787 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1788 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1789 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1790 unsigned NumOpnds = Inst->getNumOperands();
1791 OriginalValues.reserve(NumOpnds);
1792 for (unsigned It = 0; It < NumOpnds; ++It) {
1793 // Save the current operand.
1794 Value *Val = Inst->getOperand(It);
1795 OriginalValues.push_back(Val);
1796 // Set a dummy one.
1797 // We could use OperandSetter here, but that would implied an overhead
1798 // that we are not willing to pay.
1799 Inst->setOperand(It, UndefValue::get(Val->getType()));
1800 }
1801 }
1802
1803 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001804 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001805 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1806 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1807 Inst->setOperand(It, OriginalValues[It]);
1808 }
1809 };
1810
1811 /// \brief Build a truncate instruction.
1812 class TruncBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001813 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001814 public:
1815 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1816 /// result.
1817 /// trunc Opnd to Ty.
1818 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1819 IRBuilder<> Builder(Opnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00001820 Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1821 DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001822 }
1823
Quentin Colombetac55b152014-09-16 22:36:07 +00001824 /// \brief Get the built value.
1825 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001826
1827 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001828 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001829 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1830 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1831 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001832 }
1833 };
1834
1835 /// \brief Build a sign extension instruction.
1836 class SExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001837 Value *Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001838 public:
1839 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1840 /// result.
1841 /// sext Opnd to Ty.
1842 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001843 : TypePromotionAction(InsertPt) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001844 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001845 Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1846 DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001847 }
1848
Quentin Colombetac55b152014-09-16 22:36:07 +00001849 /// \brief Get the built value.
1850 Value *getBuiltValue() { return Val; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001851
1852 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001853 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001854 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1855 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1856 IVal->eraseFromParent();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001857 }
1858 };
1859
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001860 /// \brief Build a zero extension instruction.
1861 class ZExtBuilder : public TypePromotionAction {
Quentin Colombetac55b152014-09-16 22:36:07 +00001862 Value *Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001863 public:
1864 /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1865 /// result.
1866 /// zext Opnd to Ty.
1867 ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
Quentin Colombetac55b152014-09-16 22:36:07 +00001868 : TypePromotionAction(InsertPt) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001869 IRBuilder<> Builder(InsertPt);
Quentin Colombetac55b152014-09-16 22:36:07 +00001870 Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1871 DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001872 }
1873
Quentin Colombetac55b152014-09-16 22:36:07 +00001874 /// \brief Get the built value.
1875 Value *getBuiltValue() { return Val; }
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001876
1877 /// \brief Remove the built instruction.
1878 void undo() override {
Quentin Colombetac55b152014-09-16 22:36:07 +00001879 DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1880 if (Instruction *IVal = dyn_cast<Instruction>(Val))
1881 IVal->eraseFromParent();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00001882 }
1883 };
1884
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001885 /// \brief Mutate an instruction to another type.
1886 class TypeMutator : public TypePromotionAction {
1887 /// Record the original type.
1888 Type *OrigTy;
1889
1890 public:
1891 /// \brief Mutate the type of \p Inst into \p NewTy.
1892 TypeMutator(Instruction *Inst, Type *NewTy)
1893 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1894 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1895 << "\n");
1896 Inst->mutateType(NewTy);
1897 }
1898
1899 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001900 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001901 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1902 << "\n");
1903 Inst->mutateType(OrigTy);
1904 }
1905 };
1906
1907 /// \brief Replace the uses of an instruction by another instruction.
1908 class UsesReplacer : public TypePromotionAction {
1909 /// Helper structure to keep track of the replaced uses.
1910 struct InstructionAndIdx {
1911 /// The instruction using the instruction.
1912 Instruction *Inst;
1913 /// The index where this instruction is used for Inst.
1914 unsigned Idx;
1915 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1916 : Inst(Inst), Idx(Idx) {}
1917 };
1918
1919 /// Keep track of the original uses (pair Instruction, Index).
1920 SmallVector<InstructionAndIdx, 4> OriginalUses;
1921 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1922
1923 public:
1924 /// \brief Replace all the use of \p Inst by \p New.
1925 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1926 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1927 << "\n");
1928 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001929 for (Use &U : Inst->uses()) {
1930 Instruction *UserI = cast<Instruction>(U.getUser());
1931 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001932 }
1933 // Now, we can replace the uses.
1934 Inst->replaceAllUsesWith(New);
1935 }
1936
1937 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001938 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001939 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1940 for (use_iterator UseIt = OriginalUses.begin(),
1941 EndIt = OriginalUses.end();
1942 UseIt != EndIt; ++UseIt) {
1943 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1944 }
1945 }
1946 };
1947
1948 /// \brief Remove an instruction from the IR.
1949 class InstructionRemover : public TypePromotionAction {
1950 /// Original position of the instruction.
1951 InsertionHandler Inserter;
1952 /// Helper structure to hide all the link to the instruction. In other
1953 /// words, this helps to do as if the instruction was removed.
1954 OperandsHider Hider;
1955 /// Keep track of the uses replaced, if any.
1956 UsesReplacer *Replacer;
1957
1958 public:
1959 /// \brief Remove all reference of \p Inst and optinally replace all its
1960 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001961 /// \pre If !Inst->use_empty(), then New != nullptr
1962 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001963 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001964 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001965 if (New)
1966 Replacer = new UsesReplacer(Inst, New);
1967 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1968 Inst->removeFromParent();
1969 }
1970
Alexander Kornienkof817c1c2015-04-11 02:11:45 +00001971 ~InstructionRemover() override { delete Replacer; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001972
1973 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001974 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001975
1976 /// \brief Resurrect the instruction and reassign it to the proper uses if
1977 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001978 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001979 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1980 Inserter.insert(Inst);
1981 if (Replacer)
1982 Replacer->undo();
1983 Hider.undo();
1984 }
1985 };
1986
1987public:
1988 /// Restoration point.
1989 /// The restoration point is a pointer to an action instead of an iterator
1990 /// because the iterator may be invalidated but not the pointer.
1991 typedef const TypePromotionAction *ConstRestorationPt;
1992 /// Advocate every changes made in that transaction.
1993 void commit();
1994 /// Undo all the changes made after the given point.
1995 void rollback(ConstRestorationPt Point);
1996 /// Get the current restoration point.
1997 ConstRestorationPt getRestorationPoint() const;
1998
1999 /// \name API for IR modification with state keeping to support rollback.
2000 /// @{
2001 /// Same as Instruction::setOperand.
2002 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
2003 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00002004 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002005 /// Same as Value::replaceAllUsesWith.
2006 void replaceAllUsesWith(Instruction *Inst, Value *New);
2007 /// Same as Value::mutateType.
2008 void mutateType(Instruction *Inst, Type *NewTy);
2009 /// Same as IRBuilder::createTrunc.
Quentin Colombetac55b152014-09-16 22:36:07 +00002010 Value *createTrunc(Instruction *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002011 /// Same as IRBuilder::createSExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002012 Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002013 /// Same as IRBuilder::createZExt.
Quentin Colombetac55b152014-09-16 22:36:07 +00002014 Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002015 /// Same as Instruction::moveBefore.
2016 void moveBefore(Instruction *Inst, Instruction *Before);
2017 /// @}
2018
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002019private:
2020 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00002021 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
2022 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002023};
2024
2025void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
2026 Value *NewVal) {
2027 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002028 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002029}
2030
2031void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
2032 Value *NewVal) {
2033 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002034 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002035}
2036
2037void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
2038 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00002039 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002040}
2041
2042void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00002043 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002044}
2045
Quentin Colombetac55b152014-09-16 22:36:07 +00002046Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
2047 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002048 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002049 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002050 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002051 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002052}
2053
Quentin Colombetac55b152014-09-16 22:36:07 +00002054Value *TypePromotionTransaction::createSExt(Instruction *Inst,
2055 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00002056 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002057 Value *Val = Ptr->getBuiltValue();
David Blaikie7620b312014-04-15 06:17:44 +00002058 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002059 return Val;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002060}
2061
Quentin Colombetac55b152014-09-16 22:36:07 +00002062Value *TypePromotionTransaction::createZExt(Instruction *Inst,
2063 Value *Opnd, Type *Ty) {
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002064 std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
Quentin Colombetac55b152014-09-16 22:36:07 +00002065 Value *Val = Ptr->getBuiltValue();
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002066 Actions.push_back(std::move(Ptr));
Quentin Colombetac55b152014-09-16 22:36:07 +00002067 return Val;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002068}
2069
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002070void TypePromotionTransaction::moveBefore(Instruction *Inst,
2071 Instruction *Before) {
2072 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00002073 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002074}
2075
2076TypePromotionTransaction::ConstRestorationPt
2077TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00002078 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002079}
2080
2081void TypePromotionTransaction::commit() {
2082 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00002083 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002084 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002085 Actions.clear();
2086}
2087
2088void TypePromotionTransaction::rollback(
2089 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00002090 while (!Actions.empty() && Point != Actions.back().get()) {
2091 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002092 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002093 }
2094}
2095
Chandler Carruthc8925912013-01-05 02:09:22 +00002096/// \brief A helper class for matching addressing modes.
2097///
2098/// This encapsulates the logic for matching the target-legal addressing modes.
2099class AddressingModeMatcher {
2100 SmallVectorImpl<Instruction*> &AddrModeInsts;
Eric Christopherd75c00c2015-02-26 22:38:34 +00002101 const TargetMachine &TM;
Chandler Carruthc8925912013-01-05 02:09:22 +00002102 const TargetLowering &TLI;
Mehdi Amini4fe37982015-07-07 18:45:17 +00002103 const DataLayout &DL;
Chandler Carruthc8925912013-01-05 02:09:22 +00002104
2105 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
2106 /// the memory instruction that we're computing this address for.
2107 Type *AccessTy;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002108 unsigned AddrSpace;
Chandler Carruthc8925912013-01-05 02:09:22 +00002109 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00002110
Chandler Carruthc8925912013-01-05 02:09:22 +00002111 /// AddrMode - This is the addressing mode that we're building up. This is
2112 /// part of the return value of this addressing mode matching stuff.
2113 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002114
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002115 /// The instructions inserted by other CodeGenPrepare optimizations.
2116 const SetOfInstrs &InsertedInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002117 /// A map from the instructions to their type before promotion.
2118 InstrToOrigTy &PromotedInsts;
2119 /// The ongoing transaction where every action should be registered.
2120 TypePromotionTransaction &TPT;
2121
Chandler Carruthc8925912013-01-05 02:09:22 +00002122 /// IgnoreProfitability - This is set to true when we should not do
2123 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
2124 /// always returns true.
2125 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00002126
Eric Christopherd75c00c2015-02-26 22:38:34 +00002127 AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002128 const TargetMachine &TM, Type *AT, unsigned AS,
2129 Instruction *MI, ExtAddrMode &AM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002130 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002131 InstrToOrigTy &PromotedInsts,
2132 TypePromotionTransaction &TPT)
Eric Christopherd75c00c2015-02-26 22:38:34 +00002133 : AddrModeInsts(AMI), TM(TM),
2134 TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
2135 ->getTargetLowering()),
Mehdi Amini4fe37982015-07-07 18:45:17 +00002136 DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
2137 MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
2138 PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002139 IgnoreProfitability = false;
2140 }
2141public:
Stephen Lin837bba12013-07-15 17:55:02 +00002142
Chandler Carruthc8925912013-01-05 02:09:22 +00002143 /// Match - Find the maximal addressing mode that a load/store of V can fold,
2144 /// give an access type of AccessTy. This returns a list of involved
2145 /// instructions in AddrModeInsts.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002146 /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002147 /// optimizations.
2148 /// \p PromotedInsts maps the instructions to their type before promotion.
2149 /// \p The ongoing transaction where every action should be registered.
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002150 static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
Chandler Carruthc8925912013-01-05 02:09:22 +00002151 Instruction *MemoryInst,
2152 SmallVectorImpl<Instruction*> &AddrModeInsts,
Eric Christopherd75c00c2015-02-26 22:38:34 +00002153 const TargetMachine &TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002154 const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002155 InstrToOrigTy &PromotedInsts,
2156 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002157 ExtAddrMode Result;
2158
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002159 bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002160 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002161 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00002162 (void)Success; assert(Success && "Couldn't select *anything*?");
2163 return Result;
2164 }
2165private:
2166 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
2167 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002168 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00002169 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00002170 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
2171 ExtAddrMode &AMBefore,
2172 ExtAddrMode &AMAfter);
2173 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002174 bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost,
Quentin Colombet867c5502014-02-14 22:23:22 +00002175 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00002176};
2177
2178/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
2179/// Return true and update AddrMode if this addr mode is legal for the target,
2180/// false if not.
2181bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
2182 unsigned Depth) {
2183 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
2184 // mode. Just process that directly.
2185 if (Scale == 1)
2186 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00002187
Chandler Carruthc8925912013-01-05 02:09:22 +00002188 // If the scale is 0, it takes nothing to add this.
2189 if (Scale == 0)
2190 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002191
Chandler Carruthc8925912013-01-05 02:09:22 +00002192 // If we already have a scale of this value, we can add to it, otherwise, we
2193 // need an available scale field.
2194 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
2195 return false;
2196
2197 ExtAddrMode TestAddrMode = AddrMode;
2198
2199 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
2200 // [A+B + A*7] -> [B+A*8].
2201 TestAddrMode.Scale += Scale;
2202 TestAddrMode.ScaledReg = ScaleReg;
2203
2204 // If the new address isn't legal, bail out.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002205 if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002206 return false;
2207
2208 // It was legal, so commit it.
2209 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00002210
Chandler Carruthc8925912013-01-05 02:09:22 +00002211 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
2212 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
2213 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002214 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002215 if (isa<Instruction>(ScaleReg) && // not a constant expr.
2216 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
2217 TestAddrMode.ScaledReg = AddLHS;
2218 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002219
Chandler Carruthc8925912013-01-05 02:09:22 +00002220 // If this addressing mode is legal, commit it and remember that we folded
2221 // this instruction.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002222 if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002223 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
2224 AddrMode = TestAddrMode;
2225 return true;
2226 }
2227 }
2228
2229 // Otherwise, not (x+c)*scale, just return what we have.
2230 return true;
2231}
2232
2233/// MightBeFoldableInst - This is a little filter, which returns true if an
2234/// addressing computation involving I might be folded into a load/store
2235/// accessing it. This doesn't need to be perfect, but needs to accept at least
2236/// the set of instructions that MatchOperationAddr can.
2237static bool MightBeFoldableInst(Instruction *I) {
2238 switch (I->getOpcode()) {
2239 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00002240 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00002241 // Don't touch identity bitcasts.
2242 if (I->getType() == I->getOperand(0)->getType())
2243 return false;
2244 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
2245 case Instruction::PtrToInt:
2246 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2247 return true;
2248 case Instruction::IntToPtr:
2249 // We know the input is intptr_t, so this is foldable.
2250 return true;
2251 case Instruction::Add:
2252 return true;
2253 case Instruction::Mul:
2254 case Instruction::Shl:
2255 // Can only handle X*C and X << C.
2256 return isa<ConstantInt>(I->getOperand(1));
2257 case Instruction::GetElementPtr:
2258 return true;
2259 default:
2260 return false;
2261 }
2262}
2263
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002264/// \brief Check whether or not \p Val is a legal instruction for \p TLI.
2265/// \note \p Val is assumed to be the product of some type promotion.
2266/// Therefore if \p Val has an undefined state in \p TLI, this is assumed
2267/// to be legal, as the non-promoted value would have had the same state.
Mehdi Amini44ede332015-07-09 02:09:04 +00002268static bool isPromotedInstructionLegal(const TargetLowering &TLI,
2269 const DataLayout &DL, Value *Val) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002270 Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2271 if (!PromotedInst)
2272 return false;
2273 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2274 // If the ISDOpcode is undefined, it was undefined before the promotion.
2275 if (!ISDOpcode)
2276 return true;
2277 // Otherwise, check if the promoted instruction is legal or not.
2278 return TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00002279 ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002280}
2281
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002282/// \brief Hepler class to perform type promotion.
2283class TypePromotionHelper {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002284 /// \brief Utility function to check whether or not a sign or zero extension
2285 /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2286 /// either using the operands of \p Inst or promoting \p Inst.
2287 /// The type of the extension is defined by \p IsSExt.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002288 /// In other words, check if:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002289 /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002290 /// #1 Promotion applies:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002291 /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002292 /// #2 Operand reuses:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002293 /// ext opnd1 to ConsideredExtType.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002294 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002295 static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2296 const InstrToOrigTy &PromotedInsts, bool IsSExt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002297
2298 /// \brief Utility function to determine if \p OpIdx should be promoted when
2299 /// promoting \p Inst.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002300 static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002301 if (isa<SelectInst>(Inst) && OpIdx == 0)
2302 return false;
2303 return true;
2304 }
2305
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002306 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002307 /// operand is a promotable trunc or sext or zext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002308 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002309 /// \p CreatedInstsCost[out] contains the cost of all instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002310 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002311 /// Newly added extensions are inserted in \p Exts.
2312 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002313 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002314 /// \return The promoted value which is used instead of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002315 static Value *promoteOperandForTruncAndAnyExt(
2316 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002317 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002318 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002319 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002320
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002321 /// \brief Utility function to promote the operand of \p Ext when this
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002322 /// operand is promotable and is not a supported trunc or sext.
2323 /// \p PromotedInsts maps the instructions to their type before promotion.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002324 /// \p CreatedInstsCost[out] contains the cost of all the instructions
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002325 /// created to promote the operand of Ext.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002326 /// Newly added extensions are inserted in \p Exts.
2327 /// Newly added truncates are inserted in \p Truncs.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002328 /// Should never be called directly.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002329 /// \return The promoted value which is used instead of Ext.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002330 static Value *promoteOperandForOther(Instruction *Ext,
2331 TypePromotionTransaction &TPT,
2332 InstrToOrigTy &PromotedInsts,
2333 unsigned &CreatedInstsCost,
2334 SmallVectorImpl<Instruction *> *Exts,
2335 SmallVectorImpl<Instruction *> *Truncs,
2336 const TargetLowering &TLI, bool IsSExt);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002337
2338 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002339 static Value *signExtendOperandForOther(
2340 Instruction *Ext, TypePromotionTransaction &TPT,
2341 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2342 SmallVectorImpl<Instruction *> *Exts,
2343 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2344 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2345 Exts, Truncs, TLI, true);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002346 }
2347
2348 /// \see promoteOperandForOther.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002349 static Value *zeroExtendOperandForOther(
2350 Instruction *Ext, TypePromotionTransaction &TPT,
2351 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2352 SmallVectorImpl<Instruction *> *Exts,
2353 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2354 return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2355 Exts, Truncs, TLI, false);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002356 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002357
2358public:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002359 /// Type for the utility function that promotes the operand of Ext.
2360 typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002361 InstrToOrigTy &PromotedInsts,
2362 unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002363 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002364 SmallVectorImpl<Instruction *> *Truncs,
2365 const TargetLowering &TLI);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002366 /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2367 /// action to promote the operand of \p Ext instead of using Ext.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002368 /// \return NULL if no promotable action is possible with the current
2369 /// sign extension.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002370 /// \p InsertedInsts keeps track of all the instructions inserted by the
2371 /// other CodeGenPrepare optimizations. This information is important
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002372 /// because we do not want to promote these instructions as CodeGenPrepare
2373 /// will reinsert them later. Thus creating an infinite loop: create/remove.
2374 /// \p PromotedInsts maps the instructions to their type before promotion.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002375 static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002376 const TargetLowering &TLI,
2377 const InstrToOrigTy &PromotedInsts);
2378};
2379
2380bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002381 Type *ConsideredExtType,
2382 const InstrToOrigTy &PromotedInsts,
2383 bool IsSExt) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002384 // The promotion helper does not know how to deal with vector types yet.
2385 // To be able to fix that, we would need to fix the places where we
2386 // statically extend, e.g., constants and such.
2387 if (Inst->getType()->isVectorTy())
2388 return false;
2389
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002390 // We can always get through zext.
2391 if (isa<ZExtInst>(Inst))
2392 return true;
2393
2394 // sext(sext) is ok too.
2395 if (IsSExt && isa<SExtInst>(Inst))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002396 return true;
2397
2398 // We can get through binary operator, if it is legal. In other words, the
2399 // binary operator must have a nuw or nsw flag.
2400 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2401 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002402 ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2403 (IsSExt && BinOp->hasNoSignedWrap())))
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002404 return true;
2405
2406 // Check if we can do the following simplification.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002407 // ext(trunc(opnd)) --> ext(opnd)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002408 if (!isa<TruncInst>(Inst))
2409 return false;
2410
2411 Value *OpndVal = Inst->getOperand(0);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002412 // Check if we can use this operand in the extension.
2413 // If the type is larger than the result type of the extension,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002414 // we cannot.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002415 if (!OpndVal->getType()->isIntegerTy() ||
2416 OpndVal->getType()->getIntegerBitWidth() >
2417 ConsideredExtType->getIntegerBitWidth())
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002418 return false;
2419
2420 // If the operand of the truncate is not an instruction, we will not have
2421 // any information on the dropped bits.
2422 // (Actually we could for constant but it is not worth the extra logic).
2423 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2424 if (!Opnd)
2425 return false;
2426
2427 // Check if the source of the type is narrow enough.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002428 // I.e., check that trunc just drops extended bits of the same kind of
2429 // the extension.
2430 // #1 get the type of the operand and check the kind of the extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002431 const Type *OpndType;
2432 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
Benjamin Kramer4cd5faa2015-07-31 17:00:39 +00002433 if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2434 OpndType = It->second.getPointer();
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002435 else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2436 OpndType = Opnd->getOperand(0)->getType();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002437 else
2438 return false;
2439
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002440 // #2 check that the truncate just drop extended bits.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002441 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2442 return true;
2443
2444 return false;
2445}
2446
2447TypePromotionHelper::Action TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002448 Instruction *Ext, const SetOfInstrs &InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002449 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002450 assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2451 "Unexpected instruction type");
2452 Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2453 Type *ExtTy = Ext->getType();
2454 bool IsSExt = isa<SExtInst>(Ext);
2455 // If the operand of the extension is not an instruction, we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002456 // get through.
2457 // If it, check we can get through.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002458 if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
Craig Topperc0196b12014-04-14 00:51:57 +00002459 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002460
2461 // Do not promote if the operand has been added by codegenprepare.
2462 // Otherwise, it means we are undoing an optimization that is likely to be
2463 // redone, thus causing potential infinite loop.
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002464 if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00002465 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002466
2467 // SExt or Trunc instructions.
2468 // Return the related handler.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002469 if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2470 isa<ZExtInst>(ExtOpnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002471 return promoteOperandForTruncAndAnyExt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002472
2473 // Regular instruction.
2474 // Abort early if we will have to insert non-free instructions.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002475 if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00002476 return nullptr;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002477 return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002478}
2479
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002480Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002481 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002482 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002483 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002484 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002485 // By construction, the operand of SExt is an instruction. Otherwise we cannot
2486 // get through it and this method should not be called.
2487 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
Quentin Colombetac55b152014-09-16 22:36:07 +00002488 Value *ExtVal = SExt;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002489 bool HasMergedNonFreeExt = false;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002490 if (isa<ZExtInst>(SExtOpnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002491 // Replace s|zext(zext(opnd))
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002492 // => zext(opnd).
Quentin Colombet1b274f92015-03-10 21:48:15 +00002493 HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
Quentin Colombetac55b152014-09-16 22:36:07 +00002494 Value *ZExt =
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002495 TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2496 TPT.replaceAllUsesWith(SExt, ZExt);
2497 TPT.eraseInstruction(SExt);
Quentin Colombetac55b152014-09-16 22:36:07 +00002498 ExtVal = ZExt;
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002499 } else {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002500 // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2501 // => z|sext(opnd).
Quentin Colombetb2c5c6d2014-09-11 21:22:14 +00002502 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2503 }
Quentin Colombet1b274f92015-03-10 21:48:15 +00002504 CreatedInstsCost = 0;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002505
2506 // Remove dead code.
2507 if (SExtOpnd->use_empty())
2508 TPT.eraseInstruction(SExtOpnd);
2509
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002510 // Check if the extension is still needed.
Quentin Colombetac55b152014-09-16 22:36:07 +00002511 Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002512 if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
Quentin Colombet1b274f92015-03-10 21:48:15 +00002513 if (ExtInst) {
2514 if (Exts)
2515 Exts->push_back(ExtInst);
2516 CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2517 }
Quentin Colombetac55b152014-09-16 22:36:07 +00002518 return ExtVal;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002519 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002520
Quentin Colombet9dcb7242014-09-15 18:26:58 +00002521 // At this point we have: ext ty opnd to ty.
2522 // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2523 Value *NextVal = ExtInst->getOperand(0);
2524 TPT.eraseInstruction(ExtInst, NextVal);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002525 return NextVal;
2526}
2527
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002528Value *TypePromotionHelper::promoteOperandForOther(
2529 Instruction *Ext, TypePromotionTransaction &TPT,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002530 InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002531 SmallVectorImpl<Instruction *> *Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00002532 SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2533 bool IsSExt) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002534 // By construction, the operand of Ext is an instruction. Otherwise we cannot
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002535 // get through it and this method should not be called.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002536 Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
Quentin Colombet1b274f92015-03-10 21:48:15 +00002537 CreatedInstsCost = 0;
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002538 if (!ExtOpnd->hasOneUse()) {
2539 // ExtOpnd will be promoted.
2540 // All its uses, but Ext, will need to use a truncated value of the
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002541 // promoted version.
2542 // Create the truncate now.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002543 Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
Quentin Colombetac55b152014-09-16 22:36:07 +00002544 if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2545 ITrunc->removeFromParent();
2546 // Insert it just after the definition.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002547 ITrunc->insertAfter(ExtOpnd);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002548 if (Truncs)
2549 Truncs->push_back(ITrunc);
Quentin Colombetac55b152014-09-16 22:36:07 +00002550 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002551
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002552 TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2553 // Restore the operand of Ext (which has been replace by the previous call
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002554 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002555 TPT.setOperand(Ext, 0, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002556 }
2557
2558 // Get through the Instruction:
2559 // 1. Update its type.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002560 // 2. Replace the uses of Ext by Inst.
2561 // 3. Extend each operand that needs to be extended.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002562
2563 // Remember the original type of the instruction before promotion.
2564 // This is useful to know that the high bits are sign extended bits.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002565 PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2566 ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002567 // Step #1.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002568 TPT.mutateType(ExtOpnd, Ext->getType());
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002569 // Step #2.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002570 TPT.replaceAllUsesWith(Ext, ExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002571 // Step #3.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002572 Instruction *ExtForOpnd = Ext;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002573
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002574 DEBUG(dbgs() << "Propagate Ext to operands\n");
2575 for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002576 ++OpIdx) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002577 DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2578 if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2579 !shouldExtOperand(ExtOpnd, OpIdx)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002580 DEBUG(dbgs() << "No need to propagate\n");
2581 continue;
2582 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002583 // Check if we can statically extend the operand.
2584 Value *Opnd = ExtOpnd->getOperand(OpIdx);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002585 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002586 DEBUG(dbgs() << "Statically extend\n");
2587 unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2588 APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2589 : Cst->getValue().zext(BitWidth);
2590 TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002591 continue;
2592 }
2593 // UndefValue are typed, so we have to statically sign extend them.
2594 if (isa<UndefValue>(Opnd)) {
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002595 DEBUG(dbgs() << "Statically extend\n");
2596 TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002597 continue;
2598 }
2599
2600 // Otherwise we have to explicity sign extend the operand.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002601 // Check if Ext was reused to extend an operand.
2602 if (!ExtForOpnd) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002603 // If yes, create a new one.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002604 DEBUG(dbgs() << "More operands to ext\n");
Quentin Colombet84f89cc2014-12-22 18:11:52 +00002605 Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2606 : TPT.createZExt(Ext, Opnd, Ext->getType());
2607 if (!isa<Instruction>(ValForExtOpnd)) {
2608 TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2609 continue;
2610 }
2611 ExtForOpnd = cast<Instruction>(ValForExtOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002612 }
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002613 if (Exts)
2614 Exts->push_back(ExtForOpnd);
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002615 TPT.setOperand(ExtForOpnd, 0, Opnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002616
2617 // Move the sign extension before the insertion point.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002618 TPT.moveBefore(ExtForOpnd, ExtOpnd);
2619 TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
Quentin Colombet1b274f92015-03-10 21:48:15 +00002620 CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002621 // If more sext are required, new instructions will have to be created.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002622 ExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002623 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002624 if (ExtForOpnd == Ext) {
2625 DEBUG(dbgs() << "Extension is useless now\n");
2626 TPT.eraseInstruction(Ext);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002627 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002628 return ExtOpnd;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002629}
2630
Quentin Colombet867c5502014-02-14 22:23:22 +00002631/// IsPromotionProfitable - Check whether or not promoting an instruction
2632/// to a wider type was profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002633/// \p NewCost gives the cost of extension instructions created by the
2634/// promotion.
2635/// \p OldCost gives the cost of extension instructions before the promotion
2636/// plus the number of instructions that have been
2637/// matched in the addressing mode the promotion.
Quentin Colombet867c5502014-02-14 22:23:22 +00002638/// \p PromotedOperand is the value that has been promoted.
2639/// \return True if the promotion is profitable, false otherwise.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002640bool AddressingModeMatcher::IsPromotionProfitable(
2641 unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2642 DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2643 // The cost of the new extensions is greater than the cost of the
2644 // old extension plus what we folded.
Quentin Colombet867c5502014-02-14 22:23:22 +00002645 // This is not profitable.
Quentin Colombet1b274f92015-03-10 21:48:15 +00002646 if (NewCost > OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002647 return false;
Quentin Colombet1b274f92015-03-10 21:48:15 +00002648 if (NewCost < OldCost)
Quentin Colombet867c5502014-02-14 22:23:22 +00002649 return true;
2650 // The promotion is neutral but it may help folding the sign extension in
2651 // loads for instance.
2652 // Check that we did not create an illegal instruction.
Mehdi Amini44ede332015-07-09 02:09:04 +00002653 return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
Quentin Colombet867c5502014-02-14 22:23:22 +00002654}
2655
Chandler Carruthc8925912013-01-05 02:09:22 +00002656/// MatchOperationAddr - Given an instruction or constant expr, see if we can
2657/// fold the operation into the addressing mode. If so, update the addressing
2658/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002659/// If \p MovedAway is not NULL, it contains the information of whether or
2660/// not AddrInst has to be folded into the addressing mode on success.
2661/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2662/// because it has been moved away.
2663/// Thus AddrInst must not be added in the matched instructions.
2664/// This state can happen when AddrInst is a sext, since it may be moved away.
2665/// Therefore, AddrInst may not be valid when MovedAway is true and it must
2666/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00002667bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002668 unsigned Depth,
2669 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002670 // Avoid exponential behavior on extremely deep expression trees.
2671 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002672
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002673 // By default, all matched instructions stay in place.
2674 if (MovedAway)
2675 *MovedAway = false;
2676
Chandler Carruthc8925912013-01-05 02:09:22 +00002677 switch (Opcode) {
2678 case Instruction::PtrToInt:
2679 // PtrToInt is always a noop, as we know that the int type is pointer sized.
2680 return MatchAddr(AddrInst->getOperand(0), Depth);
Mehdi Amini44ede332015-07-09 02:09:04 +00002681 case Instruction::IntToPtr: {
2682 auto AS = AddrInst->getType()->getPointerAddressSpace();
2683 auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
Chandler Carruthc8925912013-01-05 02:09:22 +00002684 // This inttoptr is a no-op if the integer type is pointer sized.
Mehdi Amini44ede332015-07-09 02:09:04 +00002685 if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00002686 return MatchAddr(AddrInst->getOperand(0), Depth);
2687 return false;
Mehdi Amini44ede332015-07-09 02:09:04 +00002688 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002689 case Instruction::BitCast:
2690 // BitCast is always a noop, and we can handle it as long as it is
2691 // int->int or pointer->pointer (we don't want int<->fp or something).
2692 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2693 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2694 // Don't touch identity bitcasts. These were probably put here by LSR,
2695 // and we don't want to mess around with them. Assume it knows what it
2696 // is doing.
2697 AddrInst->getOperand(0)->getType() != AddrInst->getType())
2698 return MatchAddr(AddrInst->getOperand(0), Depth);
2699 return false;
Matt Arsenaultf05b0232015-05-26 16:59:43 +00002700 case Instruction::AddrSpaceCast: {
2701 unsigned SrcAS
2702 = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2703 unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2704 if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2705 return MatchAddr(AddrInst->getOperand(0), Depth);
2706 return false;
2707 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002708 case Instruction::Add: {
2709 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2710 ExtAddrMode BackupAddrMode = AddrMode;
2711 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002712 // Start a transaction at this point.
2713 // The LHS may match but not the RHS.
2714 // Therefore, we need a higher level restoration point to undo partially
2715 // matched operation.
2716 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2717 TPT.getRestorationPoint();
2718
Chandler Carruthc8925912013-01-05 02:09:22 +00002719 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2720 MatchAddr(AddrInst->getOperand(0), Depth+1))
2721 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002722
Chandler Carruthc8925912013-01-05 02:09:22 +00002723 // Restore the old addr mode info.
2724 AddrMode = BackupAddrMode;
2725 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002726 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002727
Chandler Carruthc8925912013-01-05 02:09:22 +00002728 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2729 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2730 MatchAddr(AddrInst->getOperand(1), Depth+1))
2731 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002732
Chandler Carruthc8925912013-01-05 02:09:22 +00002733 // Otherwise we definitely can't merge the ADD in.
2734 AddrMode = BackupAddrMode;
2735 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002736 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002737 break;
2738 }
2739 //case Instruction::Or:
2740 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2741 //break;
2742 case Instruction::Mul:
2743 case Instruction::Shl: {
2744 // Can only handle X*C and X << C.
2745 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002746 if (!RHS)
2747 return false;
Chandler Carruthc8925912013-01-05 02:09:22 +00002748 int64_t Scale = RHS->getSExtValue();
2749 if (Opcode == Instruction::Shl)
2750 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002751
Chandler Carruthc8925912013-01-05 02:09:22 +00002752 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2753 }
2754 case Instruction::GetElementPtr: {
2755 // Scan the GEP. We check it if it contains constant offsets and at most
2756 // one variable offset.
2757 int VariableOperand = -1;
2758 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002759
Chandler Carruthc8925912013-01-05 02:09:22 +00002760 int64_t ConstantOffset = 0;
Chandler Carruthc8925912013-01-05 02:09:22 +00002761 gep_type_iterator GTI = gep_type_begin(AddrInst);
2762 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2763 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002764 const StructLayout *SL = DL.getStructLayout(STy);
Chandler Carruthc8925912013-01-05 02:09:22 +00002765 unsigned Idx =
2766 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2767 ConstantOffset += SL->getElementOffset(Idx);
2768 } else {
Mehdi Amini4fe37982015-07-07 18:45:17 +00002769 uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
Chandler Carruthc8925912013-01-05 02:09:22 +00002770 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2771 ConstantOffset += CI->getSExtValue()*TypeSize;
2772 } else if (TypeSize) { // Scales of zero don't do anything.
2773 // We only allow one variable index at the moment.
2774 if (VariableOperand != -1)
2775 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002776
Chandler Carruthc8925912013-01-05 02:09:22 +00002777 // Remember the variable index.
2778 VariableOperand = i;
2779 VariableScale = TypeSize;
2780 }
2781 }
2782 }
Stephen Lin837bba12013-07-15 17:55:02 +00002783
Chandler Carruthc8925912013-01-05 02:09:22 +00002784 // A common case is for the GEP to only do a constant offset. In this case,
2785 // just add it to the disp field and check validity.
2786 if (VariableOperand == -1) {
2787 AddrMode.BaseOffs += ConstantOffset;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00002788 if (ConstantOffset == 0 ||
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002789 TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002790 // Check to see if we can fold the base pointer in too.
2791 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2792 return true;
2793 }
2794 AddrMode.BaseOffs -= ConstantOffset;
2795 return false;
2796 }
2797
2798 // Save the valid addressing mode in case we can't match.
2799 ExtAddrMode BackupAddrMode = AddrMode;
2800 unsigned OldSize = AddrModeInsts.size();
2801
2802 // See if the scale and offset amount is valid for this target.
2803 AddrMode.BaseOffs += ConstantOffset;
2804
2805 // Match the base operand of the GEP.
2806 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2807 // If it couldn't be matched, just stuff the value in a register.
2808 if (AddrMode.HasBaseReg) {
2809 AddrMode = BackupAddrMode;
2810 AddrModeInsts.resize(OldSize);
2811 return false;
2812 }
2813 AddrMode.HasBaseReg = true;
2814 AddrMode.BaseReg = AddrInst->getOperand(0);
2815 }
2816
2817 // Match the remaining variable portion of the GEP.
2818 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2819 Depth)) {
2820 // If it couldn't be matched, try stuffing the base into a register
2821 // instead of matching it, and retrying the match of the scale.
2822 AddrMode = BackupAddrMode;
2823 AddrModeInsts.resize(OldSize);
2824 if (AddrMode.HasBaseReg)
2825 return false;
2826 AddrMode.HasBaseReg = true;
2827 AddrMode.BaseReg = AddrInst->getOperand(0);
2828 AddrMode.BaseOffs += ConstantOffset;
2829 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2830 VariableScale, Depth)) {
2831 // If even that didn't work, bail.
2832 AddrMode = BackupAddrMode;
2833 AddrModeInsts.resize(OldSize);
2834 return false;
2835 }
2836 }
2837
2838 return true;
2839 }
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002840 case Instruction::SExt:
2841 case Instruction::ZExt: {
2842 Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2843 if (!Ext)
Sanjay Pateld3bbfa12014-07-16 22:40:28 +00002844 return false;
Sanjay Patelab60d042014-07-16 21:08:10 +00002845
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002846 // Try to move this ext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002847 // Ask for a method for doing so.
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002848 TypePromotionHelper::Action TPH =
Ahmed Bougachaf3299142015-06-17 20:44:32 +00002849 TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002850 if (!TPH)
2851 return false;
2852
2853 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2854 TPT.getRestorationPoint();
Quentin Colombet1b274f92015-03-10 21:48:15 +00002855 unsigned CreatedInstsCost = 0;
2856 unsigned ExtCost = !TLI.isExtFree(Ext);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00002857 Value *PromotedOperand =
Quentin Colombet1b274f92015-03-10 21:48:15 +00002858 TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002859 // SExt has been moved away.
2860 // Thus either it will be rematched later in the recursive calls or it is
2861 // gone. Anyway, we must not fold it into the addressing mode at this point.
2862 // E.g.,
2863 // op = add opnd, 1
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002864 // idx = ext op
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002865 // addr = gep base, idx
2866 // is now:
Quentin Colombetf5485bb2014-11-13 01:44:51 +00002867 // promotedOpnd = ext opnd <- no match here
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002868 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2869 // addr = gep base, op <- match
2870 if (MovedAway)
2871 *MovedAway = true;
2872
2873 assert(PromotedOperand &&
2874 "TypePromotionHelper should have filtered out those cases");
2875
2876 ExtAddrMode BackupAddrMode = AddrMode;
2877 unsigned OldSize = AddrModeInsts.size();
2878
2879 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet1b274f92015-03-10 21:48:15 +00002880 // The total of the new cost is equals to the cost of the created
2881 // instructions.
2882 // The total of the old cost is equals to the cost of the extension plus
2883 // what we have saved in the addressing mode.
2884 !IsPromotionProfitable(CreatedInstsCost,
2885 ExtCost + (AddrModeInsts.size() - OldSize),
Quentin Colombet867c5502014-02-14 22:23:22 +00002886 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002887 AddrMode = BackupAddrMode;
2888 AddrModeInsts.resize(OldSize);
2889 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2890 TPT.rollback(LastKnownGood);
2891 return false;
2892 }
2893 return true;
2894 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002895 }
2896 return false;
2897}
2898
2899/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2900/// addressing mode. If Addr can't be added to AddrMode this returns false and
2901/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2902/// or intptr_t for the target.
2903///
2904bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002905 // Start a transaction at this point that we will rollback if the matching
2906 // fails.
2907 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2908 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002909 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2910 // Fold in immediates if legal for the target.
2911 AddrMode.BaseOffs += CI->getSExtValue();
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002912 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002913 return true;
2914 AddrMode.BaseOffs -= CI->getSExtValue();
2915 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2916 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002917 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002918 AddrMode.BaseGV = GV;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002919 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002920 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002921 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002922 }
2923 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2924 ExtAddrMode BackupAddrMode = AddrMode;
2925 unsigned OldSize = AddrModeInsts.size();
2926
2927 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002928 bool MovedAway = false;
2929 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2930 // This instruction may have been move away. If so, there is nothing
2931 // to check here.
2932 if (MovedAway)
2933 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002934 // Okay, it's possible to fold this. Check to see if it is actually
2935 // *profitable* to do so. We use a simple cost model to avoid increasing
2936 // register pressure too much.
2937 if (I->hasOneUse() ||
2938 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2939 AddrModeInsts.push_back(I);
2940 return true;
2941 }
Stephen Lin837bba12013-07-15 17:55:02 +00002942
Chandler Carruthc8925912013-01-05 02:09:22 +00002943 // It isn't profitable to do this, roll back.
2944 //cerr << "NOT FOLDING: " << *I;
2945 AddrMode = BackupAddrMode;
2946 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002947 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002948 }
2949 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2950 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2951 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002952 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002953 } else if (isa<ConstantPointerNull>(Addr)) {
2954 // Null pointer gets folded without affecting the addressing mode.
2955 return true;
2956 }
2957
2958 // Worse case, the target should support [reg] addressing modes. :)
2959 if (!AddrMode.HasBaseReg) {
2960 AddrMode.HasBaseReg = true;
2961 AddrMode.BaseReg = Addr;
2962 // Still check for legality in case the target supports [imm] but not [i+r].
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002963 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002964 return true;
2965 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002966 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002967 }
2968
2969 // If the base register is already taken, see if we can do [r+r].
2970 if (AddrMode.Scale == 0) {
2971 AddrMode.Scale = 1;
2972 AddrMode.ScaledReg = Addr;
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00002973 if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
Chandler Carruthc8925912013-01-05 02:09:22 +00002974 return true;
2975 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002976 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002977 }
2978 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002979 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002980 return false;
2981}
2982
2983/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2984/// inline asm call are due to memory operands. If so, return true, otherwise
2985/// return false.
2986static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
Eric Christopher11e4df72015-02-26 22:38:43 +00002987 const TargetMachine &TM) {
2988 const Function *F = CI->getParent()->getParent();
2989 const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2990 const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
Eric Christopherd75c00c2015-02-26 22:38:34 +00002991 TargetLowering::AsmOperandInfoVector TargetConstraints =
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00002992 TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
2993 ImmutableCallSite(CI));
Chandler Carruthc8925912013-01-05 02:09:22 +00002994 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2995 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002996
Chandler Carruthc8925912013-01-05 02:09:22 +00002997 // Compute the constraint code and ConstraintType to use.
Eric Christopher11e4df72015-02-26 22:38:43 +00002998 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Chandler Carruthc8925912013-01-05 02:09:22 +00002999
3000 // If this asm operand is our Value*, and if it isn't an indirect memory
3001 // operand, we can't fold it!
3002 if (OpInfo.CallOperandVal == OpVal &&
3003 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3004 !OpInfo.isIndirect))
3005 return false;
3006 }
3007
3008 return true;
3009}
3010
3011/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
3012/// memory use. If we find an obviously non-foldable instruction, return true.
3013/// Add the ultimately found memory instructions to MemoryUses.
Eric Christopher11e4df72015-02-26 22:38:43 +00003014static bool FindAllMemoryUses(
3015 Instruction *I,
3016 SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3017 SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003018 // If we already considered this instruction, we're done.
David Blaikie70573dc2014-11-19 07:49:26 +00003019 if (!ConsideredInsts.insert(I).second)
Chandler Carruthc8925912013-01-05 02:09:22 +00003020 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003021
Chandler Carruthc8925912013-01-05 02:09:22 +00003022 // If this is an obviously unfoldable instruction, bail out.
3023 if (!MightBeFoldableInst(I))
3024 return true;
3025
3026 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003027 for (Use &U : I->uses()) {
3028 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00003029
Chandler Carruthcdf47882014-03-09 03:16:01 +00003030 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3031 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00003032 continue;
3033 }
Stephen Lin837bba12013-07-15 17:55:02 +00003034
Chandler Carruthcdf47882014-03-09 03:16:01 +00003035 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3036 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00003037 if (opNo == 0) return true; // Storing addr, not into addr.
3038 MemoryUses.push_back(std::make_pair(SI, opNo));
3039 continue;
3040 }
Stephen Lin837bba12013-07-15 17:55:02 +00003041
Chandler Carruthcdf47882014-03-09 03:16:01 +00003042 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00003043 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3044 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003045
Chandler Carruthc8925912013-01-05 02:09:22 +00003046 // If this is a memory operand, we're cool, otherwise bail out.
Eric Christopher11e4df72015-02-26 22:38:43 +00003047 if (!IsOperandAMemoryOperand(CI, IA, I, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003048 return true;
3049 continue;
3050 }
Stephen Lin837bba12013-07-15 17:55:02 +00003051
Eric Christopher11e4df72015-02-26 22:38:43 +00003052 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003053 return true;
3054 }
3055
3056 return false;
3057}
3058
3059/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
3060/// the use site that we're folding it into. If so, there is no cost to
3061/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
3062/// that we know are live at the instruction already.
3063bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
3064 Value *KnownLive2) {
3065 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00003066 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00003067 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003068
Chandler Carruthc8925912013-01-05 02:09:22 +00003069 // All values other than instructions and arguments (e.g. constants) are live.
3070 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003071
Chandler Carruthc8925912013-01-05 02:09:22 +00003072 // If Val is a constant sized alloca in the entry block, it is live, this is
3073 // true because it is just a reference to the stack/frame pointer, which is
3074 // live for the whole function.
3075 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3076 if (AI->isStaticAlloca())
3077 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003078
Chandler Carruthc8925912013-01-05 02:09:22 +00003079 // Check to see if this value is already used in the memory instruction's
3080 // block. If so, it's already live into the block at the very least, so we
3081 // can reasonably fold it.
3082 return Val->isUsedInBasicBlock(MemoryInst->getParent());
3083}
3084
3085/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
3086/// mode of the machine to fold the specified instruction into a load or store
3087/// that ultimately uses it. However, the specified instruction has multiple
3088/// uses. Given this, it may actually increase register pressure to fold it
3089/// into the load. For example, consider this code:
3090///
3091/// X = ...
3092/// Y = X+1
3093/// use(Y) -> nonload/store
3094/// Z = Y+1
3095/// load Z
3096///
3097/// In this case, Y has multiple uses, and can be folded into the load of Z
3098/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
3099/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
3100/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
3101/// number of computations either.
3102///
3103/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
3104/// X was live across 'load Z' for other reasons, we actually *would* want to
3105/// fold the addressing mode in the Z case. This would make Y die earlier.
3106bool AddressingModeMatcher::
3107IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
3108 ExtAddrMode &AMAfter) {
3109 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00003110
Chandler Carruthc8925912013-01-05 02:09:22 +00003111 // AMBefore is the addressing mode before this instruction was folded into it,
3112 // and AMAfter is the addressing mode after the instruction was folded. Get
3113 // the set of registers referenced by AMAfter and subtract out those
3114 // referenced by AMBefore: this is the set of values which folding in this
3115 // address extends the lifetime of.
3116 //
3117 // Note that there are only two potential values being referenced here,
3118 // BaseReg and ScaleReg (global addresses are always available, as are any
3119 // folded immediates).
3120 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00003121
Chandler Carruthc8925912013-01-05 02:09:22 +00003122 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3123 // lifetime wasn't extended by adding this instruction.
3124 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003125 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003126 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00003127 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00003128
3129 // If folding this instruction (and it's subexprs) didn't extend any live
3130 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00003131 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00003132 return true;
3133
3134 // If all uses of this instruction are ultimately load/store/inlineasm's,
3135 // check to see if their addressing modes will include this instruction. If
3136 // so, we can fold it into all uses, so it doesn't matter if it has multiple
3137 // uses.
3138 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3139 SmallPtrSet<Instruction*, 16> ConsideredInsts;
Eric Christopher11e4df72015-02-26 22:38:43 +00003140 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
Chandler Carruthc8925912013-01-05 02:09:22 +00003141 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00003142
Chandler Carruthc8925912013-01-05 02:09:22 +00003143 // Now that we know that all uses of this instruction are part of a chain of
3144 // computation involving only operations that could theoretically be folded
3145 // into a memory use, loop over each of these uses and see if they could
3146 // *actually* fold the instruction.
3147 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3148 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3149 Instruction *User = MemoryUses[i].first;
3150 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00003151
Chandler Carruthc8925912013-01-05 02:09:22 +00003152 // Get the access type of this use. If the use isn't a pointer, we don't
3153 // know what it accesses.
3154 Value *Address = User->getOperand(OpNo);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003155 PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3156 if (!AddrTy)
Chandler Carruthc8925912013-01-05 02:09:22 +00003157 return false;
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003158 Type *AddressAccessTy = AddrTy->getElementType();
3159 unsigned AS = AddrTy->getAddressSpace();
Stephen Lin837bba12013-07-15 17:55:02 +00003160
Chandler Carruthc8925912013-01-05 02:09:22 +00003161 // Do a match against the root of this address, ignoring profitability. This
3162 // will tell us if the addressing mode for the memory operation will
3163 // *actually* cover the shared instruction.
3164 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003165 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3166 TPT.getRestorationPoint();
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003167 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003168 MemoryInst, Result, InsertedInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003169 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00003170 Matcher.IgnoreProfitability = true;
3171 bool Success = Matcher.MatchAddr(Address, 0);
3172 (void)Success; assert(Success && "Couldn't select *anything*?");
3173
Quentin Colombet5a69dda2014-02-11 01:59:02 +00003174 // The match was to check the profitability, the changes made are not
3175 // part of the original matcher. Therefore, they should be dropped
3176 // otherwise the original matcher will not present the right state.
3177 TPT.rollback(LastKnownGood);
3178
Chandler Carruthc8925912013-01-05 02:09:22 +00003179 // If the match didn't cover I, then it won't be shared by it.
3180 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3181 I) == MatchedAddrModeInsts.end())
3182 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00003183
Chandler Carruthc8925912013-01-05 02:09:22 +00003184 MatchedAddrModeInsts.clear();
3185 }
Stephen Lin837bba12013-07-15 17:55:02 +00003186
Chandler Carruthc8925912013-01-05 02:09:22 +00003187 return true;
3188}
3189
3190} // end anonymous namespace
3191
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003192/// IsNonLocalValue - Return true if the specified values are defined in a
3193/// different basic block than BB.
3194static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3195 if (Instruction *I = dyn_cast<Instruction>(V))
3196 return I->getParent() != BB;
3197 return false;
3198}
3199
Bob Wilson53bdae32009-12-03 21:47:07 +00003200/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003201/// addressing modes that can do significant amounts of computation. As such,
3202/// instruction selection will try to get the load or store to do as much
3203/// computation as possible for the program. The problem is that isel can only
3204/// see within a single block. As such, we sink as much legal addressing mode
3205/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00003206///
3207/// This method is used to optimize both load/store and inline asms with memory
3208/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003209bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003210 Type *AccessTy, unsigned AddrSpace) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003211 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00003212
3213 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003214 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00003215 SmallVector<Value*, 8> worklist;
3216 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003217 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00003218
Owen Anderson8ba5f392010-11-27 08:15:55 +00003219 // Use a worklist to iteratively look through PHI nodes, and ensure that
3220 // the addressing mode obtained from the non-PHI roots of the graph
3221 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00003222 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003223 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003224 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003225 SmallVector<Instruction*, 16> AddrModeInsts;
3226 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003227 TypePromotionTransaction TPT;
3228 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3229 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00003230 while (!worklist.empty()) {
3231 Value *V = worklist.back();
3232 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00003233
Owen Anderson8ba5f392010-11-27 08:15:55 +00003234 // Break use-def graph loops.
David Blaikie70573dc2014-11-19 07:49:26 +00003235 if (!Visited.insert(V).second) {
Craig Topperc0196b12014-04-14 00:51:57 +00003236 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003237 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003238 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003239
Owen Anderson8ba5f392010-11-27 08:15:55 +00003240 // For a PHI node, push all of its incoming values.
3241 if (PHINode *P = dyn_cast<PHINode>(V)) {
Pete Cooper833f34d2015-05-12 20:05:31 +00003242 for (Value *IncValue : P->incoming_values())
3243 worklist.push_back(IncValue);
Owen Anderson8ba5f392010-11-27 08:15:55 +00003244 continue;
3245 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003246
Owen Anderson8ba5f392010-11-27 08:15:55 +00003247 // For non-PHIs, determine the addressing mode being computed.
3248 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003249 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003250 V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003251 InsertedInsts, PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00003252
3253 // This check is broken into two cases with very similar code to avoid using
3254 // getNumUses() as much as possible. Some values have a lot of uses, so
3255 // calling getNumUses() unconditionally caused a significant compile-time
3256 // regression.
3257 if (!Consensus) {
3258 Consensus = V;
3259 AddrMode = NewAddrMode;
3260 AddrModeInsts = NewAddrModeInsts;
3261 continue;
3262 } else if (NewAddrMode == AddrMode) {
3263 if (!IsNumUsesConsensusValid) {
3264 NumUsesConsensus = Consensus->getNumUses();
3265 IsNumUsesConsensusValid = true;
3266 }
3267
3268 // Ensure that the obtained addressing mode is equivalent to that obtained
3269 // for all other roots of the PHI traversal. Also, when choosing one
3270 // such root as representative, select the one with the most uses in order
3271 // to keep the cost modeling heuristics in AddressingModeMatcher
3272 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003273 unsigned NumUses = V->getNumUses();
3274 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00003275 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00003276 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003277 AddrModeInsts = NewAddrModeInsts;
3278 }
3279 continue;
3280 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003281
Craig Topperc0196b12014-04-14 00:51:57 +00003282 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00003283 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003284 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003285
Owen Anderson8ba5f392010-11-27 08:15:55 +00003286 // If the addressing mode couldn't be determined, or if multiple different
3287 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00003288 if (!Consensus) {
3289 TPT.rollback(LastKnownGood);
3290 return false;
3291 }
3292 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00003293
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003294 // Check to see if any of the instructions supersumed by this addr mode are
3295 // non-local to I's BB.
3296 bool AnyNonLocal = false;
3297 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00003298 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003299 AnyNonLocal = true;
3300 break;
3301 }
3302 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003303
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003304 // If all the instructions matched are already in this BB, don't do anything.
3305 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00003306 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003307 return false;
3308 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003309
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003310 // Insert this computation right after this user. Since our caller is
3311 // scanning from the top of the BB to the bottom, reuse of the expr are
3312 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00003313 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003314
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003315 // Now that we determined the addressing expression we want to use and know
3316 // that we have to sink it into this block. Check to see if we have already
3317 // done this for some other load/store instr in this block. If so, reuse the
3318 // computation.
3319 Value *&SunkAddr = SunkAddrs[Addr];
3320 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00003321 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003322 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003323 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003324 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Eric Christopherfccff372015-01-27 01:01:38 +00003325 } else if (AddrSinkUsingGEPs ||
3326 (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
Eric Christopher2c635492015-01-27 07:54:39 +00003327 TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3328 ->useAA())) {
Hal Finkelc3998302014-04-12 00:59:48 +00003329 // By default, we use the GEP-based method when AA is used later. This
3330 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3331 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003332 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003333 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003334 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003335
3336 // First, find the pointer.
3337 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3338 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00003339 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003340 }
3341
3342 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3343 // We can't add more than one pointer together, nor can we scale a
3344 // pointer (both of which seem meaningless).
3345 if (ResultPtr || AddrMode.Scale != 1)
3346 return false;
3347
3348 ResultPtr = AddrMode.ScaledReg;
3349 AddrMode.Scale = 0;
3350 }
3351
3352 if (AddrMode.BaseGV) {
3353 if (ResultPtr)
3354 return false;
3355
3356 ResultPtr = AddrMode.BaseGV;
3357 }
3358
3359 // If the real base value actually came from an inttoptr, then the matcher
3360 // will look through it and provide only the integer value. In that case,
3361 // use it here.
3362 if (!ResultPtr && AddrMode.BaseReg) {
3363 ResultPtr =
3364 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00003365 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00003366 } else if (!ResultPtr && AddrMode.Scale == 1) {
3367 ResultPtr =
3368 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3369 AddrMode.Scale = 0;
3370 }
3371
3372 if (!ResultPtr &&
3373 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3374 SunkAddr = Constant::getNullValue(Addr->getType());
3375 } else if (!ResultPtr) {
3376 return false;
3377 } else {
3378 Type *I8PtrTy =
David Blaikie3909da72015-03-30 20:42:56 +00003379 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3380 Type *I8Ty = Builder.getInt8Ty();
Hal Finkelc3998302014-04-12 00:59:48 +00003381
3382 // Start with the base register. Do this first so that subsequent address
3383 // matching finds it last, which will prevent it from trying to match it
3384 // as the scaled value in case it happens to be a mul. That would be
3385 // problematic if we've sunk a different mul for the scale, because then
3386 // we'd end up sinking both muls.
3387 if (AddrMode.BaseReg) {
3388 Value *V = AddrMode.BaseReg;
3389 if (V->getType() != IntPtrTy)
3390 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3391
3392 ResultIndex = V;
3393 }
3394
3395 // Add the scale value.
3396 if (AddrMode.Scale) {
3397 Value *V = AddrMode.ScaledReg;
3398 if (V->getType() == IntPtrTy) {
3399 // done.
3400 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3401 cast<IntegerType>(V->getType())->getBitWidth()) {
3402 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3403 } else {
3404 // It is only safe to sign extend the BaseReg if we know that the math
3405 // required to create it did not overflow before we extend it. Since
3406 // the original IR value was tossed in favor of a constant back when
3407 // the AddrMode was created we need to bail out gracefully if widths
3408 // do not match instead of extending it.
3409 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3410 if (I && (ResultIndex != AddrMode.BaseReg))
3411 I->eraseFromParent();
3412 return false;
3413 }
3414
3415 if (AddrMode.Scale != 1)
3416 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3417 "sunkaddr");
3418 if (ResultIndex)
3419 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3420 else
3421 ResultIndex = V;
3422 }
3423
3424 // Add in the Base Offset if present.
3425 if (AddrMode.BaseOffs) {
3426 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3427 if (ResultIndex) {
NAKAMURA Takumif51a34e2014-10-29 15:23:11 +00003428 // We need to add this separately from the scale above to help with
3429 // SDAG consecutive load/store merging.
Hal Finkelc3998302014-04-12 00:59:48 +00003430 if (ResultPtr->getType() != I8PtrTy)
3431 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003432 ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003433 }
3434
3435 ResultIndex = V;
3436 }
3437
3438 if (!ResultIndex) {
3439 SunkAddr = ResultPtr;
3440 } else {
3441 if (ResultPtr->getType() != I8PtrTy)
3442 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
David Blaikie3909da72015-03-30 20:42:56 +00003443 SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
Hal Finkelc3998302014-04-12 00:59:48 +00003444 }
3445
3446 if (SunkAddr->getType() != Addr->getType())
3447 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3448 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003449 } else {
David Greene74e2d492010-01-05 01:27:11 +00003450 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00003451 << *MemoryInst << "\n");
Mehdi Amini4fe37982015-07-07 18:45:17 +00003452 Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00003453 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00003454
3455 // Start with the base register. Do this first so that subsequent address
3456 // matching finds it last, which will prevent it from trying to match it
3457 // as the scaled value in case it happens to be a mul. That would be
3458 // problematic if we've sunk a different mul for the scale, because then
3459 // we'd end up sinking both muls.
3460 if (AddrMode.BaseReg) {
3461 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00003462 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00003463 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003464 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00003465 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00003466 Result = V;
3467 }
3468
3469 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003470 if (AddrMode.Scale) {
3471 Value *V = AddrMode.ScaledReg;
3472 if (V->getType() == IntPtrTy) {
3473 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00003474 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003475 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003476 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3477 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003478 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003479 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00003480 // It is only safe to sign extend the BaseReg if we know that the math
3481 // required to create it did not overflow before we extend it. Since
3482 // the original IR value was tossed in favor of a constant back when
3483 // the AddrMode was created we need to bail out gracefully if widths
3484 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00003485 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00003486 if (I && (Result != AddrMode.BaseReg))
3487 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00003488 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003489 }
3490 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00003491 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3492 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003493 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003494 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003495 else
3496 Result = V;
3497 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003498
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003499 // Add in the BaseGV if present.
3500 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00003501 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003502 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003503 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003504 else
3505 Result = V;
3506 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003507
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003508 // Add in the Base Offset if present.
3509 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00003510 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003511 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00003512 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003513 else
3514 Result = V;
3515 }
3516
Craig Topperc0196b12014-04-14 00:51:57 +00003517 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00003518 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003519 else
Devang Patelc10e52a2011-09-06 18:49:53 +00003520 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003521 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00003522
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003523 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003524
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003525 // If we have no uses, recursively delete the value and all dead instructions
3526 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00003527 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003528 // This can cause recursive deletion, which can invalidate our iterator.
3529 // Use a WeakVH to hold onto it in case this happens.
3530 WeakVH IterHandle(CurInstIterator);
3531 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00003532
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00003533 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00003534
3535 if (IterHandle != CurInstIterator) {
3536 // If the iterator instruction was recursively deleted, start over at the
3537 // start of the block.
3538 CurInstIterator = BB->begin();
3539 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00003540 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00003541 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00003542 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00003543 return true;
3544}
3545
Evan Cheng1da25002008-02-26 02:42:37 +00003546/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00003547/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00003548/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00003549bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00003550 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00003551
Eric Christopher11e4df72015-02-26 22:38:43 +00003552 const TargetRegisterInfo *TRI =
3553 TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
Mehdi Amini8ac7a9d2015-07-07 19:07:19 +00003554 TargetLowering::AsmOperandInfoVector TargetConstraints =
3555 TLI->ParseConstraints(*DL, TRI, CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003556 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00003557 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3558 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00003559
Evan Cheng1da25002008-02-26 02:42:37 +00003560 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00003561 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00003562
Eli Friedman666bbe32008-02-26 18:37:49 +00003563 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3564 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00003565 Value *OpVal = CS->getArgOperand(ArgNo++);
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00003566 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00003567 } else if (OpInfo.Type == InlineAsm::isInput)
3568 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00003569 }
3570
3571 return MadeChange;
3572}
3573
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003574/// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3575/// sign extensions.
3576static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3577 assert(!Inst->use_empty() && "Input must have at least one use");
3578 const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3579 bool IsSExt = isa<SExtInst>(FirstUser);
3580 Type *ExtTy = FirstUser->getType();
3581 for (const User *U : Inst->users()) {
3582 const Instruction *UI = cast<Instruction>(U);
3583 if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3584 return false;
3585 Type *CurTy = UI->getType();
3586 // Same input and output types: Same instruction after CSE.
3587 if (CurTy == ExtTy)
3588 continue;
3589
3590 // If IsSExt is true, we are in this situation:
3591 // a = Inst
3592 // b = sext ty1 a to ty2
3593 // c = sext ty1 a to ty3
3594 // Assuming ty2 is shorter than ty3, this could be turned into:
3595 // a = Inst
3596 // b = sext ty1 a to ty2
3597 // c = sext ty2 b to ty3
3598 // However, the last sext is not free.
3599 if (IsSExt)
3600 return false;
3601
3602 // This is a ZExt, maybe this is free to extend from one type to another.
3603 // In that case, we would not account for a different use.
3604 Type *NarrowTy;
3605 Type *LargeTy;
3606 if (ExtTy->getScalarType()->getIntegerBitWidth() >
3607 CurTy->getScalarType()->getIntegerBitWidth()) {
3608 NarrowTy = CurTy;
3609 LargeTy = ExtTy;
3610 } else {
3611 NarrowTy = ExtTy;
3612 LargeTy = CurTy;
3613 }
3614
3615 if (!TLI.isZExtFree(NarrowTy, LargeTy))
3616 return false;
3617 }
3618 // All uses are the same or can be derived from one another for free.
3619 return true;
3620}
3621
3622/// \brief Try to form ExtLd by promoting \p Exts until they reach a
3623/// load instruction.
3624/// If an ext(load) can be formed, it is returned via \p LI for the load
3625/// and \p Inst for the extension.
3626/// Otherwise LI == nullptr and Inst == nullptr.
3627/// When some promotion happened, \p TPT contains the proper state to
3628/// revert them.
3629///
3630/// \return true when promoting was necessary to expose the ext(load)
3631/// opportunity, false otherwise.
3632///
3633/// Example:
3634/// \code
3635/// %ld = load i32* %addr
3636/// %add = add nuw i32 %ld, 4
3637/// %zext = zext i32 %add to i64
3638/// \endcode
3639/// =>
3640/// \code
3641/// %ld = load i32* %addr
3642/// %zext = zext i32 %ld to i64
3643/// %add = add nuw i64 %zext, 4
3644/// \encode
3645/// Thanks to the promotion, we can match zext(load i32*) to i64.
3646bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3647 LoadInst *&LI, Instruction *&Inst,
3648 const SmallVectorImpl<Instruction *> &Exts,
Quentin Colombet1b274f92015-03-10 21:48:15 +00003649 unsigned CreatedInstsCost = 0) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003650 // Iterate over all the extensions to see if one form an ext(load).
3651 for (auto I : Exts) {
3652 // Check if we directly have ext(load).
3653 if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3654 Inst = I;
3655 // No promotion happened here.
3656 return false;
3657 }
3658 // Check whether or not we want to do any promotion.
3659 if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3660 continue;
3661 // Get the action to perform the promotion.
3662 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003663 I, InsertedInsts, *TLI, PromotedInsts);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003664 // Check if we can promote.
3665 if (!TPH)
3666 continue;
3667 // Save the current state.
3668 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3669 TPT.getRestorationPoint();
3670 SmallVector<Instruction *, 4> NewExts;
Quentin Colombet1b274f92015-03-10 21:48:15 +00003671 unsigned NewCreatedInstsCost = 0;
3672 unsigned ExtCost = !TLI->isExtFree(I);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003673 // Promote.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003674 Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3675 &NewExts, nullptr, *TLI);
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003676 assert(PromotedVal &&
3677 "TypePromotionHelper should have filtered out those cases");
3678
3679 // We would be able to merge only one extension in a load.
3680 // Therefore, if we have more than 1 new extension we heuristically
3681 // cut this search path, because it means we degrade the code quality.
3682 // With exactly 2, the transformation is neutral, because we will merge
3683 // one extension but leave one. However, we optimistically keep going,
3684 // because the new extension may be removed too.
Quentin Colombet1b274f92015-03-10 21:48:15 +00003685 long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3686 TotalCreatedInstsCost -= ExtCost;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003687 if (!StressExtLdPromotion &&
Quentin Colombet1b274f92015-03-10 21:48:15 +00003688 (TotalCreatedInstsCost > 1 ||
Mehdi Amini44ede332015-07-09 02:09:04 +00003689 !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003690 // The promotion is not profitable, rollback to the previous state.
3691 TPT.rollback(LastKnownGood);
3692 continue;
3693 }
3694 // The promotion is profitable.
3695 // Check if it exposes an ext(load).
Quentin Colombet1b274f92015-03-10 21:48:15 +00003696 (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
3697 if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003698 // If we have created a new extension, i.e., now we have two
3699 // extensions. We must make sure one of them is merged with
3700 // the load, otherwise we may degrade the code quality.
3701 (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3702 // Promotion happened.
3703 return true;
3704 // If this does not help to expose an ext(load) then, rollback.
3705 TPT.rollback(LastKnownGood);
3706 }
3707 // None of the extension can form an ext(load).
3708 LI = nullptr;
3709 Inst = nullptr;
3710 return false;
3711}
3712
Dan Gohman99429a02009-10-16 20:59:35 +00003713/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3714/// basic block as the load, unless conditions are unfavorable. This allows
3715/// SelectionDAG to fold the extend into the load.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003716/// \p I[in/out] the extension may be modified during the process if some
3717/// promotions apply.
Dan Gohman99429a02009-10-16 20:59:35 +00003718///
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003719bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3720 // Try to promote a chain of computation if it allows to form
3721 // an extended load.
3722 TypePromotionTransaction TPT;
3723 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3724 TPT.getRestorationPoint();
3725 SmallVector<Instruction *, 1> Exts;
3726 Exts.push_back(I);
Dan Gohman99429a02009-10-16 20:59:35 +00003727 // Look for a load being extended.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003728 LoadInst *LI = nullptr;
3729 Instruction *OldExt = I;
3730 bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3731 if (!LI || !I) {
3732 assert(!HasPromoted && !LI && "If we did not match any load instruction "
3733 "the code must remain the same");
3734 I = OldExt;
3735 return false;
3736 }
Dan Gohman99429a02009-10-16 20:59:35 +00003737
3738 // If they're already in the same block, there's nothing to do.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003739 // Make the cheap checks first if we did not promote.
3740 // If we promoted, we need to check if it is indeed profitable.
3741 if (!HasPromoted && LI->getParent() == I->getParent())
Dan Gohman99429a02009-10-16 20:59:35 +00003742 return false;
3743
Mehdi Amini44ede332015-07-09 02:09:04 +00003744 EVT VT = TLI->getValueType(*DL, I->getType());
3745 EVT LoadVT = TLI->getValueType(*DL, LI->getType());
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003746
Dan Gohman99429a02009-10-16 20:59:35 +00003747 // If the load has other users and the truncate is not free, this probably
3748 // isn't worthwhile.
Ahmed Bougacha55e3c2d2014-12-05 18:04:40 +00003749 if (!LI->hasOneUse() && TLI &&
3750 (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003751 !TLI->isTruncateFree(I->getType(), LI->getType())) {
3752 I = OldExt;
3753 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003754 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003755 }
Dan Gohman99429a02009-10-16 20:59:35 +00003756
3757 // Check whether the target supports casts folded into loads.
3758 unsigned LType;
3759 if (isa<ZExtInst>(I))
3760 LType = ISD::ZEXTLOAD;
3761 else {
3762 assert(isa<SExtInst>(I) && "Unexpected ext type!");
3763 LType = ISD::SEXTLOAD;
3764 }
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +00003765 if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003766 I = OldExt;
3767 TPT.rollback(LastKnownGood);
Dan Gohman99429a02009-10-16 20:59:35 +00003768 return false;
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003769 }
Dan Gohman99429a02009-10-16 20:59:35 +00003770
3771 // Move the extend into the same block as the load, so that SelectionDAG
3772 // can fold it.
Quentin Colombetfc2201e2014-12-17 01:36:17 +00003773 TPT.commit();
Dan Gohman99429a02009-10-16 20:59:35 +00003774 I->removeFromParent();
3775 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00003776 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00003777 return true;
3778}
3779
Evan Chengd3d80172007-12-05 23:58:20 +00003780bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3781 BasicBlock *DefBB = I->getParent();
3782
Bob Wilsonff714f92010-09-21 21:44:14 +00003783 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00003784 // other uses of the source with result of extension.
3785 Value *Src = I->getOperand(0);
3786 if (Src->hasOneUse())
3787 return false;
3788
Evan Cheng2011df42007-12-13 07:50:36 +00003789 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00003790 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00003791 return false;
3792
Evan Cheng7bc89422007-12-12 00:51:06 +00003793 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00003794 // this block.
3795 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00003796 return false;
3797
Evan Chengd3d80172007-12-05 23:58:20 +00003798 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003799 for (User *U : I->users()) {
3800 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00003801
3802 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003803 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00003804 if (UserBB == DefBB) continue;
3805 DefIsLiveOut = true;
3806 break;
3807 }
3808 if (!DefIsLiveOut)
3809 return false;
3810
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00003811 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003812 for (User *U : Src->users()) {
3813 Instruction *UI = cast<Instruction>(U);
3814 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00003815 if (UserBB == DefBB) continue;
3816 // Be conservative. We don't want this xform to end up introducing
3817 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003818 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00003819 return false;
3820 }
3821
Evan Chengd3d80172007-12-05 23:58:20 +00003822 // InsertedTruncs - Only insert one trunc in each block once.
3823 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3824
3825 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003826 for (Use &U : Src->uses()) {
3827 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00003828
3829 // Figure out which BB this ext is used in.
3830 BasicBlock *UserBB = User->getParent();
3831 if (UserBB == DefBB) continue;
3832
3833 // Both src and def are live in this block. Rewrite the use.
3834 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3835
3836 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00003837 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00003838 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Ahmed Bougachaf3299142015-06-17 20:44:32 +00003839 InsertedInsts.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00003840 }
3841
3842 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003843 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00003844 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00003845 MadeChange = true;
3846 }
3847
3848 return MadeChange;
3849}
3850
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003851/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3852/// turned into an explicit branch.
3853static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3854 // FIXME: This should use the same heuristics as IfConversion to determine
3855 // whether a select is better represented as a branch. This requires that
3856 // branch probability metadata is preserved for the select, which is not the
3857 // case currently.
3858
3859 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3860
3861 // If the branch is predicted right, an out of order CPU can avoid blocking on
3862 // the compare. Emit cmovs on compares with a memory operand as branches to
3863 // avoid stalls on the load from memory. If the compare has more than one use
3864 // there's probably another cmov or setcc around so it's not worth emitting a
3865 // branch.
3866 if (!Cmp)
3867 return false;
3868
3869 Value *CmpOp0 = Cmp->getOperand(0);
3870 Value *CmpOp1 = Cmp->getOperand(1);
3871
3872 // We check that the memory operand has one use to avoid uses of the loaded
3873 // value directly after the compare, making branches unprofitable.
3874 return Cmp->hasOneUse() &&
3875 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3876 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3877}
3878
3879
Nadav Rotem9d832022012-09-02 12:10:19 +00003880/// If we have a SelectInst that will likely profit from branch prediction,
3881/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003882bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00003883 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3884
3885 // Can we convert the 'select' to CF ?
3886 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003887 return false;
3888
Nadav Rotem9d832022012-09-02 12:10:19 +00003889 TargetLowering::SelectSupportKind SelectKind;
3890 if (VectorCond)
3891 SelectKind = TargetLowering::VectorMaskSelect;
3892 else if (SI->getType()->isVectorTy())
3893 SelectKind = TargetLowering::ScalarCondVectorVal;
3894 else
3895 SelectKind = TargetLowering::ScalarValSelect;
3896
3897 // Do we have efficient codegen support for this kind of 'selects' ?
3898 if (TLI->isSelectSupported(SelectKind)) {
3899 // We have efficient codegen support for the select instruction.
3900 // Check if it is profitable to keep this 'select'.
3901 if (!TLI->isPredictableSelectExpensive() ||
3902 !isFormingBranchFromSelectProfitable(SI))
3903 return false;
3904 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003905
3906 ModifiedDT = true;
3907
3908 // First, we split the block containing the select into 2 blocks.
3909 BasicBlock *StartBlock = SI->getParent();
3910 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3911 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3912
3913 // Create a new block serving as the landing pad for the branch.
3914 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3915 NextBlock->getParent(), NextBlock);
3916
3917 // Move the unconditional branch from the block with the select in it into our
3918 // landing pad block.
3919 StartBlock->getTerminator()->eraseFromParent();
3920 BranchInst::Create(NextBlock, SmallBlock);
3921
3922 // Insert the real conditional branch based on the original condition.
3923 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3924
3925 // The select itself is replaced with a PHI Node.
3926 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3927 PN->takeName(SI);
3928 PN->addIncoming(SI->getTrueValue(), StartBlock);
3929 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3930 SI->replaceAllUsesWith(PN);
3931 SI->eraseFromParent();
3932
3933 // Instruct OptimizeBlock to skip to the next block.
3934 CurInstIterator = StartBlock->end();
3935 ++NumSelectsExpanded;
3936 return true;
3937}
3938
Benjamin Kramer573ff362014-03-01 17:24:40 +00003939static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003940 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3941 int SplatElem = -1;
3942 for (unsigned i = 0; i < Mask.size(); ++i) {
3943 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3944 return false;
3945 SplatElem = Mask[i];
3946 }
3947
3948 return true;
3949}
3950
3951/// Some targets have expensive vector shifts if the lanes aren't all the same
3952/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3953/// it's often worth sinking a shufflevector splat down to its use so that
3954/// codegen can spot all lanes are identical.
3955bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3956 BasicBlock *DefBB = SVI->getParent();
3957
3958 // Only do this xform if variable vector shifts are particularly expensive.
3959 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3960 return false;
3961
3962 // We only expect better codegen by sinking a shuffle if we can recognise a
3963 // constant splat.
3964 if (!isBroadcastShuffle(SVI))
3965 return false;
3966
3967 // InsertedShuffles - Only insert a shuffle in each block once.
3968 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3969
3970 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003971 for (User *U : SVI->users()) {
3972 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003973
3974 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003975 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003976 if (UserBB == DefBB) continue;
3977
3978 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003979 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003980
3981 // Everything checks out, sink the shuffle if the user's block doesn't
3982 // already have a copy.
3983 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3984
3985 if (!InsertedShuffle) {
3986 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3987 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3988 SVI->getOperand(1),
3989 SVI->getOperand(2), "", InsertPt);
3990 }
3991
Chandler Carruthcdf47882014-03-09 03:16:01 +00003992 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003993 MadeChange = true;
3994 }
3995
3996 // If we removed all uses, nuke the shuffle.
3997 if (SVI->use_empty()) {
3998 SVI->eraseFromParent();
3999 MadeChange = true;
4000 }
4001
4002 return MadeChange;
4003}
4004
Quentin Colombetc32615d2014-10-31 17:52:53 +00004005namespace {
4006/// \brief Helper class to promote a scalar operation to a vector one.
4007/// This class is used to move downward extractelement transition.
4008/// E.g.,
4009/// a = vector_op <2 x i32>
4010/// b = extractelement <2 x i32> a, i32 0
4011/// c = scalar_op b
4012/// store c
4013///
4014/// =>
4015/// a = vector_op <2 x i32>
4016/// c = vector_op a (equivalent to scalar_op on the related lane)
4017/// * d = extractelement <2 x i32> c, i32 0
4018/// * store d
4019/// Assuming both extractelement and store can be combine, we get rid of the
4020/// transition.
4021class VectorPromoteHelper {
Mehdi Amini44ede332015-07-09 02:09:04 +00004022 /// DataLayout associated with the current module.
4023 const DataLayout &DL;
4024
Quentin Colombetc32615d2014-10-31 17:52:53 +00004025 /// Used to perform some checks on the legality of vector operations.
4026 const TargetLowering &TLI;
4027
4028 /// Used to estimated the cost of the promoted chain.
4029 const TargetTransformInfo &TTI;
4030
4031 /// The transition being moved downwards.
4032 Instruction *Transition;
4033 /// The sequence of instructions to be promoted.
4034 SmallVector<Instruction *, 4> InstsToBePromoted;
4035 /// Cost of combining a store and an extract.
4036 unsigned StoreExtractCombineCost;
4037 /// Instruction that will be combined with the transition.
4038 Instruction *CombineInst;
4039
4040 /// \brief The instruction that represents the current end of the transition.
4041 /// Since we are faking the promotion until we reach the end of the chain
4042 /// of computation, we need a way to get the current end of the transition.
4043 Instruction *getEndOfTransition() const {
4044 if (InstsToBePromoted.empty())
4045 return Transition;
4046 return InstsToBePromoted.back();
4047 }
4048
4049 /// \brief Return the index of the original value in the transition.
4050 /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4051 /// c, is at index 0.
4052 unsigned getTransitionOriginalValueIdx() const {
4053 assert(isa<ExtractElementInst>(Transition) &&
4054 "Other kind of transitions are not supported yet");
4055 return 0;
4056 }
4057
4058 /// \brief Return the index of the index in the transition.
4059 /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4060 /// is at index 1.
4061 unsigned getTransitionIdx() const {
4062 assert(isa<ExtractElementInst>(Transition) &&
4063 "Other kind of transitions are not supported yet");
4064 return 1;
4065 }
4066
4067 /// \brief Get the type of the transition.
4068 /// This is the type of the original value.
4069 /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4070 /// transition is <2 x i32>.
4071 Type *getTransitionType() const {
4072 return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4073 }
4074
4075 /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4076 /// I.e., we have the following sequence:
4077 /// Def = Transition <ty1> a to <ty2>
4078 /// b = ToBePromoted <ty2> Def, ...
4079 /// =>
4080 /// b = ToBePromoted <ty1> a, ...
4081 /// Def = Transition <ty1> ToBePromoted to <ty2>
4082 void promoteImpl(Instruction *ToBePromoted);
4083
4084 /// \brief Check whether or not it is profitable to promote all the
4085 /// instructions enqueued to be promoted.
4086 bool isProfitableToPromote() {
4087 Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4088 unsigned Index = isa<ConstantInt>(ValIdx)
4089 ? cast<ConstantInt>(ValIdx)->getZExtValue()
4090 : -1;
4091 Type *PromotedType = getTransitionType();
4092
4093 StoreInst *ST = cast<StoreInst>(CombineInst);
4094 unsigned AS = ST->getPointerAddressSpace();
4095 unsigned Align = ST->getAlignment();
4096 // Check if this store is supported.
4097 if (!TLI.allowsMisalignedMemoryAccesses(
Mehdi Amini44ede332015-07-09 02:09:04 +00004098 TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4099 Align)) {
Quentin Colombetc32615d2014-10-31 17:52:53 +00004100 // If this is not supported, there is no way we can combine
4101 // the extract with the store.
4102 return false;
4103 }
4104
4105 // The scalar chain of computation has to pay for the transition
4106 // scalar to vector.
4107 // The vector chain has to account for the combining cost.
4108 uint64_t ScalarCost =
4109 TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4110 uint64_t VectorCost = StoreExtractCombineCost;
4111 for (const auto &Inst : InstsToBePromoted) {
4112 // Compute the cost.
4113 // By construction, all instructions being promoted are arithmetic ones.
4114 // Moreover, one argument is a constant that can be viewed as a splat
4115 // constant.
4116 Value *Arg0 = Inst->getOperand(0);
4117 bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4118 isa<ConstantFP>(Arg0);
4119 TargetTransformInfo::OperandValueKind Arg0OVK =
4120 IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4121 : TargetTransformInfo::OK_AnyValue;
4122 TargetTransformInfo::OperandValueKind Arg1OVK =
4123 !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4124 : TargetTransformInfo::OK_AnyValue;
4125 ScalarCost += TTI.getArithmeticInstrCost(
4126 Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4127 VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4128 Arg0OVK, Arg1OVK);
4129 }
4130 DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4131 << ScalarCost << "\nVector: " << VectorCost << '\n');
4132 return ScalarCost > VectorCost;
4133 }
4134
4135 /// \brief Generate a constant vector with \p Val with the same
4136 /// number of elements as the transition.
4137 /// \p UseSplat defines whether or not \p Val should be replicated
4138 /// accross the whole vector.
4139 /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4140 /// otherwise we generate a vector with as many undef as possible:
4141 /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4142 /// used at the index of the extract.
4143 Value *getConstantVector(Constant *Val, bool UseSplat) const {
4144 unsigned ExtractIdx = UINT_MAX;
4145 if (!UseSplat) {
4146 // If we cannot determine where the constant must be, we have to
4147 // use a splat constant.
4148 Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4149 if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4150 ExtractIdx = CstVal->getSExtValue();
4151 else
4152 UseSplat = true;
4153 }
4154
4155 unsigned End = getTransitionType()->getVectorNumElements();
4156 if (UseSplat)
4157 return ConstantVector::getSplat(End, Val);
4158
4159 SmallVector<Constant *, 4> ConstVec;
4160 UndefValue *UndefVal = UndefValue::get(Val->getType());
4161 for (unsigned Idx = 0; Idx != End; ++Idx) {
4162 if (Idx == ExtractIdx)
4163 ConstVec.push_back(Val);
4164 else
4165 ConstVec.push_back(UndefVal);
4166 }
4167 return ConstantVector::get(ConstVec);
4168 }
4169
4170 /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4171 /// in \p Use can trigger undefined behavior.
4172 static bool canCauseUndefinedBehavior(const Instruction *Use,
4173 unsigned OperandIdx) {
4174 // This is not safe to introduce undef when the operand is on
4175 // the right hand side of a division-like instruction.
4176 if (OperandIdx != 1)
4177 return false;
4178 switch (Use->getOpcode()) {
4179 default:
4180 return false;
4181 case Instruction::SDiv:
4182 case Instruction::UDiv:
4183 case Instruction::SRem:
4184 case Instruction::URem:
4185 return true;
4186 case Instruction::FDiv:
4187 case Instruction::FRem:
4188 return !Use->hasNoNaNs();
4189 }
4190 llvm_unreachable(nullptr);
4191 }
4192
4193public:
Mehdi Amini44ede332015-07-09 02:09:04 +00004194 VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4195 const TargetTransformInfo &TTI, Instruction *Transition,
4196 unsigned CombineCost)
4197 : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
Quentin Colombetc32615d2014-10-31 17:52:53 +00004198 StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4199 assert(Transition && "Do not know how to promote null");
4200 }
4201
4202 /// \brief Check if we can promote \p ToBePromoted to \p Type.
4203 bool canPromote(const Instruction *ToBePromoted) const {
4204 // We could support CastInst too.
4205 return isa<BinaryOperator>(ToBePromoted);
4206 }
4207
4208 /// \brief Check if it is profitable to promote \p ToBePromoted
4209 /// by moving downward the transition through.
4210 bool shouldPromote(const Instruction *ToBePromoted) const {
4211 // Promote only if all the operands can be statically expanded.
4212 // Indeed, we do not want to introduce any new kind of transitions.
4213 for (const Use &U : ToBePromoted->operands()) {
4214 const Value *Val = U.get();
4215 if (Val == getEndOfTransition()) {
4216 // If the use is a division and the transition is on the rhs,
4217 // we cannot promote the operation, otherwise we may create a
4218 // division by zero.
4219 if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4220 return false;
4221 continue;
4222 }
4223 if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4224 !isa<ConstantFP>(Val))
4225 return false;
4226 }
4227 // Check that the resulting operation is legal.
4228 int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4229 if (!ISDOpcode)
4230 return false;
4231 return StressStoreExtract ||
Ahmed Bougacha026600d2014-11-12 23:05:03 +00004232 TLI.isOperationLegalOrCustom(
Mehdi Amini44ede332015-07-09 02:09:04 +00004233 ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
Quentin Colombetc32615d2014-10-31 17:52:53 +00004234 }
4235
4236 /// \brief Check whether or not \p Use can be combined
4237 /// with the transition.
4238 /// I.e., is it possible to do Use(Transition) => AnotherUse?
4239 bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4240
4241 /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4242 void enqueueForPromotion(Instruction *ToBePromoted) {
4243 InstsToBePromoted.push_back(ToBePromoted);
4244 }
4245
4246 /// \brief Set the instruction that will be combined with the transition.
4247 void recordCombineInstruction(Instruction *ToBeCombined) {
4248 assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4249 CombineInst = ToBeCombined;
4250 }
4251
4252 /// \brief Promote all the instructions enqueued for promotion if it is
4253 /// is profitable.
4254 /// \return True if the promotion happened, false otherwise.
4255 bool promote() {
4256 // Check if there is something to promote.
4257 // Right now, if we do not have anything to combine with,
4258 // we assume the promotion is not profitable.
4259 if (InstsToBePromoted.empty() || !CombineInst)
4260 return false;
4261
4262 // Check cost.
4263 if (!StressStoreExtract && !isProfitableToPromote())
4264 return false;
4265
4266 // Promote.
4267 for (auto &ToBePromoted : InstsToBePromoted)
4268 promoteImpl(ToBePromoted);
4269 InstsToBePromoted.clear();
4270 return true;
4271 }
4272};
4273} // End of anonymous namespace.
4274
4275void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4276 // At this point, we know that all the operands of ToBePromoted but Def
4277 // can be statically promoted.
4278 // For Def, we need to use its parameter in ToBePromoted:
4279 // b = ToBePromoted ty1 a
4280 // Def = Transition ty1 b to ty2
4281 // Move the transition down.
4282 // 1. Replace all uses of the promoted operation by the transition.
4283 // = ... b => = ... Def.
4284 assert(ToBePromoted->getType() == Transition->getType() &&
4285 "The type of the result of the transition does not match "
4286 "the final type");
4287 ToBePromoted->replaceAllUsesWith(Transition);
4288 // 2. Update the type of the uses.
4289 // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4290 Type *TransitionTy = getTransitionType();
4291 ToBePromoted->mutateType(TransitionTy);
4292 // 3. Update all the operands of the promoted operation with promoted
4293 // operands.
4294 // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4295 for (Use &U : ToBePromoted->operands()) {
4296 Value *Val = U.get();
4297 Value *NewVal = nullptr;
4298 if (Val == Transition)
4299 NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4300 else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4301 isa<ConstantFP>(Val)) {
4302 // Use a splat constant if it is not safe to use undef.
4303 NewVal = getConstantVector(
4304 cast<Constant>(Val),
4305 isa<UndefValue>(Val) ||
4306 canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4307 } else
Craig Topperd3c02f12015-01-05 10:15:49 +00004308 llvm_unreachable("Did you modified shouldPromote and forgot to update "
4309 "this?");
Quentin Colombetc32615d2014-10-31 17:52:53 +00004310 ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4311 }
4312 Transition->removeFromParent();
4313 Transition->insertAfter(ToBePromoted);
4314 Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4315}
4316
4317/// Some targets can do store(extractelement) with one instruction.
4318/// Try to push the extractelement towards the stores when the target
4319/// has this feature and this is profitable.
4320bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4321 unsigned CombineCost = UINT_MAX;
4322 if (DisableStoreExtract || !TLI ||
4323 (!StressStoreExtract &&
4324 !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4325 Inst->getOperand(1), CombineCost)))
4326 return false;
4327
4328 // At this point we know that Inst is a vector to scalar transition.
4329 // Try to move it down the def-use chain, until:
4330 // - We can combine the transition with its single use
4331 // => we got rid of the transition.
4332 // - We escape the current basic block
4333 // => we would need to check that we are moving it at a cheaper place and
4334 // we do not do that for now.
4335 BasicBlock *Parent = Inst->getParent();
4336 DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
Mehdi Amini44ede332015-07-09 02:09:04 +00004337 VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
Quentin Colombetc32615d2014-10-31 17:52:53 +00004338 // If the transition has more than one use, assume this is not going to be
4339 // beneficial.
4340 while (Inst->hasOneUse()) {
4341 Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4342 DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4343
4344 if (ToBePromoted->getParent() != Parent) {
4345 DEBUG(dbgs() << "Instruction to promote is in a different block ("
4346 << ToBePromoted->getParent()->getName()
4347 << ") than the transition (" << Parent->getName() << ").\n");
4348 return false;
4349 }
4350
4351 if (VPH.canCombine(ToBePromoted)) {
4352 DEBUG(dbgs() << "Assume " << *Inst << '\n'
4353 << "will be combined with: " << *ToBePromoted << '\n');
4354 VPH.recordCombineInstruction(ToBePromoted);
4355 bool Changed = VPH.promote();
4356 NumStoreExtractExposed += Changed;
4357 return Changed;
4358 }
4359
4360 DEBUG(dbgs() << "Try promoting.\n");
4361 if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4362 return false;
4363
4364 DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4365
4366 VPH.enqueueForPromotion(ToBePromoted);
4367 Inst = ToBePromoted;
4368 }
4369 return false;
4370}
4371
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004372bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
Ahmed Bougachaf3299142015-06-17 20:44:32 +00004373 // Bail out if we inserted the instruction to prevent optimizations from
4374 // stepping on each other's toes.
4375 if (InsertedInsts.count(I))
4376 return false;
4377
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004378 if (PHINode *P = dyn_cast<PHINode>(I)) {
4379 // It is possible for very late stage optimizations (such as SimplifyCFG)
4380 // to introduce PHI nodes too late to be cleaned up. If we detect such a
4381 // trivial PHI, go ahead and zap it here.
Mehdi Amini4fe37982015-07-07 18:45:17 +00004382 if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004383 P->replaceAllUsesWith(V);
4384 P->eraseFromParent();
4385 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00004386 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004387 }
Chris Lattneree588de2011-01-15 07:29:01 +00004388 return false;
4389 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004390
Chris Lattneree588de2011-01-15 07:29:01 +00004391 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004392 // If the source of the cast is a constant, then this should have
4393 // already been constant folded. The only reason NOT to constant fold
4394 // it is if something (e.g. LSR) was careful to place the constant
4395 // evaluation in a block other than then one that uses it (e.g. to hoist
4396 // the address of globals out of a loop). If this is the case, we don't
4397 // want to forward-subst the cast.
4398 if (isa<Constant>(CI->getOperand(0)))
4399 return false;
4400
Mehdi Amini44ede332015-07-09 02:09:04 +00004401 if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
Chris Lattneree588de2011-01-15 07:29:01 +00004402 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004403
Chris Lattneree588de2011-01-15 07:29:01 +00004404 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004405 /// Sink a zext or sext into its user blocks if the target type doesn't
4406 /// fit in one register
Mehdi Amini44ede332015-07-09 02:09:04 +00004407 if (TLI &&
4408 TLI->getTypeAction(CI->getContext(),
4409 TLI->getValueType(*DL, CI->getType())) ==
4410 TargetLowering::TypeExpandInteger) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00004411 return SinkCast(CI);
4412 } else {
4413 bool MadeChange = MoveExtToFormExtLoad(I);
4414 return MadeChange | OptimizeExtUses(I);
4415 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004416 }
Chris Lattneree588de2011-01-15 07:29:01 +00004417 return false;
4418 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004419
Chris Lattneree588de2011-01-15 07:29:01 +00004420 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00004421 if (!TLI || !TLI->hasMultipleConditionRegisters())
4422 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00004423
Chris Lattneree588de2011-01-15 07:29:01 +00004424 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004425 if (TLI) {
4426 unsigned AS = LI->getPointerAddressSpace();
4427 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
4428 }
Hans Wennborgf3254832012-10-30 11:23:25 +00004429 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00004430 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004431
Chris Lattneree588de2011-01-15 07:29:01 +00004432 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004433 if (TLI) {
4434 unsigned AS = SI->getPointerAddressSpace();
Chris Lattneree588de2011-01-15 07:29:01 +00004435 return OptimizeMemoryInst(I, SI->getOperand(1),
Matt Arsenaultf72b49b2015-06-04 16:17:38 +00004436 SI->getOperand(0)->getType(), AS);
4437 }
Chris Lattneree588de2011-01-15 07:29:01 +00004438 return false;
4439 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004440
Yi Jiangd069f632014-04-21 19:34:27 +00004441 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4442
4443 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4444 BinOp->getOpcode() == Instruction::LShr)) {
4445 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4446 if (TLI && CI && TLI->hasExtractBitsInsn())
Mehdi Amini44ede332015-07-09 02:09:04 +00004447 return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
Yi Jiangd069f632014-04-21 19:34:27 +00004448
4449 return false;
4450 }
4451
Chris Lattneree588de2011-01-15 07:29:01 +00004452 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004453 if (GEPI->hasAllZeroIndices()) {
4454 /// The GEP operand must be a pointer, so must its result -> BitCast
4455 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4456 GEPI->getName(), GEPI);
4457 GEPI->replaceAllUsesWith(NC);
4458 GEPI->eraseFromParent();
4459 ++NumGEPsElim;
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004460 OptimizeInst(NC, ModifiedDT);
Chris Lattneree588de2011-01-15 07:29:01 +00004461 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00004462 }
Chris Lattneree588de2011-01-15 07:29:01 +00004463 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004464 }
Nadav Rotem465834c2012-07-24 10:51:42 +00004465
Chris Lattneree588de2011-01-15 07:29:01 +00004466 if (CallInst *CI = dyn_cast<CallInst>(I))
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004467 return OptimizeCallInst(CI, ModifiedDT);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004468
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00004469 if (SelectInst *SI = dyn_cast<SelectInst>(I))
4470 return OptimizeSelectInst(SI);
4471
Tim Northoveraeb8e062014-02-19 10:02:43 +00004472 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4473 return OptimizeShuffleVectorInst(SVI);
4474
Quentin Colombetc32615d2014-10-31 17:52:53 +00004475 if (isa<ExtractElementInst>(I))
4476 return OptimizeExtractElementInst(I);
4477
Chris Lattneree588de2011-01-15 07:29:01 +00004478 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00004479}
4480
Chris Lattnerf2836d12007-03-31 04:06:36 +00004481// In this pass we look for GEP and cast instructions that are used
4482// across basic blocks and rewrite them to improve basic-block-at-a-time
4483// selection.
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004484bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00004485 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00004486 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00004487
Chris Lattner7a277142011-01-15 07:14:54 +00004488 CurInstIterator = BB.begin();
Elena Demikhovsky87700a72014-12-28 08:54:45 +00004489 while (CurInstIterator != BB.end()) {
4490 MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4491 if (ModifiedDT)
4492 return true;
4493 }
Benjamin Kramer455fa352012-11-23 19:17:06 +00004494 MadeChange |= DupRetToEnableTailCallOpts(&BB);
4495
Chris Lattnerf2836d12007-03-31 04:06:36 +00004496 return MadeChange;
4497}
Devang Patel53771ba2011-08-18 00:50:51 +00004498
4499// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00004500// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00004501// find a node corresponding to the value.
4502bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4503 bool MadeChange = false;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004504 for (BasicBlock &BB : F) {
Craig Topperc0196b12014-04-14 00:51:57 +00004505 Instruction *PrevNonDbgInst = nullptr;
Duncan P. N. Exon Smith5914a972015-01-08 20:44:33 +00004506 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
Duncan P. N. Exon Smithe90f1162015-01-08 21:07:55 +00004507 Instruction *Insn = BI++;
Devang Patel53771ba2011-08-18 00:50:51 +00004508 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00004509 // Leave dbg.values that refer to an alloca alone. These
4510 // instrinsics describe the address of a variable (= the alloca)
4511 // being taken. They should not be moved next to the alloca
4512 // (and to the beginning of the scope), but rather stay close to
4513 // where said address is used.
4514 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00004515 PrevNonDbgInst = Insn;
4516 continue;
4517 }
4518
4519 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4520 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4521 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4522 DVI->removeFromParent();
4523 if (isa<PHINode>(VI))
4524 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4525 else
4526 DVI->insertAfter(VI);
4527 MadeChange = true;
4528 ++NumDbgValueMoved;
4529 }
4530 }
4531 }
4532 return MadeChange;
4533}
Tim Northovercea0abb2014-03-29 08:22:29 +00004534
4535// If there is a sequence that branches based on comparing a single bit
4536// against zero that can be combined into a single instruction, and the
4537// target supports folding these into a single instruction, sink the
4538// mask and compare into the branch uses. Do this before OptimizeBlock ->
4539// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4540// searched for.
4541bool CodeGenPrepare::sinkAndCmp(Function &F) {
4542 if (!EnableAndCmpSinking)
4543 return false;
4544 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4545 return false;
4546 bool MadeChange = false;
4547 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4548 BasicBlock *BB = I++;
4549
4550 // Does this BB end with the following?
4551 // %andVal = and %val, #single-bit-set
4552 // %icmpVal = icmp %andResult, 0
4553 // br i1 %cmpVal label %dest1, label %dest2"
4554 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4555 if (!Brcc || !Brcc->isConditional())
4556 continue;
4557 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4558 if (!Cmp || Cmp->getParent() != BB)
4559 continue;
4560 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4561 if (!Zero || !Zero->isZero())
4562 continue;
4563 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4564 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4565 continue;
4566 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4567 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4568 continue;
4569 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4570
4571 // Push the "and; icmp" for any users that are conditional branches.
4572 // Since there can only be one branch use per BB, we don't need to keep
4573 // track of which BBs we insert into.
4574 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4575 UI != E; ) {
4576 Use &TheUse = *UI;
4577 // Find brcc use.
4578 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4579 ++UI;
4580 if (!BrccUser || !BrccUser->isConditional())
4581 continue;
4582 BasicBlock *UserBB = BrccUser->getParent();
4583 if (UserBB == BB) continue;
4584 DEBUG(dbgs() << "found Brcc use\n");
4585
4586 // Sink the "and; icmp" to use.
4587 MadeChange = true;
4588 BinaryOperator *NewAnd =
4589 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4590 BrccUser);
4591 CmpInst *NewCmp =
4592 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4593 "", BrccUser);
4594 TheUse = NewCmp;
4595 ++NumAndCmpsMoved;
4596 DEBUG(BrccUser->getParent()->dump());
4597 }
4598 }
4599 return MadeChange;
4600}
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004601
Juergen Ributzka194350a2014-12-09 17:32:12 +00004602/// \brief Retrieve the probabilities of a conditional branch. Returns true on
4603/// success, or returns false if no or invalid metadata was found.
4604static bool extractBranchMetadata(BranchInst *BI,
4605 uint64_t &ProbTrue, uint64_t &ProbFalse) {
4606 assert(BI->isConditional() &&
4607 "Looking for probabilities on unconditional branch?");
4608 auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4609 if (!ProfileData || ProfileData->getNumOperands() != 3)
4610 return false;
4611
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00004612 const auto *CITrue =
4613 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4614 const auto *CIFalse =
4615 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
Juergen Ributzka194350a2014-12-09 17:32:12 +00004616 if (!CITrue || !CIFalse)
4617 return false;
4618
4619 ProbTrue = CITrue->getValue().getZExtValue();
4620 ProbFalse = CIFalse->getValue().getZExtValue();
4621
4622 return true;
4623}
4624
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004625/// \brief Scale down both weights to fit into uint32_t.
4626static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4627 uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4628 uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4629 NewTrue = NewTrue / Scale;
4630 NewFalse = NewFalse / Scale;
4631}
4632
4633/// \brief Some targets prefer to split a conditional branch like:
4634/// \code
4635/// %0 = icmp ne i32 %a, 0
4636/// %1 = icmp ne i32 %b, 0
4637/// %or.cond = or i1 %0, %1
4638/// br i1 %or.cond, label %TrueBB, label %FalseBB
4639/// \endcode
4640/// into multiple branch instructions like:
4641/// \code
4642/// bb1:
4643/// %0 = icmp ne i32 %a, 0
4644/// br i1 %0, label %TrueBB, label %bb2
4645/// bb2:
4646/// %1 = icmp ne i32 %b, 0
4647/// br i1 %1, label %TrueBB, label %FalseBB
4648/// \endcode
4649/// This usually allows instruction selection to do even further optimizations
4650/// and combine the compare with the branch instruction. Currently this is
4651/// applied for targets which have "cheap" jump instructions.
4652///
4653/// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4654///
4655bool CodeGenPrepare::splitBranchCondition(Function &F) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00004656 if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004657 return false;
4658
4659 bool MadeChange = false;
4660 for (auto &BB : F) {
4661 // Does this BB end with the following?
4662 // %cond1 = icmp|fcmp|binary instruction ...
4663 // %cond2 = icmp|fcmp|binary instruction ...
4664 // %cond.or = or|and i1 %cond1, cond2
4665 // br i1 %cond.or label %dest1, label %dest2"
4666 BinaryOperator *LogicOp;
4667 BasicBlock *TBB, *FBB;
4668 if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4669 continue;
4670
4671 unsigned Opc;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004672 Value *Cond1, *Cond2;
4673 if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4674 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004675 Opc = Instruction::And;
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004676 else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4677 m_OneUse(m_Value(Cond2)))))
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004678 Opc = Instruction::Or;
4679 else
4680 continue;
4681
4682 if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4683 !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
4684 continue;
4685
4686 DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4687
4688 // Create a new BB.
4689 auto *InsertBefore = std::next(Function::iterator(BB))
4690 .getNodePtrUnchecked();
4691 auto TmpBB = BasicBlock::Create(BB.getContext(),
4692 BB.getName() + ".cond.split",
4693 BB.getParent(), InsertBefore);
4694
4695 // Update original basic block by using the first condition directly by the
4696 // branch instruction and removing the no longer needed and/or instruction.
4697 auto *Br1 = cast<BranchInst>(BB.getTerminator());
4698 Br1->setCondition(Cond1);
4699 LogicOp->eraseFromParent();
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004700
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004701 // Depending on the conditon we have to either replace the true or the false
4702 // successor of the original branch instruction.
4703 if (Opc == Instruction::And)
4704 Br1->setSuccessor(0, TmpBB);
4705 else
4706 Br1->setSuccessor(1, TmpBB);
4707
4708 // Fill in the new basic block.
4709 auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
Juergen Ributzka8bda7382014-12-09 17:50:10 +00004710 if (auto *I = dyn_cast<Instruction>(Cond2)) {
4711 I->removeFromParent();
4712 I->insertBefore(Br2);
4713 }
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004714
4715 // Update PHI nodes in both successors. The original BB needs to be
4716 // replaced in one succesor's PHI nodes, because the branch comes now from
4717 // the newly generated BB (NewBB). In the other successor we need to add one
4718 // incoming edge to the PHI nodes, because both branch instructions target
4719 // now the same successor. Depending on the original branch condition
4720 // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4721 // we perfrom the correct update for the PHI nodes.
4722 // This doesn't change the successor order of the just created branch
4723 // instruction (or any other instruction).
4724 if (Opc == Instruction::Or)
4725 std::swap(TBB, FBB);
4726
4727 // Replace the old BB with the new BB.
4728 for (auto &I : *TBB) {
4729 PHINode *PN = dyn_cast<PHINode>(&I);
4730 if (!PN)
4731 break;
4732 int i;
4733 while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4734 PN->setIncomingBlock(i, TmpBB);
4735 }
4736
4737 // Add another incoming edge form the new BB.
4738 for (auto &I : *FBB) {
4739 PHINode *PN = dyn_cast<PHINode>(&I);
4740 if (!PN)
4741 break;
4742 auto *Val = PN->getIncomingValueForBlock(&BB);
4743 PN->addIncoming(Val, TmpBB);
4744 }
4745
4746 // Update the branch weights (from SelectionDAGBuilder::
4747 // FindMergedConditions).
4748 if (Opc == Instruction::Or) {
4749 // Codegen X | Y as:
4750 // BB1:
4751 // jmp_if_X TBB
4752 // jmp TmpBB
4753 // TmpBB:
4754 // jmp_if_Y TBB
4755 // jmp FBB
4756 //
4757
4758 // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4759 // The requirement is that
4760 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4761 // = TrueProb for orignal BB.
4762 // Assuming the orignal weights are A and B, one choice is to set BB1's
4763 // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4764 // assumes that
4765 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4766 // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4767 // TmpBB, but the math is more complicated.
4768 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004769 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004770 uint64_t NewTrueWeight = TrueWeight;
4771 uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4772 scaleWeights(NewTrueWeight, NewFalseWeight);
4773 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4774 .createBranchWeights(TrueWeight, FalseWeight));
4775
4776 NewTrueWeight = TrueWeight;
4777 NewFalseWeight = 2 * FalseWeight;
4778 scaleWeights(NewTrueWeight, NewFalseWeight);
4779 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4780 .createBranchWeights(TrueWeight, FalseWeight));
4781 }
4782 } else {
4783 // Codegen X & Y as:
4784 // BB1:
4785 // jmp_if_X TmpBB
4786 // jmp FBB
4787 // TmpBB:
4788 // jmp_if_Y TBB
4789 // jmp FBB
4790 //
4791 // This requires creation of TmpBB after CurBB.
4792
4793 // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4794 // The requirement is that
4795 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4796 // = FalseProb for orignal BB.
4797 // Assuming the orignal weights are A and B, one choice is to set BB1's
4798 // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4799 // assumes that
4800 // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4801 uint64_t TrueWeight, FalseWeight;
Juergen Ributzka194350a2014-12-09 17:32:12 +00004802 if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004803 uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4804 uint64_t NewFalseWeight = FalseWeight;
4805 scaleWeights(NewTrueWeight, NewFalseWeight);
4806 Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4807 .createBranchWeights(TrueWeight, FalseWeight));
4808
4809 NewTrueWeight = 2 * TrueWeight;
4810 NewFalseWeight = FalseWeight;
4811 scaleWeights(NewTrueWeight, NewFalseWeight);
4812 Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4813 .createBranchWeights(TrueWeight, FalseWeight));
4814 }
4815 }
4816
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004817 // Note: No point in getting fancy here, since the DT info is never
Quentin Colombet7bdd50d2015-03-18 23:17:28 +00004818 // available to CodeGenPrepare.
Juergen Ributzkac1bbcbb2014-12-09 16:36:13 +00004819 ModifiedDT = true;
4820
4821 MadeChange = true;
4822
4823 DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4824 TmpBB->dump());
4825 }
4826 return MadeChange;
4827}