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 MergeBasicBlockIntoOnlyPred(DestBB);
209 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
213 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
214 // to handle the new incoming edges it is about to have.
216 for (BasicBlock::iterator BBI = DestBB->begin();
217 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
218 // Remove the incoming value for BB, and remember it.
219 Value *InVal = PN->removeIncomingValue(BB, false);
221 // Two options: either the InVal is a phi node defined in BB or it is some
222 // value that dominates BB.
223 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
224 if (InValPhi && InValPhi->getParent() == BB) {
225 // Add all of the input values of the input PHI as inputs of this phi.
226 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
227 PN->addIncoming(InValPhi->getIncomingValue(i),
228 InValPhi->getIncomingBlock(i));
230 // Otherwise, add one instance of the dominating value for each edge that
231 // we will be adding.
232 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
233 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
234 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
236 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
237 PN->addIncoming(InVal, *PI);
242 // The PHIs are now updated, change everything that refers to BB to use
243 // DestBB and remove BB.
244 BB->replaceAllUsesWith(DestBB);
245 BB->eraseFromParent();
247 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
251 /// SplitEdgeNicely - Split the critical edge from TI to its specified
252 /// successor if it will improve codegen. We only do this if the successor has
253 /// phi nodes (otherwise critical edges are ok). If there is already another
254 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
255 /// instead of introducing a new block.
256 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
257 BasicBlock *TIBB = TI->getParent();
258 BasicBlock *Dest = TI->getSuccessor(SuccNum);
259 assert(isa<PHINode>(Dest->begin()) &&
260 "This should only be called if Dest has a PHI!");
262 // As a hack, never split backedges of loops. Even though the copy for any
263 // PHIs inserted on the backedge would be dead for exits from the loop, we
264 // assume that the cost of *splitting* the backedge would be too high.
268 /// TIPHIValues - This array is lazily computed to determine the values of
269 /// PHIs in Dest that TI would provide.
270 SmallVector<Value*, 32> TIPHIValues;
272 // Check to see if Dest has any blocks that can be used as a split edge for
274 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
275 BasicBlock *Pred = *PI;
276 // To be usable, the pred has to end with an uncond branch to the dest.
277 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
278 if (!PredBr || !PredBr->isUnconditional() ||
279 // Must be empty other than the branch.
280 &Pred->front() != PredBr ||
281 // Cannot be the entry block; its label does not get emitted.
282 Pred == &(Dest->getParent()->getEntryBlock()))
285 // Finally, since we know that Dest has phi nodes in it, we have to make
286 // sure that jumping to Pred will have the same affect as going to Dest in
287 // terms of PHI values.
290 bool FoundMatch = true;
291 for (BasicBlock::iterator I = Dest->begin();
292 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
293 if (PHINo == TIPHIValues.size())
294 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
296 // If the PHI entry doesn't work, we can't use this pred.
297 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
303 // If we found a workable predecessor, change TI to branch to Succ.
305 Dest->removePredecessor(TIBB);
306 TI->setSuccessor(SuccNum, Pred);
311 SplitCriticalEdge(TI, SuccNum, P, true);
314 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
315 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
316 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
317 /// registers that must be created and coalesced.
319 /// Return true if any changes are made.
321 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
322 // If this is a noop copy,
323 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
324 MVT DstVT = TLI.getValueType(CI->getType());
326 // This is an fp<->int conversion?
327 if (SrcVT.isInteger() != DstVT.isInteger())
330 // If this is an extension, it will be a zero or sign extension, which
332 if (SrcVT.bitsLT(DstVT)) return false;
334 // If these values will be promoted, find out what they will be promoted
335 // to. This helps us consider truncates on PPC as noop copies when they
337 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
338 SrcVT = TLI.getTypeToTransformTo(SrcVT);
339 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
340 DstVT = TLI.getTypeToTransformTo(DstVT);
342 // If, after promotion, these are the same types, this is a noop copy.
346 BasicBlock *DefBB = CI->getParent();
348 /// InsertedCasts - Only insert a cast in each block once.
349 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
351 bool MadeChange = false;
352 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
354 Use &TheUse = UI.getUse();
355 Instruction *User = cast<Instruction>(*UI);
357 // Figure out which BB this cast is used in. For PHI's this is the
358 // appropriate predecessor block.
359 BasicBlock *UserBB = User->getParent();
360 if (PHINode *PN = dyn_cast<PHINode>(User)) {
361 unsigned OpVal = UI.getOperandNo()/2;
362 UserBB = PN->getIncomingBlock(OpVal);
365 // Preincrement use iterator so we don't invalidate it.
368 // If this user is in the same block as the cast, don't change the cast.
369 if (UserBB == DefBB) continue;
371 // If we have already inserted a cast into this block, use it.
372 CastInst *&InsertedCast = InsertedCasts[UserBB];
375 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
378 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
383 // Replace a use of the cast with a use of the new cast.
384 TheUse = InsertedCast;
387 // If we removed all uses, nuke the cast.
388 if (CI->use_empty()) {
389 CI->eraseFromParent();
396 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
397 /// the number of virtual registers that must be created and coalesced. This is
398 /// a clear win except on targets with multiple condition code registers
399 /// (PowerPC), where it might lose; some adjustment may be wanted there.
401 /// Return true if any changes are made.
402 static bool OptimizeCmpExpression(CmpInst *CI) {
403 BasicBlock *DefBB = CI->getParent();
405 /// InsertedCmp - Only insert a cmp in each block once.
406 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
408 bool MadeChange = false;
409 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
411 Use &TheUse = UI.getUse();
412 Instruction *User = cast<Instruction>(*UI);
414 // Preincrement use iterator so we don't invalidate it.
417 // Don't bother for PHI nodes.
418 if (isa<PHINode>(User))
421 // Figure out which BB this cmp is used in.
422 BasicBlock *UserBB = User->getParent();
424 // If this user is in the same block as the cmp, don't change the cmp.
425 if (UserBB == DefBB) continue;
427 // If we have already inserted a cmp into this block, use it.
428 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
431 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
434 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
435 CI->getOperand(1), "", InsertPt);
439 // Replace a use of the cmp with a use of the new cmp.
440 TheUse = InsertedCmp;
443 // If we removed all uses, nuke the cmp.
445 CI->eraseFromParent();
450 /// EraseDeadInstructions - Erase any dead instructions, recursively.
451 static void EraseDeadInstructions(Value *V) {
452 Instruction *I = dyn_cast<Instruction>(V);
453 if (!I || !I->use_empty()) return;
455 SmallPtrSet<Instruction*, 16> Insts;
458 while (!Insts.empty()) {
461 if (isInstructionTriviallyDead(I)) {
462 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
463 if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
465 I->eraseFromParent();
470 //===----------------------------------------------------------------------===//
471 // Addressing Mode Analysis and Optimization
472 //===----------------------------------------------------------------------===//
475 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
476 /// which holds actual Value*'s for register values.
477 struct ExtAddrMode : public TargetLowering::AddrMode {
480 ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
481 void print(OStream &OS) const;
487 } // end anonymous namespace
489 static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
494 void ExtAddrMode::print(OStream &OS) const {
495 bool NeedPlus = false;
498 OS << (NeedPlus ? " + " : "")
499 << "GV:%" << BaseGV->getName(), NeedPlus = true;
502 OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
505 OS << (NeedPlus ? " + " : "")
506 << "Base:%" << BaseReg->getName(), NeedPlus = true;
508 OS << (NeedPlus ? " + " : "")
509 << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
515 /// AddressingModeMatcher - This class exposes a single public method, which is
516 /// used to construct a "maximal munch" of the addressing mode for the target
517 /// specified by TLI for an access to "V" with an access type of AccessTy. This
518 /// returns the addressing mode that is actually matched by value, but also
519 /// returns the list of instructions involved in that addressing computation in
521 class AddressingModeMatcher {
522 SmallVectorImpl<Instruction*> &AddrModeInsts;
523 const TargetLowering &TLI;
525 /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
526 /// the memory instruction that we're computing this address for.
527 const Type *AccessTy;
528 Instruction *MemoryInst;
530 /// AddrMode - This is the addressing mode that we're building up. This is
531 /// part of the return value of this addressing mode matching stuff.
532 ExtAddrMode &AddrMode;
534 /// IgnoreProfitability - This is set to true when we should not do
535 /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
536 /// always returns true.
537 bool IgnoreProfitability;
539 AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
540 const TargetLowering &T, const Type *AT,
541 Instruction *MI, ExtAddrMode &AM)
542 : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
543 IgnoreProfitability = false;
547 /// Match - Find the maximal addressing mode that a load/store of V can fold,
548 /// give an access type of AccessTy. This returns a list of involved
549 /// instructions in AddrModeInsts.
550 static ExtAddrMode Match(Value *V, const Type *AccessTy,
551 Instruction *MemoryInst,
552 SmallVectorImpl<Instruction*> &AddrModeInsts,
553 const TargetLowering &TLI) {
557 AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
558 MemoryInst, Result).MatchAddr(V, 0);
559 Success = Success; assert(Success && "Couldn't select *anything*?");
563 bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
564 bool MatchAddr(Value *V, unsigned Depth);
565 bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
566 bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
567 ExtAddrMode &AMBefore,
568 ExtAddrMode &AMAfter);
569 bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
571 } // end anonymous namespace
573 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
574 /// Return true and update AddrMode if this addr mode is legal for the target,
576 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
578 // If Scale is 1, then this is the same as adding ScaleReg to the addressing
579 // mode. Just process that directly.
581 return MatchAddr(ScaleReg, Depth);
583 // If the scale is 0, it takes nothing to add this.
587 // If we already have a scale of this value, we can add to it, otherwise, we
588 // need an available scale field.
589 if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
592 ExtAddrMode TestAddrMode = AddrMode;
594 // Add scale to turn X*4+X*3 -> X*7. This could also do things like
595 // [A+B + A*7] -> [B+A*8].
596 TestAddrMode.Scale += Scale;
597 TestAddrMode.ScaledReg = ScaleReg;
599 // If the new address isn't legal, bail out.
600 if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
603 // It was legal, so commit it.
604 AddrMode = TestAddrMode;
606 // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
607 // to see if ScaleReg is actually X+C. If so, we can turn this into adding
608 // X*Scale + C*Scale to addr mode.
609 ConstantInt *CI; Value *AddLHS;
610 if (match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
611 TestAddrMode.ScaledReg = AddLHS;
612 TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
614 // If this addressing mode is legal, commit it and remember that we folded
616 if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
617 AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
618 AddrMode = TestAddrMode;
623 // Otherwise, not (x+c)*scale, just return what we have.
627 /// MightBeFoldableInst - This is a little filter, which returns true if an
628 /// addressing computation involving I might be folded into a load/store
629 /// accessing it. This doesn't need to be perfect, but needs to accept at least
630 /// the set of instructions that MatchOperationAddr can.
631 static bool MightBeFoldableInst(Instruction *I) {
632 switch (I->getOpcode()) {
633 case Instruction::BitCast:
634 // Don't touch identity bitcasts.
635 if (I->getType() == I->getOperand(0)->getType())
637 return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
638 case Instruction::PtrToInt:
639 // PtrToInt is always a noop, as we know that the int type is pointer sized.
641 case Instruction::IntToPtr:
642 // We know the input is intptr_t, so this is foldable.
644 case Instruction::Add:
646 case Instruction::Mul:
647 case Instruction::Shl:
648 // Can only handle X*C and X << C.
649 return isa<ConstantInt>(I->getOperand(1));
650 case Instruction::GetElementPtr:
658 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
659 /// fold the operation into the addressing mode. If so, update the addressing
660 /// mode and return true, otherwise return false without modifying AddrMode.
661 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
663 // Avoid exponential behavior on extremely deep expression trees.
664 if (Depth >= 5) return false;
667 case Instruction::PtrToInt:
668 // PtrToInt is always a noop, as we know that the int type is pointer sized.
669 return MatchAddr(AddrInst->getOperand(0), Depth);
670 case Instruction::IntToPtr:
671 // This inttoptr is a no-op if the integer type is pointer sized.
672 if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
674 return MatchAddr(AddrInst->getOperand(0), Depth);
676 case Instruction::BitCast:
677 // BitCast is always a noop, and we can handle it as long as it is
678 // int->int or pointer->pointer (we don't want int<->fp or something).
679 if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
680 isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
681 // Don't touch identity bitcasts. These were probably put here by LSR,
682 // and we don't want to mess around with them. Assume it knows what it
684 AddrInst->getOperand(0)->getType() != AddrInst->getType())
685 return MatchAddr(AddrInst->getOperand(0), Depth);
687 case Instruction::Add: {
688 // Check to see if we can merge in the RHS then the LHS. If so, we win.
689 ExtAddrMode BackupAddrMode = AddrMode;
690 unsigned OldSize = AddrModeInsts.size();
691 if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
692 MatchAddr(AddrInst->getOperand(0), Depth+1))
695 // Restore the old addr mode info.
696 AddrMode = BackupAddrMode;
697 AddrModeInsts.resize(OldSize);
699 // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
700 if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
701 MatchAddr(AddrInst->getOperand(1), Depth+1))
704 // Otherwise we definitely can't merge the ADD in.
705 AddrMode = BackupAddrMode;
706 AddrModeInsts.resize(OldSize);
709 //case Instruction::Or:
710 // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
712 case Instruction::Mul:
713 case Instruction::Shl: {
714 // Can only handle X*C and X << C.
715 ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
716 if (!RHS) return false;
717 int64_t Scale = RHS->getSExtValue();
718 if (Opcode == Instruction::Shl)
721 return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
723 case Instruction::GetElementPtr: {
724 // Scan the GEP. We check it if it contains constant offsets and at most
725 // one variable offset.
726 int VariableOperand = -1;
727 unsigned VariableScale = 0;
729 int64_t ConstantOffset = 0;
730 const TargetData *TD = TLI.getTargetData();
731 gep_type_iterator GTI = gep_type_begin(AddrInst);
732 for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
733 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
734 const StructLayout *SL = TD->getStructLayout(STy);
736 cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
737 ConstantOffset += SL->getElementOffset(Idx);
739 uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
740 if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
741 ConstantOffset += CI->getSExtValue()*TypeSize;
742 } else if (TypeSize) { // Scales of zero don't do anything.
743 // We only allow one variable index at the moment.
744 if (VariableOperand != -1)
747 // Remember the variable index.
749 VariableScale = TypeSize;
754 // A common case is for the GEP to only do a constant offset. In this case,
755 // just add it to the disp field and check validity.
756 if (VariableOperand == -1) {
757 AddrMode.BaseOffs += ConstantOffset;
758 if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
759 // Check to see if we can fold the base pointer in too.
760 if (MatchAddr(AddrInst->getOperand(0), Depth+1))
763 AddrMode.BaseOffs -= ConstantOffset;
767 // Save the valid addressing mode in case we can't match.
768 ExtAddrMode BackupAddrMode = AddrMode;
770 // Check that this has no base reg yet. If so, we won't have a place to
771 // put the base of the GEP (assuming it is not a null ptr).
772 bool SetBaseReg = true;
773 if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
774 SetBaseReg = false; // null pointer base doesn't need representation.
775 else if (AddrMode.HasBaseReg)
776 return false; // Base register already specified, can't match GEP.
778 // Otherwise, we'll use the GEP base as the BaseReg.
779 AddrMode.HasBaseReg = true;
780 AddrMode.BaseReg = AddrInst->getOperand(0);
783 // See if the scale and offset amount is valid for this target.
784 AddrMode.BaseOffs += ConstantOffset;
786 if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
788 AddrMode = BackupAddrMode;
792 // If we have a null as the base of the GEP, folding in the constant offset
793 // plus variable scale is all we can do.
794 if (!SetBaseReg) return true;
796 // If this match succeeded, we know that we can form an address with the
797 // GepBase as the basereg. Match the base pointer of the GEP more
798 // aggressively by zeroing out BaseReg and rematching. If the base is
799 // (for example) another GEP, this allows merging in that other GEP into
800 // the addressing mode we're forming.
801 AddrMode.HasBaseReg = false;
802 AddrMode.BaseReg = 0;
803 bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
804 assert(Success && "MatchAddr should be able to fill in BaseReg!");
812 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
813 /// addressing mode. If Addr can't be added to AddrMode this returns false and
814 /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
815 /// or intptr_t for the target.
817 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
818 if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
819 // Fold in immediates if legal for the target.
820 AddrMode.BaseOffs += CI->getSExtValue();
821 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
823 AddrMode.BaseOffs -= CI->getSExtValue();
824 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
825 // If this is a global variable, try to fold it into the addressing mode.
826 if (AddrMode.BaseGV == 0) {
827 AddrMode.BaseGV = GV;
828 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
832 } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
833 ExtAddrMode BackupAddrMode = AddrMode;
834 unsigned OldSize = AddrModeInsts.size();
836 // Check to see if it is possible to fold this operation.
837 if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
838 // Okay, it's possible to fold this. Check to see if it is actually
839 // *profitable* to do so. We use a simple cost model to avoid increasing
840 // register pressure too much.
841 if (I->hasOneUse() ||
842 IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
843 AddrModeInsts.push_back(I);
847 // It isn't profitable to do this, roll back.
848 //cerr << "NOT FOLDING: " << *I;
849 AddrMode = BackupAddrMode;
850 AddrModeInsts.resize(OldSize);
852 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
853 if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
855 } else if (isa<ConstantPointerNull>(Addr)) {
856 // Null pointer gets folded without affecting the addressing mode.
860 // Worse case, the target should support [reg] addressing modes. :)
861 if (!AddrMode.HasBaseReg) {
862 AddrMode.HasBaseReg = true;
863 AddrMode.BaseReg = Addr;
864 // Still check for legality in case the target supports [imm] but not [i+r].
865 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
867 AddrMode.HasBaseReg = false;
868 AddrMode.BaseReg = 0;
871 // If the base register is already taken, see if we can do [r+r].
872 if (AddrMode.Scale == 0) {
874 AddrMode.ScaledReg = Addr;
875 if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
878 AddrMode.ScaledReg = 0;
885 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
886 /// inline asm call are due to memory operands. If so, return true, otherwise
888 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
889 const TargetLowering &TLI) {
890 std::vector<InlineAsm::ConstraintInfo>
891 Constraints = IA->ParseConstraints();
893 unsigned ArgNo = 1; // ArgNo - The operand of the CallInst.
894 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
895 TargetLowering::AsmOperandInfo OpInfo(Constraints[i]);
897 // Compute the value type for each operand.
898 switch (OpInfo.Type) {
899 case InlineAsm::isOutput:
900 if (OpInfo.isIndirect)
901 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
903 case InlineAsm::isInput:
904 OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
906 case InlineAsm::isClobber:
911 // Compute the constraint code and ConstraintType to use.
912 TLI.ComputeConstraintToUse(OpInfo, SDValue(),
913 OpInfo.ConstraintType == TargetLowering::C_Memory);
915 // If this asm operand is our Value*, and if it isn't an indirect memory
916 // operand, we can't fold it!
917 if (OpInfo.CallOperandVal == OpVal &&
918 (OpInfo.ConstraintType != TargetLowering::C_Memory ||
927 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
928 /// memory use. If we find an obviously non-foldable instruction, return true.
929 /// Add the ultimately found memory instructions to MemoryUses.
930 static bool FindAllMemoryUses(Instruction *I,
931 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
932 SmallPtrSet<Instruction*, 16> &ConsideredInsts,
933 const TargetLowering &TLI) {
934 // If we already considered this instruction, we're done.
935 if (!ConsideredInsts.insert(I))
938 // If this is an obviously unfoldable instruction, bail out.
939 if (!MightBeFoldableInst(I))
942 // Loop over all the uses, recursively processing them.
943 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
945 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
946 MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
950 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
951 if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
952 MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
956 if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
957 InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
958 if (IA == 0) return true;
960 // If this is a memory operand, we're cool, otherwise bail out.
961 if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
966 if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts,
975 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
976 /// the use site that we're folding it into. If so, there is no cost to
977 /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
978 /// that we know are live at the instruction already.
979 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
981 // If Val is either of the known-live values, we know it is live!
982 if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
985 // All values other than instructions and arguments (e.g. constants) are live.
986 if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
988 // If Val is a constant sized alloca in the entry block, it is live, this is
989 // true because it is just a reference to the stack/frame pointer, which is
990 // live for the whole function.
991 if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
992 if (AI->isStaticAlloca())
995 // Check to see if this value is already used in the memory instruction's
996 // block. If so, it's already live into the block at the very least, so we
997 // can reasonably fold it.
998 BasicBlock *MemBB = MemoryInst->getParent();
999 for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
1001 // We know that uses of arguments and instructions have to be instructions.
1002 if (cast<Instruction>(*UI)->getParent() == MemBB)
1010 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1011 /// mode of the machine to fold the specified instruction into a load or store
1012 /// that ultimately uses it. However, the specified instruction has multiple
1013 /// uses. Given this, it may actually increase register pressure to fold it
1014 /// into the load. For example, consider this code:
1018 /// use(Y) -> nonload/store
1022 /// In this case, Y has multiple uses, and can be folded into the load of Z
1023 /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
1024 /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
1025 /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
1026 /// number of computations either.
1028 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
1029 /// X was live across 'load Z' for other reasons, we actually *would* want to
1030 /// fold the addressing mode in the Z case. This would make Y die earlier.
1031 bool AddressingModeMatcher::
1032 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1033 ExtAddrMode &AMAfter) {
1034 if (IgnoreProfitability) return true;
1036 // AMBefore is the addressing mode before this instruction was folded into it,
1037 // and AMAfter is the addressing mode after the instruction was folded. Get
1038 // the set of registers referenced by AMAfter and subtract out those
1039 // referenced by AMBefore: this is the set of values which folding in this
1040 // address extends the lifetime of.
1042 // Note that there are only two potential values being referenced here,
1043 // BaseReg and ScaleReg (global addresses are always available, as are any
1044 // folded immediates).
1045 Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1047 // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1048 // lifetime wasn't extended by adding this instruction.
1049 if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1051 if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1054 // If folding this instruction (and it's subexprs) didn't extend any live
1055 // ranges, we're ok with it.
1056 if (BaseReg == 0 && ScaledReg == 0)
1059 // If all uses of this instruction are ultimately load/store/inlineasm's,
1060 // check to see if their addressing modes will include this instruction. If
1061 // so, we can fold it into all uses, so it doesn't matter if it has multiple
1063 SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1064 SmallPtrSet<Instruction*, 16> ConsideredInsts;
1065 if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
1066 return false; // Has a non-memory, non-foldable use!
1068 // Now that we know that all uses of this instruction are part of a chain of
1069 // computation involving only operations that could theoretically be folded
1070 // into a memory use, loop over each of these uses and see if they could
1071 // *actually* fold the instruction.
1072 SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1073 for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1074 Instruction *User = MemoryUses[i].first;
1075 unsigned OpNo = MemoryUses[i].second;
1077 // Get the access type of this use. If the use isn't a pointer, we don't
1078 // know what it accesses.
1079 Value *Address = User->getOperand(OpNo);
1080 if (!isa<PointerType>(Address->getType()))
1082 const Type *AddressAccessTy =
1083 cast<PointerType>(Address->getType())->getElementType();
1085 // Do a match against the root of this address, ignoring profitability. This
1086 // will tell us if the addressing mode for the memory operation will
1087 // *actually* cover the shared instruction.
1089 AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
1090 MemoryInst, Result);
1091 Matcher.IgnoreProfitability = true;
1092 bool Success = Matcher.MatchAddr(Address, 0);
1093 Success = Success; assert(Success && "Couldn't select *anything*?");
1095 // If the match didn't cover I, then it won't be shared by it.
1096 if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1097 I) == MatchedAddrModeInsts.end())
1100 MatchedAddrModeInsts.clear();
1107 //===----------------------------------------------------------------------===//
1108 // Memory Optimization
1109 //===----------------------------------------------------------------------===//
1111 /// IsNonLocalValue - Return true if the specified values are defined in a
1112 /// different basic block than BB.
1113 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1114 if (Instruction *I = dyn_cast<Instruction>(V))
1115 return I->getParent() != BB;
1119 /// OptimizeMemoryInst - Load and Store Instructions have often have
1120 /// addressing modes that can do significant amounts of computation. As such,
1121 /// instruction selection will try to get the load or store to do as much
1122 /// computation as possible for the program. The problem is that isel can only
1123 /// see within a single block. As such, we sink as much legal addressing mode
1124 /// stuff into the block as possible.
1126 /// This method is used to optimize both load/store and inline asms with memory
1128 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
1129 const Type *AccessTy,
1130 DenseMap<Value*,Value*> &SunkAddrs) {
1131 // Figure out what addressing mode will be built up for this operation.
1132 SmallVector<Instruction*, 16> AddrModeInsts;
1133 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
1134 AddrModeInsts, *TLI);
1136 // Check to see if any of the instructions supersumed by this addr mode are
1137 // non-local to I's BB.
1138 bool AnyNonLocal = false;
1139 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
1140 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
1146 // If all the instructions matched are already in this BB, don't do anything.
1148 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
1152 // Insert this computation right after this user. Since our caller is
1153 // scanning from the top of the BB to the bottom, reuse of the expr are
1154 // guaranteed to happen later.
1155 BasicBlock::iterator InsertPt = MemoryInst;
1157 // Now that we determined the addressing expression we want to use and know
1158 // that we have to sink it into this block. Check to see if we have already
1159 // done this for some other load/store instr in this block. If so, reuse the
1161 Value *&SunkAddr = SunkAddrs[Addr];
1163 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
1164 if (SunkAddr->getType() != Addr->getType())
1165 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
1167 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
1168 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
1171 // Start with the scale value.
1172 if (AddrMode.Scale) {
1173 Value *V = AddrMode.ScaledReg;
1174 if (V->getType() == IntPtrTy) {
1176 } else if (isa<PointerType>(V->getType())) {
1177 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1178 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1179 cast<IntegerType>(V->getType())->getBitWidth()) {
1180 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
1182 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
1184 if (AddrMode.Scale != 1)
1185 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
1187 "sunkaddr", InsertPt);
1191 // Add in the base register.
1192 if (AddrMode.BaseReg) {
1193 Value *V = AddrMode.BaseReg;
1194 if (V->getType() != IntPtrTy)
1195 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1197 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1202 // Add in the BaseGV if present.
1203 if (AddrMode.BaseGV) {
1204 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
1207 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1212 // Add in the Base Offset if present.
1213 if (AddrMode.BaseOffs) {
1214 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1216 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1222 SunkAddr = Constant::getNullValue(Addr->getType());
1224 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
1227 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
1229 if (Addr->use_empty())
1230 EraseDeadInstructions(Addr);
1234 /// OptimizeInlineAsmInst - If there are any memory operands, use
1235 /// OptimizeMemoryInst to sink their address computing into the block when
1236 /// possible / profitable.
1237 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
1238 DenseMap<Value*,Value*> &SunkAddrs) {
1239 bool MadeChange = false;
1240 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
1242 // Do a prepass over the constraints, canonicalizing them, and building up the
1243 // ConstraintOperands list.
1244 std::vector<InlineAsm::ConstraintInfo>
1245 ConstraintInfos = IA->ParseConstraints();
1247 /// ConstraintOperands - Information about all of the constraints.
1248 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
1249 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
1250 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
1252 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
1253 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
1255 // Compute the value type for each operand.
1256 switch (OpInfo.Type) {
1257 case InlineAsm::isOutput:
1258 if (OpInfo.isIndirect)
1259 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1261 case InlineAsm::isInput:
1262 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1264 case InlineAsm::isClobber:
1269 // Compute the constraint code and ConstraintType to use.
1270 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
1271 OpInfo.ConstraintType == TargetLowering::C_Memory);
1273 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1274 OpInfo.isIndirect) {
1275 Value *OpVal = OpInfo.CallOperandVal;
1276 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
1283 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1284 BasicBlock *DefBB = I->getParent();
1286 // If both result of the {s|z}xt and its source are live out, rewrite all
1287 // other uses of the source with result of extension.
1288 Value *Src = I->getOperand(0);
1289 if (Src->hasOneUse())
1292 // Only do this xform if truncating is free.
1293 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1296 // Only safe to perform the optimization if the source is also defined in
1298 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1301 bool DefIsLiveOut = false;
1302 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1304 Instruction *User = cast<Instruction>(*UI);
1306 // Figure out which BB this ext is used in.
1307 BasicBlock *UserBB = User->getParent();
1308 if (UserBB == DefBB) continue;
1309 DefIsLiveOut = true;
1315 // Make sure non of the uses are PHI nodes.
1316 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1318 Instruction *User = cast<Instruction>(*UI);
1319 BasicBlock *UserBB = User->getParent();
1320 if (UserBB == DefBB) continue;
1321 // Be conservative. We don't want this xform to end up introducing
1322 // reloads just before load / store instructions.
1323 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1327 // InsertedTruncs - Only insert one trunc in each block once.
1328 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1330 bool MadeChange = false;
1331 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1333 Use &TheUse = UI.getUse();
1334 Instruction *User = cast<Instruction>(*UI);
1336 // Figure out which BB this ext is used in.
1337 BasicBlock *UserBB = User->getParent();
1338 if (UserBB == DefBB) continue;
1340 // Both src and def are live in this block. Rewrite the use.
1341 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1343 if (!InsertedTrunc) {
1344 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
1346 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1349 // Replace a use of the {s|z}ext source with a use of the result.
1350 TheUse = InsertedTrunc;
1358 // In this pass we look for GEP and cast instructions that are used
1359 // across basic blocks and rewrite them to improve basic-block-at-a-time
1361 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1362 bool MadeChange = false;
1364 // Split all critical edges where the dest block has a PHI and where the phi
1365 // has shared immediate operands.
1366 TerminatorInst *BBTI = BB.getTerminator();
1367 if (BBTI->getNumSuccessors() > 1) {
1368 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1369 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1370 isCriticalEdge(BBTI, i, true))
1371 SplitEdgeNicely(BBTI, i, this);
1375 // Keep track of non-local addresses that have been sunk into this block.
1376 // This allows us to avoid inserting duplicate code for blocks with multiple
1377 // load/stores of the same address.
1378 DenseMap<Value*, Value*> SunkAddrs;
1380 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1381 Instruction *I = BBI++;
1383 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1384 // If the source of the cast is a constant, then this should have
1385 // already been constant folded. The only reason NOT to constant fold
1386 // it is if something (e.g. LSR) was careful to place the constant
1387 // evaluation in a block other than then one that uses it (e.g. to hoist
1388 // the address of globals out of a loop). If this is the case, we don't
1389 // want to forward-subst the cast.
1390 if (isa<Constant>(CI->getOperand(0)))
1393 bool Change = false;
1395 Change = OptimizeNoopCopyExpression(CI, *TLI);
1396 MadeChange |= Change;
1399 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1400 MadeChange |= OptimizeExtUses(I);
1401 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1402 MadeChange |= OptimizeCmpExpression(CI);
1403 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1405 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1407 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1409 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1410 SI->getOperand(0)->getType(),
1412 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1413 if (GEPI->hasAllZeroIndices()) {
1414 /// The GEP operand must be a pointer, so must its result -> BitCast
1415 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1416 GEPI->getName(), GEPI);
1417 GEPI->replaceAllUsesWith(NC);
1418 GEPI->eraseFromParent();
1422 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1423 // If we found an inline asm expession, and if the target knows how to
1424 // lower it to normal LLVM code, do so now.
1425 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1426 if (const TargetAsmInfo *TAI =
1427 TLI->getTargetMachine().getTargetAsmInfo()) {
1428 if (TAI->ExpandInlineAsm(CI))
1431 // Sink address computing for memory operands into the block.
1432 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);