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/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/ProfileInfo.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.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/Transforms/Utils/BuildLibCalls.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/Assembly/Writer.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/GetElementPtrTypeIterator.h"
41 #include "llvm/Support/PatternMatch.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/IRBuilder.h"
45 using namespace llvm::PatternMatch;
47 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
48 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
49 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
50 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
52 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
54 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
55 "computations were sunk");
56 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
57 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
60 CriticalEdgeSplit("cgp-critical-edge-splitting",
61 cl::desc("Split critical edges during codegen prepare"),
62 cl::init(false), cl::Hidden);
65 class CodeGenPrepare : public FunctionPass {
66 /// TLI - Keep a pointer of a TargetLowering to consult for determining
67 /// transformation profitability.
68 const TargetLowering *TLI;
71 /// BackEdges - Keep a set of all the loop back edges.
73 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
75 // Keeps track of non-local addresses that have been sunk into a block. This
76 // allows us to avoid inserting duplicate code for blocks with multiple
77 // load/stores of the same address.
78 DenseMap<Value*, Value*> SunkAddrs;
81 static char ID; // Pass identification, replacement for typeid
82 explicit CodeGenPrepare(const TargetLowering *tli = 0)
83 : FunctionPass(ID), TLI(tli) {
84 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
86 bool runOnFunction(Function &F);
88 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
89 AU.addPreserved<ProfileInfo>();
92 virtual void releaseMemory() {
97 bool EliminateMostlyEmptyBlocks(Function &F);
98 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
99 void EliminateMostlyEmptyBlock(BasicBlock *BB);
100 bool OptimizeBlock(BasicBlock &BB);
101 bool OptimizeInst(Instruction *I);
102 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
103 DenseMap<Value*,Value*> &SunkAddrs);
104 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
105 DenseMap<Value*,Value*> &SunkAddrs);
106 bool OptimizeCallInst(CallInst *CI);
107 bool MoveExtToFormExtLoad(Instruction *I);
108 bool OptimizeExtUses(Instruction *I);
109 void findLoopBackEdges(const Function &F);
113 char CodeGenPrepare::ID = 0;
114 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
115 "Optimize for code generation", false, false)
117 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
118 return new CodeGenPrepare(TLI);
121 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
123 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
124 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
125 FindFunctionBackedges(F, Edges);
127 BackEdges.insert(Edges.begin(), Edges.end());
131 bool CodeGenPrepare::runOnFunction(Function &F) {
132 bool EverMadeChange = false;
134 PFI = getAnalysisIfAvailable<ProfileInfo>();
135 // First pass, eliminate blocks that contain only PHI nodes and an
136 // unconditional branch.
137 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
139 // Now find loop back edges, but only if they are being used to decide which
140 // critical edges to split.
141 if (CriticalEdgeSplit)
142 findLoopBackEdges(F);
144 bool MadeChange = true;
147 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
148 MadeChange |= OptimizeBlock(*BB);
149 EverMadeChange |= MadeChange;
154 return EverMadeChange;
157 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
158 /// debug info directives, and an unconditional branch. Passes before isel
159 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
160 /// isel. Start by eliminating these blocks so we can split them the way we
162 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
163 bool MadeChange = false;
164 // Note that this intentionally skips the entry block.
165 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
166 BasicBlock *BB = I++;
168 // If this block doesn't end with an uncond branch, ignore it.
169 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
170 if (!BI || !BI->isUnconditional())
173 // If the instruction before the branch (skipping debug info) isn't a phi
174 // node, then other stuff is happening here.
175 BasicBlock::iterator BBI = BI;
176 if (BBI != BB->begin()) {
178 while (isa<DbgInfoIntrinsic>(BBI)) {
179 if (BBI == BB->begin())
183 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
187 // Do not break infinite loops.
188 BasicBlock *DestBB = BI->getSuccessor(0);
192 if (!CanMergeBlocks(BB, DestBB))
195 EliminateMostlyEmptyBlock(BB);
201 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
202 /// single uncond branch between them, and BB contains no other non-phi
204 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
205 const BasicBlock *DestBB) const {
206 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
207 // the successor. If there are more complex condition (e.g. preheaders),
208 // don't mess around with them.
209 BasicBlock::const_iterator BBI = BB->begin();
210 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
211 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
213 const Instruction *User = cast<Instruction>(*UI);
214 if (User->getParent() != DestBB || !isa<PHINode>(User))
216 // If User is inside DestBB block and it is a PHINode then check
217 // incoming value. If incoming value is not from BB then this is
218 // a complex condition (e.g. preheaders) we want to avoid here.
219 if (User->getParent() == DestBB) {
220 if (const PHINode *UPN = dyn_cast<PHINode>(User))
221 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
222 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
223 if (Insn && Insn->getParent() == BB &&
224 Insn->getParent() != UPN->getIncomingBlock(I))
231 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
232 // and DestBB may have conflicting incoming values for the block. If so, we
233 // can't merge the block.
234 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
235 if (!DestBBPN) return true; // no conflict.
237 // Collect the preds of BB.
238 SmallPtrSet<const BasicBlock*, 16> BBPreds;
239 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
240 // It is faster to get preds from a PHI than with pred_iterator.
241 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
242 BBPreds.insert(BBPN->getIncomingBlock(i));
244 BBPreds.insert(pred_begin(BB), pred_end(BB));
247 // Walk the preds of DestBB.
248 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
249 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
250 if (BBPreds.count(Pred)) { // Common predecessor?
251 BBI = DestBB->begin();
252 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
253 const Value *V1 = PN->getIncomingValueForBlock(Pred);
254 const Value *V2 = PN->getIncomingValueForBlock(BB);
256 // If V2 is a phi node in BB, look up what the mapped value will be.
257 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
258 if (V2PN->getParent() == BB)
259 V2 = V2PN->getIncomingValueForBlock(Pred);
261 // If there is a conflict, bail out.
262 if (V1 != V2) return false;
271 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
272 /// an unconditional branch in it.
273 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
274 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
275 BasicBlock *DestBB = BI->getSuccessor(0);
277 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
279 // If the destination block has a single pred, then this is a trivial edge,
281 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
282 if (SinglePred != DestBB) {
283 // Remember if SinglePred was the entry block of the function. If so, we
284 // will need to move BB back to the entry position.
285 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
286 MergeBasicBlockIntoOnlyPred(DestBB, this);
288 if (isEntry && BB != &BB->getParent()->getEntryBlock())
289 BB->moveBefore(&BB->getParent()->getEntryBlock());
291 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
296 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
297 // to handle the new incoming edges it is about to have.
299 for (BasicBlock::iterator BBI = DestBB->begin();
300 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
301 // Remove the incoming value for BB, and remember it.
302 Value *InVal = PN->removeIncomingValue(BB, false);
304 // Two options: either the InVal is a phi node defined in BB or it is some
305 // value that dominates BB.
306 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
307 if (InValPhi && InValPhi->getParent() == BB) {
308 // Add all of the input values of the input PHI as inputs of this phi.
309 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
310 PN->addIncoming(InValPhi->getIncomingValue(i),
311 InValPhi->getIncomingBlock(i));
313 // Otherwise, add one instance of the dominating value for each edge that
314 // we will be adding.
315 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
316 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
317 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
319 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
320 PN->addIncoming(InVal, *PI);
325 // The PHIs are now updated, change everything that refers to BB to use
326 // DestBB and remove BB.
327 BB->replaceAllUsesWith(DestBB);
329 PFI->replaceAllUses(BB, DestBB);
330 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
332 BB->eraseFromParent();
335 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
338 /// FindReusablePredBB - Check all of the predecessors of the block DestPHI
339 /// lives in to see if there is a block that we can reuse as a critical edge
341 static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
342 BasicBlock *Dest = DestPHI->getParent();
344 /// TIPHIValues - This array is lazily computed to determine the values of
345 /// PHIs in Dest that TI would provide.
346 SmallVector<Value*, 32> TIPHIValues;
348 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
349 unsigned TIBBEntryNo = 0;
351 // Check to see if Dest has any blocks that can be used as a split edge for
353 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
354 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
355 // To be usable, the pred has to end with an uncond branch to the dest.
356 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
357 if (!PredBr || !PredBr->isUnconditional())
359 // Must be empty other than the branch and debug info.
360 BasicBlock::iterator I = Pred->begin();
361 while (isa<DbgInfoIntrinsic>(I))
365 // Cannot be the entry block; its label does not get emitted.
366 if (Pred == &Dest->getParent()->getEntryBlock())
369 // Finally, since we know that Dest has phi nodes in it, we have to make
370 // sure that jumping to Pred will have the same effect as going to Dest in
371 // terms of PHI values.
374 unsigned PredEntryNo = pi;
376 bool FoundMatch = true;
377 for (BasicBlock::iterator I = Dest->begin();
378 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
379 if (PHINo == TIPHIValues.size()) {
380 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
381 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
382 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
385 // If the PHI entry doesn't work, we can't use this pred.
386 if (PN->getIncomingBlock(PredEntryNo) != Pred)
387 PredEntryNo = PN->getBasicBlockIndex(Pred);
389 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
395 // If we found a workable predecessor, change TI to branch to Succ.
403 /// SplitEdgeNicely - Split the critical edge from TI to its specified
404 /// successor if it will improve codegen. We only do this if the successor has
405 /// phi nodes (otherwise critical edges are ok). If there is already another
406 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
407 /// instead of introducing a new block.
408 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
409 SmallSet<std::pair<const BasicBlock*,
410 const BasicBlock*>, 8> &BackEdges,
412 BasicBlock *TIBB = TI->getParent();
413 BasicBlock *Dest = TI->getSuccessor(SuccNum);
414 assert(isa<PHINode>(Dest->begin()) &&
415 "This should only be called if Dest has a PHI!");
416 PHINode *DestPHI = cast<PHINode>(Dest->begin());
418 // Do not split edges to EH landing pads.
419 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
420 if (Invoke->getSuccessor(1) == Dest)
423 // As a hack, never split backedges of loops. Even though the copy for any
424 // PHIs inserted on the backedge would be dead for exits from the loop, we
425 // assume that the cost of *splitting* the backedge would be too high.
426 if (BackEdges.count(std::make_pair(TIBB, Dest)))
429 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
430 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
432 PFI->splitEdge(TIBB, Dest, ReuseBB);
433 Dest->removePredecessor(TIBB);
434 TI->setSuccessor(SuccNum, ReuseBB);
438 SplitCriticalEdge(TI, SuccNum, P, true);
442 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
443 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
444 /// sink it into user blocks to reduce the number of virtual
445 /// registers that must be created and coalesced.
447 /// Return true if any changes are made.
449 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
450 // If this is a noop copy,
451 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
452 EVT DstVT = TLI.getValueType(CI->getType());
454 // This is an fp<->int conversion?
455 if (SrcVT.isInteger() != DstVT.isInteger())
458 // If this is an extension, it will be a zero or sign extension, which
460 if (SrcVT.bitsLT(DstVT)) return false;
462 // If these values will be promoted, find out what they will be promoted
463 // to. This helps us consider truncates on PPC as noop copies when they
465 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
466 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
467 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
468 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
470 // If, after promotion, these are the same types, this is a noop copy.
474 BasicBlock *DefBB = CI->getParent();
476 /// InsertedCasts - Only insert a cast in each block once.
477 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
479 bool MadeChange = false;
480 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
482 Use &TheUse = UI.getUse();
483 Instruction *User = cast<Instruction>(*UI);
485 // Figure out which BB this cast is used in. For PHI's this is the
486 // appropriate predecessor block.
487 BasicBlock *UserBB = User->getParent();
488 if (PHINode *PN = dyn_cast<PHINode>(User)) {
489 UserBB = PN->getIncomingBlock(UI);
492 // Preincrement use iterator so we don't invalidate it.
495 // If this user is in the same block as the cast, don't change the cast.
496 if (UserBB == DefBB) continue;
498 // If we have already inserted a cast into this block, use it.
499 CastInst *&InsertedCast = InsertedCasts[UserBB];
502 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
505 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
510 // Replace a use of the cast with a use of the new cast.
511 TheUse = InsertedCast;
515 // If we removed all uses, nuke the cast.
516 if (CI->use_empty()) {
517 CI->eraseFromParent();
524 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
525 /// the number of virtual registers that must be created and coalesced. This is
526 /// a clear win except on targets with multiple condition code registers
527 /// (PowerPC), where it might lose; some adjustment may be wanted there.
529 /// Return true if any changes are made.
530 static bool OptimizeCmpExpression(CmpInst *CI) {
531 BasicBlock *DefBB = CI->getParent();
533 /// InsertedCmp - Only insert a cmp in each block once.
534 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
536 bool MadeChange = false;
537 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
539 Use &TheUse = UI.getUse();
540 Instruction *User = cast<Instruction>(*UI);
542 // Preincrement use iterator so we don't invalidate it.
545 // Don't bother for PHI nodes.
546 if (isa<PHINode>(User))
549 // Figure out which BB this cmp is used in.
550 BasicBlock *UserBB = User->getParent();
552 // If this user is in the same block as the cmp, don't change the cmp.
553 if (UserBB == DefBB) continue;
555 // If we have already inserted a cmp into this block, use it.
556 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
559 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
562 CmpInst::Create(CI->getOpcode(),
563 CI->getPredicate(), CI->getOperand(0),
564 CI->getOperand(1), "", InsertPt);
568 // Replace a use of the cmp with a use of the new cmp.
569 TheUse = InsertedCmp;
573 // If we removed all uses, nuke the cmp.
575 CI->eraseFromParent();
581 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
583 void replaceCall(Value *With) {
584 CI->replaceAllUsesWith(With);
585 CI->eraseFromParent();
587 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
588 if (ConstantInt *SizeCI =
589 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
590 return SizeCI->isAllOnesValue();
594 } // end anonymous namespace
596 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
597 // Lower all uses of llvm.objectsize.*
598 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
599 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
600 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
601 const Type *ReturnTy = CI->getType();
602 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
603 CI->replaceAllUsesWith(RetVal);
604 CI->eraseFromParent();
608 // From here on out we're working with named functions.
609 if (CI->getCalledFunction() == 0) return false;
611 // We'll need TargetData from here on out.
612 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
613 if (!TD) return false;
615 // Lower all default uses of _chk calls. This is very similar
616 // to what InstCombineCalls does, but here we are only lowering calls
617 // that have the default "don't know" as the objectsize. Anything else
618 // should be left alone.
619 CodeGenPrepareFortifiedLibCalls Simplifier;
620 return Simplifier.fold(CI, TD);
622 //===----------------------------------------------------------------------===//
623 // Memory Optimization
624 //===----------------------------------------------------------------------===//
626 /// IsNonLocalValue - Return true if the specified values are defined in a
627 /// different basic block than BB.
628 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
629 if (Instruction *I = dyn_cast<Instruction>(V))
630 return I->getParent() != BB;
634 /// OptimizeMemoryInst - Load and Store Instructions often have
635 /// addressing modes that can do significant amounts of computation. As such,
636 /// instruction selection will try to get the load or store to do as much
637 /// computation as possible for the program. The problem is that isel can only
638 /// see within a single block. As such, we sink as much legal addressing mode
639 /// stuff into the block as possible.
641 /// This method is used to optimize both load/store and inline asms with memory
643 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
644 const Type *AccessTy,
645 DenseMap<Value*,Value*> &SunkAddrs) {
648 // Try to collapse single-value PHI nodes. This is necessary to undo
649 // unprofitable PRE transformations.
650 SmallVector<Value*, 8> worklist;
651 SmallPtrSet<Value*, 16> Visited;
652 worklist.push_back(Addr);
654 // Use a worklist to iteratively look through PHI nodes, and ensure that
655 // the addressing mode obtained from the non-PHI roots of the graph
657 Value *Consensus = 0;
658 unsigned NumUses = 0;
659 SmallVector<Instruction*, 16> AddrModeInsts;
660 ExtAddrMode AddrMode;
661 while (!worklist.empty()) {
662 Value *V = worklist.back();
665 // Break use-def graph loops.
666 if (Visited.count(V)) {
673 // For a PHI node, push all of its incoming values.
674 if (PHINode *P = dyn_cast<PHINode>(V)) {
675 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
676 worklist.push_back(P->getIncomingValue(i));
680 // For non-PHIs, determine the addressing mode being computed.
681 SmallVector<Instruction*, 16> NewAddrModeInsts;
682 ExtAddrMode NewAddrMode =
683 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
684 NewAddrModeInsts, *TLI);
686 // Ensure that the obtained addressing mode is equivalent to that obtained
687 // for all other roots of the PHI traversal. Also, when choosing one
688 // such root as representative, select the one with the most uses in order
689 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
690 if (!Consensus || NewAddrMode == AddrMode) {
691 if (V->getNumUses() > NumUses) {
693 NumUses = V->getNumUses();
694 AddrMode = NewAddrMode;
695 AddrModeInsts = NewAddrModeInsts;
704 // If the addressing mode couldn't be determined, or if multiple different
705 // ones were determined, bail out now.
706 if (!Consensus) return false;
708 // Check to see if any of the instructions supersumed by this addr mode are
709 // non-local to I's BB.
710 bool AnyNonLocal = false;
711 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
712 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
718 // If all the instructions matched are already in this BB, don't do anything.
720 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
724 // Insert this computation right after this user. Since our caller is
725 // scanning from the top of the BB to the bottom, reuse of the expr are
726 // guaranteed to happen later.
727 BasicBlock::iterator InsertPt = MemoryInst;
729 // Now that we determined the addressing expression we want to use and know
730 // that we have to sink it into this block. Check to see if we have already
731 // done this for some other load/store instr in this block. If so, reuse the
733 Value *&SunkAddr = SunkAddrs[Addr];
735 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
737 if (SunkAddr->getType() != Addr->getType())
738 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
740 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
742 const Type *IntPtrTy =
743 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
747 // Start with the base register. Do this first so that subsequent address
748 // matching finds it last, which will prevent it from trying to match it
749 // as the scaled value in case it happens to be a mul. That would be
750 // problematic if we've sunk a different mul for the scale, because then
751 // we'd end up sinking both muls.
752 if (AddrMode.BaseReg) {
753 Value *V = AddrMode.BaseReg;
754 if (V->getType()->isPointerTy())
755 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
756 if (V->getType() != IntPtrTy)
757 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
758 "sunkaddr", InsertPt);
762 // Add the scale value.
763 if (AddrMode.Scale) {
764 Value *V = AddrMode.ScaledReg;
765 if (V->getType() == IntPtrTy) {
767 } else if (V->getType()->isPointerTy()) {
768 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
769 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
770 cast<IntegerType>(V->getType())->getBitWidth()) {
771 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
773 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
775 if (AddrMode.Scale != 1)
776 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
778 "sunkaddr", InsertPt);
780 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
785 // Add in the BaseGV if present.
786 if (AddrMode.BaseGV) {
787 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
790 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
795 // Add in the Base Offset if present.
796 if (AddrMode.BaseOffs) {
797 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
799 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
805 SunkAddr = Constant::getNullValue(Addr->getType());
807 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
810 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
812 if (Repl->use_empty()) {
813 RecursivelyDeleteTriviallyDeadInstructions(Repl);
814 // This address is now available for reassignment, so erase the table entry;
815 // we don't want to match some completely different instruction.
822 /// OptimizeInlineAsmInst - If there are any memory operands, use
823 /// OptimizeMemoryInst to sink their address computing into the block when
824 /// possible / profitable.
825 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
826 DenseMap<Value*,Value*> &SunkAddrs) {
827 bool MadeChange = false;
829 TargetLowering::AsmOperandInfoVector TargetConstraints = TLI->ParseConstraints(CS);
831 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
832 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
834 // Compute the constraint code and ConstraintType to use.
835 TLI->ComputeConstraintToUse(OpInfo, SDValue());
837 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
839 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
840 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
841 } else if (OpInfo.Type == InlineAsm::isInput)
848 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
849 /// basic block as the load, unless conditions are unfavorable. This allows
850 /// SelectionDAG to fold the extend into the load.
852 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
853 // Look for a load being extended.
854 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
855 if (!LI) return false;
857 // If they're already in the same block, there's nothing to do.
858 if (LI->getParent() == I->getParent())
861 // If the load has other users and the truncate is not free, this probably
863 if (!LI->hasOneUse() &&
864 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
865 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
866 !TLI->isTruncateFree(I->getType(), LI->getType()))
869 // Check whether the target supports casts folded into loads.
871 if (isa<ZExtInst>(I))
872 LType = ISD::ZEXTLOAD;
874 assert(isa<SExtInst>(I) && "Unexpected ext type!");
875 LType = ISD::SEXTLOAD;
877 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
880 // Move the extend into the same block as the load, so that SelectionDAG
882 I->removeFromParent();
888 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
889 BasicBlock *DefBB = I->getParent();
891 // If the result of a {s|z}ext and its source are both live out, rewrite all
892 // other uses of the source with result of extension.
893 Value *Src = I->getOperand(0);
894 if (Src->hasOneUse())
897 // Only do this xform if truncating is free.
898 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
901 // Only safe to perform the optimization if the source is also defined in
903 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
906 bool DefIsLiveOut = false;
907 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
909 Instruction *User = cast<Instruction>(*UI);
911 // Figure out which BB this ext is used in.
912 BasicBlock *UserBB = User->getParent();
913 if (UserBB == DefBB) continue;
920 // Make sure non of the uses are PHI nodes.
921 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
923 Instruction *User = cast<Instruction>(*UI);
924 BasicBlock *UserBB = User->getParent();
925 if (UserBB == DefBB) continue;
926 // Be conservative. We don't want this xform to end up introducing
927 // reloads just before load / store instructions.
928 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
932 // InsertedTruncs - Only insert one trunc in each block once.
933 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
935 bool MadeChange = false;
936 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
938 Use &TheUse = UI.getUse();
939 Instruction *User = cast<Instruction>(*UI);
941 // Figure out which BB this ext is used in.
942 BasicBlock *UserBB = User->getParent();
943 if (UserBB == DefBB) continue;
945 // Both src and def are live in this block. Rewrite the use.
946 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
948 if (!InsertedTrunc) {
949 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
951 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
954 // Replace a use of the {s|z}ext source with a use of the result.
955 TheUse = InsertedTrunc;
963 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
964 bool MadeChange = false;
966 if (PHINode *P = dyn_cast<PHINode>(I)) {
967 // It is possible for very late stage optimizations (such as SimplifyCFG)
968 // to introduce PHI nodes too late to be cleaned up. If we detect such a
969 // trivial PHI, go ahead and zap it here.
970 if (Value *V = SimplifyInstruction(P)) {
971 P->replaceAllUsesWith(V);
972 P->eraseFromParent();
975 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
976 // If the source of the cast is a constant, then this should have
977 // already been constant folded. The only reason NOT to constant fold
978 // it is if something (e.g. LSR) was careful to place the constant
979 // evaluation in a block other than then one that uses it (e.g. to hoist
980 // the address of globals out of a loop). If this is the case, we don't
981 // want to forward-subst the cast.
982 if (isa<Constant>(CI->getOperand(0)))
987 Change = OptimizeNoopCopyExpression(CI, *TLI);
988 MadeChange |= Change;
991 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
992 MadeChange |= MoveExtToFormExtLoad(I);
993 MadeChange |= OptimizeExtUses(I);
995 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
996 MadeChange |= OptimizeCmpExpression(CI);
997 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
999 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1001 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1003 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1004 SI->getOperand(0)->getType(),
1011 // In this pass we look for GEP and cast instructions that are used
1012 // across basic blocks and rewrite them to improve basic-block-at-a-time
1014 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1015 bool MadeChange = false;
1017 // Split all critical edges where the dest block has a PHI.
1018 if (CriticalEdgeSplit) {
1019 TerminatorInst *BBTI = BB.getTerminator();
1020 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
1021 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1022 BasicBlock *SuccBB = BBTI->getSuccessor(i);
1023 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1024 SplitEdgeNicely(BBTI, i, BackEdges, this);
1031 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1032 Instruction *I = BBI++;
1034 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1035 if (GEPI->hasAllZeroIndices()) {
1036 /// The GEP operand must be a pointer, so must its result -> BitCast
1037 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1038 GEPI->getName(), GEPI);
1039 GEPI->replaceAllUsesWith(NC);
1040 GEPI->eraseFromParent();
1045 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1046 // If we found an inline asm expession, and if the target knows how to
1047 // lower it to normal LLVM code, do so now.
1048 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1049 if (TLI->ExpandInlineAsm(CI)) {
1051 // Avoid processing instructions out of order, which could cause
1052 // reuse before a value is defined.
1055 // Sink address computing for memory operands into the block.
1056 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
1058 // Other CallInst optimizations that don't need to muck with the
1059 // enclosing iterator here.
1060 MadeChange |= OptimizeCallInst(CI);
1063 MadeChange |= OptimizeInst(I);