blob: f2c7e642710ac6975232dcf06d6516528197c256 [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 Carruth219b89b2014-03-04 11:01:28 +000021#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000025#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000027#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/IRBuilder.h"
29#include "llvm/IR/InlineAsm.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000033#include "llvm/IR/ValueHandle.h"
Chandler Carrutha4ea2692014-03-04 11:26:31 +000034#include "llvm/IR/ValueMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000035#include "llvm/Pass.h"
Evan Cheng8b637b12010-08-17 01:34:49 +000036#include "llvm/Support/CommandLine.h"
Evan Chengd3d80172007-12-05 23:58:20 +000037#include "llvm/Support/Debug.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000038#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000039#include "llvm/Target/TargetLibraryInfo.h"
40#include "llvm/Target/TargetLowering.h"
Hal Finkelc3998302014-04-12 00:59:48 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000042#include "llvm/Transforms/Utils/BasicBlockUtils.h"
43#include "llvm/Transforms/Utils/BuildLibCalls.h"
Preston Gurdcdf540d2012-09-04 18:22:17 +000044#include "llvm/Transforms/Utils/BypassSlowDivision.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000045#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000046using namespace llvm;
Chris Lattnerd616ef52008-11-25 04:42:10 +000047using namespace llvm::PatternMatch;
Chris Lattnerf2836d12007-03-31 04:06:36 +000048
Chandler Carruth1b9dde02014-04-22 02:02:50 +000049#define DEBUG_TYPE "codegenprepare"
50
Cameron Zwarichced753f2011-01-05 17:27:27 +000051STATISTIC(NumBlocksElim, "Number of blocks eliminated");
Evan Cheng0663f232011-03-21 01:19:09 +000052STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
53STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
Cameron Zwarichced753f2011-01-05 17:27:27 +000054STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
55 "sunken Cmps");
56STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
57 "of sunken Casts");
58STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
59 "computations were sunk");
Evan Cheng0663f232011-03-21 01:19:09 +000060STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
61STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
62STATISTIC(NumRetsDup, "Number of return instructions duplicated");
Devang Patel53771ba2011-08-18 00:50:51 +000063STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000064STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
Tim Northovercea0abb2014-03-29 08:22:29 +000065STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
Jakob Stoklund Oleseneb12f492010-09-30 20:51:52 +000066
Cameron Zwarich338d3622011-03-11 21:52:04 +000067static cl::opt<bool> DisableBranchOpts(
68 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
69 cl::desc("Disable branch optimizations in CodeGenPrepare"));
70
Benjamin Kramer3d38c172012-05-06 14:25:16 +000071static cl::opt<bool> DisableSelectToBranch(
72 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
73 cl::desc("Disable select to branch conversion."));
Benjamin Kramer047d7ca2012-05-05 12:49:22 +000074
Hal Finkelc3998302014-04-12 00:59:48 +000075static cl::opt<bool> AddrSinkUsingGEPs(
76 "addr-sink-using-gep", cl::Hidden, cl::init(false),
77 cl::desc("Address sinking in CGP using GEPs."));
78
Tim Northovercea0abb2014-03-29 08:22:29 +000079static cl::opt<bool> EnableAndCmpSinking(
80 "enable-andcmp-sinking", cl::Hidden, cl::init(true),
81 cl::desc("Enable sinkinig and/cmp into branches."));
82
Eric Christopherc1ea1492008-09-24 05:32:41 +000083namespace {
Quentin Colombet3a4bf042014-02-06 21:44:56 +000084typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
85typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
86
Chris Lattner2dd09db2009-09-02 06:11:42 +000087 class CodeGenPrepare : public FunctionPass {
Chris Lattnerf2836d12007-03-31 04:06:36 +000088 /// TLI - Keep a pointer of a TargetLowering to consult for determining
89 /// transformation profitability.
Bill Wendling7a639ea2013-06-19 21:07:11 +000090 const TargetMachine *TM;
Chris Lattnerf2836d12007-03-31 04:06:36 +000091 const TargetLowering *TLI;
Chad Rosierc24b86f2011-12-01 03:08:23 +000092 const TargetLibraryInfo *TLInfo;
Cameron Zwarich84986b22011-01-08 17:01:52 +000093 DominatorTree *DT;
Nadav Rotem465834c2012-07-24 10:51:42 +000094
Chris Lattner7a277142011-01-15 07:14:54 +000095 /// CurInstIterator - As we scan instructions optimizing them, this is the
96 /// next instruction to optimize. Xforms that can invalidate this should
97 /// update it.
98 BasicBlock::iterator CurInstIterator;
Evan Cheng3b3de7c2008-12-19 18:03:11 +000099
Evan Cheng0663f232011-03-21 01:19:09 +0000100 /// Keeps track of non-local addresses that have been sunk into a block.
101 /// This allows us to avoid inserting duplicate code for blocks with
102 /// multiple load/stores of the same address.
Nick Lewycky5fb19632013-05-08 09:00:10 +0000103 ValueMap<Value*, Value*> SunkAddrs;
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000104
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000105 /// Keeps track of all truncates inserted for the current function.
106 SetOfInstrs InsertedTruncsSet;
107 /// Keeps track of the type of the related instruction before their
108 /// promotion for the current function.
109 InstrToOrigTy PromotedInsts;
110
Devang Patel8f606d72011-03-24 15:35:25 +0000111 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
Evan Cheng0663f232011-03-21 01:19:09 +0000112 /// be updated.
Devang Patel8f606d72011-03-24 15:35:25 +0000113 bool ModifiedDT;
Evan Cheng0663f232011-03-21 01:19:09 +0000114
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000115 /// OptSize - True if optimizing for size.
116 bool OptSize;
117
Chris Lattnerf2836d12007-03-31 04:06:36 +0000118 public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000119 static char ID; // Pass identification, replacement for typeid
Craig Topperc0196b12014-04-14 00:51:57 +0000120 explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
121 : FunctionPass(ID), TM(TM), TLI(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +0000122 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
123 }
Craig Topper4584cd52014-03-07 09:26:03 +0000124 bool runOnFunction(Function &F) override;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000125
Craig Topper4584cd52014-03-07 09:26:03 +0000126 const char *getPassName() const override { return "CodeGen Prepare"; }
Evan Cheng99cafb12012-12-21 01:48:14 +0000127
Craig Topper4584cd52014-03-07 09:26:03 +0000128 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth73523022014-01-13 13:07:17 +0000129 AU.addPreserved<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000130 AU.addRequired<TargetLibraryInfo>();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000131 }
132
Chris Lattnerf2836d12007-03-31 04:06:36 +0000133 private:
Nadav Rotem70409992012-08-14 05:19:07 +0000134 bool EliminateFallThrough(Function &F);
Chris Lattnerc3748562007-04-02 01:35:34 +0000135 bool EliminateMostlyEmptyBlocks(Function &F);
136 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
137 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000138 bool OptimizeBlock(BasicBlock &BB);
Cameron Zwarich14ac8652011-01-06 02:37:26 +0000139 bool OptimizeInst(Instruction *I);
Chris Lattner229907c2011-07-18 04:54:35 +0000140 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
Chris Lattner7a277142011-01-15 07:14:54 +0000141 bool OptimizeInlineAsmInst(CallInst *CS);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000142 bool OptimizeCallInst(CallInst *CI);
Dan Gohman99429a02009-10-16 20:59:35 +0000143 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengd3d80172007-12-05 23:58:20 +0000144 bool OptimizeExtUses(Instruction *I);
Benjamin Kramer047d7ca2012-05-05 12:49:22 +0000145 bool OptimizeSelectInst(SelectInst *SI);
Tim Northoveraeb8e062014-02-19 10:02:43 +0000146 bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
Benjamin Kramer455fa352012-11-23 19:17:06 +0000147 bool DupRetToEnableTailCallOpts(BasicBlock *BB);
Devang Patel53771ba2011-08-18 00:50:51 +0000148 bool PlaceDbgValues(Function &F);
Tim Northovercea0abb2014-03-29 08:22:29 +0000149 bool sinkAndCmp(Function &F);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000150 };
151}
Devang Patel09f162c2007-05-01 21:15:47 +0000152
Devang Patel8c78a0b2007-05-03 01:11:54 +0000153char CodeGenPrepare::ID = 0;
Jiangning Liud623c522014-06-11 07:04:37 +0000154INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
155 "Optimize for code generation", false, false)
Chris Lattnerf2836d12007-03-31 04:06:36 +0000156
Bill Wendling7a639ea2013-06-19 21:07:11 +0000157FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
158 return new CodeGenPrepare(TM);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000159}
160
Chris Lattnerf2836d12007-03-31 04:06:36 +0000161bool CodeGenPrepare::runOnFunction(Function &F) {
Paul Robinson7c99ec52014-03-31 17:43:35 +0000162 if (skipOptnoneFunction(F))
163 return false;
164
Chris Lattnerf2836d12007-03-31 04:06:36 +0000165 bool EverMadeChange = false;
Quentin Colombet3a4bf042014-02-06 21:44:56 +0000166 // Clear per function information.
167 InsertedTruncsSet.clear();
168 PromotedInsts.clear();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000169
Devang Patel8f606d72011-03-24 15:35:25 +0000170 ModifiedDT = false;
Bill Wendling7a639ea2013-06-19 21:07:11 +0000171 if (TM) TLI = TM->getTargetLowering();
Chad Rosierc24b86f2011-12-01 03:08:23 +0000172 TLInfo = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +0000173 DominatorTreeWrapperPass *DTWP =
174 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
Craig Topperc0196b12014-04-14 00:51:57 +0000175 DT = DTWP ? &DTWP->getDomTree() : nullptr;
Bill Wendling698e84f2012-12-30 10:32:01 +0000176 OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
177 Attribute::OptimizeForSize);
Evan Cheng0663f232011-03-21 01:19:09 +0000178
Preston Gurdcdf540d2012-09-04 18:22:17 +0000179 /// This optimization identifies DIV instructions that can be
180 /// profitably bypassed and carried out with a shorter, faster divide.
Preston Gurd485296d2013-03-04 18:13:57 +0000181 if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
Preston Gurd0d67f512012-10-04 21:33:40 +0000182 const DenseMap<unsigned int, unsigned int> &BypassWidths =
183 TLI->getBypassSlowDivWidths();
Evan Cheng71be12b2012-09-14 21:25:34 +0000184 for (Function::iterator I = F.begin(); I != F.end(); I++)
Preston Gurd0d67f512012-10-04 21:33:40 +0000185 EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
Preston Gurdcdf540d2012-09-04 18:22:17 +0000186 }
187
188 // Eliminate blocks that contain only PHI nodes and an
Chris Lattnerc3748562007-04-02 01:35:34 +0000189 // unconditional branch.
190 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000191
Devang Patel53771ba2011-08-18 00:50:51 +0000192 // llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +0000193 // handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +0000194 // find a node corresponding to the value.
195 EverMadeChange |= PlaceDbgValues(F);
196
Tim Northovercea0abb2014-03-29 08:22:29 +0000197 // If there is a mask, compare against zero, and branch that can be combined
198 // into a single target instruction, push the mask and compare into branch
199 // users. Do this before OptimizeBlock -> OptimizeInst ->
200 // OptimizeCmpExpression, which perturbs the pattern being searched for.
201 if (!DisableBranchOpts)
202 EverMadeChange |= sinkAndCmp(F);
203
Chris Lattnerc3748562007-04-02 01:35:34 +0000204 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000205 while (MadeChange) {
206 MadeChange = false;
Hans Wennborg02fbc712012-09-19 07:48:16 +0000207 for (Function::iterator I = F.begin(); I != F.end(); ) {
Evan Cheng0663f232011-03-21 01:19:09 +0000208 BasicBlock *BB = I++;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000209 MadeChange |= OptimizeBlock(*BB);
Evan Cheng0663f232011-03-21 01:19:09 +0000210 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000211 EverMadeChange |= MadeChange;
212 }
Cameron Zwarichce3b9302011-01-06 00:42:50 +0000213
214 SunkAddrs.clear();
215
Cameron Zwarich338d3622011-03-11 21:52:04 +0000216 if (!DisableBranchOpts) {
217 MadeChange = false;
Bill Wendling97b93592012-03-04 10:46:01 +0000218 SmallPtrSet<BasicBlock*, 8> WorkList;
219 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
220 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
Frits van Bommelad964552011-05-22 16:24:18 +0000221 MadeChange |= ConstantFoldTerminator(BB, true);
Bill Wendling97b93592012-03-04 10:46:01 +0000222 if (!MadeChange) continue;
223
224 for (SmallVectorImpl<BasicBlock*>::iterator
225 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
226 if (pred_begin(*II) == pred_end(*II))
227 WorkList.insert(*II);
228 }
229
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000230 // Delete the dead blocks and any of their dead successors.
Bill Wendlingab417b62012-12-06 00:30:20 +0000231 MadeChange |= !WorkList.empty();
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000232 while (!WorkList.empty()) {
233 BasicBlock *BB = *WorkList.begin();
234 WorkList.erase(BB);
235 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
236
237 DeleteDeadBlock(BB);
Stephen Lin837bba12013-07-15 17:55:02 +0000238
Bill Wendlingf3614fd2012-11-28 23:23:48 +0000239 for (SmallVectorImpl<BasicBlock*>::iterator
240 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
241 if (pred_begin(*II) == pred_end(*II))
242 WorkList.insert(*II);
243 }
Cameron Zwarich338d3622011-03-11 21:52:04 +0000244
Nadav Rotem70409992012-08-14 05:19:07 +0000245 // Merge pairs of basic blocks with unconditional branches, connected by
246 // a single edge.
247 if (EverMadeChange || MadeChange)
248 MadeChange |= EliminateFallThrough(F);
249
Evan Cheng0663f232011-03-21 01:19:09 +0000250 if (MadeChange)
Devang Patel8f606d72011-03-24 15:35:25 +0000251 ModifiedDT = true;
Cameron Zwarich338d3622011-03-11 21:52:04 +0000252 EverMadeChange |= MadeChange;
253 }
254
Devang Patel8f606d72011-03-24 15:35:25 +0000255 if (ModifiedDT && DT)
Chandler Carruth73523022014-01-13 13:07:17 +0000256 DT->recalculate(F);
Evan Cheng0663f232011-03-21 01:19:09 +0000257
Chris Lattnerf2836d12007-03-31 04:06:36 +0000258 return EverMadeChange;
259}
260
Nadav Rotem70409992012-08-14 05:19:07 +0000261/// EliminateFallThrough - Merge basic blocks which are connected
262/// by a single edge, where one of the basic blocks has a single successor
263/// pointing to the other basic block, which has a single predecessor.
264bool CodeGenPrepare::EliminateFallThrough(Function &F) {
265 bool Changed = false;
266 // Scan all of the blocks in the function, except for the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000267 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Nadav Rotem70409992012-08-14 05:19:07 +0000268 BasicBlock *BB = I++;
269 // If the destination block has a single pred, then this is a trivial
270 // edge, just collapse it.
271 BasicBlock *SinglePred = BB->getSinglePredecessor();
272
Evan Cheng64a223a2012-09-28 23:58:57 +0000273 // Don't merge if BB's address is taken.
274 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
Nadav Rotem70409992012-08-14 05:19:07 +0000275
276 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
277 if (Term && !Term->isConditional()) {
278 Changed = true;
Michael Liao6e12d122012-08-21 05:55:22 +0000279 DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
Nadav Rotem70409992012-08-14 05:19:07 +0000280 // Remember if SinglePred was the entry block of the function.
281 // If so, we will need to move BB back to the entry position.
282 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
283 MergeBasicBlockIntoOnlyPred(BB, this);
284
285 if (isEntry && BB != &BB->getParent()->getEntryBlock())
286 BB->moveBefore(&BB->getParent()->getEntryBlock());
287
288 // We have erased a block. Update the iterator.
289 I = BB;
Nadav Rotem70409992012-08-14 05:19:07 +0000290 }
291 }
292 return Changed;
293}
294
Dale Johannesen4026b042009-03-27 01:13:37 +0000295/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
296/// debug info directives, and an unconditional branch. Passes before isel
297/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
298/// isel. Start by eliminating these blocks so we can split them the way we
299/// want them.
Chris Lattnerc3748562007-04-02 01:35:34 +0000300bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
301 bool MadeChange = false;
302 // Note that this intentionally skips the entry block.
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000303 for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
Chris Lattnerc3748562007-04-02 01:35:34 +0000304 BasicBlock *BB = I++;
305
306 // If this block doesn't end with an uncond branch, ignore it.
307 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
308 if (!BI || !BI->isUnconditional())
309 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000310
Dale Johannesen4026b042009-03-27 01:13:37 +0000311 // If the instruction before the branch (skipping debug info) isn't a phi
312 // node, then other stuff is happening here.
Chris Lattnerc3748562007-04-02 01:35:34 +0000313 BasicBlock::iterator BBI = BI;
314 if (BBI != BB->begin()) {
315 --BBI;
Dale Johannesen4026b042009-03-27 01:13:37 +0000316 while (isa<DbgInfoIntrinsic>(BBI)) {
317 if (BBI == BB->begin())
318 break;
319 --BBI;
320 }
321 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
322 continue;
Chris Lattnerc3748562007-04-02 01:35:34 +0000323 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000324
Chris Lattnerc3748562007-04-02 01:35:34 +0000325 // Do not break infinite loops.
326 BasicBlock *DestBB = BI->getSuccessor(0);
327 if (DestBB == BB)
328 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000329
Chris Lattnerc3748562007-04-02 01:35:34 +0000330 if (!CanMergeBlocks(BB, DestBB))
331 continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000332
Chris Lattnerc3748562007-04-02 01:35:34 +0000333 EliminateMostlyEmptyBlock(BB);
334 MadeChange = true;
335 }
336 return MadeChange;
337}
338
339/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
340/// single uncond branch between them, and BB contains no other non-phi
341/// instructions.
342bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
343 const BasicBlock *DestBB) const {
344 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
345 // the successor. If there are more complex condition (e.g. preheaders),
346 // don't mess around with them.
347 BasicBlock::const_iterator BBI = BB->begin();
348 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000349 for (const User *U : PN->users()) {
350 const Instruction *UI = cast<Instruction>(U);
351 if (UI->getParent() != DestBB || !isa<PHINode>(UI))
Chris Lattnerc3748562007-04-02 01:35:34 +0000352 return false;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000353 // If User is inside DestBB block and it is a PHINode then check
354 // incoming value. If incoming value is not from BB then this is
Devang Pateld3208522007-04-25 00:37:04 +0000355 // a complex condition (e.g. preheaders) we want to avoid here.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000356 if (UI->getParent() == DestBB) {
357 if (const PHINode *UPN = dyn_cast<PHINode>(UI))
Devang Pateld3208522007-04-25 00:37:04 +0000358 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
359 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
360 if (Insn && Insn->getParent() == BB &&
361 Insn->getParent() != UPN->getIncomingBlock(I))
362 return false;
363 }
364 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000365 }
366 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000367
Chris Lattnerc3748562007-04-02 01:35:34 +0000368 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
369 // and DestBB may have conflicting incoming values for the block. If so, we
370 // can't merge the block.
371 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
372 if (!DestBBPN) return true; // no conflict.
Eric Christopherc1ea1492008-09-24 05:32:41 +0000373
Chris Lattnerc3748562007-04-02 01:35:34 +0000374 // Collect the preds of BB.
Chris Lattner8201a9b2007-11-06 22:07:40 +0000375 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerc3748562007-04-02 01:35:34 +0000376 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
377 // It is faster to get preds from a PHI than with pred_iterator.
378 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
379 BBPreds.insert(BBPN->getIncomingBlock(i));
380 } else {
381 BBPreds.insert(pred_begin(BB), pred_end(BB));
382 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000383
Chris Lattnerc3748562007-04-02 01:35:34 +0000384 // Walk the preds of DestBB.
385 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
386 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
387 if (BBPreds.count(Pred)) { // Common predecessor?
388 BBI = DestBB->begin();
389 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
390 const Value *V1 = PN->getIncomingValueForBlock(Pred);
391 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000392
Chris Lattnerc3748562007-04-02 01:35:34 +0000393 // If V2 is a phi node in BB, look up what the mapped value will be.
394 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
395 if (V2PN->getParent() == BB)
396 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000397
Chris Lattnerc3748562007-04-02 01:35:34 +0000398 // If there is a conflict, bail out.
399 if (V1 != V2) return false;
400 }
401 }
402 }
403
404 return true;
405}
406
407
408/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
409/// an unconditional branch in it.
410void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
411 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
412 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000413
David Greene74e2d492010-01-05 01:27:11 +0000414 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000415
Chris Lattnerc3748562007-04-02 01:35:34 +0000416 // If the destination block has a single pred, then this is a trivial edge,
417 // just collapse it.
Chris Lattner4059f432008-11-27 19:29:14 +0000418 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattner8a172da2008-11-28 19:54:49 +0000419 if (SinglePred != DestBB) {
420 // Remember if SinglePred was the entry block of the function. If so, we
421 // will need to move BB back to the entry position.
422 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterf8cb7582009-09-16 09:26:52 +0000423 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner4059f432008-11-27 19:29:14 +0000424
Chris Lattner8a172da2008-11-28 19:54:49 +0000425 if (isEntry && BB != &BB->getParent()->getEntryBlock())
426 BB->moveBefore(&BB->getParent()->getEntryBlock());
Nadav Rotem465834c2012-07-24 10:51:42 +0000427
David Greene74e2d492010-01-05 01:27:11 +0000428 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattner8a172da2008-11-28 19:54:49 +0000429 return;
430 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000431 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000432
Chris Lattnerc3748562007-04-02 01:35:34 +0000433 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
434 // to handle the new incoming edges it is about to have.
435 PHINode *PN;
436 for (BasicBlock::iterator BBI = DestBB->begin();
437 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
438 // Remove the incoming value for BB, and remember it.
439 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000440
Chris Lattnerc3748562007-04-02 01:35:34 +0000441 // Two options: either the InVal is a phi node defined in BB or it is some
442 // value that dominates BB.
443 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
444 if (InValPhi && InValPhi->getParent() == BB) {
445 // Add all of the input values of the input PHI as inputs of this phi.
446 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
447 PN->addIncoming(InValPhi->getIncomingValue(i),
448 InValPhi->getIncomingBlock(i));
449 } else {
450 // Otherwise, add one instance of the dominating value for each edge that
451 // we will be adding.
452 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
453 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
454 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
455 } else {
456 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
457 PN->addIncoming(InVal, *PI);
458 }
459 }
460 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000461
Chris Lattnerc3748562007-04-02 01:35:34 +0000462 // The PHIs are now updated, change everything that refers to BB to use
463 // DestBB and remove BB.
464 BB->replaceAllUsesWith(DestBB);
Devang Patel8f606d72011-03-24 15:35:25 +0000465 if (DT && !ModifiedDT) {
Cameron Zwarich84986b22011-01-08 17:01:52 +0000466 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
467 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
468 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
469 DT->changeImmediateDominator(DestBB, NewIDom);
470 DT->eraseNode(BB);
471 }
Chris Lattnerc3748562007-04-02 01:35:34 +0000472 BB->eraseFromParent();
Cameron Zwarichced753f2011-01-05 17:27:27 +0000473 ++NumBlocksElim;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000474
David Greene74e2d492010-01-05 01:27:11 +0000475 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerc3748562007-04-02 01:35:34 +0000476}
477
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000478/// SinkCast - Sink the specified cast instruction into its user blocks
479static bool SinkCast(CastInst *CI) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000480 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000481
Chris Lattnerf2836d12007-03-31 04:06:36 +0000482 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000483 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000484
Chris Lattnerf2836d12007-03-31 04:06:36 +0000485 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000486 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Chris Lattnerf2836d12007-03-31 04:06:36 +0000487 UI != E; ) {
488 Use &TheUse = UI.getUse();
489 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000490
Chris Lattnerf2836d12007-03-31 04:06:36 +0000491 // Figure out which BB this cast is used in. For PHI's this is the
492 // appropriate predecessor block.
493 BasicBlock *UserBB = User->getParent();
494 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000495 UserBB = PN->getIncomingBlock(TheUse);
Chris Lattnerf2836d12007-03-31 04:06:36 +0000496 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000497
Chris Lattnerf2836d12007-03-31 04:06:36 +0000498 // Preincrement use iterator so we don't invalidate it.
499 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000500
Chris Lattnerf2836d12007-03-31 04:06:36 +0000501 // If this user is in the same block as the cast, don't change the cast.
502 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000503
Chris Lattnerf2836d12007-03-31 04:06:36 +0000504 // If we have already inserted a cast into this block, use it.
505 CastInst *&InsertedCast = InsertedCasts[UserBB];
506
507 if (!InsertedCast) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000508 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000509 InsertedCast =
510 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerf2836d12007-03-31 04:06:36 +0000511 InsertPt);
512 MadeChange = true;
513 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000514
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000515 // Replace a use of the cast with a use of the new cast.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000516 TheUse = InsertedCast;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000517 ++NumCastUses;
Chris Lattnerf2836d12007-03-31 04:06:36 +0000518 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000519
Chris Lattnerf2836d12007-03-31 04:06:36 +0000520 // If we removed all uses, nuke the cast.
Duncan Sandsafa84da42008-01-20 16:51:46 +0000521 if (CI->use_empty()) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000522 CI->eraseFromParent();
Duncan Sandsafa84da42008-01-20 16:51:46 +0000523 MadeChange = true;
524 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000525
Chris Lattnerf2836d12007-03-31 04:06:36 +0000526 return MadeChange;
527}
528
Manuel Jacoba7c48f92014-03-13 13:36:25 +0000529/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
530/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
531/// sink it into user blocks to reduce the number of virtual
532/// registers that must be created and coalesced.
533///
534/// Return true if any changes are made.
535///
536static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
537 // If this is a noop copy,
538 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
539 EVT DstVT = TLI.getValueType(CI->getType());
540
541 // This is an fp<->int conversion?
542 if (SrcVT.isInteger() != DstVT.isInteger())
543 return false;
544
545 // If this is an extension, it will be a zero or sign extension, which
546 // isn't a noop.
547 if (SrcVT.bitsLT(DstVT)) return false;
548
549 // If these values will be promoted, find out what they will be promoted
550 // to. This helps us consider truncates on PPC as noop copies when they
551 // are.
552 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
553 TargetLowering::TypePromoteInteger)
554 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
555 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
556 TargetLowering::TypePromoteInteger)
557 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
558
559 // If, after promotion, these are the same types, this is a noop copy.
560 if (SrcVT != DstVT)
561 return false;
562
563 return SinkCast(CI);
564}
565
Eric Christopherc1ea1492008-09-24 05:32:41 +0000566/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000567/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner27406942007-08-02 16:53:43 +0000568/// a clear win except on targets with multiple condition code registers
569/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000570///
571/// Return true if any changes are made.
Chris Lattner6416a6b2008-11-24 22:44:16 +0000572static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000573 BasicBlock *DefBB = CI->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000574
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000575 /// InsertedCmp - Only insert a cmp in each block once.
576 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000577
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000578 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000579 for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000580 UI != E; ) {
581 Use &TheUse = UI.getUse();
582 Instruction *User = cast<Instruction>(*UI);
Eric Christopherc1ea1492008-09-24 05:32:41 +0000583
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000584 // Preincrement use iterator so we don't invalidate it.
585 ++UI;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000586
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000587 // Don't bother for PHI nodes.
588 if (isa<PHINode>(User))
589 continue;
590
591 // Figure out which BB this cmp is used in.
592 BasicBlock *UserBB = User->getParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000593
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000594 // If this user is in the same block as the cmp, don't change the cmp.
595 if (UserBB == DefBB) continue;
Eric Christopherc1ea1492008-09-24 05:32:41 +0000596
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000597 // If we have already inserted a cmp into this block, use it.
598 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
599
600 if (!InsertedCmp) {
Bill Wendling8ddfc092011-08-16 20:45:24 +0000601 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000602 InsertedCmp =
Dan Gohmanad1f0a12009-08-25 23:17:54 +0000603 CmpInst::Create(CI->getOpcode(),
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000604 CI->getPredicate(), CI->getOperand(0),
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000605 CI->getOperand(1), "", InsertPt);
606 MadeChange = true;
607 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000608
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000609 // Replace a use of the cmp with a use of the new cmp.
610 TheUse = InsertedCmp;
Cameron Zwarichced753f2011-01-05 17:27:27 +0000611 ++NumCmpUses;
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000612 }
Eric Christopherc1ea1492008-09-24 05:32:41 +0000613
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000614 // If we removed all uses, nuke the cmp.
615 if (CI->use_empty())
616 CI->eraseFromParent();
Eric Christopherc1ea1492008-09-24 05:32:41 +0000617
Dale Johannesenedfec0b2007-06-12 16:50:17 +0000618 return MadeChange;
619}
620
Yi Jiangd069f632014-04-21 19:34:27 +0000621/// isExtractBitsCandidateUse - Check if the candidates could
622/// be combined with shift instruction, which includes:
623/// 1. Truncate instruction
624/// 2. And instruction and the imm is a mask of the low bits:
625/// imm & (imm+1) == 0
Benjamin Kramer322053c2014-04-27 14:54:59 +0000626static bool isExtractBitsCandidateUse(Instruction *User) {
Yi Jiangd069f632014-04-21 19:34:27 +0000627 if (!isa<TruncInst>(User)) {
628 if (User->getOpcode() != Instruction::And ||
629 !isa<ConstantInt>(User->getOperand(1)))
630 return false;
631
Quentin Colombetd4f44692014-04-22 01:20:34 +0000632 const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
Yi Jiangd069f632014-04-21 19:34:27 +0000633
Quentin Colombetd4f44692014-04-22 01:20:34 +0000634 if ((Cimm & (Cimm + 1)).getBoolValue())
Yi Jiangd069f632014-04-21 19:34:27 +0000635 return false;
636 }
637 return true;
638}
639
640/// SinkShiftAndTruncate - sink both shift and truncate instruction
641/// to the use of truncate's BB.
Benjamin Kramer322053c2014-04-27 14:54:59 +0000642static bool
Yi Jiangd069f632014-04-21 19:34:27 +0000643SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
644 DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
645 const TargetLowering &TLI) {
646 BasicBlock *UserBB = User->getParent();
647 DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
648 TruncInst *TruncI = dyn_cast<TruncInst>(User);
649 bool MadeChange = false;
650
651 for (Value::user_iterator TruncUI = TruncI->user_begin(),
652 TruncE = TruncI->user_end();
653 TruncUI != TruncE;) {
654
655 Use &TruncTheUse = TruncUI.getUse();
656 Instruction *TruncUser = cast<Instruction>(*TruncUI);
657 // Preincrement use iterator so we don't invalidate it.
658
659 ++TruncUI;
660
661 int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
662 if (!ISDOpcode)
663 continue;
664
665 // If the use is actually a legal node, there will not be an implicit
666 // truncate.
667 if (TLI.isOperationLegalOrCustom(ISDOpcode,
668 EVT::getEVT(TruncUser->getType())))
669 continue;
670
671 // Don't bother for PHI nodes.
672 if (isa<PHINode>(TruncUser))
673 continue;
674
675 BasicBlock *TruncUserBB = TruncUser->getParent();
676
677 if (UserBB == TruncUserBB)
678 continue;
679
680 BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
681 CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
682
683 if (!InsertedShift && !InsertedTrunc) {
684 BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
685 // Sink the shift
686 if (ShiftI->getOpcode() == Instruction::AShr)
687 InsertedShift =
688 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
689 else
690 InsertedShift =
691 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
692
693 // Sink the trunc
694 BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
695 TruncInsertPt++;
696
697 InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
698 TruncI->getType(), "", TruncInsertPt);
699
700 MadeChange = true;
701
702 TruncTheUse = InsertedTrunc;
703 }
704 }
705 return MadeChange;
706}
707
708/// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
709/// the uses could potentially be combined with this shift instruction and
710/// generate BitExtract instruction. It will only be applied if the architecture
711/// supports BitExtract instruction. Here is an example:
712/// BB1:
713/// %x.extract.shift = lshr i64 %arg1, 32
714/// BB2:
715/// %x.extract.trunc = trunc i64 %x.extract.shift to i16
716/// ==>
717///
718/// BB2:
719/// %x.extract.shift.1 = lshr i64 %arg1, 32
720/// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
721///
722/// CodeGen will recoginze the pattern in BB2 and generate BitExtract
723/// instruction.
724/// Return true if any changes are made.
725static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
726 const TargetLowering &TLI) {
727 BasicBlock *DefBB = ShiftI->getParent();
728
729 /// Only insert instructions in each block once.
730 DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
731
732 bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
733
734 bool MadeChange = false;
735 for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
736 UI != E;) {
737 Use &TheUse = UI.getUse();
738 Instruction *User = cast<Instruction>(*UI);
739 // Preincrement use iterator so we don't invalidate it.
740 ++UI;
741
742 // Don't bother for PHI nodes.
743 if (isa<PHINode>(User))
744 continue;
745
746 if (!isExtractBitsCandidateUse(User))
747 continue;
748
749 BasicBlock *UserBB = User->getParent();
750
751 if (UserBB == DefBB) {
752 // If the shift and truncate instruction are in the same BB. The use of
753 // the truncate(TruncUse) may still introduce another truncate if not
754 // legal. In this case, we would like to sink both shift and truncate
755 // instruction to the BB of TruncUse.
756 // for example:
757 // BB1:
758 // i64 shift.result = lshr i64 opnd, imm
759 // trunc.result = trunc shift.result to i16
760 //
761 // BB2:
762 // ----> We will have an implicit truncate here if the architecture does
763 // not have i16 compare.
764 // cmp i16 trunc.result, opnd2
765 //
766 if (isa<TruncInst>(User) && shiftIsLegal
767 // If the type of the truncate is legal, no trucate will be
768 // introduced in other basic blocks.
769 && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
770 MadeChange =
771 SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
772
773 continue;
774 }
775 // If we have already inserted a shift into this block, use it.
776 BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
777
778 if (!InsertedShift) {
779 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
780
781 if (ShiftI->getOpcode() == Instruction::AShr)
782 InsertedShift =
783 BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
784 else
785 InsertedShift =
786 BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
787
788 MadeChange = true;
789 }
790
791 // Replace a use of the shift with a use of the new shift.
792 TheUse = InsertedShift;
793 }
794
795 // If we removed all uses, nuke the shift.
796 if (ShiftI->use_empty())
797 ShiftI->eraseFromParent();
798
799 return MadeChange;
800}
801
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000802namespace {
803class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
804protected:
Craig Topper4584cd52014-03-07 09:26:03 +0000805 void replaceCall(Value *With) override {
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000806 CI->replaceAllUsesWith(With);
807 CI->eraseFromParent();
808 }
Craig Topper4584cd52014-03-07 09:26:03 +0000809 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
Gabor Greif6d673952010-07-16 09:38:02 +0000810 if (ConstantInt *SizeCI =
811 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
812 return SizeCI->isAllOnesValue();
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000813 return false;
814 }
815};
816} // end anonymous namespace
817
Eric Christopher4b7948e2010-03-11 02:41:03 +0000818bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Chris Lattner7a277142011-01-15 07:14:54 +0000819 BasicBlock *BB = CI->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +0000820
Chris Lattner7a277142011-01-15 07:14:54 +0000821 // Lower inline assembly if we can.
822 // If we found an inline asm expession, and if the target knows how to
823 // lower it to normal LLVM code, do so now.
824 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
825 if (TLI->ExpandInlineAsm(CI)) {
826 // Avoid invalidating the iterator.
827 CurInstIterator = BB->begin();
828 // Avoid processing instructions out of order, which could cause
829 // reuse before a value is defined.
830 SunkAddrs.clear();
831 return true;
832 }
833 // Sink address computing for memory operands into the block.
834 if (OptimizeInlineAsmInst(CI))
835 return true;
836 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000837
Eric Christopher4b7948e2010-03-11 02:41:03 +0000838 // Lower all uses of llvm.objectsize.*
839 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
840 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greif4a39b842010-06-24 00:44:01 +0000841 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Chris Lattner229907c2011-07-18 04:54:35 +0000842 Type *ReturnTy = CI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +0000843 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
844
Chris Lattner1b93be52011-01-15 07:25:29 +0000845 // Substituting this can cause recursive simplifications, which can
846 // invalidate our iterator. Use a WeakVH to hold onto it in case this
847 // happens.
848 WeakVH IterHandle(CurInstIterator);
Nadav Rotem465834c2012-07-24 10:51:42 +0000849
Craig Topperc0196b12014-04-14 00:51:57 +0000850 replaceAndRecursivelySimplify(CI, RetVal,
851 TLI ? TLI->getDataLayout() : nullptr,
852 TLInfo, ModifiedDT ? nullptr : DT);
Chris Lattner1b93be52011-01-15 07:25:29 +0000853
854 // If the iterator instruction was recursively deleted, start over at the
855 // start of the block.
Chris Lattner86d56c62011-01-18 20:53:04 +0000856 if (IterHandle != CurInstIterator) {
Chris Lattner1b93be52011-01-15 07:25:29 +0000857 CurInstIterator = BB->begin();
Chris Lattner86d56c62011-01-18 20:53:04 +0000858 SunkAddrs.clear();
859 }
Eric Christopher4b7948e2010-03-11 02:41:03 +0000860 return true;
861 }
862
Pete Cooper615fd892012-03-13 20:59:56 +0000863 if (II && TLI) {
864 SmallVector<Value*, 2> PtrOps;
865 Type *AccessTy;
866 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
867 while (!PtrOps.empty())
868 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
869 return true;
870 }
871
Eric Christopher4b7948e2010-03-11 02:41:03 +0000872 // From here on out we're working with named functions.
Craig Topperc0196b12014-04-14 00:51:57 +0000873 if (!CI->getCalledFunction()) return false;
Devang Patel0da52502011-05-26 21:51:06 +0000874
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000875 // We'll need DataLayout from here on out.
Craig Topperc0196b12014-04-14 00:51:57 +0000876 const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
Eric Christopher4b7948e2010-03-11 02:41:03 +0000877 if (!TD) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +0000878
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000879 // Lower all default uses of _chk calls. This is very similar
880 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher4b7948e2010-03-11 02:41:03 +0000881 // that have the default "don't know" as the objectsize. Anything else
882 // should be left alone.
Benjamin Kramer7b88a492010-03-12 09:27:41 +0000883 CodeGenPrepareFortifiedLibCalls Simplifier;
Nuno Lopes89702e92012-07-25 16:46:31 +0000884 return Simplifier.fold(CI, TD, TLInfo);
Eric Christopher4b7948e2010-03-11 02:41:03 +0000885}
Chris Lattner1b93be52011-01-15 07:25:29 +0000886
Evan Cheng0663f232011-03-21 01:19:09 +0000887/// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
888/// instructions to the predecessor to enable tail call optimizations. The
889/// case it is currently looking for is:
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000890/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000891/// bb0:
892/// %tmp0 = tail call i32 @f0()
893/// br label %return
894/// bb1:
895/// %tmp1 = tail call i32 @f1()
896/// br label %return
897/// bb2:
898/// %tmp2 = tail call i32 @f2()
899/// br label %return
900/// return:
901/// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
902/// ret i32 %retval
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000903/// @endcode
Evan Cheng0663f232011-03-21 01:19:09 +0000904///
905/// =>
906///
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000907/// @code
Evan Cheng0663f232011-03-21 01:19:09 +0000908/// bb0:
909/// %tmp0 = tail call i32 @f0()
910/// ret i32 %tmp0
911/// bb1:
912/// %tmp1 = tail call i32 @f1()
913/// ret i32 %tmp1
914/// bb2:
915/// %tmp2 = tail call i32 @f2()
916/// ret i32 %tmp2
Dmitri Gribenko2bc1d482012-09-13 12:34:29 +0000917/// @endcode
Benjamin Kramer455fa352012-11-23 19:17:06 +0000918bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
Cameron Zwarich47e71752011-03-24 04:51:51 +0000919 if (!TLI)
920 return false;
921
Benjamin Kramer455fa352012-11-23 19:17:06 +0000922 ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
923 if (!RI)
924 return false;
925
Craig Topperc0196b12014-04-14 00:51:57 +0000926 PHINode *PN = nullptr;
927 BitCastInst *BCI = nullptr;
Evan Cheng0663f232011-03-21 01:19:09 +0000928 Value *V = RI->getReturnValue();
Evan Cheng249716e2012-07-27 21:21:26 +0000929 if (V) {
930 BCI = dyn_cast<BitCastInst>(V);
931 if (BCI)
932 V = BCI->getOperand(0);
933
934 PN = dyn_cast<PHINode>(V);
935 if (!PN)
936 return false;
937 }
Evan Cheng0663f232011-03-21 01:19:09 +0000938
Cameron Zwarich4649f172011-03-24 04:52:10 +0000939 if (PN && PN->getParent() != BB)
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000940 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000941
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000942 // It's not safe to eliminate the sign / zero extension of the return value.
943 // See llvm::isInTailCallPosition().
944 const Function *F = BB->getParent();
Bill Wendling658d24d2013-01-18 21:53:16 +0000945 AttributeSet CallerAttrs = F->getAttributes();
946 if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
947 CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000948 return false;
Evan Cheng0663f232011-03-21 01:19:09 +0000949
Cameron Zwarich4649f172011-03-24 04:52:10 +0000950 // Make sure there are no instructions between the PHI and return, or that the
951 // return is the first instruction in the block.
952 if (PN) {
953 BasicBlock::iterator BI = BB->begin();
954 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
Evan Cheng249716e2012-07-27 21:21:26 +0000955 if (&*BI == BCI)
956 // Also skip over the bitcast.
957 ++BI;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000958 if (&*BI != RI)
959 return false;
960 } else {
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000961 BasicBlock::iterator BI = BB->begin();
962 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
963 if (&*BI != RI)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000964 return false;
965 }
Evan Cheng0663f232011-03-21 01:19:09 +0000966
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000967 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
968 /// call.
969 SmallVector<CallInst*, 4> TailCalls;
Cameron Zwarich4649f172011-03-24 04:52:10 +0000970 if (PN) {
971 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
972 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
973 // Make sure the phi value is indeed produced by the tail call.
974 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
975 TLI->mayBeEmittedAsTailCall(CI))
976 TailCalls.push_back(CI);
977 }
978 } else {
979 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
980 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
981 if (!VisitedBBs.insert(*PI))
982 continue;
983
984 BasicBlock::InstListType &InstList = (*PI)->getInstList();
985 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
986 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000987 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
988 if (RI == RE)
Cameron Zwarich4649f172011-03-24 04:52:10 +0000989 continue;
Cameron Zwarich74157ab2011-03-24 16:34:59 +0000990
Cameron Zwarich4649f172011-03-24 04:52:10 +0000991 CallInst *CI = dyn_cast<CallInst>(&*RI);
Cameron Zwarich2edfe772011-03-24 15:54:11 +0000992 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
Cameron Zwarich4649f172011-03-24 04:52:10 +0000993 TailCalls.push_back(CI);
994 }
Evan Cheng0663f232011-03-21 01:19:09 +0000995 }
996
Cameron Zwarich0e331c02011-03-24 04:52:07 +0000997 bool Changed = false;
998 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
999 CallInst *CI = TailCalls[i];
1000 CallSite CS(CI);
1001
1002 // Conservatively require the attributes of the call to match those of the
1003 // return. Ignore noalias because it doesn't affect the call sequence.
Bill Wendling658d24d2013-01-18 21:53:16 +00001004 AttributeSet CalleeAttrs = CS.getAttributes();
1005 if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001006 removeAttribute(Attribute::NoAlias) !=
Bill Wendling658d24d2013-01-18 21:53:16 +00001007 AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
Bill Wendling3d7b0b82012-12-19 07:18:57 +00001008 removeAttribute(Attribute::NoAlias))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001009 continue;
1010
1011 // Make sure the call instruction is followed by an unconditional branch to
1012 // the return block.
1013 BasicBlock *CallBB = CI->getParent();
1014 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1015 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1016 continue;
1017
1018 // Duplicate the return into CallBB.
1019 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
Devang Patel8f606d72011-03-24 15:35:25 +00001020 ModifiedDT = Changed = true;
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001021 ++NumRetsDup;
1022 }
1023
1024 // If we eliminated all predecessors of the block, delete the block now.
Evan Cheng64a223a2012-09-28 23:58:57 +00001025 if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
Cameron Zwarich0e331c02011-03-24 04:52:07 +00001026 BB->eraseFromParent();
1027
1028 return Changed;
Evan Cheng0663f232011-03-21 01:19:09 +00001029}
1030
Chris Lattner728f9022008-11-25 07:09:13 +00001031//===----------------------------------------------------------------------===//
Chris Lattner728f9022008-11-25 07:09:13 +00001032// Memory Optimization
1033//===----------------------------------------------------------------------===//
1034
Chandler Carruthc8925912013-01-05 02:09:22 +00001035namespace {
1036
1037/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1038/// which holds actual Value*'s for register values.
Chandler Carruth95f83e02013-01-07 15:14:13 +00001039struct ExtAddrMode : public TargetLowering::AddrMode {
Chandler Carruthc8925912013-01-05 02:09:22 +00001040 Value *BaseReg;
1041 Value *ScaledReg;
Craig Topperc0196b12014-04-14 00:51:57 +00001042 ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
Chandler Carruthc8925912013-01-05 02:09:22 +00001043 void print(raw_ostream &OS) const;
1044 void dump() const;
Stephen Lin837bba12013-07-15 17:55:02 +00001045
Chandler Carruthc8925912013-01-05 02:09:22 +00001046 bool operator==(const ExtAddrMode& O) const {
1047 return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1048 (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1049 (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1050 }
1051};
1052
Eli Friedmanc1f1f852013-09-10 23:09:24 +00001053#ifndef NDEBUG
1054static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1055 AM.print(OS);
1056 return OS;
1057}
1058#endif
1059
Chandler Carruthc8925912013-01-05 02:09:22 +00001060void ExtAddrMode::print(raw_ostream &OS) const {
1061 bool NeedPlus = false;
1062 OS << "[";
1063 if (BaseGV) {
1064 OS << (NeedPlus ? " + " : "")
1065 << "GV:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001066 BaseGV->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001067 NeedPlus = true;
1068 }
1069
Richard Trieuc0f91212014-05-30 03:15:17 +00001070 if (BaseOffs) {
1071 OS << (NeedPlus ? " + " : "")
1072 << BaseOffs;
1073 NeedPlus = true;
1074 }
Chandler Carruthc8925912013-01-05 02:09:22 +00001075
1076 if (BaseReg) {
1077 OS << (NeedPlus ? " + " : "")
1078 << "Base:";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001079 BaseReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001080 NeedPlus = true;
1081 }
1082 if (Scale) {
1083 OS << (NeedPlus ? " + " : "")
1084 << Scale << "*";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00001085 ScaledReg->printAsOperand(OS, /*PrintType=*/false);
Chandler Carruthc8925912013-01-05 02:09:22 +00001086 }
1087
1088 OS << ']';
1089}
1090
1091#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1092void ExtAddrMode::dump() const {
1093 print(dbgs());
1094 dbgs() << '\n';
1095}
1096#endif
1097
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001098/// \brief This class provides transaction based operation on the IR.
1099/// Every change made through this class is recorded in the internal state and
1100/// can be undone (rollback) until commit is called.
1101class TypePromotionTransaction {
1102
1103 /// \brief This represents the common interface of the individual transaction.
1104 /// Each class implements the logic for doing one specific modification on
1105 /// the IR via the TypePromotionTransaction.
1106 class TypePromotionAction {
1107 protected:
1108 /// The Instruction modified.
1109 Instruction *Inst;
1110
1111 public:
1112 /// \brief Constructor of the action.
1113 /// The constructor performs the related action on the IR.
1114 TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1115
1116 virtual ~TypePromotionAction() {}
1117
1118 /// \brief Undo the modification done by this action.
1119 /// When this method is called, the IR must be in the same state as it was
1120 /// before this action was applied.
1121 /// \pre Undoing the action works if and only if the IR is in the exact same
1122 /// state as it was directly after this action was applied.
1123 virtual void undo() = 0;
1124
1125 /// \brief Advocate every change made by this action.
1126 /// When the results on the IR of the action are to be kept, it is important
1127 /// to call this function, otherwise hidden information may be kept forever.
1128 virtual void commit() {
1129 // Nothing to be done, this action is not doing anything.
1130 }
1131 };
1132
1133 /// \brief Utility to remember the position of an instruction.
1134 class InsertionHandler {
1135 /// Position of an instruction.
1136 /// Either an instruction:
1137 /// - Is the first in a basic block: BB is used.
1138 /// - Has a previous instructon: PrevInst is used.
1139 union {
1140 Instruction *PrevInst;
1141 BasicBlock *BB;
1142 } Point;
1143 /// Remember whether or not the instruction had a previous instruction.
1144 bool HasPrevInstruction;
1145
1146 public:
1147 /// \brief Record the position of \p Inst.
1148 InsertionHandler(Instruction *Inst) {
1149 BasicBlock::iterator It = Inst;
1150 HasPrevInstruction = (It != (Inst->getParent()->begin()));
1151 if (HasPrevInstruction)
1152 Point.PrevInst = --It;
1153 else
1154 Point.BB = Inst->getParent();
1155 }
1156
1157 /// \brief Insert \p Inst at the recorded position.
1158 void insert(Instruction *Inst) {
1159 if (HasPrevInstruction) {
1160 if (Inst->getParent())
1161 Inst->removeFromParent();
1162 Inst->insertAfter(Point.PrevInst);
1163 } else {
1164 Instruction *Position = Point.BB->getFirstInsertionPt();
1165 if (Inst->getParent())
1166 Inst->moveBefore(Position);
1167 else
1168 Inst->insertBefore(Position);
1169 }
1170 }
1171 };
1172
1173 /// \brief Move an instruction before another.
1174 class InstructionMoveBefore : public TypePromotionAction {
1175 /// Original position of the instruction.
1176 InsertionHandler Position;
1177
1178 public:
1179 /// \brief Move \p Inst before \p Before.
1180 InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1181 : TypePromotionAction(Inst), Position(Inst) {
1182 DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1183 Inst->moveBefore(Before);
1184 }
1185
1186 /// \brief Move the instruction back to its original position.
Craig Topper4584cd52014-03-07 09:26:03 +00001187 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001188 DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1189 Position.insert(Inst);
1190 }
1191 };
1192
1193 /// \brief Set the operand of an instruction with a new value.
1194 class OperandSetter : public TypePromotionAction {
1195 /// Original operand of the instruction.
1196 Value *Origin;
1197 /// Index of the modified instruction.
1198 unsigned Idx;
1199
1200 public:
1201 /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1202 OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1203 : TypePromotionAction(Inst), Idx(Idx) {
1204 DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1205 << "for:" << *Inst << "\n"
1206 << "with:" << *NewVal << "\n");
1207 Origin = Inst->getOperand(Idx);
1208 Inst->setOperand(Idx, NewVal);
1209 }
1210
1211 /// \brief Restore the original value of the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001212 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001213 DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1214 << "for: " << *Inst << "\n"
1215 << "with: " << *Origin << "\n");
1216 Inst->setOperand(Idx, Origin);
1217 }
1218 };
1219
1220 /// \brief Hide the operands of an instruction.
1221 /// Do as if this instruction was not using any of its operands.
1222 class OperandsHider : public TypePromotionAction {
1223 /// The list of original operands.
1224 SmallVector<Value *, 4> OriginalValues;
1225
1226 public:
1227 /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1228 OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1229 DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1230 unsigned NumOpnds = Inst->getNumOperands();
1231 OriginalValues.reserve(NumOpnds);
1232 for (unsigned It = 0; It < NumOpnds; ++It) {
1233 // Save the current operand.
1234 Value *Val = Inst->getOperand(It);
1235 OriginalValues.push_back(Val);
1236 // Set a dummy one.
1237 // We could use OperandSetter here, but that would implied an overhead
1238 // that we are not willing to pay.
1239 Inst->setOperand(It, UndefValue::get(Val->getType()));
1240 }
1241 }
1242
1243 /// \brief Restore the original list of uses.
Craig Topper4584cd52014-03-07 09:26:03 +00001244 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001245 DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1246 for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1247 Inst->setOperand(It, OriginalValues[It]);
1248 }
1249 };
1250
1251 /// \brief Build a truncate instruction.
1252 class TruncBuilder : public TypePromotionAction {
1253 public:
1254 /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1255 /// result.
1256 /// trunc Opnd to Ty.
1257 TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1258 IRBuilder<> Builder(Opnd);
1259 Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1260 DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1261 }
1262
1263 /// \brief Get the built instruction.
1264 Instruction *getBuiltInstruction() { return Inst; }
1265
1266 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001267 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001268 DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1269 Inst->eraseFromParent();
1270 }
1271 };
1272
1273 /// \brief Build a sign extension instruction.
1274 class SExtBuilder : public TypePromotionAction {
1275 public:
1276 /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1277 /// result.
1278 /// sext Opnd to Ty.
1279 SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1280 : TypePromotionAction(Inst) {
1281 IRBuilder<> Builder(InsertPt);
1282 Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1283 DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1284 }
1285
1286 /// \brief Get the built instruction.
1287 Instruction *getBuiltInstruction() { return Inst; }
1288
1289 /// \brief Remove the built instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001290 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001291 DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1292 Inst->eraseFromParent();
1293 }
1294 };
1295
1296 /// \brief Mutate an instruction to another type.
1297 class TypeMutator : public TypePromotionAction {
1298 /// Record the original type.
1299 Type *OrigTy;
1300
1301 public:
1302 /// \brief Mutate the type of \p Inst into \p NewTy.
1303 TypeMutator(Instruction *Inst, Type *NewTy)
1304 : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1305 DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1306 << "\n");
1307 Inst->mutateType(NewTy);
1308 }
1309
1310 /// \brief Mutate the instruction back to its original type.
Craig Topper4584cd52014-03-07 09:26:03 +00001311 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001312 DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1313 << "\n");
1314 Inst->mutateType(OrigTy);
1315 }
1316 };
1317
1318 /// \brief Replace the uses of an instruction by another instruction.
1319 class UsesReplacer : public TypePromotionAction {
1320 /// Helper structure to keep track of the replaced uses.
1321 struct InstructionAndIdx {
1322 /// The instruction using the instruction.
1323 Instruction *Inst;
1324 /// The index where this instruction is used for Inst.
1325 unsigned Idx;
1326 InstructionAndIdx(Instruction *Inst, unsigned Idx)
1327 : Inst(Inst), Idx(Idx) {}
1328 };
1329
1330 /// Keep track of the original uses (pair Instruction, Index).
1331 SmallVector<InstructionAndIdx, 4> OriginalUses;
1332 typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1333
1334 public:
1335 /// \brief Replace all the use of \p Inst by \p New.
1336 UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1337 DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1338 << "\n");
1339 // Record the original uses.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001340 for (Use &U : Inst->uses()) {
1341 Instruction *UserI = cast<Instruction>(U.getUser());
1342 OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001343 }
1344 // Now, we can replace the uses.
1345 Inst->replaceAllUsesWith(New);
1346 }
1347
1348 /// \brief Reassign the original uses of Inst to Inst.
Craig Topper4584cd52014-03-07 09:26:03 +00001349 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001350 DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1351 for (use_iterator UseIt = OriginalUses.begin(),
1352 EndIt = OriginalUses.end();
1353 UseIt != EndIt; ++UseIt) {
1354 UseIt->Inst->setOperand(UseIt->Idx, Inst);
1355 }
1356 }
1357 };
1358
1359 /// \brief Remove an instruction from the IR.
1360 class InstructionRemover : public TypePromotionAction {
1361 /// Original position of the instruction.
1362 InsertionHandler Inserter;
1363 /// Helper structure to hide all the link to the instruction. In other
1364 /// words, this helps to do as if the instruction was removed.
1365 OperandsHider Hider;
1366 /// Keep track of the uses replaced, if any.
1367 UsesReplacer *Replacer;
1368
1369 public:
1370 /// \brief Remove all reference of \p Inst and optinally replace all its
1371 /// uses with New.
Craig Topperc0196b12014-04-14 00:51:57 +00001372 /// \pre If !Inst->use_empty(), then New != nullptr
1373 InstructionRemover(Instruction *Inst, Value *New = nullptr)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001374 : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
Craig Topperc0196b12014-04-14 00:51:57 +00001375 Replacer(nullptr) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001376 if (New)
1377 Replacer = new UsesReplacer(Inst, New);
1378 DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1379 Inst->removeFromParent();
1380 }
1381
1382 ~InstructionRemover() { delete Replacer; }
1383
1384 /// \brief Really remove the instruction.
Craig Topper4584cd52014-03-07 09:26:03 +00001385 void commit() override { delete Inst; }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001386
1387 /// \brief Resurrect the instruction and reassign it to the proper uses if
1388 /// new value was provided when build this action.
Craig Topper4584cd52014-03-07 09:26:03 +00001389 void undo() override {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001390 DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1391 Inserter.insert(Inst);
1392 if (Replacer)
1393 Replacer->undo();
1394 Hider.undo();
1395 }
1396 };
1397
1398public:
1399 /// Restoration point.
1400 /// The restoration point is a pointer to an action instead of an iterator
1401 /// because the iterator may be invalidated but not the pointer.
1402 typedef const TypePromotionAction *ConstRestorationPt;
1403 /// Advocate every changes made in that transaction.
1404 void commit();
1405 /// Undo all the changes made after the given point.
1406 void rollback(ConstRestorationPt Point);
1407 /// Get the current restoration point.
1408 ConstRestorationPt getRestorationPoint() const;
1409
1410 /// \name API for IR modification with state keeping to support rollback.
1411 /// @{
1412 /// Same as Instruction::setOperand.
1413 void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1414 /// Same as Instruction::eraseFromParent.
Craig Topperc0196b12014-04-14 00:51:57 +00001415 void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001416 /// Same as Value::replaceAllUsesWith.
1417 void replaceAllUsesWith(Instruction *Inst, Value *New);
1418 /// Same as Value::mutateType.
1419 void mutateType(Instruction *Inst, Type *NewTy);
1420 /// Same as IRBuilder::createTrunc.
1421 Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1422 /// Same as IRBuilder::createSExt.
1423 Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1424 /// Same as Instruction::moveBefore.
1425 void moveBefore(Instruction *Inst, Instruction *Before);
1426 /// @}
1427
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001428private:
1429 /// The ordered list of actions made so far.
David Blaikie7620b312014-04-15 06:17:44 +00001430 SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1431 typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001432};
1433
1434void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1435 Value *NewVal) {
1436 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001437 make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001438}
1439
1440void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1441 Value *NewVal) {
1442 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001443 make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001444}
1445
1446void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1447 Value *New) {
David Blaikie7620b312014-04-15 06:17:44 +00001448 Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001449}
1450
1451void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
David Blaikie7620b312014-04-15 06:17:44 +00001452 Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001453}
1454
1455Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1456 Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001457 std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1458 Instruction *I = Ptr->getBuiltInstruction();
1459 Actions.push_back(std::move(Ptr));
1460 return I;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001461}
1462
1463Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1464 Value *Opnd, Type *Ty) {
David Blaikie7620b312014-04-15 06:17:44 +00001465 std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1466 Instruction *I = Ptr->getBuiltInstruction();
1467 Actions.push_back(std::move(Ptr));
1468 return I;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001469}
1470
1471void TypePromotionTransaction::moveBefore(Instruction *Inst,
1472 Instruction *Before) {
1473 Actions.push_back(
David Blaikie7620b312014-04-15 06:17:44 +00001474 make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001475}
1476
1477TypePromotionTransaction::ConstRestorationPt
1478TypePromotionTransaction::getRestorationPoint() const {
David Blaikie7620b312014-04-15 06:17:44 +00001479 return !Actions.empty() ? Actions.back().get() : nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001480}
1481
1482void TypePromotionTransaction::commit() {
1483 for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
David Blaikie7620b312014-04-15 06:17:44 +00001484 ++It)
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001485 (*It)->commit();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001486 Actions.clear();
1487}
1488
1489void TypePromotionTransaction::rollback(
1490 TypePromotionTransaction::ConstRestorationPt Point) {
David Blaikie7620b312014-04-15 06:17:44 +00001491 while (!Actions.empty() && Point != Actions.back().get()) {
1492 std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001493 Curr->undo();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001494 }
1495}
1496
Chandler Carruthc8925912013-01-05 02:09:22 +00001497/// \brief A helper class for matching addressing modes.
1498///
1499/// This encapsulates the logic for matching the target-legal addressing modes.
1500class AddressingModeMatcher {
1501 SmallVectorImpl<Instruction*> &AddrModeInsts;
1502 const TargetLowering &TLI;
1503
1504 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1505 /// the memory instruction that we're computing this address for.
1506 Type *AccessTy;
1507 Instruction *MemoryInst;
Stephen Lin837bba12013-07-15 17:55:02 +00001508
Chandler Carruthc8925912013-01-05 02:09:22 +00001509 /// AddrMode - This is the addressing mode that we're building up. This is
1510 /// part of the return value of this addressing mode matching stuff.
1511 ExtAddrMode &AddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001512
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001513 /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1514 const SetOfInstrs &InsertedTruncs;
1515 /// A map from the instructions to their type before promotion.
1516 InstrToOrigTy &PromotedInsts;
1517 /// The ongoing transaction where every action should be registered.
1518 TypePromotionTransaction &TPT;
1519
Chandler Carruthc8925912013-01-05 02:09:22 +00001520 /// IgnoreProfitability - This is set to true when we should not do
1521 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
1522 /// always returns true.
1523 bool IgnoreProfitability;
Stephen Lin837bba12013-07-15 17:55:02 +00001524
Chandler Carruthc8925912013-01-05 02:09:22 +00001525 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1526 const TargetLowering &T, Type *AT,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001527 Instruction *MI, ExtAddrMode &AM,
1528 const SetOfInstrs &InsertedTruncs,
1529 InstrToOrigTy &PromotedInsts,
1530 TypePromotionTransaction &TPT)
1531 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1532 InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001533 IgnoreProfitability = false;
1534 }
1535public:
Stephen Lin837bba12013-07-15 17:55:02 +00001536
Chandler Carruthc8925912013-01-05 02:09:22 +00001537 /// Match - Find the maximal addressing mode that a load/store of V can fold,
1538 /// give an access type of AccessTy. This returns a list of involved
1539 /// instructions in AddrModeInsts.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001540 /// \p InsertedTruncs The truncate instruction inserted by other
1541 /// CodeGenPrepare
1542 /// optimizations.
1543 /// \p PromotedInsts maps the instructions to their type before promotion.
1544 /// \p The ongoing transaction where every action should be registered.
Chandler Carruthc8925912013-01-05 02:09:22 +00001545 static ExtAddrMode Match(Value *V, Type *AccessTy,
1546 Instruction *MemoryInst,
1547 SmallVectorImpl<Instruction*> &AddrModeInsts,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001548 const TargetLowering &TLI,
1549 const SetOfInstrs &InsertedTruncs,
1550 InstrToOrigTy &PromotedInsts,
1551 TypePromotionTransaction &TPT) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001552 ExtAddrMode Result;
1553
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001554 bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1555 MemoryInst, Result, InsertedTruncs,
1556 PromotedInsts, TPT).MatchAddr(V, 0);
Chandler Carruthc8925912013-01-05 02:09:22 +00001557 (void)Success; assert(Success && "Couldn't select *anything*?");
1558 return Result;
1559 }
1560private:
1561 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1562 bool MatchAddr(Value *V, unsigned Depth);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001563 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
Craig Topperc0196b12014-04-14 00:51:57 +00001564 bool *MovedAway = nullptr);
Chandler Carruthc8925912013-01-05 02:09:22 +00001565 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1566 ExtAddrMode &AMBefore,
1567 ExtAddrMode &AMAfter);
1568 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
Quentin Colombet867c5502014-02-14 22:23:22 +00001569 bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1570 Value *PromotedOperand) const;
Chandler Carruthc8925912013-01-05 02:09:22 +00001571};
1572
1573/// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1574/// Return true and update AddrMode if this addr mode is legal for the target,
1575/// false if not.
1576bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1577 unsigned Depth) {
1578 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1579 // mode. Just process that directly.
1580 if (Scale == 1)
1581 return MatchAddr(ScaleReg, Depth);
Stephen Lin837bba12013-07-15 17:55:02 +00001582
Chandler Carruthc8925912013-01-05 02:09:22 +00001583 // If the scale is 0, it takes nothing to add this.
1584 if (Scale == 0)
1585 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00001586
Chandler Carruthc8925912013-01-05 02:09:22 +00001587 // If we already have a scale of this value, we can add to it, otherwise, we
1588 // need an available scale field.
1589 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1590 return false;
1591
1592 ExtAddrMode TestAddrMode = AddrMode;
1593
1594 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
1595 // [A+B + A*7] -> [B+A*8].
1596 TestAddrMode.Scale += Scale;
1597 TestAddrMode.ScaledReg = ScaleReg;
1598
1599 // If the new address isn't legal, bail out.
1600 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1601 return false;
1602
1603 // It was legal, so commit it.
1604 AddrMode = TestAddrMode;
Stephen Lin837bba12013-07-15 17:55:02 +00001605
Chandler Carruthc8925912013-01-05 02:09:22 +00001606 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
1607 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
1608 // X*Scale + C*Scale to addr mode.
Craig Topperc0196b12014-04-14 00:51:57 +00001609 ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00001610 if (isa<Instruction>(ScaleReg) && // not a constant expr.
1611 match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1612 TestAddrMode.ScaledReg = AddLHS;
1613 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00001614
Chandler Carruthc8925912013-01-05 02:09:22 +00001615 // If this addressing mode is legal, commit it and remember that we folded
1616 // this instruction.
1617 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1618 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1619 AddrMode = TestAddrMode;
1620 return true;
1621 }
1622 }
1623
1624 // Otherwise, not (x+c)*scale, just return what we have.
1625 return true;
1626}
1627
1628/// MightBeFoldableInst - This is a little filter, which returns true if an
1629/// addressing computation involving I might be folded into a load/store
1630/// accessing it. This doesn't need to be perfect, but needs to accept at least
1631/// the set of instructions that MatchOperationAddr can.
1632static bool MightBeFoldableInst(Instruction *I) {
1633 switch (I->getOpcode()) {
1634 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00001635 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00001636 // Don't touch identity bitcasts.
1637 if (I->getType() == I->getOperand(0)->getType())
1638 return false;
1639 return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1640 case Instruction::PtrToInt:
1641 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1642 return true;
1643 case Instruction::IntToPtr:
1644 // We know the input is intptr_t, so this is foldable.
1645 return true;
1646 case Instruction::Add:
1647 return true;
1648 case Instruction::Mul:
1649 case Instruction::Shl:
1650 // Can only handle X*C and X << C.
1651 return isa<ConstantInt>(I->getOperand(1));
1652 case Instruction::GetElementPtr:
1653 return true;
1654 default:
1655 return false;
1656 }
1657}
1658
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001659/// \brief Hepler class to perform type promotion.
1660class TypePromotionHelper {
1661 /// \brief Utility function to check whether or not a sign extension of
1662 /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1663 /// using the operands of \p Inst or promoting \p Inst.
1664 /// In other words, check if:
1665 /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1666 /// #1 Promotion applies:
1667 /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1668 /// #2 Operand reuses:
1669 /// sext opnd1 to ConsideredSExtType.
1670 /// \p PromotedInsts maps the instructions to their type before promotion.
1671 static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1672 const InstrToOrigTy &PromotedInsts);
1673
1674 /// \brief Utility function to determine if \p OpIdx should be promoted when
1675 /// promoting \p Inst.
1676 static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1677 if (isa<SelectInst>(Inst) && OpIdx == 0)
1678 return false;
1679 return true;
1680 }
1681
1682 /// \brief Utility function to promote the operand of \p SExt when this
1683 /// operand is a promotable trunc or sext.
1684 /// \p PromotedInsts maps the instructions to their type before promotion.
1685 /// \p CreatedInsts[out] contains how many non-free instructions have been
1686 /// created to promote the operand of SExt.
1687 /// Should never be called directly.
1688 /// \return The promoted value which is used instead of SExt.
1689 static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1690 TypePromotionTransaction &TPT,
1691 InstrToOrigTy &PromotedInsts,
1692 unsigned &CreatedInsts);
1693
1694 /// \brief Utility function to promote the operand of \p SExt when this
1695 /// operand is promotable and is not a supported trunc or sext.
1696 /// \p PromotedInsts maps the instructions to their type before promotion.
1697 /// \p CreatedInsts[out] contains how many non-free instructions have been
1698 /// created to promote the operand of SExt.
1699 /// Should never be called directly.
1700 /// \return The promoted value which is used instead of SExt.
1701 static Value *promoteOperandForOther(Instruction *SExt,
1702 TypePromotionTransaction &TPT,
1703 InstrToOrigTy &PromotedInsts,
1704 unsigned &CreatedInsts);
1705
1706public:
1707 /// Type for the utility function that promotes the operand of SExt.
1708 typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1709 InstrToOrigTy &PromotedInsts,
1710 unsigned &CreatedInsts);
1711 /// \brief Given a sign extend instruction \p SExt, return the approriate
1712 /// action to promote the operand of \p SExt instead of using SExt.
1713 /// \return NULL if no promotable action is possible with the current
1714 /// sign extension.
1715 /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1716 /// the others CodeGenPrepare optimizations. This information is important
1717 /// because we do not want to promote these instructions as CodeGenPrepare
1718 /// will reinsert them later. Thus creating an infinite loop: create/remove.
1719 /// \p PromotedInsts maps the instructions to their type before promotion.
1720 static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1721 const TargetLowering &TLI,
1722 const InstrToOrigTy &PromotedInsts);
1723};
1724
1725bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1726 Type *ConsideredSExtType,
1727 const InstrToOrigTy &PromotedInsts) {
1728 // We can always get through sext.
1729 if (isa<SExtInst>(Inst))
1730 return true;
1731
1732 // We can get through binary operator, if it is legal. In other words, the
1733 // binary operator must have a nuw or nsw flag.
1734 const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1735 if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1736 (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1737 return true;
1738
1739 // Check if we can do the following simplification.
1740 // sext(trunc(sext)) --> sext
1741 if (!isa<TruncInst>(Inst))
1742 return false;
1743
1744 Value *OpndVal = Inst->getOperand(0);
1745 // Check if we can use this operand in the sext.
1746 // If the type is larger than the result type of the sign extension,
1747 // we cannot.
1748 if (OpndVal->getType()->getIntegerBitWidth() >
1749 ConsideredSExtType->getIntegerBitWidth())
1750 return false;
1751
1752 // If the operand of the truncate is not an instruction, we will not have
1753 // any information on the dropped bits.
1754 // (Actually we could for constant but it is not worth the extra logic).
1755 Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1756 if (!Opnd)
1757 return false;
1758
1759 // Check if the source of the type is narrow enough.
1760 // I.e., check that trunc just drops sign extended bits.
1761 // #1 get the type of the operand.
1762 const Type *OpndType;
1763 InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1764 if (It != PromotedInsts.end())
1765 OpndType = It->second;
1766 else if (isa<SExtInst>(Opnd))
1767 OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1768 else
1769 return false;
1770
1771 // #2 check that the truncate just drop sign extended bits.
1772 if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1773 return true;
1774
1775 return false;
1776}
1777
1778TypePromotionHelper::Action TypePromotionHelper::getAction(
1779 Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1780 const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1781 Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1782 Type *SExtTy = SExt->getType();
1783 // If the operand of the sign extension is not an instruction, we cannot
1784 // get through.
1785 // If it, check we can get through.
1786 if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
Craig Topperc0196b12014-04-14 00:51:57 +00001787 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001788
1789 // Do not promote if the operand has been added by codegenprepare.
1790 // Otherwise, it means we are undoing an optimization that is likely to be
1791 // redone, thus causing potential infinite loop.
1792 if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
Craig Topperc0196b12014-04-14 00:51:57 +00001793 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001794
1795 // SExt or Trunc instructions.
1796 // Return the related handler.
1797 if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1798 return promoteOperandForTruncAndSExt;
1799
1800 // Regular instruction.
1801 // Abort early if we will have to insert non-free instructions.
1802 if (!SExtOpnd->hasOneUse() &&
1803 !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
Craig Topperc0196b12014-04-14 00:51:57 +00001804 return nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001805 return promoteOperandForOther;
1806}
1807
1808Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1809 llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1810 InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1811 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1812 // get through it and this method should not be called.
1813 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1814 // Replace sext(trunc(opnd)) or sext(sext(opnd))
1815 // => sext(opnd).
1816 TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1817 CreatedInsts = 0;
1818
1819 // Remove dead code.
1820 if (SExtOpnd->use_empty())
1821 TPT.eraseInstruction(SExtOpnd);
1822
1823 // Check if the sext is still needed.
1824 if (SExt->getType() != SExt->getOperand(0)->getType())
1825 return SExt;
1826
1827 // At this point we have: sext ty opnd to ty.
1828 // Reassign the uses of SExt to the opnd and remove SExt.
1829 Value *NextVal = SExt->getOperand(0);
1830 TPT.eraseInstruction(SExt, NextVal);
1831 return NextVal;
1832}
1833
1834Value *
1835TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1836 TypePromotionTransaction &TPT,
1837 InstrToOrigTy &PromotedInsts,
1838 unsigned &CreatedInsts) {
1839 // By construction, the operand of SExt is an instruction. Otherwise we cannot
1840 // get through it and this method should not be called.
1841 Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1842 CreatedInsts = 0;
1843 if (!SExtOpnd->hasOneUse()) {
1844 // SExtOpnd will be promoted.
1845 // All its uses, but SExt, will need to use a truncated value of the
1846 // promoted version.
1847 // Create the truncate now.
1848 Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1849 Trunc->removeFromParent();
1850 // Insert it just after the definition.
1851 Trunc->insertAfter(SExtOpnd);
1852
1853 TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1854 // Restore the operand of SExt (which has been replace by the previous call
1855 // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1856 TPT.setOperand(SExt, 0, SExtOpnd);
1857 }
1858
1859 // Get through the Instruction:
1860 // 1. Update its type.
1861 // 2. Replace the uses of SExt by Inst.
1862 // 3. Sign extend each operand that needs to be sign extended.
1863
1864 // Remember the original type of the instruction before promotion.
1865 // This is useful to know that the high bits are sign extended bits.
1866 PromotedInsts.insert(
1867 std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1868 // Step #1.
1869 TPT.mutateType(SExtOpnd, SExt->getType());
1870 // Step #2.
1871 TPT.replaceAllUsesWith(SExt, SExtOpnd);
1872 // Step #3.
1873 Instruction *SExtForOpnd = SExt;
1874
1875 DEBUG(dbgs() << "Propagate SExt to operands\n");
1876 for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1877 ++OpIdx) {
1878 DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1879 if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1880 !shouldSExtOperand(SExtOpnd, OpIdx)) {
1881 DEBUG(dbgs() << "No need to propagate\n");
1882 continue;
1883 }
1884 // Check if we can statically sign extend the operand.
1885 Value *Opnd = SExtOpnd->getOperand(OpIdx);
1886 if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1887 DEBUG(dbgs() << "Statically sign extend\n");
1888 TPT.setOperand(
1889 SExtOpnd, OpIdx,
1890 ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1891 continue;
1892 }
1893 // UndefValue are typed, so we have to statically sign extend them.
1894 if (isa<UndefValue>(Opnd)) {
1895 DEBUG(dbgs() << "Statically sign extend\n");
1896 TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1897 continue;
1898 }
1899
1900 // Otherwise we have to explicity sign extend the operand.
1901 // Check if SExt was reused to sign extend an operand.
1902 if (!SExtForOpnd) {
1903 // If yes, create a new one.
1904 DEBUG(dbgs() << "More operands to sext\n");
1905 SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1906 ++CreatedInsts;
1907 }
1908
1909 TPT.setOperand(SExtForOpnd, 0, Opnd);
1910
1911 // Move the sign extension before the insertion point.
1912 TPT.moveBefore(SExtForOpnd, SExtOpnd);
1913 TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1914 // If more sext are required, new instructions will have to be created.
Craig Topperc0196b12014-04-14 00:51:57 +00001915 SExtForOpnd = nullptr;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001916 }
1917 if (SExtForOpnd == SExt) {
1918 DEBUG(dbgs() << "Sign extension is useless now\n");
1919 TPT.eraseInstruction(SExt);
1920 }
1921 return SExtOpnd;
1922}
1923
Quentin Colombet867c5502014-02-14 22:23:22 +00001924/// IsPromotionProfitable - Check whether or not promoting an instruction
1925/// to a wider type was profitable.
1926/// \p MatchedSize gives the number of instructions that have been matched
1927/// in the addressing mode after the promotion was applied.
1928/// \p SizeWithPromotion gives the number of created instructions for
1929/// the promotion plus the number of instructions that have been
1930/// matched in the addressing mode before the promotion.
1931/// \p PromotedOperand is the value that has been promoted.
1932/// \return True if the promotion is profitable, false otherwise.
1933bool
1934AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
1935 unsigned SizeWithPromotion,
1936 Value *PromotedOperand) const {
1937 // We folded less instructions than what we created to promote the operand.
1938 // This is not profitable.
1939 if (MatchedSize < SizeWithPromotion)
1940 return false;
1941 if (MatchedSize > SizeWithPromotion)
1942 return true;
1943 // The promotion is neutral but it may help folding the sign extension in
1944 // loads for instance.
1945 // Check that we did not create an illegal instruction.
1946 Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
1947 if (!PromotedInst)
1948 return false;
Quentin Colombet1627a412014-02-22 01:06:41 +00001949 int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
1950 // If the ISDOpcode is undefined, it was undefined before the promotion.
1951 if (!ISDOpcode)
1952 return true;
1953 // Otherwise, check if the promoted instruction is legal or not.
1954 return TLI.isOperationLegalOrCustom(ISDOpcode,
Quentin Colombet867c5502014-02-14 22:23:22 +00001955 EVT::getEVT(PromotedInst->getType()));
1956}
1957
Chandler Carruthc8925912013-01-05 02:09:22 +00001958/// MatchOperationAddr - Given an instruction or constant expr, see if we can
1959/// fold the operation into the addressing mode. If so, update the addressing
1960/// mode and return true, otherwise return false without modifying AddrMode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001961/// If \p MovedAway is not NULL, it contains the information of whether or
1962/// not AddrInst has to be folded into the addressing mode on success.
1963/// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1964/// because it has been moved away.
1965/// Thus AddrInst must not be added in the matched instructions.
1966/// This state can happen when AddrInst is a sext, since it may be moved away.
1967/// Therefore, AddrInst may not be valid when MovedAway is true and it must
1968/// not be referenced anymore.
Chandler Carruthc8925912013-01-05 02:09:22 +00001969bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001970 unsigned Depth,
1971 bool *MovedAway) {
Chandler Carruthc8925912013-01-05 02:09:22 +00001972 // Avoid exponential behavior on extremely deep expression trees.
1973 if (Depth >= 5) return false;
Stephen Lin837bba12013-07-15 17:55:02 +00001974
Quentin Colombet3a4bf042014-02-06 21:44:56 +00001975 // By default, all matched instructions stay in place.
1976 if (MovedAway)
1977 *MovedAway = false;
1978
Chandler Carruthc8925912013-01-05 02:09:22 +00001979 switch (Opcode) {
1980 case Instruction::PtrToInt:
1981 // PtrToInt is always a noop, as we know that the int type is pointer sized.
1982 return MatchAddr(AddrInst->getOperand(0), Depth);
1983 case Instruction::IntToPtr:
1984 // This inttoptr is a no-op if the integer type is pointer sized.
1985 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
Matt Arsenault37d42ec2013-09-06 00:18:43 +00001986 TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
Chandler Carruthc8925912013-01-05 02:09:22 +00001987 return MatchAddr(AddrInst->getOperand(0), Depth);
1988 return false;
1989 case Instruction::BitCast:
Eli Benderskyf13a0562014-05-22 00:02:52 +00001990 case Instruction::AddrSpaceCast:
Chandler Carruthc8925912013-01-05 02:09:22 +00001991 // BitCast is always a noop, and we can handle it as long as it is
1992 // int->int or pointer->pointer (we don't want int<->fp or something).
1993 if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1994 AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1995 // Don't touch identity bitcasts. These were probably put here by LSR,
1996 // and we don't want to mess around with them. Assume it knows what it
1997 // is doing.
1998 AddrInst->getOperand(0)->getType() != AddrInst->getType())
1999 return MatchAddr(AddrInst->getOperand(0), Depth);
2000 return false;
2001 case Instruction::Add: {
2002 // Check to see if we can merge in the RHS then the LHS. If so, we win.
2003 ExtAddrMode BackupAddrMode = AddrMode;
2004 unsigned OldSize = AddrModeInsts.size();
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002005 // Start a transaction at this point.
2006 // The LHS may match but not the RHS.
2007 // Therefore, we need a higher level restoration point to undo partially
2008 // matched operation.
2009 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2010 TPT.getRestorationPoint();
2011
Chandler Carruthc8925912013-01-05 02:09:22 +00002012 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2013 MatchAddr(AddrInst->getOperand(0), Depth+1))
2014 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002015
Chandler Carruthc8925912013-01-05 02:09:22 +00002016 // Restore the old addr mode info.
2017 AddrMode = BackupAddrMode;
2018 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002019 TPT.rollback(LastKnownGood);
Stephen Lin837bba12013-07-15 17:55:02 +00002020
Chandler Carruthc8925912013-01-05 02:09:22 +00002021 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
2022 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2023 MatchAddr(AddrInst->getOperand(1), Depth+1))
2024 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002025
Chandler Carruthc8925912013-01-05 02:09:22 +00002026 // Otherwise we definitely can't merge the ADD in.
2027 AddrMode = BackupAddrMode;
2028 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002029 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002030 break;
2031 }
2032 //case Instruction::Or:
2033 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2034 //break;
2035 case Instruction::Mul:
2036 case Instruction::Shl: {
2037 // Can only handle X*C and X << C.
2038 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2039 if (!RHS) return false;
2040 int64_t Scale = RHS->getSExtValue();
2041 if (Opcode == Instruction::Shl)
2042 Scale = 1LL << Scale;
Stephen Lin837bba12013-07-15 17:55:02 +00002043
Chandler Carruthc8925912013-01-05 02:09:22 +00002044 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2045 }
2046 case Instruction::GetElementPtr: {
2047 // Scan the GEP. We check it if it contains constant offsets and at most
2048 // one variable offset.
2049 int VariableOperand = -1;
2050 unsigned VariableScale = 0;
Stephen Lin837bba12013-07-15 17:55:02 +00002051
Chandler Carruthc8925912013-01-05 02:09:22 +00002052 int64_t ConstantOffset = 0;
2053 const DataLayout *TD = TLI.getDataLayout();
2054 gep_type_iterator GTI = gep_type_begin(AddrInst);
2055 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2056 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2057 const StructLayout *SL = TD->getStructLayout(STy);
2058 unsigned Idx =
2059 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2060 ConstantOffset += SL->getElementOffset(Idx);
2061 } else {
2062 uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2063 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2064 ConstantOffset += CI->getSExtValue()*TypeSize;
2065 } else if (TypeSize) { // Scales of zero don't do anything.
2066 // We only allow one variable index at the moment.
2067 if (VariableOperand != -1)
2068 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002069
Chandler Carruthc8925912013-01-05 02:09:22 +00002070 // Remember the variable index.
2071 VariableOperand = i;
2072 VariableScale = TypeSize;
2073 }
2074 }
2075 }
Stephen Lin837bba12013-07-15 17:55:02 +00002076
Chandler Carruthc8925912013-01-05 02:09:22 +00002077 // A common case is for the GEP to only do a constant offset. In this case,
2078 // just add it to the disp field and check validity.
2079 if (VariableOperand == -1) {
2080 AddrMode.BaseOffs += ConstantOffset;
2081 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2082 // Check to see if we can fold the base pointer in too.
2083 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2084 return true;
2085 }
2086 AddrMode.BaseOffs -= ConstantOffset;
2087 return false;
2088 }
2089
2090 // Save the valid addressing mode in case we can't match.
2091 ExtAddrMode BackupAddrMode = AddrMode;
2092 unsigned OldSize = AddrModeInsts.size();
2093
2094 // See if the scale and offset amount is valid for this target.
2095 AddrMode.BaseOffs += ConstantOffset;
2096
2097 // Match the base operand of the GEP.
2098 if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2099 // If it couldn't be matched, just stuff the value in a register.
2100 if (AddrMode.HasBaseReg) {
2101 AddrMode = BackupAddrMode;
2102 AddrModeInsts.resize(OldSize);
2103 return false;
2104 }
2105 AddrMode.HasBaseReg = true;
2106 AddrMode.BaseReg = AddrInst->getOperand(0);
2107 }
2108
2109 // Match the remaining variable portion of the GEP.
2110 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2111 Depth)) {
2112 // If it couldn't be matched, try stuffing the base into a register
2113 // instead of matching it, and retrying the match of the scale.
2114 AddrMode = BackupAddrMode;
2115 AddrModeInsts.resize(OldSize);
2116 if (AddrMode.HasBaseReg)
2117 return false;
2118 AddrMode.HasBaseReg = true;
2119 AddrMode.BaseReg = AddrInst->getOperand(0);
2120 AddrMode.BaseOffs += ConstantOffset;
2121 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2122 VariableScale, Depth)) {
2123 // If even that didn't work, bail.
2124 AddrMode = BackupAddrMode;
2125 AddrModeInsts.resize(OldSize);
2126 return false;
2127 }
2128 }
2129
2130 return true;
2131 }
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002132 case Instruction::SExt: {
Sanjay Patelab60d042014-07-16 21:08:10 +00002133 // Make sure this isn't a ConstantExpr (PR20314).
2134 Instruction *SExt = dyn_cast<Instruction>(AddrInst);
2135 if (!SExt) return false;
2136
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002137 // Try to move this sext out of the way of the addressing mode.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002138 // Ask for a method for doing so.
2139 TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
2140 SExt, InsertedTruncs, TLI, PromotedInsts);
2141 if (!TPH)
2142 return false;
2143
2144 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2145 TPT.getRestorationPoint();
2146 unsigned CreatedInsts = 0;
2147 Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
2148 // SExt has been moved away.
2149 // Thus either it will be rematched later in the recursive calls or it is
2150 // gone. Anyway, we must not fold it into the addressing mode at this point.
2151 // E.g.,
2152 // op = add opnd, 1
2153 // idx = sext op
2154 // addr = gep base, idx
2155 // is now:
2156 // promotedOpnd = sext opnd <- no match here
2157 // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
2158 // addr = gep base, op <- match
2159 if (MovedAway)
2160 *MovedAway = true;
2161
2162 assert(PromotedOperand &&
2163 "TypePromotionHelper should have filtered out those cases");
2164
2165 ExtAddrMode BackupAddrMode = AddrMode;
2166 unsigned OldSize = AddrModeInsts.size();
2167
2168 if (!MatchAddr(PromotedOperand, Depth) ||
Quentin Colombet867c5502014-02-14 22:23:22 +00002169 !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2170 PromotedOperand)) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002171 AddrMode = BackupAddrMode;
2172 AddrModeInsts.resize(OldSize);
2173 DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2174 TPT.rollback(LastKnownGood);
2175 return false;
2176 }
2177 return true;
2178 }
Chandler Carruthc8925912013-01-05 02:09:22 +00002179 }
2180 return false;
2181}
2182
2183/// MatchAddr - If we can, try to add the value of 'Addr' into the current
2184/// addressing mode. If Addr can't be added to AddrMode this returns false and
2185/// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
2186/// or intptr_t for the target.
2187///
2188bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002189 // Start a transaction at this point that we will rollback if the matching
2190 // fails.
2191 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2192 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002193 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2194 // Fold in immediates if legal for the target.
2195 AddrMode.BaseOffs += CI->getSExtValue();
2196 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2197 return true;
2198 AddrMode.BaseOffs -= CI->getSExtValue();
2199 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2200 // If this is a global variable, try to fold it into the addressing mode.
Craig Topperc0196b12014-04-14 00:51:57 +00002201 if (!AddrMode.BaseGV) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002202 AddrMode.BaseGV = GV;
2203 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2204 return true;
Craig Topperc0196b12014-04-14 00:51:57 +00002205 AddrMode.BaseGV = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002206 }
2207 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2208 ExtAddrMode BackupAddrMode = AddrMode;
2209 unsigned OldSize = AddrModeInsts.size();
2210
2211 // Check to see if it is possible to fold this operation.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002212 bool MovedAway = false;
2213 if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2214 // This instruction may have been move away. If so, there is nothing
2215 // to check here.
2216 if (MovedAway)
2217 return true;
Chandler Carruthc8925912013-01-05 02:09:22 +00002218 // Okay, it's possible to fold this. Check to see if it is actually
2219 // *profitable* to do so. We use a simple cost model to avoid increasing
2220 // register pressure too much.
2221 if (I->hasOneUse() ||
2222 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2223 AddrModeInsts.push_back(I);
2224 return true;
2225 }
Stephen Lin837bba12013-07-15 17:55:02 +00002226
Chandler Carruthc8925912013-01-05 02:09:22 +00002227 // It isn't profitable to do this, roll back.
2228 //cerr << "NOT FOLDING: " << *I;
2229 AddrMode = BackupAddrMode;
2230 AddrModeInsts.resize(OldSize);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002231 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002232 }
2233 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2234 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2235 return true;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002236 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002237 } else if (isa<ConstantPointerNull>(Addr)) {
2238 // Null pointer gets folded without affecting the addressing mode.
2239 return true;
2240 }
2241
2242 // Worse case, the target should support [reg] addressing modes. :)
2243 if (!AddrMode.HasBaseReg) {
2244 AddrMode.HasBaseReg = true;
2245 AddrMode.BaseReg = Addr;
2246 // Still check for legality in case the target supports [imm] but not [i+r].
2247 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2248 return true;
2249 AddrMode.HasBaseReg = false;
Craig Topperc0196b12014-04-14 00:51:57 +00002250 AddrMode.BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002251 }
2252
2253 // If the base register is already taken, see if we can do [r+r].
2254 if (AddrMode.Scale == 0) {
2255 AddrMode.Scale = 1;
2256 AddrMode.ScaledReg = Addr;
2257 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2258 return true;
2259 AddrMode.Scale = 0;
Craig Topperc0196b12014-04-14 00:51:57 +00002260 AddrMode.ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002261 }
2262 // Couldn't match.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002263 TPT.rollback(LastKnownGood);
Chandler Carruthc8925912013-01-05 02:09:22 +00002264 return false;
2265}
2266
2267/// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2268/// inline asm call are due to memory operands. If so, return true, otherwise
2269/// return false.
2270static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2271 const TargetLowering &TLI) {
2272 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2273 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2274 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Stephen Lin837bba12013-07-15 17:55:02 +00002275
Chandler Carruthc8925912013-01-05 02:09:22 +00002276 // Compute the constraint code and ConstraintType to use.
2277 TLI.ComputeConstraintToUse(OpInfo, SDValue());
2278
2279 // If this asm operand is our Value*, and if it isn't an indirect memory
2280 // operand, we can't fold it!
2281 if (OpInfo.CallOperandVal == OpVal &&
2282 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2283 !OpInfo.isIndirect))
2284 return false;
2285 }
2286
2287 return true;
2288}
2289
2290/// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2291/// memory use. If we find an obviously non-foldable instruction, return true.
2292/// Add the ultimately found memory instructions to MemoryUses.
2293static bool FindAllMemoryUses(Instruction *I,
2294 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2295 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2296 const TargetLowering &TLI) {
2297 // If we already considered this instruction, we're done.
2298 if (!ConsideredInsts.insert(I))
2299 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002300
Chandler Carruthc8925912013-01-05 02:09:22 +00002301 // If this is an obviously unfoldable instruction, bail out.
2302 if (!MightBeFoldableInst(I))
2303 return true;
2304
2305 // Loop over all the uses, recursively processing them.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002306 for (Use &U : I->uses()) {
2307 Instruction *UserI = cast<Instruction>(U.getUser());
Chandler Carruthc8925912013-01-05 02:09:22 +00002308
Chandler Carruthcdf47882014-03-09 03:16:01 +00002309 if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2310 MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
Chandler Carruthc8925912013-01-05 02:09:22 +00002311 continue;
2312 }
Stephen Lin837bba12013-07-15 17:55:02 +00002313
Chandler Carruthcdf47882014-03-09 03:16:01 +00002314 if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2315 unsigned opNo = U.getOperandNo();
Chandler Carruthc8925912013-01-05 02:09:22 +00002316 if (opNo == 0) return true; // Storing addr, not into addr.
2317 MemoryUses.push_back(std::make_pair(SI, opNo));
2318 continue;
2319 }
Stephen Lin837bba12013-07-15 17:55:02 +00002320
Chandler Carruthcdf47882014-03-09 03:16:01 +00002321 if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
Chandler Carruthc8925912013-01-05 02:09:22 +00002322 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2323 if (!IA) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002324
Chandler Carruthc8925912013-01-05 02:09:22 +00002325 // If this is a memory operand, we're cool, otherwise bail out.
2326 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2327 return true;
2328 continue;
2329 }
Stephen Lin837bba12013-07-15 17:55:02 +00002330
Chandler Carruthcdf47882014-03-09 03:16:01 +00002331 if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
Chandler Carruthc8925912013-01-05 02:09:22 +00002332 return true;
2333 }
2334
2335 return false;
2336}
2337
2338/// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2339/// the use site that we're folding it into. If so, there is no cost to
2340/// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
2341/// that we know are live at the instruction already.
2342bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2343 Value *KnownLive2) {
2344 // If Val is either of the known-live values, we know it is live!
Craig Topperc0196b12014-04-14 00:51:57 +00002345 if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
Chandler Carruthc8925912013-01-05 02:09:22 +00002346 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002347
Chandler Carruthc8925912013-01-05 02:09:22 +00002348 // All values other than instructions and arguments (e.g. constants) are live.
2349 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002350
Chandler Carruthc8925912013-01-05 02:09:22 +00002351 // If Val is a constant sized alloca in the entry block, it is live, this is
2352 // true because it is just a reference to the stack/frame pointer, which is
2353 // live for the whole function.
2354 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2355 if (AI->isStaticAlloca())
2356 return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002357
Chandler Carruthc8925912013-01-05 02:09:22 +00002358 // Check to see if this value is already used in the memory instruction's
2359 // block. If so, it's already live into the block at the very least, so we
2360 // can reasonably fold it.
2361 return Val->isUsedInBasicBlock(MemoryInst->getParent());
2362}
2363
2364/// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2365/// mode of the machine to fold the specified instruction into a load or store
2366/// that ultimately uses it. However, the specified instruction has multiple
2367/// uses. Given this, it may actually increase register pressure to fold it
2368/// into the load. For example, consider this code:
2369///
2370/// X = ...
2371/// Y = X+1
2372/// use(Y) -> nonload/store
2373/// Z = Y+1
2374/// load Z
2375///
2376/// In this case, Y has multiple uses, and can be folded into the load of Z
2377/// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
2378/// be live at the use(Y) line. If we don't fold Y into load Z, we use one
2379/// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
2380/// number of computations either.
2381///
2382/// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
2383/// X was live across 'load Z' for other reasons, we actually *would* want to
2384/// fold the addressing mode in the Z case. This would make Y die earlier.
2385bool AddressingModeMatcher::
2386IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2387 ExtAddrMode &AMAfter) {
2388 if (IgnoreProfitability) return true;
Stephen Lin837bba12013-07-15 17:55:02 +00002389
Chandler Carruthc8925912013-01-05 02:09:22 +00002390 // AMBefore is the addressing mode before this instruction was folded into it,
2391 // and AMAfter is the addressing mode after the instruction was folded. Get
2392 // the set of registers referenced by AMAfter and subtract out those
2393 // referenced by AMBefore: this is the set of values which folding in this
2394 // address extends the lifetime of.
2395 //
2396 // Note that there are only two potential values being referenced here,
2397 // BaseReg and ScaleReg (global addresses are always available, as are any
2398 // folded immediates).
2399 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
Stephen Lin837bba12013-07-15 17:55:02 +00002400
Chandler Carruthc8925912013-01-05 02:09:22 +00002401 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2402 // lifetime wasn't extended by adding this instruction.
2403 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002404 BaseReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002405 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
Craig Topperc0196b12014-04-14 00:51:57 +00002406 ScaledReg = nullptr;
Chandler Carruthc8925912013-01-05 02:09:22 +00002407
2408 // If folding this instruction (and it's subexprs) didn't extend any live
2409 // ranges, we're ok with it.
Craig Topperc0196b12014-04-14 00:51:57 +00002410 if (!BaseReg && !ScaledReg)
Chandler Carruthc8925912013-01-05 02:09:22 +00002411 return true;
2412
2413 // If all uses of this instruction are ultimately load/store/inlineasm's,
2414 // check to see if their addressing modes will include this instruction. If
2415 // so, we can fold it into all uses, so it doesn't matter if it has multiple
2416 // uses.
2417 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2418 SmallPtrSet<Instruction*, 16> ConsideredInsts;
2419 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2420 return false; // Has a non-memory, non-foldable use!
Stephen Lin837bba12013-07-15 17:55:02 +00002421
Chandler Carruthc8925912013-01-05 02:09:22 +00002422 // Now that we know that all uses of this instruction are part of a chain of
2423 // computation involving only operations that could theoretically be folded
2424 // into a memory use, loop over each of these uses and see if they could
2425 // *actually* fold the instruction.
2426 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2427 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2428 Instruction *User = MemoryUses[i].first;
2429 unsigned OpNo = MemoryUses[i].second;
Stephen Lin837bba12013-07-15 17:55:02 +00002430
Chandler Carruthc8925912013-01-05 02:09:22 +00002431 // Get the access type of this use. If the use isn't a pointer, we don't
2432 // know what it accesses.
2433 Value *Address = User->getOperand(OpNo);
2434 if (!Address->getType()->isPointerTy())
2435 return false;
Matt Arsenault8227b9f2013-09-06 00:37:24 +00002436 Type *AddressAccessTy = Address->getType()->getPointerElementType();
Stephen Lin837bba12013-07-15 17:55:02 +00002437
Chandler Carruthc8925912013-01-05 02:09:22 +00002438 // Do a match against the root of this address, ignoring profitability. This
2439 // will tell us if the addressing mode for the memory operation will
2440 // *actually* cover the shared instruction.
2441 ExtAddrMode Result;
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002442 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2443 TPT.getRestorationPoint();
Chandler Carruthc8925912013-01-05 02:09:22 +00002444 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002445 MemoryInst, Result, InsertedTruncs,
2446 PromotedInsts, TPT);
Chandler Carruthc8925912013-01-05 02:09:22 +00002447 Matcher.IgnoreProfitability = true;
2448 bool Success = Matcher.MatchAddr(Address, 0);
2449 (void)Success; assert(Success && "Couldn't select *anything*?");
2450
Quentin Colombet5a69dda2014-02-11 01:59:02 +00002451 // The match was to check the profitability, the changes made are not
2452 // part of the original matcher. Therefore, they should be dropped
2453 // otherwise the original matcher will not present the right state.
2454 TPT.rollback(LastKnownGood);
2455
Chandler Carruthc8925912013-01-05 02:09:22 +00002456 // If the match didn't cover I, then it won't be shared by it.
2457 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2458 I) == MatchedAddrModeInsts.end())
2459 return false;
Stephen Lin837bba12013-07-15 17:55:02 +00002460
Chandler Carruthc8925912013-01-05 02:09:22 +00002461 MatchedAddrModeInsts.clear();
2462 }
Stephen Lin837bba12013-07-15 17:55:02 +00002463
Chandler Carruthc8925912013-01-05 02:09:22 +00002464 return true;
2465}
2466
2467} // end anonymous namespace
2468
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002469/// IsNonLocalValue - Return true if the specified values are defined in a
2470/// different basic block than BB.
2471static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2472 if (Instruction *I = dyn_cast<Instruction>(V))
2473 return I->getParent() != BB;
2474 return false;
2475}
2476
Bob Wilson53bdae32009-12-03 21:47:07 +00002477/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002478/// addressing modes that can do significant amounts of computation. As such,
2479/// instruction selection will try to get the load or store to do as much
2480/// computation as possible for the program. The problem is that isel can only
2481/// see within a single block. As such, we sink as much legal addressing mode
2482/// stuff into the block as possible.
Chris Lattner728f9022008-11-25 07:09:13 +00002483///
2484/// This method is used to optimize both load/store and inline asms with memory
2485/// operands.
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002486bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner229907c2011-07-18 04:54:35 +00002487 Type *AccessTy) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002488 Value *Repl = Addr;
Nadav Rotem465834c2012-07-24 10:51:42 +00002489
2490 // Try to collapse single-value PHI nodes. This is necessary to undo
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002491 // unprofitable PRE transformations.
Cameron Zwarich43cecb12011-01-03 06:33:01 +00002492 SmallVector<Value*, 8> worklist;
2493 SmallPtrSet<Value*, 16> Visited;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002494 worklist.push_back(Addr);
Nadav Rotem465834c2012-07-24 10:51:42 +00002495
Owen Anderson8ba5f392010-11-27 08:15:55 +00002496 // Use a worklist to iteratively look through PHI nodes, and ensure that
2497 // the addressing mode obtained from the non-PHI roots of the graph
2498 // are equivalent.
Craig Topperc0196b12014-04-14 00:51:57 +00002499 Value *Consensus = nullptr;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002500 unsigned NumUsesConsensus = 0;
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002501 bool IsNumUsesConsensusValid = false;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002502 SmallVector<Instruction*, 16> AddrModeInsts;
2503 ExtAddrMode AddrMode;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002504 TypePromotionTransaction TPT;
2505 TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2506 TPT.getRestorationPoint();
Owen Anderson8ba5f392010-11-27 08:15:55 +00002507 while (!worklist.empty()) {
2508 Value *V = worklist.back();
2509 worklist.pop_back();
Nadav Rotem465834c2012-07-24 10:51:42 +00002510
Owen Anderson8ba5f392010-11-27 08:15:55 +00002511 // Break use-def graph loops.
Nick Lewyckya3e7ffd2011-09-29 23:40:12 +00002512 if (!Visited.insert(V)) {
Craig Topperc0196b12014-04-14 00:51:57 +00002513 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002514 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002515 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002516
Owen Anderson8ba5f392010-11-27 08:15:55 +00002517 // For a PHI node, push all of its incoming values.
2518 if (PHINode *P = dyn_cast<PHINode>(V)) {
2519 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2520 worklist.push_back(P->getIncomingValue(i));
2521 continue;
2522 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002523
Owen Anderson8ba5f392010-11-27 08:15:55 +00002524 // For non-PHIs, determine the addressing mode being computed.
2525 SmallVector<Instruction*, 16> NewAddrModeInsts;
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002526 ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2527 V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2528 PromotedInsts, TPT);
Cameron Zwarich13c885d2011-03-05 08:12:26 +00002529
2530 // This check is broken into two cases with very similar code to avoid using
2531 // getNumUses() as much as possible. Some values have a lot of uses, so
2532 // calling getNumUses() unconditionally caused a significant compile-time
2533 // regression.
2534 if (!Consensus) {
2535 Consensus = V;
2536 AddrMode = NewAddrMode;
2537 AddrModeInsts = NewAddrModeInsts;
2538 continue;
2539 } else if (NewAddrMode == AddrMode) {
2540 if (!IsNumUsesConsensusValid) {
2541 NumUsesConsensus = Consensus->getNumUses();
2542 IsNumUsesConsensusValid = true;
2543 }
2544
2545 // Ensure that the obtained addressing mode is equivalent to that obtained
2546 // for all other roots of the PHI traversal. Also, when choosing one
2547 // such root as representative, select the one with the most uses in order
2548 // to keep the cost modeling heuristics in AddressingModeMatcher
2549 // applicable.
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002550 unsigned NumUses = V->getNumUses();
2551 if (NumUses > NumUsesConsensus) {
Owen Anderson8ba5f392010-11-27 08:15:55 +00002552 Consensus = V;
Cameron Zwarichb7f8eaa2011-03-01 21:13:53 +00002553 NumUsesConsensus = NumUses;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002554 AddrModeInsts = NewAddrModeInsts;
2555 }
2556 continue;
2557 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002558
Craig Topperc0196b12014-04-14 00:51:57 +00002559 Consensus = nullptr;
Owen Anderson8ba5f392010-11-27 08:15:55 +00002560 break;
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002561 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002562
Owen Anderson8ba5f392010-11-27 08:15:55 +00002563 // If the addressing mode couldn't be determined, or if multiple different
2564 // ones were determined, bail out now.
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002565 if (!Consensus) {
2566 TPT.rollback(LastKnownGood);
2567 return false;
2568 }
2569 TPT.commit();
Nadav Rotem465834c2012-07-24 10:51:42 +00002570
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002571 // Check to see if any of the instructions supersumed by this addr mode are
2572 // non-local to I's BB.
2573 bool AnyNonLocal = false;
2574 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner6d71b7f2008-11-26 03:20:37 +00002575 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002576 AnyNonLocal = true;
2577 break;
2578 }
2579 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002580
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002581 // If all the instructions matched are already in this BB, don't do anything.
2582 if (!AnyNonLocal) {
David Greene74e2d492010-01-05 01:27:11 +00002583 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002584 return false;
2585 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002586
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002587 // Insert this computation right after this user. Since our caller is
2588 // scanning from the top of the BB to the bottom, reuse of the expr are
2589 // guaranteed to happen later.
Devang Patelc10e52a2011-09-06 18:49:53 +00002590 IRBuilder<> Builder(MemoryInst);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002591
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002592 // Now that we determined the addressing expression we want to use and know
2593 // that we have to sink it into this block. Check to see if we have already
2594 // done this for some other load/store instr in this block. If so, reuse the
2595 // computation.
2596 Value *&SunkAddr = SunkAddrs[Addr];
2597 if (SunkAddr) {
David Greene74e2d492010-01-05 01:27:11 +00002598 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002599 << *MemoryInst << "\n");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002600 if (SunkAddr->getType() != Addr->getType())
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002601 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
Hal Finkelc3998302014-04-12 00:59:48 +00002602 } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2603 TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2604 // By default, we use the GEP-based method when AA is used later. This
2605 // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2606 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002607 << *MemoryInst << "\n");
Hal Finkelc3998302014-04-12 00:59:48 +00002608 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002609 Value *ResultPtr = nullptr, *ResultIndex = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002610
2611 // First, find the pointer.
2612 if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2613 ResultPtr = AddrMode.BaseReg;
Craig Topperc0196b12014-04-14 00:51:57 +00002614 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002615 }
2616
2617 if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2618 // We can't add more than one pointer together, nor can we scale a
2619 // pointer (both of which seem meaningless).
2620 if (ResultPtr || AddrMode.Scale != 1)
2621 return false;
2622
2623 ResultPtr = AddrMode.ScaledReg;
2624 AddrMode.Scale = 0;
2625 }
2626
2627 if (AddrMode.BaseGV) {
2628 if (ResultPtr)
2629 return false;
2630
2631 ResultPtr = AddrMode.BaseGV;
2632 }
2633
2634 // If the real base value actually came from an inttoptr, then the matcher
2635 // will look through it and provide only the integer value. In that case,
2636 // use it here.
2637 if (!ResultPtr && AddrMode.BaseReg) {
2638 ResultPtr =
2639 Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
Craig Topperc0196b12014-04-14 00:51:57 +00002640 AddrMode.BaseReg = nullptr;
Hal Finkelc3998302014-04-12 00:59:48 +00002641 } else if (!ResultPtr && AddrMode.Scale == 1) {
2642 ResultPtr =
2643 Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2644 AddrMode.Scale = 0;
2645 }
2646
2647 if (!ResultPtr &&
2648 !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2649 SunkAddr = Constant::getNullValue(Addr->getType());
2650 } else if (!ResultPtr) {
2651 return false;
2652 } else {
2653 Type *I8PtrTy =
2654 Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2655
2656 // Start with the base register. Do this first so that subsequent address
2657 // matching finds it last, which will prevent it from trying to match it
2658 // as the scaled value in case it happens to be a mul. That would be
2659 // problematic if we've sunk a different mul for the scale, because then
2660 // we'd end up sinking both muls.
2661 if (AddrMode.BaseReg) {
2662 Value *V = AddrMode.BaseReg;
2663 if (V->getType() != IntPtrTy)
2664 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2665
2666 ResultIndex = V;
2667 }
2668
2669 // Add the scale value.
2670 if (AddrMode.Scale) {
2671 Value *V = AddrMode.ScaledReg;
2672 if (V->getType() == IntPtrTy) {
2673 // done.
2674 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2675 cast<IntegerType>(V->getType())->getBitWidth()) {
2676 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2677 } else {
2678 // It is only safe to sign extend the BaseReg if we know that the math
2679 // required to create it did not overflow before we extend it. Since
2680 // the original IR value was tossed in favor of a constant back when
2681 // the AddrMode was created we need to bail out gracefully if widths
2682 // do not match instead of extending it.
2683 Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2684 if (I && (ResultIndex != AddrMode.BaseReg))
2685 I->eraseFromParent();
2686 return false;
2687 }
2688
2689 if (AddrMode.Scale != 1)
2690 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2691 "sunkaddr");
2692 if (ResultIndex)
2693 ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2694 else
2695 ResultIndex = V;
2696 }
2697
2698 // Add in the Base Offset if present.
2699 if (AddrMode.BaseOffs) {
2700 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2701 if (ResultIndex) {
2702 // We need to add this separately from the scale above to help with
2703 // SDAG consecutive load/store merging.
2704 if (ResultPtr->getType() != I8PtrTy)
2705 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2706 ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2707 }
2708
2709 ResultIndex = V;
2710 }
2711
2712 if (!ResultIndex) {
2713 SunkAddr = ResultPtr;
2714 } else {
2715 if (ResultPtr->getType() != I8PtrTy)
2716 ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2717 SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2718 }
2719
2720 if (SunkAddr->getType() != Addr->getType())
2721 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2722 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002723 } else {
David Greene74e2d492010-01-05 01:27:11 +00002724 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Louis Gerbarg1b91aa22014-05-13 21:54:22 +00002725 << *MemoryInst << "\n");
Matt Arsenault37d42ec2013-09-06 00:18:43 +00002726 Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
Craig Topperc0196b12014-04-14 00:51:57 +00002727 Value *Result = nullptr;
Dan Gohmanca194452010-01-19 22:45:06 +00002728
2729 // Start with the base register. Do this first so that subsequent address
2730 // matching finds it last, which will prevent it from trying to match it
2731 // as the scaled value in case it happens to be a mul. That would be
2732 // problematic if we've sunk a different mul for the scale, because then
2733 // we'd end up sinking both muls.
2734 if (AddrMode.BaseReg) {
2735 Value *V = AddrMode.BaseReg;
Duncan Sands19d0b472010-02-16 11:11:14 +00002736 if (V->getType()->isPointerTy())
Devang Patelc10e52a2011-09-06 18:49:53 +00002737 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002738 if (V->getType() != IntPtrTy)
Devang Patelc10e52a2011-09-06 18:49:53 +00002739 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
Dan Gohmanca194452010-01-19 22:45:06 +00002740 Result = V;
2741 }
2742
2743 // Add the scale value.
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002744 if (AddrMode.Scale) {
2745 Value *V = AddrMode.ScaledReg;
2746 if (V->getType() == IntPtrTy) {
2747 // done.
Duncan Sands19d0b472010-02-16 11:11:14 +00002748 } else if (V->getType()->isPointerTy()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002749 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002750 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2751 cast<IntegerType>(V->getType())->getBitWidth()) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002752 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002753 } else {
Jim Grosbached2cd392014-03-26 17:27:01 +00002754 // It is only safe to sign extend the BaseReg if we know that the math
2755 // required to create it did not overflow before we extend it. Since
2756 // the original IR value was tossed in favor of a constant back when
2757 // the AddrMode was created we need to bail out gracefully if widths
2758 // do not match instead of extending it.
Joey Gouly12a8bf02014-05-13 15:42:45 +00002759 Instruction *I = dyn_cast_or_null<Instruction>(Result);
Jim Grosbach83b44e12014-04-10 00:27:45 +00002760 if (I && (Result != AddrMode.BaseReg))
2761 I->eraseFromParent();
Jim Grosbached2cd392014-03-26 17:27:01 +00002762 return false;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002763 }
2764 if (AddrMode.Scale != 1)
Devang Patelc10e52a2011-09-06 18:49:53 +00002765 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2766 "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002767 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002768 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002769 else
2770 Result = V;
2771 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002772
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002773 // Add in the BaseGV if present.
2774 if (AddrMode.BaseGV) {
Devang Patelc10e52a2011-09-06 18:49:53 +00002775 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002776 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002777 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002778 else
2779 Result = V;
2780 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002781
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002782 // Add in the Base Offset if present.
2783 if (AddrMode.BaseOffs) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002784 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002785 if (Result)
Devang Patelc10e52a2011-09-06 18:49:53 +00002786 Result = Builder.CreateAdd(Result, V, "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002787 else
2788 Result = V;
2789 }
2790
Craig Topperc0196b12014-04-14 00:51:57 +00002791 if (!Result)
Owen Anderson5a1acd92009-07-31 20:28:14 +00002792 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002793 else
Devang Patelc10e52a2011-09-06 18:49:53 +00002794 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002795 }
Eric Christopherc1ea1492008-09-24 05:32:41 +00002796
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002797 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
Eric Christopherc1ea1492008-09-24 05:32:41 +00002798
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002799 // If we have no uses, recursively delete the value and all dead instructions
2800 // using it.
Owen Andersondfb8c3b2010-11-19 22:15:03 +00002801 if (Repl->use_empty()) {
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002802 // This can cause recursive deletion, which can invalidate our iterator.
2803 // Use a WeakVH to hold onto it in case this happens.
2804 WeakVH IterHandle(CurInstIterator);
2805 BasicBlock *BB = CurInstIterator->getParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00002806
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002807 RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
Chris Lattneraf1bcce2011-04-09 07:05:44 +00002808
2809 if (IterHandle != CurInstIterator) {
2810 // If the iterator instruction was recursively deleted, start over at the
2811 // start of the block.
2812 CurInstIterator = BB->begin();
2813 SunkAddrs.clear();
Nadav Rotem465834c2012-07-24 10:51:42 +00002814 }
Dale Johannesenb67a6e662010-03-31 20:37:15 +00002815 }
Cameron Zwarichced753f2011-01-05 17:27:27 +00002816 ++NumMemoryInsts;
Chris Lattnerfeee64e2007-04-13 20:30:56 +00002817 return true;
2818}
2819
Evan Cheng1da25002008-02-26 02:42:37 +00002820/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner728f9022008-11-25 07:09:13 +00002821/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng1da25002008-02-26 02:42:37 +00002822/// possible / profitable.
Chris Lattner7a277142011-01-15 07:14:54 +00002823bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
Evan Cheng1da25002008-02-26 02:42:37 +00002824 bool MadeChange = false;
Evan Cheng1da25002008-02-26 02:42:37 +00002825
Nadav Rotem465834c2012-07-24 10:51:42 +00002826 TargetLowering::AsmOperandInfoVector
Chris Lattner7a277142011-01-15 07:14:54 +00002827 TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002828 unsigned ArgNo = 0;
John Thompson1094c802010-09-13 18:15:37 +00002829 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2830 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00002831
Evan Cheng1da25002008-02-26 02:42:37 +00002832 // Compute the constraint code and ConstraintType to use.
Dale Johannesence97d552010-06-25 21:55:36 +00002833 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng1da25002008-02-26 02:42:37 +00002834
Eli Friedman666bbe32008-02-26 18:37:49 +00002835 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2836 OpInfo.isIndirect) {
Chris Lattner7a277142011-01-15 07:14:54 +00002837 Value *OpVal = CS->getArgOperand(ArgNo++);
Chris Lattneree588de2011-01-15 07:29:01 +00002838 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
Dale Johannesenf95f59a2010-09-16 18:30:55 +00002839 } else if (OpInfo.Type == InlineAsm::isInput)
2840 ArgNo++;
Evan Cheng1da25002008-02-26 02:42:37 +00002841 }
2842
2843 return MadeChange;
2844}
2845
Dan Gohman99429a02009-10-16 20:59:35 +00002846/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2847/// basic block as the load, unless conditions are unfavorable. This allows
2848/// SelectionDAG to fold the extend into the load.
2849///
2850bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2851 // Look for a load being extended.
2852 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2853 if (!LI) return false;
2854
2855 // If they're already in the same block, there's nothing to do.
2856 if (LI->getParent() == I->getParent())
2857 return false;
2858
2859 // If the load has other users and the truncate is not free, this probably
2860 // isn't worthwhile.
2861 if (!LI->hasOneUse() &&
Bob Wilsonb6832a42010-09-22 18:44:56 +00002862 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2863 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson4ddcb6a2010-09-21 21:54:27 +00002864 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohman99429a02009-10-16 20:59:35 +00002865 return false;
2866
2867 // Check whether the target supports casts folded into loads.
2868 unsigned LType;
2869 if (isa<ZExtInst>(I))
2870 LType = ISD::ZEXTLOAD;
2871 else {
2872 assert(isa<SExtInst>(I) && "Unexpected ext type!");
2873 LType = ISD::SEXTLOAD;
2874 }
Patrik Hagglunde98b7a02012-12-11 11:14:33 +00002875 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
Dan Gohman99429a02009-10-16 20:59:35 +00002876 return false;
2877
2878 // Move the extend into the same block as the load, so that SelectionDAG
2879 // can fold it.
2880 I->removeFromParent();
2881 I->insertAfter(LI);
Cameron Zwarichced753f2011-01-05 17:27:27 +00002882 ++NumExtsMoved;
Dan Gohman99429a02009-10-16 20:59:35 +00002883 return true;
2884}
2885
Evan Chengd3d80172007-12-05 23:58:20 +00002886bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2887 BasicBlock *DefBB = I->getParent();
2888
Bob Wilsonff714f92010-09-21 21:44:14 +00002889 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengd3d80172007-12-05 23:58:20 +00002890 // other uses of the source with result of extension.
2891 Value *Src = I->getOperand(0);
2892 if (Src->hasOneUse())
2893 return false;
2894
Evan Cheng2011df42007-12-13 07:50:36 +00002895 // Only do this xform if truncating is free.
Gabor Greifaa261722008-02-26 19:13:21 +00002896 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Cheng37c36ed2007-12-13 03:32:53 +00002897 return false;
2898
Evan Cheng7bc89422007-12-12 00:51:06 +00002899 // Only safe to perform the optimization if the source is also defined in
Evan Cheng63d33cf2007-12-12 02:53:41 +00002900 // this block.
2901 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng7bc89422007-12-12 00:51:06 +00002902 return false;
2903
Evan Chengd3d80172007-12-05 23:58:20 +00002904 bool DefIsLiveOut = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002905 for (User *U : I->users()) {
2906 Instruction *UI = cast<Instruction>(U);
Evan Chengd3d80172007-12-05 23:58:20 +00002907
2908 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002909 BasicBlock *UserBB = UI->getParent();
Evan Chengd3d80172007-12-05 23:58:20 +00002910 if (UserBB == DefBB) continue;
2911 DefIsLiveOut = true;
2912 break;
2913 }
2914 if (!DefIsLiveOut)
2915 return false;
2916
Jim Grosbach0f38c1e2013-04-15 17:40:48 +00002917 // Make sure none of the uses are PHI nodes.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002918 for (User *U : Src->users()) {
2919 Instruction *UI = cast<Instruction>(U);
2920 BasicBlock *UserBB = UI->getParent();
Evan Cheng37c36ed2007-12-13 03:32:53 +00002921 if (UserBB == DefBB) continue;
2922 // Be conservative. We don't want this xform to end up introducing
2923 // reloads just before load / store instructions.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002924 if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
Evan Cheng63d33cf2007-12-12 02:53:41 +00002925 return false;
2926 }
2927
Evan Chengd3d80172007-12-05 23:58:20 +00002928 // InsertedTruncs - Only insert one trunc in each block once.
2929 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2930
2931 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002932 for (Use &U : Src->uses()) {
2933 Instruction *User = cast<Instruction>(U.getUser());
Evan Chengd3d80172007-12-05 23:58:20 +00002934
2935 // Figure out which BB this ext is used in.
2936 BasicBlock *UserBB = User->getParent();
2937 if (UserBB == DefBB) continue;
2938
2939 // Both src and def are live in this block. Rewrite the use.
2940 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2941
2942 if (!InsertedTrunc) {
Bill Wendling8ddfc092011-08-16 20:45:24 +00002943 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
Evan Chengd3d80172007-12-05 23:58:20 +00002944 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
Quentin Colombet3a4bf042014-02-06 21:44:56 +00002945 InsertedTruncsSet.insert(InsertedTrunc);
Evan Chengd3d80172007-12-05 23:58:20 +00002946 }
2947
2948 // Replace a use of the {s|z}ext source with a use of the result.
Chandler Carruthcdf47882014-03-09 03:16:01 +00002949 U = InsertedTrunc;
Cameron Zwarichced753f2011-01-05 17:27:27 +00002950 ++NumExtUses;
Evan Chengd3d80172007-12-05 23:58:20 +00002951 MadeChange = true;
2952 }
2953
2954 return MadeChange;
2955}
2956
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002957/// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2958/// turned into an explicit branch.
2959static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2960 // FIXME: This should use the same heuristics as IfConversion to determine
2961 // whether a select is better represented as a branch. This requires that
2962 // branch probability metadata is preserved for the select, which is not the
2963 // case currently.
2964
2965 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2966
2967 // If the branch is predicted right, an out of order CPU can avoid blocking on
2968 // the compare. Emit cmovs on compares with a memory operand as branches to
2969 // avoid stalls on the load from memory. If the compare has more than one use
2970 // there's probably another cmov or setcc around so it's not worth emitting a
2971 // branch.
2972 if (!Cmp)
2973 return false;
2974
2975 Value *CmpOp0 = Cmp->getOperand(0);
2976 Value *CmpOp1 = Cmp->getOperand(1);
2977
2978 // We check that the memory operand has one use to avoid uses of the loaded
2979 // value directly after the compare, making branches unprofitable.
2980 return Cmp->hasOneUse() &&
2981 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2982 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2983}
2984
2985
Nadav Rotem9d832022012-09-02 12:10:19 +00002986/// If we have a SelectInst that will likely profit from branch prediction,
2987/// turn it into a branch.
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002988bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
Nadav Rotem9d832022012-09-02 12:10:19 +00002989 bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2990
2991 // Can we convert the 'select' to CF ?
2992 if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00002993 return false;
2994
Nadav Rotem9d832022012-09-02 12:10:19 +00002995 TargetLowering::SelectSupportKind SelectKind;
2996 if (VectorCond)
2997 SelectKind = TargetLowering::VectorMaskSelect;
2998 else if (SI->getType()->isVectorTy())
2999 SelectKind = TargetLowering::ScalarCondVectorVal;
3000 else
3001 SelectKind = TargetLowering::ScalarValSelect;
3002
3003 // Do we have efficient codegen support for this kind of 'selects' ?
3004 if (TLI->isSelectSupported(SelectKind)) {
3005 // We have efficient codegen support for the select instruction.
3006 // Check if it is profitable to keep this 'select'.
3007 if (!TLI->isPredictableSelectExpensive() ||
3008 !isFormingBranchFromSelectProfitable(SI))
3009 return false;
3010 }
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003011
3012 ModifiedDT = true;
3013
3014 // First, we split the block containing the select into 2 blocks.
3015 BasicBlock *StartBlock = SI->getParent();
3016 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3017 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3018
3019 // Create a new block serving as the landing pad for the branch.
3020 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3021 NextBlock->getParent(), NextBlock);
3022
3023 // Move the unconditional branch from the block with the select in it into our
3024 // landing pad block.
3025 StartBlock->getTerminator()->eraseFromParent();
3026 BranchInst::Create(NextBlock, SmallBlock);
3027
3028 // Insert the real conditional branch based on the original condition.
3029 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3030
3031 // The select itself is replaced with a PHI Node.
3032 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3033 PN->takeName(SI);
3034 PN->addIncoming(SI->getTrueValue(), StartBlock);
3035 PN->addIncoming(SI->getFalseValue(), SmallBlock);
3036 SI->replaceAllUsesWith(PN);
3037 SI->eraseFromParent();
3038
3039 // Instruct OptimizeBlock to skip to the next block.
3040 CurInstIterator = StartBlock->end();
3041 ++NumSelectsExpanded;
3042 return true;
3043}
3044
Benjamin Kramer573ff362014-03-01 17:24:40 +00003045static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
Tim Northoveraeb8e062014-02-19 10:02:43 +00003046 SmallVector<int, 16> Mask(SVI->getShuffleMask());
3047 int SplatElem = -1;
3048 for (unsigned i = 0; i < Mask.size(); ++i) {
3049 if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3050 return false;
3051 SplatElem = Mask[i];
3052 }
3053
3054 return true;
3055}
3056
3057/// Some targets have expensive vector shifts if the lanes aren't all the same
3058/// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3059/// it's often worth sinking a shufflevector splat down to its use so that
3060/// codegen can spot all lanes are identical.
3061bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3062 BasicBlock *DefBB = SVI->getParent();
3063
3064 // Only do this xform if variable vector shifts are particularly expensive.
3065 if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3066 return false;
3067
3068 // We only expect better codegen by sinking a shuffle if we can recognise a
3069 // constant splat.
3070 if (!isBroadcastShuffle(SVI))
3071 return false;
3072
3073 // InsertedShuffles - Only insert a shuffle in each block once.
3074 DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3075
3076 bool MadeChange = false;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003077 for (User *U : SVI->users()) {
3078 Instruction *UI = cast<Instruction>(U);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003079
3080 // Figure out which BB this ext is used in.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003081 BasicBlock *UserBB = UI->getParent();
Tim Northoveraeb8e062014-02-19 10:02:43 +00003082 if (UserBB == DefBB) continue;
3083
3084 // For now only apply this when the splat is used by a shift instruction.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003085 if (!UI->isShift()) continue;
Tim Northoveraeb8e062014-02-19 10:02:43 +00003086
3087 // Everything checks out, sink the shuffle if the user's block doesn't
3088 // already have a copy.
3089 Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3090
3091 if (!InsertedShuffle) {
3092 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3093 InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3094 SVI->getOperand(1),
3095 SVI->getOperand(2), "", InsertPt);
3096 }
3097
Chandler Carruthcdf47882014-03-09 03:16:01 +00003098 UI->replaceUsesOfWith(SVI, InsertedShuffle);
Tim Northoveraeb8e062014-02-19 10:02:43 +00003099 MadeChange = true;
3100 }
3101
3102 // If we removed all uses, nuke the shuffle.
3103 if (SVI->use_empty()) {
3104 SVI->eraseFromParent();
3105 MadeChange = true;
3106 }
3107
3108 return MadeChange;
3109}
3110
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003111bool CodeGenPrepare::OptimizeInst(Instruction *I) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003112 if (PHINode *P = dyn_cast<PHINode>(I)) {
3113 // It is possible for very late stage optimizations (such as SimplifyCFG)
3114 // to introduce PHI nodes too late to be cleaned up. If we detect such a
3115 // trivial PHI, go ahead and zap it here.
Craig Topperc0196b12014-04-14 00:51:57 +00003116 if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
Benjamin Kramer30d249a2013-09-24 16:37:40 +00003117 TLInfo, DT)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003118 P->replaceAllUsesWith(V);
3119 P->eraseFromParent();
3120 ++NumPHIsElim;
Chris Lattneree588de2011-01-15 07:29:01 +00003121 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003122 }
Chris Lattneree588de2011-01-15 07:29:01 +00003123 return false;
3124 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003125
Chris Lattneree588de2011-01-15 07:29:01 +00003126 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003127 // If the source of the cast is a constant, then this should have
3128 // already been constant folded. The only reason NOT to constant fold
3129 // it is if something (e.g. LSR) was careful to place the constant
3130 // evaluation in a block other than then one that uses it (e.g. to hoist
3131 // the address of globals out of a loop). If this is the case, we don't
3132 // want to forward-subst the cast.
3133 if (isa<Constant>(CI->getOperand(0)))
3134 return false;
3135
Chris Lattneree588de2011-01-15 07:29:01 +00003136 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3137 return true;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003138
Chris Lattneree588de2011-01-15 07:29:01 +00003139 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
Manuel Jacoba7c48f92014-03-13 13:36:25 +00003140 /// Sink a zext or sext into its user blocks if the target type doesn't
3141 /// fit in one register
3142 if (TLI && TLI->getTypeAction(CI->getContext(),
3143 TLI->getValueType(CI->getType())) ==
3144 TargetLowering::TypeExpandInteger) {
3145 return SinkCast(CI);
3146 } else {
3147 bool MadeChange = MoveExtToFormExtLoad(I);
3148 return MadeChange | OptimizeExtUses(I);
3149 }
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003150 }
Chris Lattneree588de2011-01-15 07:29:01 +00003151 return false;
3152 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003153
Chris Lattneree588de2011-01-15 07:29:01 +00003154 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Hal Finkeldecb0242014-01-02 21:13:43 +00003155 if (!TLI || !TLI->hasMultipleConditionRegisters())
3156 return OptimizeCmpExpression(CI);
Nadav Rotem465834c2012-07-24 10:51:42 +00003157
Chris Lattneree588de2011-01-15 07:29:01 +00003158 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003159 if (TLI)
Hans Wennborgf3254832012-10-30 11:23:25 +00003160 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3161 return false;
Chris Lattneree588de2011-01-15 07:29:01 +00003162 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003163
Chris Lattneree588de2011-01-15 07:29:01 +00003164 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003165 if (TLI)
Chris Lattneree588de2011-01-15 07:29:01 +00003166 return OptimizeMemoryInst(I, SI->getOperand(1),
3167 SI->getOperand(0)->getType());
3168 return false;
3169 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003170
Yi Jiangd069f632014-04-21 19:34:27 +00003171 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3172
3173 if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3174 BinOp->getOpcode() == Instruction::LShr)) {
3175 ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3176 if (TLI && CI && TLI->hasExtractBitsInsn())
3177 return OptimizeExtractBits(BinOp, CI, *TLI);
3178
3179 return false;
3180 }
3181
Chris Lattneree588de2011-01-15 07:29:01 +00003182 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003183 if (GEPI->hasAllZeroIndices()) {
3184 /// The GEP operand must be a pointer, so must its result -> BitCast
3185 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3186 GEPI->getName(), GEPI);
3187 GEPI->replaceAllUsesWith(NC);
3188 GEPI->eraseFromParent();
3189 ++NumGEPsElim;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003190 OptimizeInst(NC);
Chris Lattneree588de2011-01-15 07:29:01 +00003191 return true;
Cameron Zwarichd28c78e2011-01-06 02:44:52 +00003192 }
Chris Lattneree588de2011-01-15 07:29:01 +00003193 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003194 }
Nadav Rotem465834c2012-07-24 10:51:42 +00003195
Chris Lattneree588de2011-01-15 07:29:01 +00003196 if (CallInst *CI = dyn_cast<CallInst>(I))
3197 return OptimizeCallInst(CI);
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003198
Benjamin Kramer047d7ca2012-05-05 12:49:22 +00003199 if (SelectInst *SI = dyn_cast<SelectInst>(I))
3200 return OptimizeSelectInst(SI);
3201
Tim Northoveraeb8e062014-02-19 10:02:43 +00003202 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3203 return OptimizeShuffleVectorInst(SVI);
3204
Chris Lattneree588de2011-01-15 07:29:01 +00003205 return false;
Cameron Zwarich14ac8652011-01-06 02:37:26 +00003206}
3207
Chris Lattnerf2836d12007-03-31 04:06:36 +00003208// In this pass we look for GEP and cast instructions that are used
3209// across basic blocks and rewrite them to improve basic-block-at-a-time
3210// selection.
3211bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
Cameron Zwarichce3b9302011-01-06 00:42:50 +00003212 SunkAddrs.clear();
Cameron Zwarich5dd2aa22011-03-02 03:31:46 +00003213 bool MadeChange = false;
Eric Christopherc1ea1492008-09-24 05:32:41 +00003214
Chris Lattner7a277142011-01-15 07:14:54 +00003215 CurInstIterator = BB.begin();
Hans Wennborg02fbc712012-09-19 07:48:16 +00003216 while (CurInstIterator != BB.end())
Chris Lattner1b93be52011-01-15 07:25:29 +00003217 MadeChange |= OptimizeInst(CurInstIterator++);
Eric Christopherc1ea1492008-09-24 05:32:41 +00003218
Benjamin Kramer455fa352012-11-23 19:17:06 +00003219 MadeChange |= DupRetToEnableTailCallOpts(&BB);
3220
Chris Lattnerf2836d12007-03-31 04:06:36 +00003221 return MadeChange;
3222}
Devang Patel53771ba2011-08-18 00:50:51 +00003223
3224// llvm.dbg.value is far away from the value then iSel may not be able
Nadav Rotem465834c2012-07-24 10:51:42 +00003225// handle it properly. iSel will drop llvm.dbg.value if it can not
Devang Patel53771ba2011-08-18 00:50:51 +00003226// find a node corresponding to the value.
3227bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3228 bool MadeChange = false;
3229 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
Craig Topperc0196b12014-04-14 00:51:57 +00003230 Instruction *PrevNonDbgInst = nullptr;
Devang Patel53771ba2011-08-18 00:50:51 +00003231 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3232 Instruction *Insn = BI; ++BI;
3233 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
Adrian Prantl32da8892014-04-25 20:49:25 +00003234 // Leave dbg.values that refer to an alloca alone. These
3235 // instrinsics describe the address of a variable (= the alloca)
3236 // being taken. They should not be moved next to the alloca
3237 // (and to the beginning of the scope), but rather stay close to
3238 // where said address is used.
3239 if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
Devang Patel53771ba2011-08-18 00:50:51 +00003240 PrevNonDbgInst = Insn;
3241 continue;
3242 }
3243
3244 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3245 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3246 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3247 DVI->removeFromParent();
3248 if (isa<PHINode>(VI))
3249 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3250 else
3251 DVI->insertAfter(VI);
3252 MadeChange = true;
3253 ++NumDbgValueMoved;
3254 }
3255 }
3256 }
3257 return MadeChange;
3258}
Tim Northovercea0abb2014-03-29 08:22:29 +00003259
3260// If there is a sequence that branches based on comparing a single bit
3261// against zero that can be combined into a single instruction, and the
3262// target supports folding these into a single instruction, sink the
3263// mask and compare into the branch uses. Do this before OptimizeBlock ->
3264// OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3265// searched for.
3266bool CodeGenPrepare::sinkAndCmp(Function &F) {
3267 if (!EnableAndCmpSinking)
3268 return false;
3269 if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3270 return false;
3271 bool MadeChange = false;
3272 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3273 BasicBlock *BB = I++;
3274
3275 // Does this BB end with the following?
3276 // %andVal = and %val, #single-bit-set
3277 // %icmpVal = icmp %andResult, 0
3278 // br i1 %cmpVal label %dest1, label %dest2"
3279 BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3280 if (!Brcc || !Brcc->isConditional())
3281 continue;
3282 ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3283 if (!Cmp || Cmp->getParent() != BB)
3284 continue;
3285 ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3286 if (!Zero || !Zero->isZero())
3287 continue;
3288 Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3289 if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3290 continue;
3291 ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3292 if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3293 continue;
3294 DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3295
3296 // Push the "and; icmp" for any users that are conditional branches.
3297 // Since there can only be one branch use per BB, we don't need to keep
3298 // track of which BBs we insert into.
3299 for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3300 UI != E; ) {
3301 Use &TheUse = *UI;
3302 // Find brcc use.
3303 BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3304 ++UI;
3305 if (!BrccUser || !BrccUser->isConditional())
3306 continue;
3307 BasicBlock *UserBB = BrccUser->getParent();
3308 if (UserBB == BB) continue;
3309 DEBUG(dbgs() << "found Brcc use\n");
3310
3311 // Sink the "and; icmp" to use.
3312 MadeChange = true;
3313 BinaryOperator *NewAnd =
3314 BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3315 BrccUser);
3316 CmpInst *NewCmp =
3317 CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3318 "", BrccUser);
3319 TheUse = NewCmp;
3320 ++NumAndCmpsMoved;
3321 DEBUG(BrccUser->getParent()->dump());
3322 }
3323 }
3324 return MadeChange;
3325}