1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
36 #include "llvm/Support/PatternMatch.h"
38 using namespace llvm::PatternMatch;
41 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
42 /// TLI - Keep a pointer of a TargetLowering to consult for determining
43 /// transformation profitability.
44 const TargetLowering *TLI;
46 static char ID; // Pass identification, replacement for typeid
47 explicit CodeGenPrepare(const TargetLowering *tli = 0)
48 : FunctionPass(&ID), TLI(tli) {}
49 bool runOnFunction(Function &F);
52 bool EliminateMostlyEmptyBlocks(Function &F);
53 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
54 void EliminateMostlyEmptyBlock(BasicBlock *BB);
55 bool OptimizeBlock(BasicBlock &BB);
56 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
57 DenseMap<Value*,Value*> &SunkAddrs);
58 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
59 DenseMap<Value*,Value*> &SunkAddrs);
60 bool OptimizeExtUses(Instruction *I);
64 char CodeGenPrepare::ID = 0;
65 static RegisterPass<CodeGenPrepare> X("codegenprepare",
66 "Optimize for code generation");
68 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
69 return new CodeGenPrepare(TLI);
73 bool CodeGenPrepare::runOnFunction(Function &F) {
74 bool EverMadeChange = false;
76 // First pass, eliminate blocks that contain only PHI nodes and an
77 // unconditional branch.
78 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
80 bool MadeChange = true;
83 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
84 MadeChange |= OptimizeBlock(*BB);
85 EverMadeChange |= MadeChange;
87 return EverMadeChange;
90 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
91 /// and an unconditional branch. Passes before isel (e.g. LSR/loopsimplify)
92 /// often split edges in ways that are non-optimal for isel. Start by
93 /// eliminating these blocks so we can split them the way we want them.
94 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
95 bool MadeChange = false;
96 // Note that this intentionally skips the entry block.
97 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
100 // If this block doesn't end with an uncond branch, ignore it.
101 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
102 if (!BI || !BI->isUnconditional())
105 // If the instruction before the branch isn't a phi node, then other stuff
106 // is happening here.
107 BasicBlock::iterator BBI = BI;
108 if (BBI != BB->begin()) {
110 if (!isa<PHINode>(BBI)) continue;
113 // Do not break infinite loops.
114 BasicBlock *DestBB = BI->getSuccessor(0);
118 if (!CanMergeBlocks(BB, DestBB))
121 EliminateMostlyEmptyBlock(BB);
127 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
128 /// single uncond branch between them, and BB contains no other non-phi
130 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
131 const BasicBlock *DestBB) const {
132 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
133 // the successor. If there are more complex condition (e.g. preheaders),
134 // don't mess around with them.
135 BasicBlock::const_iterator BBI = BB->begin();
136 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
137 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
139 const Instruction *User = cast<Instruction>(*UI);
140 if (User->getParent() != DestBB || !isa<PHINode>(User))
142 // If User is inside DestBB block and it is a PHINode then check
143 // incoming value. If incoming value is not from BB then this is
144 // a complex condition (e.g. preheaders) we want to avoid here.
145 if (User->getParent() == DestBB) {
146 if (const PHINode *UPN = dyn_cast<PHINode>(User))
147 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
148 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
149 if (Insn && Insn->getParent() == BB &&
150 Insn->getParent() != UPN->getIncomingBlock(I))
157 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
158 // and DestBB may have conflicting incoming values for the block. If so, we
159 // can't merge the block.
160 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
161 if (!DestBBPN) return true; // no conflict.
163 // Collect the preds of BB.
164 SmallPtrSet<const BasicBlock*, 16> BBPreds;
165 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
166 // It is faster to get preds from a PHI than with pred_iterator.
167 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
168 BBPreds.insert(BBPN->getIncomingBlock(i));
170 BBPreds.insert(pred_begin(BB), pred_end(BB));
173 // Walk the preds of DestBB.
174 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
175 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
176 if (BBPreds.count(Pred)) { // Common predecessor?
177 BBI = DestBB->begin();
178 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
179 const Value *V1 = PN->getIncomingValueForBlock(Pred);
180 const Value *V2 = PN->getIncomingValueForBlock(BB);
182 // If V2 is a phi node in BB, look up what the mapped value will be.
183 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
184 if (V2PN->getParent() == BB)
185 V2 = V2PN->getIncomingValueForBlock(Pred);
187 // If there is a conflict, bail out.
188 if (V1 != V2) return false;
197 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
198 /// an unconditional branch in it.
199 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
200 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
201 BasicBlock *DestBB = BI->getSuccessor(0);
203 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
205 // If the destination block has a single pred, then this is a trivial edge,
207 if (DestBB->getSinglePredecessor()) {
208 // If DestBB has single-entry PHI nodes, fold them.
209 while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
210 Value *NewVal = PN->getIncomingValue(0);
211 // Replace self referencing PHI with undef, it must be dead.
212 if (NewVal == PN) NewVal = UndefValue::get(PN->getType());
213 PN->replaceAllUsesWith(NewVal);
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.
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.
339 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
340 // If this is a noop copy,
341 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
342 MVT DstVT = TLI.getValueType(CI->getType());
344 // This is an fp<->int conversion?
345 if (SrcVT.isInteger() != DstVT.isInteger())
348 // If this is an extension, it will be a zero or sign extension, which
350 if (SrcVT.bitsLT(DstVT)) return false;
352 // If these values will be promoted, find out what they will be promoted
353 // to. This helps us consider truncates on PPC as noop copies when they
355 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
356 SrcVT = TLI.getTypeToTransformTo(SrcVT);
357 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
358 DstVT = TLI.getTypeToTransformTo(DstVT);
360 // If, after promotion, these are the same types, this is a noop copy.
364 BasicBlock *DefBB = CI->getParent();
366 /// InsertedCasts - Only insert a cast in each block once.
367 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
369 bool MadeChange = false;
370 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
372 Use &TheUse = UI.getUse();
373 Instruction *User = cast<Instruction>(*UI);
375 // Figure out which BB this cast is used in. For PHI's this is the
376 // appropriate predecessor block.
377 BasicBlock *UserBB = User->getParent();
378 if (PHINode *PN = dyn_cast<PHINode>(User)) {
379 unsigned OpVal = UI.getOperandNo()/2;
380 UserBB = PN->getIncomingBlock(OpVal);
383 // Preincrement use iterator so we don't invalidate it.
386 // If this user is in the same block as the cast, don't change the cast.
387 if (UserBB == DefBB) continue;
389 // If we have already inserted a cast into this block, use it.
390 CastInst *&InsertedCast = InsertedCasts[UserBB];
393 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
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.
406 if (CI->use_empty()) {
407 CI->eraseFromParent();
414 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
415 /// the number of virtual registers that must be created and coalesced. This is
416 /// a clear win except on targets with multiple condition code registers
417 /// (PowerPC), where it might lose; some adjustment may be wanted there.
419 /// Return true if any changes are made.
420 static bool OptimizeCmpExpression(CmpInst *CI) {
421 BasicBlock *DefBB = CI->getParent();
423 /// InsertedCmp - Only insert a cmp in each block once.
424 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
426 bool MadeChange = false;
427 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
429 Use &TheUse = UI.getUse();
430 Instruction *User = cast<Instruction>(*UI);
432 // Preincrement use iterator so we don't invalidate it.
435 // Don't bother for PHI nodes.
436 if (isa<PHINode>(User))
439 // Figure out which BB this cmp is used in.
440 BasicBlock *UserBB = User->getParent();
442 // If this user is in the same block as the cmp, don't change the cmp.
443 if (UserBB == DefBB) continue;
445 // If we have already inserted a cmp into this block, use it.
446 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
449 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
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, recursively.
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();
488 //===----------------------------------------------------------------------===//
489 // Addressing Mode Analysis and Optimization
490 //===----------------------------------------------------------------------===//
493 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
494 /// which holds actual Value*'s for register values.
495 struct ExtAddrMode : public TargetLowering::AddrMode {
498 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
499 void print(OStream &OS) const;
505 } // end anonymous namespace
507 static OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
512 void ExtAddrMode::print(OStream &OS) const {
513 bool NeedPlus = false;
516 OS << (NeedPlus ? " + " : "")
517 << "GV:%" << BaseGV->getName(), NeedPlus = true;
520 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
523 OS << (NeedPlus ? " + " : "")
524 << "Base:%" << BaseReg->getName(), NeedPlus = true;
526 OS << (NeedPlus ? " + " : "")
527 << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
533 /// AddressingModeMatcher - This class exposes a single public method, which is
534 /// used to construct a "maximal munch" of the addressing mode for the target
535 /// specified by TLI for an access to "V" with an access type of AccessTy. This
536 /// returns the addressing mode that is actually matched by value, but also
537 /// returns the list of instructions involved in that addressing computation in
539 class AddressingModeMatcher {
540 SmallVectorImpl<Instruction*> &AddrModeInsts;
541 const TargetLowering &TLI;
542 const Type *AccessTy;
543 ExtAddrMode &AddrMode;
544 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
545 const TargetLowering &T, const Type *AT,ExtAddrMode &AM)
546 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), AddrMode(AM) {}
549 static ExtAddrMode Match(Value *V, const Type *AccessTy,
550 SmallVectorImpl<Instruction*> &AddrModeInsts,
551 const TargetLowering &TLI) {
555 AddressingModeMatcher(AddrModeInsts,TLI,AccessTy,Result).MatchAddr(V, 0);
556 Success = Success; assert(Success && "Couldn't select *anything*?");
560 bool MatchScaledValue(Value *ScaleReg, int64_t Scale);
561 bool MatchAddr(Value *V, unsigned Depth);
562 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
564 } // end anonymous namespace
566 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
567 /// Return true and update AddrMode if this addr mode is legal for the target,
569 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale) {
570 // If we already have a scale of this value, we can add to it, otherwise, we
571 // need an available scale field.
572 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
575 ExtAddrMode TestAddrMode = AddrMode;
577 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
578 // [A+B + A*7] -> [B+A*8].
579 TestAddrMode.Scale += Scale;
580 TestAddrMode.ScaledReg = ScaleReg;
582 // If the new address isn't legal, bail out.
583 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
586 // It was legal, so commit it.
587 AddrMode = TestAddrMode;
589 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
590 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
591 // X*Scale + C*Scale to addr mode.
592 ConstantInt *CI; Value *AddLHS;
593 if (match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
594 TestAddrMode.ScaledReg = AddLHS;
595 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
597 // If this addressing mode is legal, commit it and remember that we folded
599 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
600 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
601 AddrMode = TestAddrMode;
606 // Otherwise, not (x+c)*scale, just return what we have.
611 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
612 /// fold the operation into the addressing mode. If so, update the addressing
613 /// mode and return true, otherwise return false without modifying AddrMode.
614 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
616 // Avoid exponential behavior on extremely deep expression trees.
617 if (Depth >= 5) return false;
620 case Instruction::PtrToInt:
621 // PtrToInt is always a noop, as we know that the int type is pointer sized.
622 return MatchAddr(AddrInst->getOperand(0), Depth);
623 case Instruction::IntToPtr:
624 // This inttoptr is a no-op if the integer type is pointer sized.
625 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
627 return MatchAddr(AddrInst->getOperand(0), Depth);
629 case Instruction::Add: {
630 // Check to see if we can merge in the RHS then the LHS. If so, we win.
631 ExtAddrMode BackupAddrMode = AddrMode;
632 unsigned OldSize = AddrModeInsts.size();
633 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
634 MatchAddr(AddrInst->getOperand(0), Depth+1))
637 // Restore the old addr mode info.
638 AddrMode = BackupAddrMode;
639 AddrModeInsts.resize(OldSize);
641 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
642 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
643 MatchAddr(AddrInst->getOperand(1), Depth+1))
646 // Otherwise we definitely can't merge the ADD in.
647 AddrMode = BackupAddrMode;
648 AddrModeInsts.resize(OldSize);
651 case Instruction::Or: {
652 //ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
654 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
657 case Instruction::Mul:
658 case Instruction::Shl: {
659 // Can only handle X*C and X << C.
660 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
661 if (!RHS) return false;
662 int64_t Scale = RHS->getSExtValue();
663 if (Opcode == Instruction::Shl)
666 return MatchScaledValue(AddrInst->getOperand(0), Scale);
668 case Instruction::GetElementPtr: {
669 // Scan the GEP. We check it if it contains constant offsets and at most
670 // one variable offset.
671 int VariableOperand = -1;
672 unsigned VariableScale = 0;
674 int64_t ConstantOffset = 0;
675 const TargetData *TD = TLI.getTargetData();
676 gep_type_iterator GTI = gep_type_begin(AddrInst);
677 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
678 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
679 const StructLayout *SL = TD->getStructLayout(STy);
681 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
682 ConstantOffset += SL->getElementOffset(Idx);
684 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
685 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
686 ConstantOffset += CI->getSExtValue()*TypeSize;
687 } else if (TypeSize) { // Scales of zero don't do anything.
688 // We only allow one variable index at the moment.
689 if (VariableOperand != -1)
692 // Remember the variable index.
694 VariableScale = TypeSize;
699 // A common case is for the GEP to only do a constant offset. In this case,
700 // just add it to the disp field and check validity.
701 if (VariableOperand == -1) {
702 AddrMode.BaseOffs += ConstantOffset;
703 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
704 // Check to see if we can fold the base pointer in too.
705 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
708 AddrMode.BaseOffs -= ConstantOffset;
712 // Save the valid addressing mode in case we can't match.
713 ExtAddrMode BackupAddrMode = AddrMode;
715 // Check that this has no base reg yet. If so, we won't have a place to
716 // put the base of the GEP (assuming it is not a null ptr).
717 bool SetBaseReg = true;
718 if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
719 SetBaseReg = false; // null pointer base doesn't need representation.
720 else if (AddrMode.HasBaseReg)
721 return false; // Base register already specified, can't match GEP.
723 // Otherwise, we'll use the GEP base as the BaseReg.
724 AddrMode.HasBaseReg = true;
725 AddrMode.BaseReg = AddrInst->getOperand(0);
728 // See if the scale and offset amount is valid for this target.
729 AddrMode.BaseOffs += ConstantOffset;
731 // FIXME: If VariableScale = 1, just call MatchAddr recursively?
732 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),VariableScale)){
733 AddrMode = BackupAddrMode;
737 // If we have a null as the base of the GEP, folding in the constant offset
738 // plus variable scale is all we can do.
739 if (!SetBaseReg) return true;
741 // If this match succeeded, we know that we can form an address with the
742 // GepBase as the basereg. Match the base pointer of the GEP more
743 // aggressively by zeroing out BaseReg and rematching. If the base is
744 // (for example) another GEP, this allows merging in that other GEP into
745 // the addressing mode we're forming.
746 AddrMode.HasBaseReg = false;
747 AddrMode.BaseReg = 0;
748 bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
749 assert(Success && "MatchAddr should be able to fill in BaseReg!");
757 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
758 /// addressing mode. If Addr can't be added to AddrMode this returns false and
759 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
760 /// or intptr_t for the target.
762 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
763 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
764 // Fold in immediates if legal for the target.
765 AddrMode.BaseOffs += CI->getSExtValue();
766 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
768 AddrMode.BaseOffs -= CI->getSExtValue();
769 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
770 // If this is a global variable, try to fold it into the addressing mode.
771 if (AddrMode.BaseGV == 0) {
772 AddrMode.BaseGV = GV;
773 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
777 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
778 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
779 AddrModeInsts.push_back(I);
782 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
783 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
785 } else if (isa<ConstantPointerNull>(Addr)) {
786 // Null pointer gets folded without affecting the addressing mode.
790 // Worse case, the target should support [reg] addressing modes. :)
791 if (!AddrMode.HasBaseReg) {
792 AddrMode.HasBaseReg = true;
793 // Still check for legality in case the target supports [imm] but not [i+r].
794 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
795 AddrMode.BaseReg = Addr;
798 AddrMode.HasBaseReg = false;
801 // If the base register is already taken, see if we can do [r+r].
802 if (AddrMode.Scale == 0) {
804 if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
805 AddrMode.ScaledReg = Addr;
815 //===----------------------------------------------------------------------===//
816 // Memory Optimization
817 //===----------------------------------------------------------------------===//
819 /// IsNonLocalValue - Return true if the specified values are defined in a
820 /// different basic block than BB.
821 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
822 if (Instruction *I = dyn_cast<Instruction>(V))
823 return I->getParent() != BB;
827 /// OptimizeMemoryInst - Load and Store Instructions have often have
828 /// addressing modes that can do significant amounts of computation. As such,
829 /// instruction selection will try to get the load or store to do as much
830 /// computation as possible for the program. The problem is that isel can only
831 /// see within a single block. As such, we sink as much legal addressing mode
832 /// stuff into the block as possible.
834 /// This method is used to optimize both load/store and inline asms with memory
836 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *LdStInst, Value *Addr,
837 const Type *AccessTy,
838 DenseMap<Value*,Value*> &SunkAddrs) {
839 // Figure out what addressing mode will be built up for this operation.
840 SmallVector<Instruction*, 16> AddrModeInsts;
841 ExtAddrMode AddrMode =
842 AddressingModeMatcher::Match(Addr, AccessTy, AddrModeInsts, *TLI);
844 // Check to see if any of the instructions supersumed by this addr mode are
845 // non-local to I's BB.
846 bool AnyNonLocal = false;
847 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
848 if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
854 // If all the instructions matched are already in this BB, don't do anything.
856 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
860 // Insert this computation right after this user. Since our caller is
861 // scanning from the top of the BB to the bottom, reuse of the expr are
862 // guaranteed to happen later.
863 BasicBlock::iterator InsertPt = LdStInst;
865 // Now that we determined the addressing expression we want to use and know
866 // that we have to sink it into this block. Check to see if we have already
867 // done this for some other load/store instr in this block. If so, reuse the
869 Value *&SunkAddr = SunkAddrs[Addr];
871 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
872 if (SunkAddr->getType() != Addr->getType())
873 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
875 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
876 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
879 // Start with the scale value.
880 if (AddrMode.Scale) {
881 Value *V = AddrMode.ScaledReg;
882 if (V->getType() == IntPtrTy) {
884 } else if (isa<PointerType>(V->getType())) {
885 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
886 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
887 cast<IntegerType>(V->getType())->getBitWidth()) {
888 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
890 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
892 if (AddrMode.Scale != 1)
893 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
895 "sunkaddr", InsertPt);
899 // Add in the base register.
900 if (AddrMode.BaseReg) {
901 Value *V = AddrMode.BaseReg;
902 if (V->getType() != IntPtrTy)
903 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
905 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
910 // Add in the BaseGV if present.
911 if (AddrMode.BaseGV) {
912 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
915 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
920 // Add in the Base Offset if present.
921 if (AddrMode.BaseOffs) {
922 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
924 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
930 SunkAddr = Constant::getNullValue(Addr->getType());
932 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
935 LdStInst->replaceUsesOfWith(Addr, SunkAddr);
937 if (Addr->use_empty())
938 EraseDeadInstructions(Addr);
942 /// OptimizeInlineAsmInst - If there are any memory operands, use
943 /// OptimizeMemoryInst to sink their address computing into the block when
944 /// possible / profitable.
945 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
946 DenseMap<Value*,Value*> &SunkAddrs) {
947 bool MadeChange = false;
948 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
950 // Do a prepass over the constraints, canonicalizing them, and building up the
951 // ConstraintOperands list.
952 std::vector<InlineAsm::ConstraintInfo>
953 ConstraintInfos = IA->ParseConstraints();
955 /// ConstraintOperands - Information about all of the constraints.
956 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
957 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
958 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
960 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
961 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
963 // Compute the value type for each operand.
964 switch (OpInfo.Type) {
965 case InlineAsm::isOutput:
966 if (OpInfo.isIndirect)
967 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
969 case InlineAsm::isInput:
970 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
972 case InlineAsm::isClobber:
977 // Compute the constraint code and ConstraintType to use.
978 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
979 OpInfo.ConstraintType == TargetLowering::C_Memory);
981 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
983 Value *OpVal = OpInfo.CallOperandVal;
984 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
991 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
992 BasicBlock *DefBB = I->getParent();
994 // If both result of the {s|z}xt and its source are live out, rewrite all
995 // other uses of the source with result of extension.
996 Value *Src = I->getOperand(0);
997 if (Src->hasOneUse())
1000 // Only do this xform if truncating is free.
1001 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1004 // Only safe to perform the optimization if the source is also defined in
1006 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1009 bool DefIsLiveOut = false;
1010 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1012 Instruction *User = cast<Instruction>(*UI);
1014 // Figure out which BB this ext is used in.
1015 BasicBlock *UserBB = User->getParent();
1016 if (UserBB == DefBB) continue;
1017 DefIsLiveOut = true;
1023 // Make sure non of the uses are PHI nodes.
1024 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1026 Instruction *User = cast<Instruction>(*UI);
1027 BasicBlock *UserBB = User->getParent();
1028 if (UserBB == DefBB) continue;
1029 // Be conservative. We don't want this xform to end up introducing
1030 // reloads just before load / store instructions.
1031 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1035 // InsertedTruncs - Only insert one trunc in each block once.
1036 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1038 bool MadeChange = false;
1039 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1041 Use &TheUse = UI.getUse();
1042 Instruction *User = cast<Instruction>(*UI);
1044 // Figure out which BB this ext is used in.
1045 BasicBlock *UserBB = User->getParent();
1046 if (UserBB == DefBB) continue;
1048 // Both src and def are live in this block. Rewrite the use.
1049 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1051 if (!InsertedTrunc) {
1052 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
1054 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1057 // Replace a use of the {s|z}ext source with a use of the result.
1058 TheUse = InsertedTrunc;
1066 // In this pass we look for GEP and cast instructions that are used
1067 // across basic blocks and rewrite them to improve basic-block-at-a-time
1069 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1070 bool MadeChange = false;
1072 // Split all critical edges where the dest block has a PHI and where the phi
1073 // has shared immediate operands.
1074 TerminatorInst *BBTI = BB.getTerminator();
1075 if (BBTI->getNumSuccessors() > 1) {
1076 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1077 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1078 isCriticalEdge(BBTI, i, true))
1079 SplitEdgeNicely(BBTI, i, this);
1083 // Keep track of non-local addresses that have been sunk into this block.
1084 // This allows us to avoid inserting duplicate code for blocks with multiple
1085 // load/stores of the same address.
1086 DenseMap<Value*, Value*> SunkAddrs;
1088 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1089 Instruction *I = BBI++;
1091 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1092 // If the source of the cast is a constant, then this should have
1093 // already been constant folded. The only reason NOT to constant fold
1094 // it is if something (e.g. LSR) was careful to place the constant
1095 // evaluation in a block other than then one that uses it (e.g. to hoist
1096 // the address of globals out of a loop). If this is the case, we don't
1097 // want to forward-subst the cast.
1098 if (isa<Constant>(CI->getOperand(0)))
1101 bool Change = false;
1103 Change = OptimizeNoopCopyExpression(CI, *TLI);
1104 MadeChange |= Change;
1107 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1108 MadeChange |= OptimizeExtUses(I);
1109 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1110 MadeChange |= OptimizeCmpExpression(CI);
1111 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1113 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1115 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1117 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1118 SI->getOperand(0)->getType(),
1120 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1121 if (GEPI->hasAllZeroIndices()) {
1122 /// The GEP operand must be a pointer, so must its result -> BitCast
1123 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1124 GEPI->getName(), GEPI);
1125 GEPI->replaceAllUsesWith(NC);
1126 GEPI->eraseFromParent();
1130 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1131 // If we found an inline asm expession, and if the target knows how to
1132 // lower it to normal LLVM code, do so now.
1133 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1134 if (const TargetAsmInfo *TAI =
1135 TLI->getTargetMachine().getTargetAsmInfo()) {
1136 if (TAI->ExpandInlineAsm(CI))
1139 // Sink address computing for memory operands into the block.
1140 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);