blob: 32226a02aa43c39003121b5b46b7469cce2b8594 [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//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass munges the code in the input function to better prepare it for
11// SelectionDAG-based code generation. This works around limitations in it's
12// basic-block-at-a-time approach. It should eventually be removed.
13//
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"
21#include "llvm/Instructions.h"
22#include "llvm/Pass.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000023#include "llvm/Target/TargetAsmInfo.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetLowering.h"
26#include "llvm/Target/TargetMachine.h"
27#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerfeee64e2007-04-13 20:30:56 +000028#include "llvm/Transforms/Utils/Local.h"
29#include "llvm/ADT/DenseMap.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000030#include "llvm/ADT/SmallSet.h"
Chris Lattnerc3748562007-04-02 01:35:34 +000031#include "llvm/Support/Debug.h"
32#include "llvm/Support/Compiler.h"
Chris Lattnerfeee64e2007-04-13 20:30:56 +000033#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerf2836d12007-03-31 04:06:36 +000034using namespace llvm;
35
36namespace {
37 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
38 /// TLI - Keep a pointer of a TargetLowering to consult for determining
39 /// transformation profitability.
40 const TargetLowering *TLI;
41 public:
42 CodeGenPrepare(const TargetLowering *tli = 0) : TLI(tli) {}
43 bool runOnFunction(Function &F);
44
45 private:
Chris Lattnerc3748562007-04-02 01:35:34 +000046 bool EliminateMostlyEmptyBlocks(Function &F);
47 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
48 void EliminateMostlyEmptyBlock(BasicBlock *BB);
Chris Lattnerf2836d12007-03-31 04:06:36 +000049 bool OptimizeBlock(BasicBlock &BB);
Chris Lattnerfeee64e2007-04-13 20:30:56 +000050 bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
51 const Type *AccessTy,
52 DenseMap<Value*,Value*> &SunkAddrs);
Chris Lattnerf2836d12007-03-31 04:06:36 +000053 };
54}
55static RegisterPass<CodeGenPrepare> X("codegenprepare",
56 "Optimize for code generation");
57
58FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
59 return new CodeGenPrepare(TLI);
60}
61
62
63bool CodeGenPrepare::runOnFunction(Function &F) {
Chris Lattnerf2836d12007-03-31 04:06:36 +000064 bool EverMadeChange = false;
Chris Lattnerc3748562007-04-02 01:35:34 +000065
66 // First pass, eliminate blocks that contain only PHI nodes and an
67 // unconditional branch.
68 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
69
70 bool MadeChange = true;
Chris Lattnerf2836d12007-03-31 04:06:36 +000071 while (MadeChange) {
72 MadeChange = false;
73 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
74 MadeChange |= OptimizeBlock(*BB);
75 EverMadeChange |= MadeChange;
76 }
77 return EverMadeChange;
78}
79
Chris Lattnerc3748562007-04-02 01:35:34 +000080/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
81/// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
82/// often split edges in ways that are non-optimal for isel. Start by
83/// eliminating these blocks so we can split them the way we want them.
84bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
85 bool MadeChange = false;
86 // Note that this intentionally skips the entry block.
87 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
88 BasicBlock *BB = I++;
89
90 // If this block doesn't end with an uncond branch, ignore it.
91 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
92 if (!BI || !BI->isUnconditional())
93 continue;
94
95 // If the instruction before the branch isn't a phi node, then other stuff
96 // is happening here.
97 BasicBlock::iterator BBI = BI;
98 if (BBI != BB->begin()) {
99 --BBI;
100 if (!isa<PHINode>(BBI)) continue;
101 }
102
103 // Do not break infinite loops.
104 BasicBlock *DestBB = BI->getSuccessor(0);
105 if (DestBB == BB)
106 continue;
107
108 if (!CanMergeBlocks(BB, DestBB))
109 continue;
110
111 EliminateMostlyEmptyBlock(BB);
112 MadeChange = true;
113 }
114 return MadeChange;
115}
116
117/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
118/// single uncond branch between them, and BB contains no other non-phi
119/// instructions.
120bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
121 const BasicBlock *DestBB) const {
122 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
123 // the successor. If there are more complex condition (e.g. preheaders),
124 // don't mess around with them.
125 BasicBlock::const_iterator BBI = BB->begin();
126 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
127 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
128 UI != E; ++UI) {
129 const Instruction *User = cast<Instruction>(*UI);
130 if (User->getParent() != DestBB || !isa<PHINode>(User))
131 return false;
132 }
133 }
134
135 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
136 // and DestBB may have conflicting incoming values for the block. If so, we
137 // can't merge the block.
138 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
139 if (!DestBBPN) return true; // no conflict.
140
141 // Collect the preds of BB.
142 SmallPtrSet<BasicBlock*, 16> BBPreds;
143 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
144 // It is faster to get preds from a PHI than with pred_iterator.
145 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
146 BBPreds.insert(BBPN->getIncomingBlock(i));
147 } else {
148 BBPreds.insert(pred_begin(BB), pred_end(BB));
149 }
150
151 // Walk the preds of DestBB.
152 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
153 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
154 if (BBPreds.count(Pred)) { // Common predecessor?
155 BBI = DestBB->begin();
156 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
157 const Value *V1 = PN->getIncomingValueForBlock(Pred);
158 const Value *V2 = PN->getIncomingValueForBlock(BB);
159
160 // If V2 is a phi node in BB, look up what the mapped value will be.
161 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
162 if (V2PN->getParent() == BB)
163 V2 = V2PN->getIncomingValueForBlock(Pred);
164
165 // If there is a conflict, bail out.
166 if (V1 != V2) return false;
167 }
168 }
169 }
170
171 return true;
172}
173
174
175/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
176/// an unconditional branch in it.
177void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
178 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
179 BasicBlock *DestBB = BI->getSuccessor(0);
180
181 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
182
183 // If the destination block has a single pred, then this is a trivial edge,
184 // just collapse it.
185 if (DestBB->getSinglePredecessor()) {
186 // If DestBB has single-entry PHI nodes, fold them.
187 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
188 PN->replaceAllUsesWith(PN->getIncomingValue(0));
189 PN->eraseFromParent();
190 }
191
192 // Splice all the PHI nodes from BB over to DestBB.
193 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
194 BB->begin(), BI);
195
196 // Anything that branched to BB now branches to DestBB.
197 BB->replaceAllUsesWith(DestBB);
198
199 // Nuke BB.
200 BB->eraseFromParent();
201
202 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
203 return;
204 }
205
206 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
207 // to handle the new incoming edges it is about to have.
208 PHINode *PN;
209 for (BasicBlock::iterator BBI = DestBB->begin();
210 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
211 // Remove the incoming value for BB, and remember it.
212 Value *InVal = PN->removeIncomingValue(BB, false);
213
214 // Two options: either the InVal is a phi node defined in BB or it is some
215 // value that dominates BB.
216 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
217 if (InValPhi && InValPhi->getParent() == BB) {
218 // Add all of the input values of the input PHI as inputs of this phi.
219 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
220 PN->addIncoming(InValPhi->getIncomingValue(i),
221 InValPhi->getIncomingBlock(i));
222 } else {
223 // Otherwise, add one instance of the dominating value for each edge that
224 // we will be adding.
225 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
226 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
227 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
228 } else {
229 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
230 PN->addIncoming(InVal, *PI);
231 }
232 }
233 }
234
235 // The PHIs are now updated, change everything that refers to BB to use
236 // DestBB and remove BB.
237 BB->replaceAllUsesWith(DestBB);
238 BB->eraseFromParent();
239
240 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
241}
242
243
Chris Lattnerf2836d12007-03-31 04:06:36 +0000244/// SplitEdgeNicely - Split the critical edge from TI to it's specified
245/// successor if it will improve codegen. We only do this if the successor has
246/// phi nodes (otherwise critical edges are ok). If there is already another
247/// predecessor of the succ that is empty (and thus has no phi nodes), use it
248/// instead of introducing a new block.
249static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
250 BasicBlock *TIBB = TI->getParent();
251 BasicBlock *Dest = TI->getSuccessor(SuccNum);
252 assert(isa<PHINode>(Dest->begin()) &&
253 "This should only be called if Dest has a PHI!");
254
255 /// TIPHIValues - This array is lazily computed to determine the values of
256 /// PHIs in Dest that TI would provide.
257 std::vector<Value*> TIPHIValues;
258
259 // Check to see if Dest has any blocks that can be used as a split edge for
260 // this terminator.
261 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
262 BasicBlock *Pred = *PI;
263 // To be usable, the pred has to end with an uncond branch to the dest.
264 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
265 if (!PredBr || !PredBr->isUnconditional() ||
266 // Must be empty other than the branch.
267 &Pred->front() != PredBr)
268 continue;
269
270 // Finally, since we know that Dest has phi nodes in it, we have to make
271 // sure that jumping to Pred will have the same affect as going to Dest in
272 // terms of PHI values.
273 PHINode *PN;
274 unsigned PHINo = 0;
275 bool FoundMatch = true;
276 for (BasicBlock::iterator I = Dest->begin();
277 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
278 if (PHINo == TIPHIValues.size())
279 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
280
281 // If the PHI entry doesn't work, we can't use this pred.
282 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
283 FoundMatch = false;
284 break;
285 }
286 }
287
288 // If we found a workable predecessor, change TI to branch to Succ.
289 if (FoundMatch) {
290 Dest->removePredecessor(TIBB);
291 TI->setSuccessor(SuccNum, Pred);
292 return;
293 }
294 }
295
296 SplitCriticalEdge(TI, SuccNum, P, true);
297}
298
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000299/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
300/// copy (e.g. it's casting from one pointer type to another, int->uint, or
301/// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
302/// registers that must be created and coallesced.
Chris Lattnerf2836d12007-03-31 04:06:36 +0000303///
304/// Return true if any changes are made.
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000305static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
306 // If this is a noop copy,
307 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
308 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
309
310 // This is an fp<->int conversion?
311 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
312 return false;
313
314 // If this is an extension, it will be a zero or sign extension, which
315 // isn't a noop.
316 if (SrcVT < DstVT) return false;
317
318 // If these values will be promoted, find out what they will be promoted
319 // to. This helps us consider truncates on PPC as noop copies when they
320 // are.
321 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
322 SrcVT = TLI.getTypeToTransformTo(SrcVT);
323 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
324 DstVT = TLI.getTypeToTransformTo(DstVT);
325
326 // If, after promotion, these are the same types, this is a noop copy.
327 if (SrcVT != DstVT)
328 return false;
329
Chris Lattnerf2836d12007-03-31 04:06:36 +0000330 BasicBlock *DefBB = CI->getParent();
331
332 /// InsertedCasts - Only insert a cast in each block once.
333 std::map<BasicBlock*, CastInst*> InsertedCasts;
334
335 bool MadeChange = false;
336 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
337 UI != E; ) {
338 Use &TheUse = UI.getUse();
339 Instruction *User = cast<Instruction>(*UI);
340
341 // Figure out which BB this cast is used in. For PHI's this is the
342 // appropriate predecessor block.
343 BasicBlock *UserBB = User->getParent();
344 if (PHINode *PN = dyn_cast<PHINode>(User)) {
345 unsigned OpVal = UI.getOperandNo()/2;
346 UserBB = PN->getIncomingBlock(OpVal);
347 }
348
349 // Preincrement use iterator so we don't invalidate it.
350 ++UI;
351
352 // If this user is in the same block as the cast, don't change the cast.
353 if (UserBB == DefBB) continue;
354
355 // If we have already inserted a cast into this block, use it.
356 CastInst *&InsertedCast = InsertedCasts[UserBB];
357
358 if (!InsertedCast) {
359 BasicBlock::iterator InsertPt = UserBB->begin();
360 while (isa<PHINode>(InsertPt)) ++InsertPt;
361
362 InsertedCast =
363 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
364 InsertPt);
365 MadeChange = true;
366 }
367
368 // Replace a use of the cast with a use of the new casat.
369 TheUse = InsertedCast;
370 }
371
372 // If we removed all uses, nuke the cast.
373 if (CI->use_empty())
374 CI->eraseFromParent();
375
376 return MadeChange;
377}
378
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000379/// EraseDeadInstructions - Erase any dead instructions
380static void EraseDeadInstructions(Value *V) {
381 Instruction *I = dyn_cast<Instruction>(V);
382 if (!I || !I->use_empty()) return;
383
384 SmallPtrSet<Instruction*, 16> Insts;
385 Insts.insert(I);
386
387 while (!Insts.empty()) {
388 I = *Insts.begin();
389 Insts.erase(I);
390 if (isInstructionTriviallyDead(I)) {
391 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
392 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
393 Insts.insert(U);
394 I->eraseFromParent();
395 }
396 }
397}
Chris Lattnerf2836d12007-03-31 04:06:36 +0000398
399
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000400/// ExtAddrMode - This is an extended version of TargetLowering::AddrMode which
401/// holds actual Value*'s for register values.
402struct ExtAddrMode : public TargetLowering::AddrMode {
403 Value *BaseReg;
404 Value *ScaledReg;
405 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
406 void dump() const;
407};
408
409static std::ostream &operator<<(std::ostream &OS, const ExtAddrMode &AM) {
410 bool NeedPlus = false;
411 OS << "[";
412 if (AM.BaseGV)
413 OS << (NeedPlus ? " + " : "")
414 << "GV:%" << AM.BaseGV->getName(), NeedPlus = true;
415
416 if (AM.BaseOffs)
417 OS << (NeedPlus ? " + " : "") << AM.BaseOffs, NeedPlus = true;
418
419 if (AM.BaseReg)
420 OS << (NeedPlus ? " + " : "")
421 << "Base:%" << AM.BaseReg->getName(), NeedPlus = true;
422 if (AM.Scale)
423 OS << (NeedPlus ? " + " : "")
424 << AM.Scale << "*%" << AM.ScaledReg->getName(), NeedPlus = true;
425
426 return OS << "]";
427}
428
429void ExtAddrMode::dump() const {
430 cerr << *this << "\n";
431}
432
433static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
434 const Type *AccessTy, ExtAddrMode &AddrMode,
435 SmallVector<Instruction*, 16> &AddrModeInsts,
436 const TargetLowering &TLI, unsigned Depth);
437
438/// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
439/// Addr into the specified addressing mode. If Addr can't be added to AddrMode
440/// this returns false. This assumes that Addr is either a pointer type or
441/// intptr_t for the target.
442static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
443 ExtAddrMode &AddrMode,
444 SmallVector<Instruction*, 16> &AddrModeInsts,
445 const TargetLowering &TLI,
446 unsigned Depth) {
447
448 // If this is a global variable, fold it into the addressing mode if possible.
449 if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
450 if (AddrMode.BaseGV == 0) {
451 AddrMode.BaseGV = GV;
452 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
453 return true;
454 AddrMode.BaseGV = 0;
455 }
456 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
457 AddrMode.BaseOffs += CI->getSExtValue();
458 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
459 return true;
460 AddrMode.BaseOffs -= CI->getSExtValue();
461 } else if (isa<ConstantPointerNull>(Addr)) {
462 return true;
463 }
464
465 // Look through constant exprs and instructions.
466 unsigned Opcode = ~0U;
467 User *AddrInst = 0;
468 if (Instruction *I = dyn_cast<Instruction>(Addr)) {
469 Opcode = I->getOpcode();
470 AddrInst = I;
471 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
472 Opcode = CE->getOpcode();
473 AddrInst = CE;
474 }
475
476 // Limit recursion to avoid exponential behavior.
477 if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
478
479 // If this is really an instruction, add it to our list of related
480 // instructions.
481 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
482 AddrModeInsts.push_back(I);
483
484 switch (Opcode) {
485 case Instruction::PtrToInt:
486 // PtrToInt is always a noop, as we know that the int type is pointer sized.
487 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
488 AddrMode, AddrModeInsts, TLI, Depth))
489 return true;
490 break;
491 case Instruction::IntToPtr:
492 // This inttoptr is a no-op if the integer type is pointer sized.
493 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
494 TLI.getPointerTy()) {
495 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
496 AddrMode, AddrModeInsts, TLI, Depth))
497 return true;
498 }
499 break;
500 case Instruction::Add: {
501 // Check to see if we can merge in the RHS then the LHS. If so, we win.
502 ExtAddrMode BackupAddrMode = AddrMode;
503 unsigned OldSize = AddrModeInsts.size();
504 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
505 AddrMode, AddrModeInsts, TLI, Depth+1) &&
506 FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
507 AddrMode, AddrModeInsts, TLI, Depth+1))
508 return true;
509
510 // Restore the old addr mode info.
511 AddrMode = BackupAddrMode;
512 AddrModeInsts.resize(OldSize);
513
514 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
515 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
516 AddrMode, AddrModeInsts, TLI, Depth+1) &&
517 FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
518 AddrMode, AddrModeInsts, TLI, Depth+1))
519 return true;
520
521 // Otherwise we definitely can't merge the ADD in.
522 AddrMode = BackupAddrMode;
523 AddrModeInsts.resize(OldSize);
524 break;
525 }
526 case Instruction::Or: {
527 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
528 if (!RHS) break;
529 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
530 break;
531 }
532 case Instruction::Mul:
533 case Instruction::Shl: {
534 // Can only handle X*C and X << C, and can only handle this when the scale
535 // field is available.
536 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
537 if (!RHS) break;
538 int64_t Scale = RHS->getSExtValue();
539 if (Opcode == Instruction::Shl)
540 Scale = 1 << Scale;
541
542 if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
543 AddrMode, AddrModeInsts, TLI, Depth))
544 return true;
545 break;
546 }
547 case Instruction::GetElementPtr: {
548 // Scan the GEP. We check it if it contains constant offsets and at most
549 // one variable offset.
550 int VariableOperand = -1;
551 unsigned VariableScale = 0;
552
553 int64_t ConstantOffset = 0;
554 const TargetData *TD = TLI.getTargetData();
555 gep_type_iterator GTI = gep_type_begin(AddrInst);
556 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
557 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
558 const StructLayout *SL = TD->getStructLayout(STy);
559 unsigned Idx =
560 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
561 ConstantOffset += SL->getElementOffset(Idx);
562 } else {
563 uint64_t TypeSize = TD->getTypeSize(GTI.getIndexedType());
564 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
565 ConstantOffset += CI->getSExtValue()*TypeSize;
566 } else if (TypeSize) { // Scales of zero don't do anything.
567 // We only allow one variable index at the moment.
568 if (VariableOperand != -1) {
569 VariableOperand = -2;
570 break;
571 }
572
573 // Remember the variable index.
574 VariableOperand = i;
575 VariableScale = TypeSize;
576 }
577 }
578 }
579
580 // If the GEP had multiple variable indices, punt.
581 if (VariableOperand == -2)
582 break;
583
584 // A common case is for the GEP to only do a constant offset. In this case,
585 // just add it to the disp field and check validity.
586 if (VariableOperand == -1) {
587 AddrMode.BaseOffs += ConstantOffset;
588 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
589 // Check to see if we can fold the base pointer in too.
590 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
591 AddrMode, AddrModeInsts, TLI,
592 Depth+1))
593 return true;
594 }
595 AddrMode.BaseOffs -= ConstantOffset;
596 } else {
597 // Check that this has no base reg yet. If so, we won't have a place to
598 // put the base of the GEP (assuming it is not a null ptr).
599 bool SetBaseReg = false;
600 if (AddrMode.HasBaseReg) {
601 if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
602 break;
603 } else {
604 AddrMode.HasBaseReg = true;
605 AddrMode.BaseReg = AddrInst->getOperand(0);
606 SetBaseReg = true;
607 }
608
609 // See if the scale amount is valid for this target.
610 AddrMode.BaseOffs += ConstantOffset;
611 if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
612 VariableScale, AccessTy, AddrMode,
613 AddrModeInsts, TLI, Depth)) {
614 if (!SetBaseReg) return true;
615
616 // If this match succeeded, we know that we can form an address with the
617 // GepBase as the basereg. See if we can match *more*.
618 AddrMode.HasBaseReg = false;
619 AddrMode.BaseReg = 0;
620 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
621 AddrMode, AddrModeInsts, TLI,
622 Depth+1))
623 return true;
624 // Strange, shouldn't happen. Restore the base reg and succeed the easy
625 // way.
626 AddrMode.HasBaseReg = true;
627 AddrMode.BaseReg = AddrInst->getOperand(0);
628 return true;
629 }
630
631 AddrMode.BaseOffs -= ConstantOffset;
632 if (SetBaseReg) {
633 AddrMode.HasBaseReg = false;
634 AddrMode.BaseReg = 0;
635 }
636 }
637 break;
638 }
639 }
640
641 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
642 assert(AddrModeInsts.back() == I && "Stack imbalance");
643 AddrModeInsts.pop_back();
644 }
645
646 // Worse case, the target should support [reg] addressing modes. :)
647 if (!AddrMode.HasBaseReg) {
648 AddrMode.HasBaseReg = true;
649 // Still check for legality in case the target supports [imm] but not [i+r].
650 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
651 AddrMode.BaseReg = Addr;
652 return true;
653 }
654 AddrMode.HasBaseReg = false;
655 }
656
657 // If the base register is already taken, see if we can do [r+r].
658 if (AddrMode.Scale == 0) {
659 AddrMode.Scale = 1;
660 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
661 AddrMode.ScaledReg = Addr;
662 return true;
663 }
664 AddrMode.Scale = 0;
665 }
666 // Couldn't match.
667 return false;
668}
669
670/// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
671/// addressing mode. Return true if this addr mode is legal for the target,
672/// false if not.
673static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
674 const Type *AccessTy, ExtAddrMode &AddrMode,
675 SmallVector<Instruction*, 16> &AddrModeInsts,
676 const TargetLowering &TLI, unsigned Depth) {
677 // If we already have a scale of this value, we can add to it, otherwise, we
678 // need an available scale field.
679 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
680 return false;
681
682 ExtAddrMode InputAddrMode = AddrMode;
683
684 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
685 // [A+B + A*7] -> [B+A*8].
686 AddrMode.Scale += Scale;
687 AddrMode.ScaledReg = ScaleReg;
688
689 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
690 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
691 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
692 // X*Scale + C*Scale to addr mode.
693 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
694 if (BinOp && BinOp->getOpcode() == Instruction::Add &&
695 isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
696
697 InputAddrMode.Scale = Scale;
698 InputAddrMode.ScaledReg = BinOp->getOperand(0);
699 InputAddrMode.BaseOffs +=
700 cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
701 if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
702 AddrModeInsts.push_back(BinOp);
703 AddrMode = InputAddrMode;
704 return true;
705 }
706 }
707
708 // Otherwise, not (x+c)*scale, just return what we have.
709 return true;
710 }
711
712 // Otherwise, back this attempt out.
713 AddrMode.Scale -= Scale;
714 if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
715
716 return false;
717}
718
719
720/// IsNonLocalValue - Return true if the specified values are defined in a
721/// different basic block than BB.
722static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
723 if (Instruction *I = dyn_cast<Instruction>(V))
724 return I->getParent() != BB;
725 return false;
726}
727
728/// OptimizeLoadStoreInst - Load and Store Instructions have often have
729/// addressing modes that can do significant amounts of computation. As such,
730/// instruction selection will try to get the load or store to do as much
731/// computation as possible for the program. The problem is that isel can only
732/// see within a single block. As such, we sink as much legal addressing mode
733/// stuff into the block as possible.
734bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
735 const Type *AccessTy,
736 DenseMap<Value*,Value*> &SunkAddrs) {
737 // Figure out what addressing mode will be built up for this operation.
738 SmallVector<Instruction*, 16> AddrModeInsts;
739 ExtAddrMode AddrMode;
740 bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
741 AddrModeInsts, *TLI, 0);
742 Success = Success; assert(Success && "Couldn't select *anything*?");
743
744 // Check to see if any of the instructions supersumed by this addr mode are
745 // non-local to I's BB.
746 bool AnyNonLocal = false;
747 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
748 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
749 AnyNonLocal = true;
750 break;
751 }
752 }
753
754 // If all the instructions matched are already in this BB, don't do anything.
755 if (!AnyNonLocal) {
756 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
757 return false;
758 }
759
760 // Insert this computation right after this user. Since our caller is
761 // scanning from the top of the BB to the bottom, reuse of the expr are
762 // guaranteed to happen later.
763 BasicBlock::iterator InsertPt = LdStInst;
764
765 // Now that we determined the addressing expression we want to use and know
766 // that we have to sink it into this block. Check to see if we have already
767 // done this for some other load/store instr in this block. If so, reuse the
768 // computation.
769 Value *&SunkAddr = SunkAddrs[Addr];
770 if (SunkAddr) {
771 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
772 if (SunkAddr->getType() != Addr->getType())
773 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
774 } else {
775 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
776 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
777
778 Value *Result = 0;
779 // Start with the scale value.
780 if (AddrMode.Scale) {
781 Value *V = AddrMode.ScaledReg;
782 if (V->getType() == IntPtrTy) {
783 // done.
784 } else if (isa<PointerType>(V->getType())) {
785 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
786 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
787 cast<IntegerType>(V->getType())->getBitWidth()) {
788 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
789 } else {
790 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
791 }
792 if (AddrMode.Scale != 1)
793 V = BinaryOperator::createMul(V, ConstantInt::get(IntPtrTy,
794 AddrMode.Scale),
795 "sunkaddr", InsertPt);
796 Result = V;
797 }
798
799 // Add in the base register.
800 if (AddrMode.BaseReg) {
801 Value *V = AddrMode.BaseReg;
802 if (V->getType() != IntPtrTy)
803 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
804 if (Result)
805 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
806 else
807 Result = V;
808 }
809
810 // Add in the BaseGV if present.
811 if (AddrMode.BaseGV) {
812 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
813 InsertPt);
814 if (Result)
815 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
816 else
817 Result = V;
818 }
819
820 // Add in the Base Offset if present.
821 if (AddrMode.BaseOffs) {
822 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
823 if (Result)
824 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
825 else
826 Result = V;
827 }
828
829 if (Result == 0)
830 SunkAddr = Constant::getNullValue(Addr->getType());
831 else
832 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
833 }
834
835 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
836
837 if (Addr->use_empty())
838 EraseDeadInstructions(Addr);
839 return true;
840}
841
Chris Lattnerf2836d12007-03-31 04:06:36 +0000842// In this pass we look for GEP and cast instructions that are used
843// across basic blocks and rewrite them to improve basic-block-at-a-time
844// selection.
845bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
846 bool MadeChange = false;
847
848 // Split all critical edges where the dest block has a PHI and where the phi
849 // has shared immediate operands.
850 TerminatorInst *BBTI = BB.getTerminator();
851 if (BBTI->getNumSuccessors() > 1) {
852 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
853 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
854 isCriticalEdge(BBTI, i, true))
855 SplitEdgeNicely(BBTI, i, this);
856 }
857
858
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000859 // Keep track of non-local addresses that have been sunk into this block.
860 // This allows us to avoid inserting duplicate code for blocks with multiple
861 // load/stores of the same address.
862 DenseMap<Value*, Value*> SunkAddrs;
863
Chris Lattnerf2836d12007-03-31 04:06:36 +0000864 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
865 Instruction *I = BBI++;
866
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000867 if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerf2836d12007-03-31 04:06:36 +0000868 // If the source of the cast is a constant, then this should have
869 // already been constant folded. The only reason NOT to constant fold
870 // it is if something (e.g. LSR) was careful to place the constant
871 // evaluation in a block other than then one that uses it (e.g. to hoist
872 // the address of globals out of a loop). If this is the case, we don't
873 // want to forward-subst the cast.
874 if (isa<Constant>(CI->getOperand(0)))
875 continue;
876
Chris Lattnerf2836d12007-03-31 04:06:36 +0000877 if (TLI)
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000878 MadeChange |= OptimizeNoopCopyExpression(CI, *TLI);
879 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
880 if (TLI)
881 MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
882 SunkAddrs);
883 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
884 if (TLI)
885 MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
886 SI->getOperand(0)->getType(),
887 SunkAddrs);
888 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
889 bool HasNonZeroIdx = false;
890 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
891 E = GEPI->op_end(); OI != E; ++OI) {
892 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
893 if (!CI->isZero()) {
894 HasNonZeroIdx = true;
895 break;
896 }
897 } else {
898 HasNonZeroIdx = true;
899 break;
900 }
901 }
902
903 if (!HasNonZeroIdx) {
904 /// The GEP operand must be a pointer, so must its result -> BitCast
905 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
906 GEPI->getName(), GEPI);
907 GEPI->replaceAllUsesWith(NC);
908 GEPI->eraseFromParent();
909 MadeChange = true;
910 BBI = NC;
911 }
912 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
913 // If we found an inline asm expession, and if the target knows how to
914 // lower it to normal LLVM code, do so now.
915 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
916 if (const TargetAsmInfo *TAI =
917 TLI->getTargetMachine().getTargetAsmInfo()) {
918 if (TAI->ExpandInlineAsm(CI))
919 BBI = BB.begin();
920 }
Chris Lattnerf2836d12007-03-31 04:06:36 +0000921 }
922 }
Chris Lattnerfeee64e2007-04-13 20:30:56 +0000923
Chris Lattnerf2836d12007-03-31 04:06:36 +0000924 return MadeChange;
925}
926