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/IntrinsicInst.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Target/TargetAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/Assembly/Writer.h"
35 #include "llvm/Support/CallSite.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/PatternMatch.h"
42 using namespace llvm::PatternMatch;
44 static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
45 cl::init(false), cl::Hidden);
48 class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
49 /// TLI - Keep a pointer of a TargetLowering to consult for determining
50 /// transformation profitability.
51 const TargetLowering *TLI;
53 /// BackEdges - Keep a set of all the loop back edges.
55 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> BackEdges;
57 static char ID; // Pass identification, replacement for typeid
58 explicit CodeGenPrepare(const TargetLowering *tli = 0)
59 : FunctionPass(&ID), TLI(tli) {}
60 bool runOnFunction(Function &F);
63 bool EliminateMostlyEmptyBlocks(Function &F);
64 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
65 void EliminateMostlyEmptyBlock(BasicBlock *BB);
66 bool OptimizeBlock(BasicBlock &BB);
67 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
68 DenseMap<Value*,Value*> &SunkAddrs);
69 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
70 DenseMap<Value*,Value*> &SunkAddrs);
71 bool OptimizeExtUses(Instruction *I);
72 void findLoopBackEdges(Function &F);
76 char CodeGenPrepare::ID = 0;
77 static RegisterPass<CodeGenPrepare> X("codegenprepare",
78 "Optimize for code generation");
80 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
81 return new CodeGenPrepare(TLI);
84 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
86 void CodeGenPrepare::findLoopBackEdges(Function &F) {
87 SmallPtrSet<BasicBlock*, 8> Visited;
88 SmallVector<std::pair<BasicBlock*, succ_iterator>, 8> VisitStack;
89 SmallPtrSet<BasicBlock*, 8> InStack;
91 BasicBlock *BB = &F.getEntryBlock();
92 if (succ_begin(BB) == succ_end(BB))
95 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
98 std::pair<BasicBlock*, succ_iterator> &Top = VisitStack.back();
99 BasicBlock *ParentBB = Top.first;
100 succ_iterator &I = Top.second;
102 bool FoundNew = false;
103 while (I != succ_end(ParentBB)) {
105 if (Visited.insert(BB)) {
109 // Successor is in VisitStack, it's a back edge.
110 if (InStack.count(BB))
111 BackEdges.insert(std::make_pair(ParentBB, BB));
115 // Go down one level if there is a unvisited successor.
117 VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
120 std::pair<BasicBlock*, succ_iterator> &Pop = VisitStack.back();
121 InStack.erase(Pop.first);
122 VisitStack.pop_back();
124 } while (!VisitStack.empty());
128 bool CodeGenPrepare::runOnFunction(Function &F) {
129 bool EverMadeChange = false;
131 // First pass, eliminate blocks that contain only PHI nodes and an
132 // unconditional branch.
133 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
135 // Now find loop back edges.
136 findLoopBackEdges(F);
138 bool MadeChange = true;
141 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
142 MadeChange |= OptimizeBlock(*BB);
143 EverMadeChange |= MadeChange;
145 return EverMadeChange;
148 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
149 /// debug info directives, and an unconditional branch. Passes before isel
150 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
151 /// isel. Start by eliminating these blocks so we can split them the way we
153 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
154 bool MadeChange = false;
155 // Note that this intentionally skips the entry block.
156 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
157 BasicBlock *BB = I++;
159 // If this block doesn't end with an uncond branch, ignore it.
160 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
161 if (!BI || !BI->isUnconditional())
164 // If the instruction before the branch (skipping debug info) isn't a phi
165 // node, then other stuff is happening here.
166 BasicBlock::iterator BBI = BI;
167 if (BBI != BB->begin()) {
169 while (isa<DbgInfoIntrinsic>(BBI)) {
170 if (BBI == BB->begin())
174 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
178 // Do not break infinite loops.
179 BasicBlock *DestBB = BI->getSuccessor(0);
183 if (!CanMergeBlocks(BB, DestBB))
186 EliminateMostlyEmptyBlock(BB);
192 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
193 /// single uncond branch between them, and BB contains no other non-phi
195 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
196 const BasicBlock *DestBB) const {
197 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
198 // the successor. If there are more complex condition (e.g. preheaders),
199 // don't mess around with them.
200 BasicBlock::const_iterator BBI = BB->begin();
201 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
202 for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
204 const Instruction *User = cast<Instruction>(*UI);
205 if (User->getParent() != DestBB || !isa<PHINode>(User))
207 // If User is inside DestBB block and it is a PHINode then check
208 // incoming value. If incoming value is not from BB then this is
209 // a complex condition (e.g. preheaders) we want to avoid here.
210 if (User->getParent() == DestBB) {
211 if (const PHINode *UPN = dyn_cast<PHINode>(User))
212 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
213 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
214 if (Insn && Insn->getParent() == BB &&
215 Insn->getParent() != UPN->getIncomingBlock(I))
222 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
223 // and DestBB may have conflicting incoming values for the block. If so, we
224 // can't merge the block.
225 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
226 if (!DestBBPN) return true; // no conflict.
228 // Collect the preds of BB.
229 SmallPtrSet<const BasicBlock*, 16> BBPreds;
230 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
231 // It is faster to get preds from a PHI than with pred_iterator.
232 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
233 BBPreds.insert(BBPN->getIncomingBlock(i));
235 BBPreds.insert(pred_begin(BB), pred_end(BB));
238 // Walk the preds of DestBB.
239 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
240 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
241 if (BBPreds.count(Pred)) { // Common predecessor?
242 BBI = DestBB->begin();
243 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
244 const Value *V1 = PN->getIncomingValueForBlock(Pred);
245 const Value *V2 = PN->getIncomingValueForBlock(BB);
247 // If V2 is a phi node in BB, look up what the mapped value will be.
248 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
249 if (V2PN->getParent() == BB)
250 V2 = V2PN->getIncomingValueForBlock(Pred);
252 // If there is a conflict, bail out.
253 if (V1 != V2) return false;
262 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
263 /// an unconditional branch in it.
264 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
265 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
266 BasicBlock *DestBB = BI->getSuccessor(0);
268 DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
270 // If the destination block has a single pred, then this is a trivial edge,
272 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
273 if (SinglePred != DestBB) {
274 // Remember if SinglePred was the entry block of the function. If so, we
275 // will need to move BB back to the entry position.
276 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
277 MergeBasicBlockIntoOnlyPred(DestBB);
279 if (isEntry && BB != &BB->getParent()->getEntryBlock())
280 BB->moveBefore(&BB->getParent()->getEntryBlock());
282 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
287 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
288 // to handle the new incoming edges it is about to have.
290 for (BasicBlock::iterator BBI = DestBB->begin();
291 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
292 // Remove the incoming value for BB, and remember it.
293 Value *InVal = PN->removeIncomingValue(BB, false);
295 // Two options: either the InVal is a phi node defined in BB or it is some
296 // value that dominates BB.
297 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
298 if (InValPhi && InValPhi->getParent() == BB) {
299 // Add all of the input values of the input PHI as inputs of this phi.
300 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
301 PN->addIncoming(InValPhi->getIncomingValue(i),
302 InValPhi->getIncomingBlock(i));
304 // Otherwise, add one instance of the dominating value for each edge that
305 // we will be adding.
306 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
307 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
308 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
310 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
311 PN->addIncoming(InVal, *PI);
316 // The PHIs are now updated, change everything that refers to BB to use
317 // DestBB and remove BB.
318 BB->replaceAllUsesWith(DestBB);
319 BB->eraseFromParent();
321 DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
325 /// SplitEdgeNicely - Split the critical edge from TI to its specified
326 /// successor if it will improve codegen. We only do this if the successor has
327 /// phi nodes (otherwise critical edges are ok). If there is already another
328 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
329 /// instead of introducing a new block.
330 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
331 SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
333 BasicBlock *TIBB = TI->getParent();
334 BasicBlock *Dest = TI->getSuccessor(SuccNum);
335 assert(isa<PHINode>(Dest->begin()) &&
336 "This should only be called if Dest has a PHI!");
338 // Do not split edges to EH landing pads.
339 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
340 if (Invoke->getSuccessor(1) == Dest)
344 // As a hack, never split backedges of loops. Even though the copy for any
345 // PHIs inserted on the backedge would be dead for exits from the loop, we
346 // assume that the cost of *splitting* the backedge would be too high.
347 if (BackEdges.count(std::make_pair(TIBB, Dest)))
350 if (!FactorCommonPreds) {
351 /// TIPHIValues - This array is lazily computed to determine the values of
352 /// PHIs in Dest that TI would provide.
353 SmallVector<Value*, 32> TIPHIValues;
355 // Check to see if Dest has any blocks that can be used as a split edge for
357 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
358 BasicBlock *Pred = *PI;
359 // To be usable, the pred has to end with an uncond branch to the dest.
360 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
361 if (!PredBr || !PredBr->isUnconditional())
363 // Must be empty other than the branch and debug info.
364 BasicBlock::iterator I = Pred->begin();
365 while (isa<DbgInfoIntrinsic>(I))
367 if (dyn_cast<Instruction>(I) != PredBr)
369 // Cannot be the entry block; its label does not get emitted.
370 if (Pred == &(Dest->getParent()->getEntryBlock()))
373 // Finally, since we know that Dest has phi nodes in it, we have to make
374 // sure that jumping to Pred will have the same effect as going to Dest in
375 // terms of PHI values.
378 bool FoundMatch = true;
379 for (BasicBlock::iterator I = Dest->begin();
380 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
381 if (PHINo == TIPHIValues.size())
382 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
384 // If the PHI entry doesn't work, we can't use this pred.
385 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
391 // If we found a workable predecessor, change TI to branch to Succ.
393 Dest->removePredecessor(TIBB);
394 TI->setSuccessor(SuccNum, Pred);
399 SplitCriticalEdge(TI, SuccNum, P, true);
404 SmallVector<Value*, 8> TIPHIValues;
405 for (BasicBlock::iterator I = Dest->begin();
406 (PN = dyn_cast<PHINode>(I)); ++I)
407 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
409 SmallVector<BasicBlock*, 8> IdenticalPreds;
410 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
411 BasicBlock *Pred = *PI;
412 if (BackEdges.count(std::make_pair(Pred, Dest)))
415 IdenticalPreds.push_back(Pred);
417 bool Identical = true;
419 for (BasicBlock::iterator I = Dest->begin();
420 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
421 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
426 IdenticalPreds.push_back(Pred);
430 assert(!IdenticalPreds.empty());
431 SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
436 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
437 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
438 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
439 /// registers that must be created and coalesced.
441 /// Return true if any changes are made.
443 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
444 // If this is a noop copy,
445 MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
446 MVT DstVT = TLI.getValueType(CI->getType());
448 // This is an fp<->int conversion?
449 if (SrcVT.isInteger() != DstVT.isInteger())
452 // If this is an extension, it will be a zero or sign extension, which
454 if (SrcVT.bitsLT(DstVT)) return false;
456 // If these values will be promoted, find out what they will be promoted
457 // to. This helps us consider truncates on PPC as noop copies when they
459 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
460 SrcVT = TLI.getTypeToTransformTo(SrcVT);
461 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
462 DstVT = TLI.getTypeToTransformTo(DstVT);
464 // If, after promotion, these are the same types, this is a noop copy.
468 BasicBlock *DefBB = CI->getParent();
470 /// InsertedCasts - Only insert a cast in each block once.
471 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
473 bool MadeChange = false;
474 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
476 Use &TheUse = UI.getUse();
477 Instruction *User = cast<Instruction>(*UI);
479 // Figure out which BB this cast is used in. For PHI's this is the
480 // appropriate predecessor block.
481 BasicBlock *UserBB = User->getParent();
482 if (PHINode *PN = dyn_cast<PHINode>(User)) {
483 UserBB = PN->getIncomingBlock(UI);
486 // Preincrement use iterator so we don't invalidate it.
489 // If this user is in the same block as the cast, don't change the cast.
490 if (UserBB == DefBB) continue;
492 // If we have already inserted a cast into this block, use it.
493 CastInst *&InsertedCast = InsertedCasts[UserBB];
496 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
499 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
504 // Replace a use of the cast with a use of the new cast.
505 TheUse = InsertedCast;
508 // If we removed all uses, nuke the cast.
509 if (CI->use_empty()) {
510 CI->eraseFromParent();
517 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
518 /// the number of virtual registers that must be created and coalesced. This is
519 /// a clear win except on targets with multiple condition code registers
520 /// (PowerPC), where it might lose; some adjustment may be wanted there.
522 /// Return true if any changes are made.
523 static bool OptimizeCmpExpression(CmpInst *CI) {
524 BasicBlock *DefBB = CI->getParent();
526 /// InsertedCmp - Only insert a cmp in each block once.
527 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
529 bool MadeChange = false;
530 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
532 Use &TheUse = UI.getUse();
533 Instruction *User = cast<Instruction>(*UI);
535 // Preincrement use iterator so we don't invalidate it.
538 // Don't bother for PHI nodes.
539 if (isa<PHINode>(User))
542 // Figure out which BB this cmp is used in.
543 BasicBlock *UserBB = User->getParent();
545 // If this user is in the same block as the cmp, don't change the cmp.
546 if (UserBB == DefBB) continue;
548 // If we have already inserted a cmp into this block, use it.
549 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
552 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
555 CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
556 CI->getOperand(1), "", InsertPt);
560 // Replace a use of the cmp with a use of the new cmp.
561 TheUse = InsertedCmp;
564 // If we removed all uses, nuke the cmp.
566 CI->eraseFromParent();
571 //===----------------------------------------------------------------------===//
572 // Memory Optimization
573 //===----------------------------------------------------------------------===//
575 /// IsNonLocalValue - Return true if the specified values are defined in a
576 /// different basic block than BB.
577 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
578 if (Instruction *I = dyn_cast<Instruction>(V))
579 return I->getParent() != BB;
583 /// OptimizeMemoryInst - Load and Store Instructions have often have
584 /// addressing modes that can do significant amounts of computation. As such,
585 /// instruction selection will try to get the load or store to do as much
586 /// computation as possible for the program. The problem is that isel can only
587 /// see within a single block. As such, we sink as much legal addressing mode
588 /// stuff into the block as possible.
590 /// This method is used to optimize both load/store and inline asms with memory
592 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
593 const Type *AccessTy,
594 DenseMap<Value*,Value*> &SunkAddrs) {
595 // Figure out what addressing mode will be built up for this operation.
596 SmallVector<Instruction*, 16> AddrModeInsts;
597 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
598 AddrModeInsts, *TLI);
600 // Check to see if any of the instructions supersumed by this addr mode are
601 // non-local to I's BB.
602 bool AnyNonLocal = false;
603 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
604 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
610 // If all the instructions matched are already in this BB, don't do anything.
612 DEBUG(cerr << "CGP: Found local addrmode: " << AddrMode << "\n");
616 // Insert this computation right after this user. Since our caller is
617 // scanning from the top of the BB to the bottom, reuse of the expr are
618 // guaranteed to happen later.
619 BasicBlock::iterator InsertPt = MemoryInst;
621 // Now that we determined the addressing expression we want to use and know
622 // that we have to sink it into this block. Check to see if we have already
623 // done this for some other load/store instr in this block. If so, reuse the
625 Value *&SunkAddr = SunkAddrs[Addr];
627 DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
629 if (SunkAddr->getType() != Addr->getType())
630 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
632 DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
634 const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
637 // Start with the scale value.
638 if (AddrMode.Scale) {
639 Value *V = AddrMode.ScaledReg;
640 if (V->getType() == IntPtrTy) {
642 } else if (isa<PointerType>(V->getType())) {
643 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
644 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
645 cast<IntegerType>(V->getType())->getBitWidth()) {
646 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
648 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
650 if (AddrMode.Scale != 1)
651 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
653 "sunkaddr", InsertPt);
657 // Add in the base register.
658 if (AddrMode.BaseReg) {
659 Value *V = AddrMode.BaseReg;
660 if (V->getType() != IntPtrTy)
661 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
663 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
668 // Add in the BaseGV if present.
669 if (AddrMode.BaseGV) {
670 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
673 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
678 // Add in the Base Offset if present.
679 if (AddrMode.BaseOffs) {
680 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
682 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
688 SunkAddr = Constant::getNullValue(Addr->getType());
690 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
693 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
695 if (Addr->use_empty())
696 RecursivelyDeleteTriviallyDeadInstructions(Addr);
700 /// OptimizeInlineAsmInst - If there are any memory operands, use
701 /// OptimizeMemoryInst to sink their address computing into the block when
702 /// possible / profitable.
703 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
704 DenseMap<Value*,Value*> &SunkAddrs) {
705 bool MadeChange = false;
706 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
708 // Do a prepass over the constraints, canonicalizing them, and building up the
709 // ConstraintOperands list.
710 std::vector<InlineAsm::ConstraintInfo>
711 ConstraintInfos = IA->ParseConstraints();
713 /// ConstraintOperands - Information about all of the constraints.
714 std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
715 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
716 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
718 push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
719 TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
721 // Compute the value type for each operand.
722 switch (OpInfo.Type) {
723 case InlineAsm::isOutput:
724 if (OpInfo.isIndirect)
725 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
727 case InlineAsm::isInput:
728 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
730 case InlineAsm::isClobber:
735 // Compute the constraint code and ConstraintType to use.
736 TLI->ComputeConstraintToUse(OpInfo, SDValue(),
737 OpInfo.ConstraintType == TargetLowering::C_Memory);
739 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
741 Value *OpVal = OpInfo.CallOperandVal;
742 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
749 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
750 BasicBlock *DefBB = I->getParent();
752 // If both result of the {s|z}xt and its source are live out, rewrite all
753 // other uses of the source with result of extension.
754 Value *Src = I->getOperand(0);
755 if (Src->hasOneUse())
758 // Only do this xform if truncating is free.
759 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
762 // Only safe to perform the optimization if the source is also defined in
764 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
767 bool DefIsLiveOut = false;
768 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
770 Instruction *User = cast<Instruction>(*UI);
772 // Figure out which BB this ext is used in.
773 BasicBlock *UserBB = User->getParent();
774 if (UserBB == DefBB) continue;
781 // Make sure non of the uses are PHI nodes.
782 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
784 Instruction *User = cast<Instruction>(*UI);
785 BasicBlock *UserBB = User->getParent();
786 if (UserBB == DefBB) continue;
787 // Be conservative. We don't want this xform to end up introducing
788 // reloads just before load / store instructions.
789 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
793 // InsertedTruncs - Only insert one trunc in each block once.
794 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
796 bool MadeChange = false;
797 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
799 Use &TheUse = UI.getUse();
800 Instruction *User = cast<Instruction>(*UI);
802 // Figure out which BB this ext is used in.
803 BasicBlock *UserBB = User->getParent();
804 if (UserBB == DefBB) continue;
806 // Both src and def are live in this block. Rewrite the use.
807 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
809 if (!InsertedTrunc) {
810 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
812 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
815 // Replace a use of the {s|z}ext source with a use of the result.
816 TheUse = InsertedTrunc;
824 // In this pass we look for GEP and cast instructions that are used
825 // across basic blocks and rewrite them to improve basic-block-at-a-time
827 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
828 bool MadeChange = false;
830 // Split all critical edges where the dest block has a PHI.
831 TerminatorInst *BBTI = BB.getTerminator();
832 if (BBTI->getNumSuccessors() > 1) {
833 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
834 BasicBlock *SuccBB = BBTI->getSuccessor(i);
835 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
836 SplitEdgeNicely(BBTI, i, BackEdges, this);
840 // Keep track of non-local addresses that have been sunk into this block.
841 // This allows us to avoid inserting duplicate code for blocks with multiple
842 // load/stores of the same address.
843 DenseMap<Value*, Value*> SunkAddrs;
845 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
846 Instruction *I = BBI++;
848 if (CastInst *CI = dyn_cast<CastInst>(I)) {
849 // If the source of the cast is a constant, then this should have
850 // already been constant folded. The only reason NOT to constant fold
851 // it is if something (e.g. LSR) was careful to place the constant
852 // evaluation in a block other than then one that uses it (e.g. to hoist
853 // the address of globals out of a loop). If this is the case, we don't
854 // want to forward-subst the cast.
855 if (isa<Constant>(CI->getOperand(0)))
860 Change = OptimizeNoopCopyExpression(CI, *TLI);
861 MadeChange |= Change;
864 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
865 MadeChange |= OptimizeExtUses(I);
866 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
867 MadeChange |= OptimizeCmpExpression(CI);
868 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
870 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
872 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
874 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
875 SI->getOperand(0)->getType(),
877 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
878 if (GEPI->hasAllZeroIndices()) {
879 /// The GEP operand must be a pointer, so must its result -> BitCast
880 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
881 GEPI->getName(), GEPI);
882 GEPI->replaceAllUsesWith(NC);
883 GEPI->eraseFromParent();
887 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
888 // If we found an inline asm expession, and if the target knows how to
889 // lower it to normal LLVM code, do so now.
890 if (TLI && isa<InlineAsm>(CI->getCalledValue()))
891 if (const TargetAsmInfo *TAI =
892 TLI->getTargetMachine().getTargetAsmInfo()) {
893 if (TAI->ExpandInlineAsm(CI)) {
895 // Avoid processing instructions out of order, which could cause
896 // reuse before a value is defined.
899 // Sink address computing for memory operands into the block.
900 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);