1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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"
23 #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"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 cl::opt<bool> OptExtUses("optimize-ext-uses",
39 cl::init(true), cl::Hidden);
41 cl::opt<bool> DontHackBackedge("backedge-hack", cl::Hidden);
45 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
46 /// TLI - Keep a pointer of a TargetLowering to consult for determining
47 /// transformation profitability.
48 const TargetLowering *TLI;
50 static char ID; // Pass identification, replacement for typeid
51 explicit CodeGenPrepare(const TargetLowering *tli = 0)
52 : FunctionPass((intptr_t)&ID), TLI(tli) {}
53 bool runOnFunction(Function &F);
56 bool EliminateMostlyEmptyBlocks(Function &F);
57 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
58 void EliminateMostlyEmptyBlock(BasicBlock *BB);
59 bool OptimizeBlock(BasicBlock &BB);
60 bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
62 DenseMap<Value*,Value*> &SunkAddrs);
63 bool OptimizeExtUses(Instruction *I);
67 char CodeGenPrepare::ID = 0;
68 static RegisterPass<CodeGenPrepare> X("codegenprepare",
69 "Optimize for code generation");
71 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
72 return new CodeGenPrepare(TLI);
76 bool CodeGenPrepare::runOnFunction(Function &F) {
77 bool EverMadeChange = false;
79 // First pass, eliminate blocks that contain only PHI nodes and an
80 // unconditional branch.
81 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
83 bool MadeChange = true;
86 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
87 MadeChange |= OptimizeBlock(*BB);
88 EverMadeChange |= MadeChange;
90 return EverMadeChange;
93 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
94 /// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
95 /// often split edges in ways that are non-optimal for isel. Start by
96 /// eliminating these blocks so we can split them the way we want them.
97 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
98 bool MadeChange = false;
99 // Note that this intentionally skips the entry block.
100 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
101 BasicBlock *BB = I++;
103 // If this block doesn't end with an uncond branch, ignore it.
104 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
105 if (!BI || !BI->isUnconditional())
108 // If the instruction before the branch isn't a phi node, then other stuff
109 // is happening here.
110 BasicBlock::iterator BBI = BI;
111 if (BBI != BB->begin()) {
113 if (!isa<PHINode>(BBI)) continue;
116 // Do not break infinite loops.
117 BasicBlock *DestBB = BI->getSuccessor(0);
121 if (!CanMergeBlocks(BB, DestBB))
124 EliminateMostlyEmptyBlock(BB);
130 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
131 /// single uncond branch between them, and BB contains no other non-phi
133 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
134 const BasicBlock *DestBB) const {
135 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
136 // the successor. If there are more complex condition (e.g. preheaders),
137 // don't mess around with them.
138 BasicBlock::const_iterator BBI = BB->begin();
139 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
140 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
142 const Instruction *User = cast<Instruction>(*UI);
143 if (User->getParent() != DestBB || !isa<PHINode>(User))
145 // If User is inside DestBB block and it is a PHINode then check
146 // incoming value. If incoming value is not from BB then this is
147 // a complex condition (e.g. preheaders) we want to avoid here.
148 if (User->getParent() == DestBB) {
149 if (const PHINode *UPN = dyn_cast<PHINode>(User))
150 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
151 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
152 if (Insn && Insn->getParent() == BB &&
153 Insn->getParent() != UPN->getIncomingBlock(I))
160 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
161 // and DestBB may have conflicting incoming values for the block. If so, we
162 // can't merge the block.
163 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
164 if (!DestBBPN) return true; // no conflict.
166 // Collect the preds of BB.
167 SmallPtrSet<const BasicBlock*, 16> BBPreds;
168 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
169 // It is faster to get preds from a PHI than with pred_iterator.
170 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
171 BBPreds.insert(BBPN->getIncomingBlock(i));
173 BBPreds.insert(pred_begin(BB), pred_end(BB));
176 // Walk the preds of DestBB.
177 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
178 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
179 if (BBPreds.count(Pred)) { // Common predecessor?
180 BBI = DestBB->begin();
181 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
182 const Value *V1 = PN->getIncomingValueForBlock(Pred);
183 const Value *V2 = PN->getIncomingValueForBlock(BB);
185 // If V2 is a phi node in BB, look up what the mapped value will be.
186 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
187 if (V2PN->getParent() == BB)
188 V2 = V2PN->getIncomingValueForBlock(Pred);
190 // If there is a conflict, bail out.
191 if (V1 != V2) return false;
200 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
201 /// an unconditional branch in it.
202 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
203 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
204 BasicBlock *DestBB = BI->getSuccessor(0);
206 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
208 // If the destination block has a single pred, then this is a trivial edge,
210 if (DestBB->getSinglePredecessor()) {
211 // If DestBB has single-entry PHI nodes, fold them.
212 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
213 PN->replaceAllUsesWith(PN->getIncomingValue(0));
214 PN->eraseFromParent();
217 // Splice all the PHI nodes from BB over to DestBB.
218 DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
221 // Anything that branched to BB now branches to DestBB.
222 BB->replaceAllUsesWith(DestBB);
225 BB->eraseFromParent();
227 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
231 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
232 // to handle the new incoming edges it is about to have.
234 for (BasicBlock::iterator BBI = DestBB->begin();
235 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
236 // Remove the incoming value for BB, and remember it.
237 Value *InVal = PN->removeIncomingValue(BB, false);
239 // Two options: either the InVal is a phi node defined in BB or it is some
240 // value that dominates BB.
241 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
242 if (InValPhi && InValPhi->getParent() == BB) {
243 // Add all of the input values of the input PHI as inputs of this phi.
244 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
245 PN->addIncoming(InValPhi->getIncomingValue(i),
246 InValPhi->getIncomingBlock(i));
248 // Otherwise, add one instance of the dominating value for each edge that
249 // we will be adding.
250 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
251 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
252 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
254 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
255 PN->addIncoming(InVal, *PI);
260 // The PHIs are now updated, change everything that refers to BB to use
261 // DestBB and remove BB.
262 BB->replaceAllUsesWith(DestBB);
263 BB->eraseFromParent();
265 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
269 /// SplitEdgeNicely - Split the critical edge from TI to its specified
270 /// successor if it will improve codegen. We only do this if the successor has
271 /// phi nodes (otherwise critical edges are ok). If there is already another
272 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
273 /// instead of introducing a new block.
274 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
275 BasicBlock *TIBB = TI->getParent();
276 BasicBlock *Dest = TI->getSuccessor(SuccNum);
277 assert(isa<PHINode>(Dest->begin()) &&
278 "This should only be called if Dest has a PHI!");
280 // As a hack, never split backedges of loops. Even though the copy for any
281 // PHIs inserted on the backedge would be dead for exits from the loop, we
282 // assume that the cost of *splitting* the backedge would be too high.
283 if (DontHackBackedge && Dest == TIBB)
286 /// TIPHIValues - This array is lazily computed to determine the values of
287 /// PHIs in Dest that TI would provide.
288 SmallVector<Value*, 32> TIPHIValues;
290 // Check to see if Dest has any blocks that can be used as a split edge for
292 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
293 BasicBlock *Pred = *PI;
294 // To be usable, the pred has to end with an uncond branch to the dest.
295 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
296 if (!PredBr || !PredBr->isUnconditional() ||
297 // Must be empty other than the branch.
298 &Pred->front() != PredBr ||
299 // Cannot be the entry block; its label does not get emitted.
300 Pred == &(Dest->getParent()->getEntryBlock()))
303 // Finally, since we know that Dest has phi nodes in it, we have to make
304 // sure that jumping to Pred will have the same affect as going to Dest in
305 // terms of PHI values.
308 bool FoundMatch = true;
309 for (BasicBlock::iterator I = Dest->begin();
310 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
311 if (PHINo == TIPHIValues.size())
312 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
314 // If the PHI entry doesn't work, we can't use this pred.
315 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
321 // If we found a workable predecessor, change TI to branch to Succ.
323 Dest->removePredecessor(TIBB);
324 TI->setSuccessor(SuccNum, Pred);
329 SplitCriticalEdge(TI, SuccNum, P, true);
332 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
333 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
334 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
335 /// registers that must be created and coalesced.
337 /// Return true if any changes are made.
338 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
339 // If this is a noop copy,
340 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
341 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
343 // This is an fp<->int conversion?
344 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
347 // If this is an extension, it will be a zero or sign extension, which
349 if (SrcVT < DstVT) return false;
351 // If these values will be promoted, find out what they will be promoted
352 // to. This helps us consider truncates on PPC as noop copies when they
354 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
355 SrcVT = TLI.getTypeToTransformTo(SrcVT);
356 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
357 DstVT = TLI.getTypeToTransformTo(DstVT);
359 // If, after promotion, these are the same types, this is a noop copy.
363 BasicBlock *DefBB = CI->getParent();
365 /// InsertedCasts - Only insert a cast in each block once.
366 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
368 bool MadeChange = false;
369 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
371 Use &TheUse = UI.getUse();
372 Instruction *User = cast<Instruction>(*UI);
374 // Figure out which BB this cast is used in. For PHI's this is the
375 // appropriate predecessor block.
376 BasicBlock *UserBB = User->getParent();
377 if (PHINode *PN = dyn_cast<PHINode>(User)) {
378 unsigned OpVal = UI.getOperandNo()/2;
379 UserBB = PN->getIncomingBlock(OpVal);
382 // Preincrement use iterator so we don't invalidate it.
385 // If this user is in the same block as the cast, don't change the cast.
386 if (UserBB == DefBB) continue;
388 // If we have already inserted a cast into this block, use it.
389 CastInst *&InsertedCast = InsertedCasts[UserBB];
392 BasicBlock::iterator InsertPt = UserBB->begin();
393 while (isa<PHINode>(InsertPt)) ++InsertPt;
396 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
401 // Replace a use of the cast with a use of the new cast.
402 TheUse = InsertedCast;
405 // If we removed all uses, nuke the cast.
407 CI->eraseFromParent();
412 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
413 /// the number of virtual registers that must be created and coalesced. This is
414 /// a clear win except on targets with multiple condition code registers
415 /// (PowerPC), where it might lose; some adjustment may be wanted there.
417 /// Return true if any changes are made.
418 static bool OptimizeCmpExpression(CmpInst *CI){
420 BasicBlock *DefBB = CI->getParent();
422 /// InsertedCmp - Only insert a cmp in each block once.
423 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
425 bool MadeChange = false;
426 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
428 Use &TheUse = UI.getUse();
429 Instruction *User = cast<Instruction>(*UI);
431 // Preincrement use iterator so we don't invalidate it.
434 // Don't bother for PHI nodes.
435 if (isa<PHINode>(User))
438 // Figure out which BB this cmp is used in.
439 BasicBlock *UserBB = User->getParent();
441 // If this user is in the same block as the cmp, don't change the cmp.
442 if (UserBB == DefBB) continue;
444 // If we have already inserted a cmp into this block, use it.
445 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
448 BasicBlock::iterator InsertPt = UserBB->begin();
449 while (isa<PHINode>(InsertPt)) ++InsertPt;
452 CmpInst::create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
453 CI->getOperand(1), "", InsertPt);
457 // Replace a use of the cmp with a use of the new cmp.
458 TheUse = InsertedCmp;
461 // If we removed all uses, nuke the cmp.
463 CI->eraseFromParent();
468 /// EraseDeadInstructions - Erase any dead instructions
469 static void EraseDeadInstructions(Value *V) {
470 Instruction *I = dyn_cast<Instruction>(V);
471 if (!I || !I->use_empty()) return;
473 SmallPtrSet<Instruction*, 16> Insts;
476 while (!Insts.empty()) {
479 if (isInstructionTriviallyDead(I)) {
480 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
481 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
483 I->eraseFromParent();
489 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode which
490 /// holds actual Value*'s for register values.
491 struct ExtAddrMode : public TargetLowering::AddrMode {
494 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
498 static std::ostream &operator<<(std::ostream &OS, const ExtAddrMode &AM) {
499 bool NeedPlus = false;
502 OS << (NeedPlus ? " + " : "")
503 << "GV:%" << AM.BaseGV->getName(), NeedPlus = true;
506 OS << (NeedPlus ? " + " : "") << AM.BaseOffs, NeedPlus = true;
509 OS << (NeedPlus ? " + " : "")
510 << "Base:%" << AM.BaseReg->getName(), NeedPlus = true;
512 OS << (NeedPlus ? " + " : "")
513 << AM.Scale << "*%" << AM.ScaledReg->getName(), NeedPlus = true;
518 void ExtAddrMode::dump() const {
519 cerr << *this << "\n";
522 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
523 const Type *AccessTy, ExtAddrMode &AddrMode,
524 SmallVector<Instruction*, 16> &AddrModeInsts,
525 const TargetLowering &TLI, unsigned Depth);
527 /// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
528 /// Addr into the specified addressing mode. If Addr can't be added to AddrMode
529 /// this returns false. This assumes that Addr is either a pointer type or
530 /// intptr_t for the target.
531 static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
532 ExtAddrMode &AddrMode,
533 SmallVector<Instruction*, 16> &AddrModeInsts,
534 const TargetLowering &TLI,
537 // If this is a global variable, fold it into the addressing mode if possible.
538 if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
539 if (AddrMode.BaseGV == 0) {
540 AddrMode.BaseGV = GV;
541 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
545 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
546 AddrMode.BaseOffs += CI->getSExtValue();
547 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
549 AddrMode.BaseOffs -= CI->getSExtValue();
550 } else if (isa<ConstantPointerNull>(Addr)) {
554 // Look through constant exprs and instructions.
555 unsigned Opcode = ~0U;
557 if (Instruction *I = dyn_cast<Instruction>(Addr)) {
558 Opcode = I->getOpcode();
560 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
561 Opcode = CE->getOpcode();
565 // Limit recursion to avoid exponential behavior.
566 if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
568 // If this is really an instruction, add it to our list of related
570 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
571 AddrModeInsts.push_back(I);
574 case Instruction::PtrToInt:
575 // PtrToInt is always a noop, as we know that the int type is pointer sized.
576 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
577 AddrMode, AddrModeInsts, TLI, Depth))
580 case Instruction::IntToPtr:
581 // This inttoptr is a no-op if the integer type is pointer sized.
582 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
583 TLI.getPointerTy()) {
584 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
585 AddrMode, AddrModeInsts, TLI, Depth))
589 case Instruction::Add: {
590 // Check to see if we can merge in the RHS then the LHS. If so, we win.
591 ExtAddrMode BackupAddrMode = AddrMode;
592 unsigned OldSize = AddrModeInsts.size();
593 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
594 AddrMode, AddrModeInsts, TLI, Depth+1) &&
595 FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
596 AddrMode, AddrModeInsts, TLI, Depth+1))
599 // Restore the old addr mode info.
600 AddrMode = BackupAddrMode;
601 AddrModeInsts.resize(OldSize);
603 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
604 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
605 AddrMode, AddrModeInsts, TLI, Depth+1) &&
606 FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
607 AddrMode, AddrModeInsts, TLI, Depth+1))
610 // Otherwise we definitely can't merge the ADD in.
611 AddrMode = BackupAddrMode;
612 AddrModeInsts.resize(OldSize);
615 case Instruction::Or: {
616 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
618 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
621 case Instruction::Mul:
622 case Instruction::Shl: {
623 // Can only handle X*C and X << C, and can only handle this when the scale
624 // field is available.
625 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
627 int64_t Scale = RHS->getSExtValue();
628 if (Opcode == Instruction::Shl)
631 if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
632 AddrMode, AddrModeInsts, TLI, Depth))
636 case Instruction::GetElementPtr: {
637 // Scan the GEP. We check it if it contains constant offsets and at most
638 // one variable offset.
639 int VariableOperand = -1;
640 unsigned VariableScale = 0;
642 int64_t ConstantOffset = 0;
643 const TargetData *TD = TLI.getTargetData();
644 gep_type_iterator GTI = gep_type_begin(AddrInst);
645 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
646 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
647 const StructLayout *SL = TD->getStructLayout(STy);
649 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
650 ConstantOffset += SL->getElementOffset(Idx);
652 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
653 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
654 ConstantOffset += CI->getSExtValue()*TypeSize;
655 } else if (TypeSize) { // Scales of zero don't do anything.
656 // We only allow one variable index at the moment.
657 if (VariableOperand != -1) {
658 VariableOperand = -2;
662 // Remember the variable index.
664 VariableScale = TypeSize;
669 // If the GEP had multiple variable indices, punt.
670 if (VariableOperand == -2)
673 // A common case is for the GEP to only do a constant offset. In this case,
674 // just add it to the disp field and check validity.
675 if (VariableOperand == -1) {
676 AddrMode.BaseOffs += ConstantOffset;
677 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
678 // Check to see if we can fold the base pointer in too.
679 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
680 AddrMode, AddrModeInsts, TLI,
684 AddrMode.BaseOffs -= ConstantOffset;
686 // Check that this has no base reg yet. If so, we won't have a place to
687 // put the base of the GEP (assuming it is not a null ptr).
688 bool SetBaseReg = false;
689 if (AddrMode.HasBaseReg) {
690 if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
693 AddrMode.HasBaseReg = true;
694 AddrMode.BaseReg = AddrInst->getOperand(0);
698 // See if the scale amount is valid for this target.
699 AddrMode.BaseOffs += ConstantOffset;
700 if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
701 VariableScale, AccessTy, AddrMode,
702 AddrModeInsts, TLI, Depth)) {
703 if (!SetBaseReg) return true;
705 // If this match succeeded, we know that we can form an address with the
706 // GepBase as the basereg. See if we can match *more*.
707 AddrMode.HasBaseReg = false;
708 AddrMode.BaseReg = 0;
709 if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
710 AddrMode, AddrModeInsts, TLI,
713 // Strange, shouldn't happen. Restore the base reg and succeed the easy
715 AddrMode.HasBaseReg = true;
716 AddrMode.BaseReg = AddrInst->getOperand(0);
720 AddrMode.BaseOffs -= ConstantOffset;
722 AddrMode.HasBaseReg = false;
723 AddrMode.BaseReg = 0;
730 if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
731 assert(AddrModeInsts.back() == I && "Stack imbalance");
732 AddrModeInsts.pop_back();
735 // Worse case, the target should support [reg] addressing modes. :)
736 if (!AddrMode.HasBaseReg) {
737 AddrMode.HasBaseReg = true;
738 // Still check for legality in case the target supports [imm] but not [i+r].
739 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
740 AddrMode.BaseReg = Addr;
743 AddrMode.HasBaseReg = false;
746 // If the base register is already taken, see if we can do [r+r].
747 if (AddrMode.Scale == 0) {
749 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
750 AddrMode.ScaledReg = Addr;
759 /// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
760 /// addressing mode. Return true if this addr mode is legal for the target,
762 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
763 const Type *AccessTy, ExtAddrMode &AddrMode,
764 SmallVector<Instruction*, 16> &AddrModeInsts,
765 const TargetLowering &TLI, unsigned Depth) {
766 // If we already have a scale of this value, we can add to it, otherwise, we
767 // need an available scale field.
768 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
771 ExtAddrMode InputAddrMode = AddrMode;
773 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
774 // [A+B + A*7] -> [B+A*8].
775 AddrMode.Scale += Scale;
776 AddrMode.ScaledReg = ScaleReg;
778 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
779 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
780 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
781 // X*Scale + C*Scale to addr mode.
782 BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
783 if (BinOp && BinOp->getOpcode() == Instruction::Add &&
784 isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
786 InputAddrMode.Scale = Scale;
787 InputAddrMode.ScaledReg = BinOp->getOperand(0);
788 InputAddrMode.BaseOffs +=
789 cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
790 if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
791 AddrModeInsts.push_back(BinOp);
792 AddrMode = InputAddrMode;
797 // Otherwise, not (x+c)*scale, just return what we have.
801 // Otherwise, back this attempt out.
802 AddrMode.Scale -= Scale;
803 if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
809 /// IsNonLocalValue - Return true if the specified values are defined in a
810 /// different basic block than BB.
811 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
812 if (Instruction *I = dyn_cast<Instruction>(V))
813 return I->getParent() != BB;
817 /// OptimizeLoadStoreInst - Load and Store Instructions have often have
818 /// addressing modes that can do significant amounts of computation. As such,
819 /// instruction selection will try to get the load or store to do as much
820 /// computation as possible for the program. The problem is that isel can only
821 /// see within a single block. As such, we sink as much legal addressing mode
822 /// stuff into the block as possible.
823 bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
824 const Type *AccessTy,
825 DenseMap<Value*,Value*> &SunkAddrs) {
826 // Figure out what addressing mode will be built up for this operation.
827 SmallVector<Instruction*, 16> AddrModeInsts;
828 ExtAddrMode AddrMode;
829 bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
830 AddrModeInsts, *TLI, 0);
831 Success = Success; assert(Success && "Couldn't select *anything*?");
833 // Check to see if any of the instructions supersumed by this addr mode are
834 // non-local to I's BB.
835 bool AnyNonLocal = false;
836 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
837 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
843 // If all the instructions matched are already in this BB, don't do anything.
845 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
849 // Insert this computation right after this user. Since our caller is
850 // scanning from the top of the BB to the bottom, reuse of the expr are
851 // guaranteed to happen later.
852 BasicBlock::iterator InsertPt = LdStInst;
854 // Now that we determined the addressing expression we want to use and know
855 // that we have to sink it into this block. Check to see if we have already
856 // done this for some other load/store instr in this block. If so, reuse the
858 Value *&SunkAddr = SunkAddrs[Addr];
860 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
861 if (SunkAddr->getType() != Addr->getType())
862 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
864 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
865 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
868 // Start with the scale value.
869 if (AddrMode.Scale) {
870 Value *V = AddrMode.ScaledReg;
871 if (V->getType() == IntPtrTy) {
873 } else if (isa<PointerType>(V->getType())) {
874 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
875 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
876 cast<IntegerType>(V->getType())->getBitWidth()) {
877 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
879 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
881 if (AddrMode.Scale != 1)
882 V = BinaryOperator::createMul(V, ConstantInt::get(IntPtrTy,
884 "sunkaddr", InsertPt);
888 // Add in the base register.
889 if (AddrMode.BaseReg) {
890 Value *V = AddrMode.BaseReg;
891 if (V->getType() != IntPtrTy)
892 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
894 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
899 // Add in the BaseGV if present.
900 if (AddrMode.BaseGV) {
901 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
904 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
909 // Add in the Base Offset if present.
910 if (AddrMode.BaseOffs) {
911 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
913 Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
919 SunkAddr = Constant::getNullValue(Addr->getType());
921 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
924 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
926 if (Addr->use_empty())
927 EraseDeadInstructions(Addr);
931 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
932 BasicBlock *DefBB = I->getParent();
934 // If both result of the {s|z}xt and its source are live out, rewrite all
935 // other uses of the source with result of extension.
936 Value *Src = I->getOperand(0);
937 if (Src->hasOneUse())
940 // Only do this xform if truncating is free.
941 if (!TLI->isTruncateFree(I->getType(), Src->getType()))
944 // Only safe to perform the optimization if the source is also defined in
946 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
949 bool DefIsLiveOut = false;
950 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
952 Instruction *User = cast<Instruction>(*UI);
954 // Figure out which BB this ext is used in.
955 BasicBlock *UserBB = User->getParent();
956 if (UserBB == DefBB) continue;
963 // Make sure non of the uses are PHI nodes.
964 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
966 Instruction *User = cast<Instruction>(*UI);
967 BasicBlock *UserBB = User->getParent();
968 if (UserBB == DefBB) continue;
969 // Be conservative. We don't want this xform to end up introducing
970 // reloads just before load / store instructions.
971 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
975 // InsertedTruncs - Only insert one trunc in each block once.
976 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
978 bool MadeChange = false;
979 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
981 Use &TheUse = UI.getUse();
982 Instruction *User = cast<Instruction>(*UI);
984 // Figure out which BB this ext is used in.
985 BasicBlock *UserBB = User->getParent();
986 if (UserBB == DefBB) continue;
988 // Both src and def are live in this block. Rewrite the use.
989 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
991 if (!InsertedTrunc) {
992 BasicBlock::iterator InsertPt = UserBB->begin();
993 while (isa<PHINode>(InsertPt)) ++InsertPt;
995 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
998 // Replace a use of the {s|z}ext source with a use of the result.
999 TheUse = InsertedTrunc;
1007 // In this pass we look for GEP and cast instructions that are used
1008 // across basic blocks and rewrite them to improve basic-block-at-a-time
1010 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1011 bool MadeChange = false;
1013 // Split all critical edges where the dest block has a PHI and where the phi
1014 // has shared immediate operands.
1015 TerminatorInst *BBTI = BB.getTerminator();
1016 if (BBTI->getNumSuccessors() > 1) {
1017 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1018 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1019 isCriticalEdge(BBTI, i, true))
1020 SplitEdgeNicely(BBTI, i, this);
1024 // Keep track of non-local addresses that have been sunk into this block.
1025 // This allows us to avoid inserting duplicate code for blocks with multiple
1026 // load/stores of the same address.
1027 DenseMap<Value*, Value*> SunkAddrs;
1029 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1030 Instruction *I = BBI++;
1032 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1033 // If the source of the cast is a constant, then this should have
1034 // already been constant folded. The only reason NOT to constant fold
1035 // it is if something (e.g. LSR) was careful to place the constant
1036 // evaluation in a block other than then one that uses it (e.g. to hoist
1037 // the address of globals out of a loop). If this is the case, we don't
1038 // want to forward-subst the cast.
1039 if (isa<Constant>(CI->getOperand(0)))
1042 bool Change = false;
1044 Change = OptimizeNoopCopyExpression(CI, *TLI);
1045 MadeChange |= Change;
1048 if (OptExtUses && !Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1049 MadeChange |= OptimizeExtUses(I);
1050 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1051 MadeChange |= OptimizeCmpExpression(CI);
1052 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1054 MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
1056 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1058 MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
1059 SI->getOperand(0)->getType(),
1061 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1062 if (GEPI->hasAllZeroIndices()) {
1063 /// The GEP operand must be a pointer, so must its result -> BitCast
1064 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1065 GEPI->getName(), GEPI);
1066 GEPI->replaceAllUsesWith(NC);
1067 GEPI->eraseFromParent();
1071 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1072 // If we found an inline asm expession, and if the target knows how to
1073 // lower it to normal LLVM code, do so now.
1074 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1075 if (const TargetAsmInfo *TAI =
1076 TLI->getTargetMachine().getTargetAsmInfo()) {
1077 if (TAI->ExpandInlineAsm(CI))