blob: 3221e143476048b1b55bf90d22e0b916e45e4821 [file] [log] [blame]
Chris Lattnerdbe0dec2007-03-31 04:06:36 +00001//===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Lattnerdbe0dec2007-03-31 04:06:36 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
Gordon Henriksena8a118b2008-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 Lattnerdbe0dec2007-03-31 04:06:36 +000013//
14//===----------------------------------------------------------------------===//
15
16#define DEBUG_TYPE "codegenprepare"
17#include "llvm/Transforms/Scalar.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000021#include "llvm/InlineAsm.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000022#include "llvm/Instructions.h"
Dale Johannesen6aae1d62009-03-26 01:15:07 +000023#include "llvm/IntrinsicInst.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000024#include "llvm/Pass.h"
Andreas Neustifterad809812009-09-16 09:26:52 +000025#include "llvm/Analysis/ProfileInfo.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetLowering.h"
Evan Chenga1fd5b32009-02-20 18:24:38 +000028#include "llvm/Transforms/Utils/AddrModeMatcher.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000030#include "llvm/Transforms/Utils/Local.h"
Eric Christopher040056f2010-03-11 02:41:03 +000031#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000032#include "llvm/ADT/DenseMap.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000033#include "llvm/ADT/SmallSet.h"
Dan Gohman03ce0422009-02-13 17:45:12 +000034#include "llvm/Assembly/Writer.h"
Evan Cheng9bf12b52008-02-26 02:42:37 +000035#include "llvm/Support/CallSite.h"
Evan Chenge1bcb442010-08-17 01:34:49 +000036#include "llvm/Support/CommandLine.h"
Evan Chengbdcb7262007-12-05 23:58:20 +000037#include "llvm/Support/Debug.h"
Chris Lattnerdd77df32007-04-13 20:30:56 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner088a1e82008-11-25 04:42:10 +000039#include "llvm/Support/PatternMatch.h"
Dan Gohman6c1980b2009-07-25 01:13:51 +000040#include "llvm/Support/raw_ostream.h"
Eric Christopher040056f2010-03-11 02:41:03 +000041#include "llvm/Support/IRBuilder.h"
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000042using namespace llvm;
Chris Lattner088a1e82008-11-25 04:42:10 +000043using namespace llvm::PatternMatch;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000044
Evan Chenge1bcb442010-08-17 01:34:49 +000045static cl::opt<bool>
46CriticalEdgeSplit("cgp-critical-edge-splitting",
47 cl::desc("Split critical edges during codegen prepare"),
48 cl::init(true), cl::Hidden);
49
Eric Christopher692bf6b2008-09-24 05:32:41 +000050namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000051 class CodeGenPrepare : public FunctionPass {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000052 /// TLI - Keep a pointer of a TargetLowering to consult for determining
53 /// transformation profitability.
54 const TargetLowering *TLI;
Evan Cheng04149f72009-12-17 09:39:49 +000055 ProfileInfo *PFI;
Evan Chengab631522008-12-19 18:03:11 +000056
57 /// BackEdges - Keep a set of all the loop back edges.
58 ///
Mike Stumpfe095f32009-05-04 18:40:41 +000059 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000060 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000061 static char ID; // Pass identification, replacement for typeid
Dan Gohmanc2bbfc12007-08-01 15:32:29 +000062 explicit CodeGenPrepare(const TargetLowering *tli = 0)
Owen Anderson90c579d2010-08-06 18:33:48 +000063 : FunctionPass(ID), TLI(tli) {}
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000064 bool runOnFunction(Function &F);
Eric Christopher692bf6b2008-09-24 05:32:41 +000065
Andreas Neustifterad809812009-09-16 09:26:52 +000066 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
67 AU.addPreserved<ProfileInfo>();
68 }
69
Dan Gohmanaa0e5232010-02-05 19:24:11 +000070 virtual void releaseMemory() {
71 BackEdges.clear();
72 }
73
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000074 private:
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +000075 bool EliminateMostlyEmptyBlocks(Function &F);
76 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
77 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000078 bool OptimizeBlock(BasicBlock &BB);
Chris Lattner88a5c832008-11-25 07:09:13 +000079 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
80 DenseMap<Value*,Value*> &SunkAddrs);
Evan Cheng9bf12b52008-02-26 02:42:37 +000081 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
82 DenseMap<Value*,Value*> &SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +000083 bool OptimizeCallInst(CallInst *CI);
Dan Gohmanb00f2362009-10-16 20:59:35 +000084 bool MoveExtToFormExtLoad(Instruction *I);
Evan Chengbdcb7262007-12-05 23:58:20 +000085 bool OptimizeExtUses(Instruction *I);
Mike Stumpfe095f32009-05-04 18:40:41 +000086 void findLoopBackEdges(const Function &F);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000087 };
88}
Devang Patel794fd752007-05-01 21:15:47 +000089
Devang Patel19974732007-05-03 01:11:54 +000090char CodeGenPrepare::ID = 0;
Owen Andersond13db2c2010-07-21 22:09:45 +000091INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
92 "Optimize for code generation", false, false);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +000093
94FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
95 return new CodeGenPrepare(TLI);
96}
97
Evan Chengab631522008-12-19 18:03:11 +000098/// findLoopBackEdges - Do a DFS walk to find loop back edges.
99///
Mike Stumpfe095f32009-05-04 18:40:41 +0000100void CodeGenPrepare::findLoopBackEdges(const Function &F) {
101 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
102 FindFunctionBackedges(F, Edges);
103
104 BackEdges.insert(Edges.begin(), Edges.end());
Evan Chengab631522008-12-19 18:03:11 +0000105}
106
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000107
108bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000109 bool EverMadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000110
Evan Cheng04149f72009-12-17 09:39:49 +0000111 PFI = getAnalysisIfAvailable<ProfileInfo>();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000112 // First pass, eliminate blocks that contain only PHI nodes and an
113 // unconditional branch.
114 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000115
Evan Cheng7e66c0d2009-01-05 21:17:27 +0000116 // Now find loop back edges.
117 findLoopBackEdges(F);
118
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000119 bool MadeChange = true;
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000120 while (MadeChange) {
121 MadeChange = false;
122 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
123 MadeChange |= OptimizeBlock(*BB);
124 EverMadeChange |= MadeChange;
125 }
126 return EverMadeChange;
127}
128
Dale Johannesen2d697242009-03-27 01:13:37 +0000129/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
130/// debug info directives, and an unconditional branch. Passes before isel
131/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
132/// isel. Start by eliminating these blocks so we can split them the way we
133/// want them.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000134bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
135 bool MadeChange = false;
136 // Note that this intentionally skips the entry block.
137 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
138 BasicBlock *BB = I++;
139
140 // If this block doesn't end with an uncond branch, ignore it.
141 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
142 if (!BI || !BI->isUnconditional())
143 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000144
Dale Johannesen2d697242009-03-27 01:13:37 +0000145 // If the instruction before the branch (skipping debug info) isn't a phi
146 // node, then other stuff is happening here.
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000147 BasicBlock::iterator BBI = BI;
148 if (BBI != BB->begin()) {
149 --BBI;
Dale Johannesen2d697242009-03-27 01:13:37 +0000150 while (isa<DbgInfoIntrinsic>(BBI)) {
151 if (BBI == BB->begin())
152 break;
153 --BBI;
154 }
155 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
156 continue;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000157 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000158
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000159 // Do not break infinite loops.
160 BasicBlock *DestBB = BI->getSuccessor(0);
161 if (DestBB == BB)
162 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000163
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000164 if (!CanMergeBlocks(BB, DestBB))
165 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000166
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000167 EliminateMostlyEmptyBlock(BB);
168 MadeChange = true;
169 }
170 return MadeChange;
171}
172
173/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
174/// single uncond branch between them, and BB contains no other non-phi
175/// instructions.
176bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
177 const BasicBlock *DestBB) const {
178 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
179 // the successor. If there are more complex condition (e.g. preheaders),
180 // don't mess around with them.
181 BasicBlock::const_iterator BBI = BB->begin();
182 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
Gabor Greif60ad7812010-03-25 23:06:16 +0000183 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000184 UI != E; ++UI) {
185 const Instruction *User = cast<Instruction>(*UI);
186 if (User->getParent() != DestBB || !isa<PHINode>(User))
187 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000188 // If User is inside DestBB block and it is a PHINode then check
189 // incoming value. If incoming value is not from BB then this is
Devang Patel75abc1e2007-04-25 00:37:04 +0000190 // a complex condition (e.g. preheaders) we want to avoid here.
191 if (User->getParent() == DestBB) {
192 if (const PHINode *UPN = dyn_cast<PHINode>(User))
193 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
194 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
195 if (Insn && Insn->getParent() == BB &&
196 Insn->getParent() != UPN->getIncomingBlock(I))
197 return false;
198 }
199 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000200 }
201 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000202
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000203 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
204 // and DestBB may have conflicting incoming values for the block. If so, we
205 // can't merge the block.
206 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
207 if (!DestBBPN) return true; // no conflict.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000208
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000209 // Collect the preds of BB.
Chris Lattnerf67f73a2007-11-06 22:07:40 +0000210 SmallPtrSet<const BasicBlock*, 16> BBPreds;
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000211 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
212 // It is faster to get preds from a PHI than with pred_iterator.
213 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
214 BBPreds.insert(BBPN->getIncomingBlock(i));
215 } else {
216 BBPreds.insert(pred_begin(BB), pred_end(BB));
217 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000218
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000219 // Walk the preds of DestBB.
220 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
221 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
222 if (BBPreds.count(Pred)) { // Common predecessor?
223 BBI = DestBB->begin();
224 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
225 const Value *V1 = PN->getIncomingValueForBlock(Pred);
226 const Value *V2 = PN->getIncomingValueForBlock(BB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000227
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000228 // If V2 is a phi node in BB, look up what the mapped value will be.
229 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
230 if (V2PN->getParent() == BB)
231 V2 = V2PN->getIncomingValueForBlock(Pred);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000232
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000233 // If there is a conflict, bail out.
234 if (V1 != V2) return false;
235 }
236 }
237 }
238
239 return true;
240}
241
242
243/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
244/// an unconditional branch in it.
245void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
246 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
247 BasicBlock *DestBB = BI->getSuccessor(0);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000248
David Greene68d67fd2010-01-05 01:27:11 +0000249 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000250
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000251 // If the destination block has a single pred, then this is a trivial edge,
252 // just collapse it.
Chris Lattner9918fb52008-11-27 19:29:14 +0000253 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
Chris Lattnerf5102a02008-11-28 19:54:49 +0000254 if (SinglePred != DestBB) {
255 // Remember if SinglePred was the entry block of the function. If so, we
256 // will need to move BB back to the entry position.
257 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
Andreas Neustifterad809812009-09-16 09:26:52 +0000258 MergeBasicBlockIntoOnlyPred(DestBB, this);
Chris Lattner9918fb52008-11-27 19:29:14 +0000259
Chris Lattnerf5102a02008-11-28 19:54:49 +0000260 if (isEntry && BB != &BB->getParent()->getEntryBlock())
261 BB->moveBefore(&BB->getParent()->getEntryBlock());
262
David Greene68d67fd2010-01-05 01:27:11 +0000263 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerf5102a02008-11-28 19:54:49 +0000264 return;
265 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000266 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000267
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000268 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
269 // to handle the new incoming edges it is about to have.
270 PHINode *PN;
271 for (BasicBlock::iterator BBI = DestBB->begin();
272 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
273 // Remove the incoming value for BB, and remember it.
274 Value *InVal = PN->removeIncomingValue(BB, false);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000275
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000276 // Two options: either the InVal is a phi node defined in BB or it is some
277 // value that dominates BB.
278 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
279 if (InValPhi && InValPhi->getParent() == BB) {
280 // Add all of the input values of the input PHI as inputs of this phi.
281 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
282 PN->addIncoming(InValPhi->getIncomingValue(i),
283 InValPhi->getIncomingBlock(i));
284 } else {
285 // Otherwise, add one instance of the dominating value for each edge that
286 // we will be adding.
287 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
288 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
289 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
290 } else {
291 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
292 PN->addIncoming(InVal, *PI);
293 }
294 }
295 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000296
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000297 // The PHIs are now updated, change everything that refers to BB to use
298 // DestBB and remove BB.
299 BB->replaceAllUsesWith(DestBB);
Evan Cheng04149f72009-12-17 09:39:49 +0000300 if (PFI) {
301 PFI->replaceAllUses(BB, DestBB);
302 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
Andreas Neustifterad809812009-09-16 09:26:52 +0000303 }
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000304 BB->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000305
David Greene68d67fd2010-01-05 01:27:11 +0000306 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000307}
308
Chris Lattner98d5c312010-02-13 05:35:08 +0000309/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
310/// lives in to see if there is a block that we can reuse as a critical edge
311/// from TIBB.
312static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
313 BasicBlock *Dest = DestPHI->getParent();
314
315 /// TIPHIValues - This array is lazily computed to determine the values of
316 /// PHIs in Dest that TI would provide.
317 SmallVector<Value*, 32> TIPHIValues;
318
319 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
320 unsigned TIBBEntryNo = 0;
321
322 // Check to see if Dest has any blocks that can be used as a split edge for
323 // this terminator.
324 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
325 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
326 // To be usable, the pred has to end with an uncond branch to the dest.
327 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
328 if (!PredBr || !PredBr->isUnconditional())
329 continue;
330 // Must be empty other than the branch and debug info.
331 BasicBlock::iterator I = Pred->begin();
332 while (isa<DbgInfoIntrinsic>(I))
333 I++;
334 if (&*I != PredBr)
335 continue;
336 // Cannot be the entry block; its label does not get emitted.
337 if (Pred == &Dest->getParent()->getEntryBlock())
338 continue;
339
340 // Finally, since we know that Dest has phi nodes in it, we have to make
341 // sure that jumping to Pred will have the same effect as going to Dest in
342 // terms of PHI values.
343 PHINode *PN;
344 unsigned PHINo = 0;
345 unsigned PredEntryNo = pi;
346
347 bool FoundMatch = true;
348 for (BasicBlock::iterator I = Dest->begin();
349 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
350 if (PHINo == TIPHIValues.size()) {
351 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
352 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
353 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
354 }
355
356 // If the PHI entry doesn't work, we can't use this pred.
357 if (PN->getIncomingBlock(PredEntryNo) != Pred)
358 PredEntryNo = PN->getBasicBlockIndex(Pred);
359
360 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
361 FoundMatch = false;
362 break;
363 }
364 }
365
366 // If we found a workable predecessor, change TI to branch to Succ.
367 if (FoundMatch)
368 return Pred;
369 }
370 return 0;
371}
372
Chris Lattnerd9c3a0d2007-04-02 01:35:34 +0000373
Chris Lattnerebe80752007-12-24 19:32:55 +0000374/// SplitEdgeNicely - Split the critical edge from TI to its specified
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000375/// successor if it will improve codegen. We only do this if the successor has
376/// phi nodes (otherwise critical edges are ok). If there is already another
377/// predecessor of the succ that is empty (and thus has no phi nodes), use it
378/// instead of introducing a new block.
Evan Chengab631522008-12-19 18:03:11 +0000379static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
Mike Stumpfe095f32009-05-04 18:40:41 +0000380 SmallSet<std::pair<const BasicBlock*,
381 const BasicBlock*>, 8> &BackEdges,
Evan Chengab631522008-12-19 18:03:11 +0000382 Pass *P) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000383 BasicBlock *TIBB = TI->getParent();
384 BasicBlock *Dest = TI->getSuccessor(SuccNum);
385 assert(isa<PHINode>(Dest->begin()) &&
386 "This should only be called if Dest has a PHI!");
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000387 PHINode *DestPHI = cast<PHINode>(Dest->begin());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000388
Evan Chengfc0b80d2009-03-13 22:59:14 +0000389 // Do not split edges to EH landing pads.
Chris Lattner3f65b5e2010-02-13 04:04:42 +0000390 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
Evan Chengfc0b80d2009-03-13 22:59:14 +0000391 if (Invoke->getSuccessor(1) == Dest)
392 return;
Evan Chengfc0b80d2009-03-13 22:59:14 +0000393
Chris Lattnerebe80752007-12-24 19:32:55 +0000394 // As a hack, never split backedges of loops. Even though the copy for any
395 // PHIs inserted on the backedge would be dead for exits from the loop, we
396 // assume that the cost of *splitting* the backedge would be too high.
Evan Chengab631522008-12-19 18:03:11 +0000397 if (BackEdges.count(std::make_pair(TIBB, Dest)))
Chris Lattnerebe80752007-12-24 19:32:55 +0000398 return;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000399
Chris Lattnerc09687b2010-02-13 19:07:06 +0000400 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
401 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
402 if (PFI)
403 PFI->splitEdge(TIBB, Dest, ReuseBB);
404 Dest->removePredecessor(TIBB);
405 TI->setSuccessor(SuccNum, ReuseBB);
Evan Chengab631522008-12-19 18:03:11 +0000406 return;
407 }
408
Chris Lattnerc09687b2010-02-13 19:07:06 +0000409 SplitCriticalEdge(TI, SuccNum, P, true);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000410}
411
Evan Chengab631522008-12-19 18:03:11 +0000412
Chris Lattnerdd77df32007-04-13 20:30:56 +0000413/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
Dan Gohmana119de82009-06-14 23:30:43 +0000414/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
415/// sink it into user blocks to reduce the number of virtual
Dale Johannesence0b2372007-06-12 16:50:17 +0000416/// registers that must be created and coalesced.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000417///
418/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000419///
Chris Lattnerdd77df32007-04-13 20:30:56 +0000420static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
Eric Christopher692bf6b2008-09-24 05:32:41 +0000421 // If this is a noop copy,
Owen Andersone50ed302009-08-10 22:56:29 +0000422 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
423 EVT DstVT = TLI.getValueType(CI->getType());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000424
Chris Lattnerdd77df32007-04-13 20:30:56 +0000425 // This is an fp<->int conversion?
Duncan Sands83ec4b62008-06-06 12:08:01 +0000426 if (SrcVT.isInteger() != DstVT.isInteger())
Chris Lattnerdd77df32007-04-13 20:30:56 +0000427 return false;
Duncan Sands8e4eb092008-06-08 20:54:56 +0000428
Chris Lattnerdd77df32007-04-13 20:30:56 +0000429 // If this is an extension, it will be a zero or sign extension, which
430 // isn't a noop.
Duncan Sands8e4eb092008-06-08 20:54:56 +0000431 if (SrcVT.bitsLT(DstVT)) return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000432
Chris Lattnerdd77df32007-04-13 20:30:56 +0000433 // If these values will be promoted, find out what they will be promoted
434 // to. This helps us consider truncates on PPC as noop copies when they
435 // are.
Chris Lattneraafe6262010-08-25 23:00:45 +0000436 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000437 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
Chris Lattneraafe6262010-08-25 23:00:45 +0000438 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
Owen Anderson23b9b192009-08-12 00:36:31 +0000439 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000440
Chris Lattnerdd77df32007-04-13 20:30:56 +0000441 // If, after promotion, these are the same types, this is a noop copy.
442 if (SrcVT != DstVT)
443 return false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000444
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000445 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000446
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000447 /// InsertedCasts - Only insert a cast in each block once.
Dale Johannesence0b2372007-06-12 16:50:17 +0000448 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000449
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000450 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000451 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000452 UI != E; ) {
453 Use &TheUse = UI.getUse();
454 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000455
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000456 // Figure out which BB this cast is used in. For PHI's this is the
457 // appropriate predecessor block.
458 BasicBlock *UserBB = User->getParent();
459 if (PHINode *PN = dyn_cast<PHINode>(User)) {
Gabor Greifa36791d2009-01-23 19:40:15 +0000460 UserBB = PN->getIncomingBlock(UI);
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000461 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000462
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000463 // Preincrement use iterator so we don't invalidate it.
464 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000465
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000466 // If this user is in the same block as the cast, don't change the cast.
467 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000468
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000469 // If we have already inserted a cast into this block, use it.
470 CastInst *&InsertedCast = InsertedCasts[UserBB];
471
472 if (!InsertedCast) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000473 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000474
475 InsertedCast =
476 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000477 InsertPt);
478 MadeChange = true;
479 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000480
Dale Johannesence0b2372007-06-12 16:50:17 +0000481 // Replace a use of the cast with a use of the new cast.
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000482 TheUse = InsertedCast;
483 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000484
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000485 // If we removed all uses, nuke the cast.
Duncan Sandse0038132008-01-20 16:51:46 +0000486 if (CI->use_empty()) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000487 CI->eraseFromParent();
Duncan Sandse0038132008-01-20 16:51:46 +0000488 MadeChange = true;
489 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000490
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000491 return MadeChange;
492}
493
Eric Christopher692bf6b2008-09-24 05:32:41 +0000494/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
Dale Johannesence0b2372007-06-12 16:50:17 +0000495/// the number of virtual registers that must be created and coalesced. This is
Chris Lattner684b22d2007-08-02 16:53:43 +0000496/// a clear win except on targets with multiple condition code registers
497/// (PowerPC), where it might lose; some adjustment may be wanted there.
Dale Johannesence0b2372007-06-12 16:50:17 +0000498///
499/// Return true if any changes are made.
Chris Lattner85fa13c2008-11-24 22:44:16 +0000500static bool OptimizeCmpExpression(CmpInst *CI) {
Dale Johannesence0b2372007-06-12 16:50:17 +0000501 BasicBlock *DefBB = CI->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000502
Dale Johannesence0b2372007-06-12 16:50:17 +0000503 /// InsertedCmp - Only insert a cmp in each block once.
504 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000505
Dale Johannesence0b2372007-06-12 16:50:17 +0000506 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000507 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
Dale Johannesence0b2372007-06-12 16:50:17 +0000508 UI != E; ) {
509 Use &TheUse = UI.getUse();
510 Instruction *User = cast<Instruction>(*UI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000511
Dale Johannesence0b2372007-06-12 16:50:17 +0000512 // Preincrement use iterator so we don't invalidate it.
513 ++UI;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000514
Dale Johannesence0b2372007-06-12 16:50:17 +0000515 // Don't bother for PHI nodes.
516 if (isa<PHINode>(User))
517 continue;
518
519 // Figure out which BB this cmp is used in.
520 BasicBlock *UserBB = User->getParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000521
Dale Johannesence0b2372007-06-12 16:50:17 +0000522 // If this user is in the same block as the cmp, don't change the cmp.
523 if (UserBB == DefBB) continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000524
Dale Johannesence0b2372007-06-12 16:50:17 +0000525 // If we have already inserted a cmp into this block, use it.
526 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
527
528 if (!InsertedCmp) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000529 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000530
531 InsertedCmp =
Dan Gohman1c8a23c2009-08-25 23:17:54 +0000532 CmpInst::Create(CI->getOpcode(),
Owen Anderson333c4002009-07-09 23:48:35 +0000533 CI->getPredicate(), CI->getOperand(0),
Dale Johannesence0b2372007-06-12 16:50:17 +0000534 CI->getOperand(1), "", InsertPt);
535 MadeChange = true;
536 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000537
Dale Johannesence0b2372007-06-12 16:50:17 +0000538 // Replace a use of the cmp with a use of the new cmp.
539 TheUse = InsertedCmp;
540 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000541
Dale Johannesence0b2372007-06-12 16:50:17 +0000542 // If we removed all uses, nuke the cmp.
543 if (CI->use_empty())
544 CI->eraseFromParent();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000545
Dale Johannesence0b2372007-06-12 16:50:17 +0000546 return MadeChange;
547}
548
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000549namespace {
550class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
551protected:
552 void replaceCall(Value *With) {
553 CI->replaceAllUsesWith(With);
554 CI->eraseFromParent();
555 }
556 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000557 if (ConstantInt *SizeCI =
558 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
559 return SizeCI->isAllOnesValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000560 return false;
561 }
562};
563} // end anonymous namespace
564
Eric Christopher040056f2010-03-11 02:41:03 +0000565bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
Eric Christopher040056f2010-03-11 02:41:03 +0000566 // Lower all uses of llvm.objectsize.*
567 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
568 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
Gabor Greifde9f5452010-06-24 00:44:01 +0000569 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Eric Christopher040056f2010-03-11 02:41:03 +0000570 const Type *ReturnTy = CI->getType();
571 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
572 CI->replaceAllUsesWith(RetVal);
573 CI->eraseFromParent();
574 return true;
575 }
576
577 // From here on out we're working with named functions.
578 if (CI->getCalledFunction() == 0) return false;
579
580 // We'll need TargetData from here on out.
581 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
582 if (!TD) return false;
583
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000584 // Lower all default uses of _chk calls. This is very similar
585 // to what InstCombineCalls does, but here we are only lowering calls
Eric Christopher040056f2010-03-11 02:41:03 +0000586 // that have the default "don't know" as the objectsize. Anything else
587 // should be left alone.
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000588 CodeGenPrepareFortifiedLibCalls Simplifier;
589 return Simplifier.fold(CI, TD);
Eric Christopher040056f2010-03-11 02:41:03 +0000590}
Chris Lattner88a5c832008-11-25 07:09:13 +0000591//===----------------------------------------------------------------------===//
Chris Lattner88a5c832008-11-25 07:09:13 +0000592// Memory Optimization
593//===----------------------------------------------------------------------===//
594
Chris Lattnerdd77df32007-04-13 20:30:56 +0000595/// IsNonLocalValue - Return true if the specified values are defined in a
596/// different basic block than BB.
597static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
598 if (Instruction *I = dyn_cast<Instruction>(V))
599 return I->getParent() != BB;
600 return false;
601}
602
Bob Wilson4a8ee232009-12-03 21:47:07 +0000603/// OptimizeMemoryInst - Load and Store Instructions often have
Chris Lattnerdd77df32007-04-13 20:30:56 +0000604/// addressing modes that can do significant amounts of computation. As such,
605/// instruction selection will try to get the load or store to do as much
606/// computation as possible for the program. The problem is that isel can only
607/// see within a single block. As such, we sink as much legal addressing mode
608/// stuff into the block as possible.
Chris Lattner88a5c832008-11-25 07:09:13 +0000609///
610/// This method is used to optimize both load/store and inline asms with memory
611/// operands.
Chris Lattner896617b2008-11-26 03:20:37 +0000612bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
Chris Lattner88a5c832008-11-25 07:09:13 +0000613 const Type *AccessTy,
614 DenseMap<Value*,Value*> &SunkAddrs) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000615 // Figure out what addressing mode will be built up for this operation.
616 SmallVector<Instruction*, 16> AddrModeInsts;
Chris Lattner896617b2008-11-26 03:20:37 +0000617 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
618 AddrModeInsts, *TLI);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000619
Chris Lattnerdd77df32007-04-13 20:30:56 +0000620 // Check to see if any of the instructions supersumed by this addr mode are
621 // non-local to I's BB.
622 bool AnyNonLocal = false;
623 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
Chris Lattner896617b2008-11-26 03:20:37 +0000624 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000625 AnyNonLocal = true;
626 break;
627 }
628 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000629
Chris Lattnerdd77df32007-04-13 20:30:56 +0000630 // If all the instructions matched are already in this BB, don't do anything.
631 if (!AnyNonLocal) {
David Greene68d67fd2010-01-05 01:27:11 +0000632 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
Chris Lattnerdd77df32007-04-13 20:30:56 +0000633 return false;
634 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000635
Chris Lattnerdd77df32007-04-13 20:30:56 +0000636 // Insert this computation right after this user. Since our caller is
637 // scanning from the top of the BB to the bottom, reuse of the expr are
638 // guaranteed to happen later.
Chris Lattner896617b2008-11-26 03:20:37 +0000639 BasicBlock::iterator InsertPt = MemoryInst;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000640
Chris Lattnerdd77df32007-04-13 20:30:56 +0000641 // Now that we determined the addressing expression we want to use and know
642 // that we have to sink it into this block. Check to see if we have already
643 // done this for some other load/store instr in this block. If so, reuse the
644 // computation.
645 Value *&SunkAddr = SunkAddrs[Addr];
646 if (SunkAddr) {
David Greene68d67fd2010-01-05 01:27:11 +0000647 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000648 << *MemoryInst);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000649 if (SunkAddr->getType() != Addr->getType())
650 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
651 } else {
David Greene68d67fd2010-01-05 01:27:11 +0000652 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
Dan Gohman6c1980b2009-07-25 01:13:51 +0000653 << *MemoryInst);
Owen Anderson1d0be152009-08-13 21:58:54 +0000654 const Type *IntPtrTy =
655 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
Eric Christopher692bf6b2008-09-24 05:32:41 +0000656
Chris Lattnerdd77df32007-04-13 20:30:56 +0000657 Value *Result = 0;
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000658
659 // Start with the base register. Do this first so that subsequent address
660 // matching finds it last, which will prevent it from trying to match it
661 // as the scaled value in case it happens to be a mul. That would be
662 // problematic if we've sunk a different mul for the scale, because then
663 // we'd end up sinking both muls.
664 if (AddrMode.BaseReg) {
665 Value *V = AddrMode.BaseReg;
Duncan Sands1df98592010-02-16 11:11:14 +0000666 if (V->getType()->isPointerTy())
Dan Gohmand8d0b6a2010-01-19 22:45:06 +0000667 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
668 if (V->getType() != IntPtrTy)
669 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
670 "sunkaddr", InsertPt);
671 Result = V;
672 }
673
674 // Add the scale value.
Chris Lattnerdd77df32007-04-13 20:30:56 +0000675 if (AddrMode.Scale) {
676 Value *V = AddrMode.ScaledReg;
677 if (V->getType() == IntPtrTy) {
678 // done.
Duncan Sands1df98592010-02-16 11:11:14 +0000679 } else if (V->getType()->isPointerTy()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000680 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
681 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
682 cast<IntegerType>(V->getType())->getBitWidth()) {
683 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
684 } else {
685 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
686 }
687 if (AddrMode.Scale != 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000688 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
Owen Andersond672ecb2009-07-03 00:17:18 +0000689 AddrMode.Scale),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000690 "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000691 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000692 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000693 else
694 Result = V;
695 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000696
Chris Lattnerdd77df32007-04-13 20:30:56 +0000697 // Add in the BaseGV if present.
698 if (AddrMode.BaseGV) {
699 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
700 InsertPt);
701 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000702 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000703 else
704 Result = V;
705 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000706
Chris Lattnerdd77df32007-04-13 20:30:56 +0000707 // Add in the Base Offset if present.
708 if (AddrMode.BaseOffs) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000709 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000710 if (Result)
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000711 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000712 else
713 Result = V;
714 }
715
716 if (Result == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +0000717 SunkAddr = Constant::getNullValue(Addr->getType());
Chris Lattnerdd77df32007-04-13 20:30:56 +0000718 else
719 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
720 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000721
Chris Lattner896617b2008-11-26 03:20:37 +0000722 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
Eric Christopher692bf6b2008-09-24 05:32:41 +0000723
Dale Johannesen536d31b2010-03-31 20:37:15 +0000724 if (Addr->use_empty()) {
Chris Lattner3481f242008-11-27 22:57:53 +0000725 RecursivelyDeleteTriviallyDeadInstructions(Addr);
Dale Johannesen536d31b2010-03-31 20:37:15 +0000726 // This address is now available for reassignment, so erase the table entry;
727 // we don't want to match some completely different instruction.
728 SunkAddrs[Addr] = 0;
729 }
Chris Lattnerdd77df32007-04-13 20:30:56 +0000730 return true;
731}
732
Evan Cheng9bf12b52008-02-26 02:42:37 +0000733/// OptimizeInlineAsmInst - If there are any memory operands, use
Chris Lattner88a5c832008-11-25 07:09:13 +0000734/// OptimizeMemoryInst to sink their address computing into the block when
Evan Cheng9bf12b52008-02-26 02:42:37 +0000735/// possible / profitable.
736bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
737 DenseMap<Value*,Value*> &SunkAddrs) {
738 bool MadeChange = false;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000739
John Thompsoneac6e1d2010-09-13 18:15:37 +0000740 std::vector<TargetLowering::AsmOperandInfo> TargetConstraints = TLI->ParseConstraints(CS);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000741 unsigned ArgNo = 0;
John Thompsoneac6e1d2010-09-13 18:15:37 +0000742 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
743 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
744
Evan Cheng9bf12b52008-02-26 02:42:37 +0000745 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +0000746 TLI->ComputeConstraintToUse(OpInfo, SDValue());
Evan Cheng9bf12b52008-02-26 02:42:37 +0000747
Eli Friedman9ec80952008-02-26 18:37:49 +0000748 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
749 OpInfo.isIndirect) {
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000750 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Chris Lattner88a5c832008-11-25 07:09:13 +0000751 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
Dale Johannesen677c6ec2010-09-16 18:30:55 +0000752 } else if (OpInfo.Type == InlineAsm::isInput)
753 ArgNo++;
Evan Cheng9bf12b52008-02-26 02:42:37 +0000754 }
755
756 return MadeChange;
757}
758
Dan Gohmanb00f2362009-10-16 20:59:35 +0000759/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
760/// basic block as the load, unless conditions are unfavorable. This allows
761/// SelectionDAG to fold the extend into the load.
762///
763bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
764 // Look for a load being extended.
765 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
766 if (!LI) return false;
767
768 // If they're already in the same block, there's nothing to do.
769 if (LI->getParent() == I->getParent())
770 return false;
771
772 // If the load has other users and the truncate is not free, this probably
773 // isn't worthwhile.
774 if (!LI->hasOneUse() &&
Bob Wilsonec57a1a2010-09-22 18:44:56 +0000775 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
776 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
Bob Wilson71dc4d92010-09-21 21:54:27 +0000777 !TLI->isTruncateFree(I->getType(), LI->getType()))
Dan Gohmanb00f2362009-10-16 20:59:35 +0000778 return false;
779
780 // Check whether the target supports casts folded into loads.
781 unsigned LType;
782 if (isa<ZExtInst>(I))
783 LType = ISD::ZEXTLOAD;
784 else {
785 assert(isa<SExtInst>(I) && "Unexpected ext type!");
786 LType = ISD::SEXTLOAD;
787 }
788 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
789 return false;
790
791 // Move the extend into the same block as the load, so that SelectionDAG
792 // can fold it.
793 I->removeFromParent();
794 I->insertAfter(LI);
795 return true;
796}
797
Evan Chengbdcb7262007-12-05 23:58:20 +0000798bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
799 BasicBlock *DefBB = I->getParent();
800
Bob Wilson9120f5c2010-09-21 21:44:14 +0000801 // If the result of a {s|z}ext and its source are both live out, rewrite all
Evan Chengbdcb7262007-12-05 23:58:20 +0000802 // other uses of the source with result of extension.
803 Value *Src = I->getOperand(0);
804 if (Src->hasOneUse())
805 return false;
806
Evan Cheng696e5c02007-12-13 07:50:36 +0000807 // Only do this xform if truncating is free.
Gabor Greif53bdbd72008-02-26 19:13:21 +0000808 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
Evan Chengf9785f92007-12-13 03:32:53 +0000809 return false;
810
Evan Cheng772de512007-12-12 00:51:06 +0000811 // Only safe to perform the optimization if the source is also defined in
Evan Cheng765dff22007-12-12 02:53:41 +0000812 // this block.
813 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
Evan Cheng772de512007-12-12 00:51:06 +0000814 return false;
815
Evan Chengbdcb7262007-12-05 23:58:20 +0000816 bool DefIsLiveOut = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000817 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000818 UI != E; ++UI) {
819 Instruction *User = cast<Instruction>(*UI);
820
821 // Figure out which BB this ext is used in.
822 BasicBlock *UserBB = User->getParent();
823 if (UserBB == DefBB) continue;
824 DefIsLiveOut = true;
825 break;
826 }
827 if (!DefIsLiveOut)
828 return false;
829
Evan Cheng765dff22007-12-12 02:53:41 +0000830 // Make sure non of the uses are PHI nodes.
Eric Christopher692bf6b2008-09-24 05:32:41 +0000831 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Cheng765dff22007-12-12 02:53:41 +0000832 UI != E; ++UI) {
833 Instruction *User = cast<Instruction>(*UI);
Evan Chengf9785f92007-12-13 03:32:53 +0000834 BasicBlock *UserBB = User->getParent();
835 if (UserBB == DefBB) continue;
836 // Be conservative. We don't want this xform to end up introducing
837 // reloads just before load / store instructions.
838 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
Evan Cheng765dff22007-12-12 02:53:41 +0000839 return false;
840 }
841
Evan Chengbdcb7262007-12-05 23:58:20 +0000842 // InsertedTruncs - Only insert one trunc in each block once.
843 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
844
845 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000846 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
Evan Chengbdcb7262007-12-05 23:58:20 +0000847 UI != E; ++UI) {
848 Use &TheUse = UI.getUse();
849 Instruction *User = cast<Instruction>(*UI);
850
851 // Figure out which BB this ext is used in.
852 BasicBlock *UserBB = User->getParent();
853 if (UserBB == DefBB) continue;
854
855 // Both src and def are live in this block. Rewrite the use.
856 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
857
858 if (!InsertedTrunc) {
Dan Gohman02dea8b2008-05-23 21:05:58 +0000859 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
Eric Christopher692bf6b2008-09-24 05:32:41 +0000860
Evan Chengbdcb7262007-12-05 23:58:20 +0000861 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
862 }
863
864 // Replace a use of the {s|z}ext source with a use of the result.
865 TheUse = InsertedTrunc;
866
867 MadeChange = true;
868 }
869
870 return MadeChange;
871}
872
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000873// In this pass we look for GEP and cast instructions that are used
874// across basic blocks and rewrite them to improve basic-block-at-a-time
875// selection.
876bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
877 bool MadeChange = false;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000878
Evan Chengab631522008-12-19 18:03:11 +0000879 // Split all critical edges where the dest block has a PHI.
Evan Chenge1bcb442010-08-17 01:34:49 +0000880 if (CriticalEdgeSplit) {
881 TerminatorInst *BBTI = BB.getTerminator();
882 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
883 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
884 BasicBlock *SuccBB = BBTI->getSuccessor(i);
885 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
886 SplitEdgeNicely(BBTI, i, BackEdges, this);
887 }
Evan Chengab631522008-12-19 18:03:11 +0000888 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000889 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000890
Chris Lattnerdd77df32007-04-13 20:30:56 +0000891 // Keep track of non-local addresses that have been sunk into this block.
892 // This allows us to avoid inserting duplicate code for blocks with multiple
893 // load/stores of the same address.
894 DenseMap<Value*, Value*> SunkAddrs;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000895
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000896 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
897 Instruction *I = BBI++;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000898
Chris Lattnerdd77df32007-04-13 20:30:56 +0000899 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000900 // If the source of the cast is a constant, then this should have
901 // already been constant folded. The only reason NOT to constant fold
902 // it is if something (e.g. LSR) was careful to place the constant
903 // evaluation in a block other than then one that uses it (e.g. to hoist
904 // the address of globals out of a loop). If this is the case, we don't
905 // want to forward-subst the cast.
906 if (isa<Constant>(CI->getOperand(0)))
907 continue;
Eric Christopher692bf6b2008-09-24 05:32:41 +0000908
Evan Chengbdcb7262007-12-05 23:58:20 +0000909 bool Change = false;
910 if (TLI) {
911 Change = OptimizeNoopCopyExpression(CI, *TLI);
912 MadeChange |= Change;
913 }
914
Dan Gohmanb00f2362009-10-16 20:59:35 +0000915 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
916 MadeChange |= MoveExtToFormExtLoad(I);
Evan Chengbdcb7262007-12-05 23:58:20 +0000917 MadeChange |= OptimizeExtUses(I);
Dan Gohmanb00f2362009-10-16 20:59:35 +0000918 }
Dale Johannesence0b2372007-06-12 16:50:17 +0000919 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
920 MadeChange |= OptimizeCmpExpression(CI);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000921 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
922 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000923 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
924 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000925 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
926 if (TLI)
Chris Lattner88a5c832008-11-25 07:09:13 +0000927 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
928 SI->getOperand(0)->getType(),
929 SunkAddrs);
Chris Lattnerdd77df32007-04-13 20:30:56 +0000930 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattnerf25646b2007-04-14 00:17:39 +0000931 if (GEPI->hasAllZeroIndices()) {
Chris Lattnerdd77df32007-04-13 20:30:56 +0000932 /// The GEP operand must be a pointer, so must its result -> BitCast
Eric Christopher692bf6b2008-09-24 05:32:41 +0000933 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattnerdd77df32007-04-13 20:30:56 +0000934 GEPI->getName(), GEPI);
935 GEPI->replaceAllUsesWith(NC);
936 GEPI->eraseFromParent();
937 MadeChange = true;
938 BBI = NC;
939 }
940 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
941 // If we found an inline asm expession, and if the target knows how to
942 // lower it to normal LLVM code, do so now.
Chris Lattner8850b362009-07-20 17:52:52 +0000943 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
944 if (TLI->ExpandInlineAsm(CI)) {
945 BBI = BB.begin();
946 // Avoid processing instructions out of order, which could cause
947 // reuse before a value is defined.
948 SunkAddrs.clear();
949 } else
950 // Sink address computing for memory operands into the block.
951 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
Eric Christopher040056f2010-03-11 02:41:03 +0000952 } else {
953 // Other CallInst optimizations that don't need to muck with the
954 // enclosing iterator here.
955 MadeChange |= OptimizeCallInst(CI);
Chris Lattner8850b362009-07-20 17:52:52 +0000956 }
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000957 }
958 }
Eric Christopher692bf6b2008-09-24 05:32:41 +0000959
Chris Lattnerdbe0dec2007-03-31 04:06:36 +0000960 return MadeChange;
961}