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/ProfileInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Transforms/Utils/BuildLibCalls.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Assembly/Writer.h"
36 #include "llvm/Support/CallSite.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/PatternMatch.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Support/IRBuilder.h"
44 using namespace llvm::PatternMatch;
46 STATISTIC(NumElim, "Number of blocks eliminated");
49 CriticalEdgeSplit("cgp-critical-edge-splitting",
50 cl::desc("Split critical edges during codegen prepare"),
51 cl::init(false), cl::Hidden);
54 class CodeGenPrepare : public FunctionPass {
55 /// TLI - Keep a pointer of a TargetLowering to consult for determining
56 /// transformation profitability.
57 const TargetLowering *TLI;
60 /// BackEdges - Keep a set of all the loop back edges.
62 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
64 static char ID; // Pass identification, replacement for typeid
65 explicit CodeGenPrepare(const TargetLowering *tli = 0)
66 : FunctionPass(ID), TLI(tli) {}
67 bool runOnFunction(Function &F);
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addPreserved<ProfileInfo>();
73 virtual void releaseMemory() {
78 bool EliminateMostlyEmptyBlocks(Function &F);
79 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
80 void EliminateMostlyEmptyBlock(BasicBlock *BB);
81 bool OptimizeBlock(BasicBlock &BB);
82 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
83 DenseMap<Value*,Value*> &SunkAddrs);
84 bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
85 DenseMap<Value*,Value*> &SunkAddrs);
86 bool OptimizeCallInst(CallInst *CI);
87 bool MoveExtToFormExtLoad(Instruction *I);
88 bool OptimizeExtUses(Instruction *I);
89 void findLoopBackEdges(const Function &F);
93 char CodeGenPrepare::ID = 0;
94 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
95 "Optimize for code generation", false, false)
97 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
98 return new CodeGenPrepare(TLI);
101 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
103 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
104 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
105 FindFunctionBackedges(F, Edges);
107 BackEdges.insert(Edges.begin(), Edges.end());
111 bool CodeGenPrepare::runOnFunction(Function &F) {
112 bool EverMadeChange = false;
114 PFI = getAnalysisIfAvailable<ProfileInfo>();
115 // First pass, eliminate blocks that contain only PHI nodes and an
116 // unconditional branch.
117 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
119 // Now find loop back edges.
120 findLoopBackEdges(F);
122 bool MadeChange = true;
125 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
126 MadeChange |= OptimizeBlock(*BB);
127 EverMadeChange |= MadeChange;
129 return EverMadeChange;
132 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
133 /// debug info directives, and an unconditional branch. Passes before isel
134 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
135 /// isel. Start by eliminating these blocks so we can split them the way we
137 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
138 bool MadeChange = false;
139 // Note that this intentionally skips the entry block.
140 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
141 BasicBlock *BB = I++;
143 // If this block doesn't end with an uncond branch, ignore it.
144 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
145 if (!BI || !BI->isUnconditional())
148 // If the instruction before the branch (skipping debug info) isn't a phi
149 // node, then other stuff is happening here.
150 BasicBlock::iterator BBI = BI;
151 if (BBI != BB->begin()) {
153 while (isa<DbgInfoIntrinsic>(BBI)) {
154 if (BBI == BB->begin())
158 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
162 // Do not break infinite loops.
163 BasicBlock *DestBB = BI->getSuccessor(0);
167 if (!CanMergeBlocks(BB, DestBB))
170 EliminateMostlyEmptyBlock(BB);
176 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
177 /// single uncond branch between them, and BB contains no other non-phi
179 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
180 const BasicBlock *DestBB) const {
181 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
182 // the successor. If there are more complex condition (e.g. preheaders),
183 // don't mess around with them.
184 BasicBlock::const_iterator BBI = BB->begin();
185 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
186 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
188 const Instruction *User = cast<Instruction>(*UI);
189 if (User->getParent() != DestBB || !isa<PHINode>(User))
191 // If User is inside DestBB block and it is a PHINode then check
192 // incoming value. If incoming value is not from BB then this is
193 // a complex condition (e.g. preheaders) we want to avoid here.
194 if (User->getParent() == DestBB) {
195 if (const PHINode *UPN = dyn_cast<PHINode>(User))
196 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
197 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
198 if (Insn && Insn->getParent() == BB &&
199 Insn->getParent() != UPN->getIncomingBlock(I))
206 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
207 // and DestBB may have conflicting incoming values for the block. If so, we
208 // can't merge the block.
209 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
210 if (!DestBBPN) return true; // no conflict.
212 // Collect the preds of BB.
213 SmallPtrSet<const BasicBlock*, 16> BBPreds;
214 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
215 // It is faster to get preds from a PHI than with pred_iterator.
216 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
217 BBPreds.insert(BBPN->getIncomingBlock(i));
219 BBPreds.insert(pred_begin(BB), pred_end(BB));
222 // Walk the preds of DestBB.
223 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
224 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
225 if (BBPreds.count(Pred)) { // Common predecessor?
226 BBI = DestBB->begin();
227 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
228 const Value *V1 = PN->getIncomingValueForBlock(Pred);
229 const Value *V2 = PN->getIncomingValueForBlock(BB);
231 // If V2 is a phi node in BB, look up what the mapped value will be.
232 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
233 if (V2PN->getParent() == BB)
234 V2 = V2PN->getIncomingValueForBlock(Pred);
236 // If there is a conflict, bail out.
237 if (V1 != V2) return false;
246 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
247 /// an unconditional branch in it.
248 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
249 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
250 BasicBlock *DestBB = BI->getSuccessor(0);
252 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
254 // If the destination block has a single pred, then this is a trivial edge,
256 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
257 if (SinglePred != DestBB) {
258 // Remember if SinglePred was the entry block of the function. If so, we
259 // will need to move BB back to the entry position.
260 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
261 MergeBasicBlockIntoOnlyPred(DestBB, this);
263 if (isEntry && BB != &BB->getParent()->getEntryBlock())
264 BB->moveBefore(&BB->getParent()->getEntryBlock());
266 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
271 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
272 // to handle the new incoming edges it is about to have.
274 for (BasicBlock::iterator BBI = DestBB->begin();
275 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
276 // Remove the incoming value for BB, and remember it.
277 Value *InVal = PN->removeIncomingValue(BB, false);
279 // Two options: either the InVal is a phi node defined in BB or it is some
280 // value that dominates BB.
281 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
282 if (InValPhi && InValPhi->getParent() == BB) {
283 // Add all of the input values of the input PHI as inputs of this phi.
284 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
285 PN->addIncoming(InValPhi->getIncomingValue(i),
286 InValPhi->getIncomingBlock(i));
288 // Otherwise, add one instance of the dominating value for each edge that
289 // we will be adding.
290 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
291 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
292 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
294 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
295 PN->addIncoming(InVal, *PI);
300 // The PHIs are now updated, change everything that refers to BB to use
301 // DestBB and remove BB.
302 BB->replaceAllUsesWith(DestBB);
304 PFI->replaceAllUses(BB, DestBB);
305 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
307 BB->eraseFromParent();
310 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
313 /// FindReusablePredBB - Check all of the predecessors of the block DestPHI
314 /// lives in to see if there is a block that we can reuse as a critical edge
316 static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
317 BasicBlock *Dest = DestPHI->getParent();
319 /// TIPHIValues - This array is lazily computed to determine the values of
320 /// PHIs in Dest that TI would provide.
321 SmallVector<Value*, 32> TIPHIValues;
323 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
324 unsigned TIBBEntryNo = 0;
326 // Check to see if Dest has any blocks that can be used as a split edge for
328 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
329 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
330 // To be usable, the pred has to end with an uncond branch to the dest.
331 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
332 if (!PredBr || !PredBr->isUnconditional())
334 // Must be empty other than the branch and debug info.
335 BasicBlock::iterator I = Pred->begin();
336 while (isa<DbgInfoIntrinsic>(I))
340 // Cannot be the entry block; its label does not get emitted.
341 if (Pred == &Dest->getParent()->getEntryBlock())
344 // Finally, since we know that Dest has phi nodes in it, we have to make
345 // sure that jumping to Pred will have the same effect as going to Dest in
346 // terms of PHI values.
349 unsigned PredEntryNo = pi;
351 bool FoundMatch = true;
352 for (BasicBlock::iterator I = Dest->begin();
353 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
354 if (PHINo == TIPHIValues.size()) {
355 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
356 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
357 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
360 // If the PHI entry doesn't work, we can't use this pred.
361 if (PN->getIncomingBlock(PredEntryNo) != Pred)
362 PredEntryNo = PN->getBasicBlockIndex(Pred);
364 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
370 // If we found a workable predecessor, change TI to branch to Succ.
378 /// SplitEdgeNicely - Split the critical edge from TI to its specified
379 /// successor if it will improve codegen. We only do this if the successor has
380 /// phi nodes (otherwise critical edges are ok). If there is already another
381 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
382 /// instead of introducing a new block.
383 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
384 SmallSet<std::pair<const BasicBlock*,
385 const BasicBlock*>, 8> &BackEdges,
387 BasicBlock *TIBB = TI->getParent();
388 BasicBlock *Dest = TI->getSuccessor(SuccNum);
389 assert(isa<PHINode>(Dest->begin()) &&
390 "This should only be called if Dest has a PHI!");
391 PHINode *DestPHI = cast<PHINode>(Dest->begin());
393 // Do not split edges to EH landing pads.
394 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
395 if (Invoke->getSuccessor(1) == Dest)
398 // As a hack, never split backedges of loops. Even though the copy for any
399 // PHIs inserted on the backedge would be dead for exits from the loop, we
400 // assume that the cost of *splitting* the backedge would be too high.
401 if (BackEdges.count(std::make_pair(TIBB, Dest)))
404 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
405 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
407 PFI->splitEdge(TIBB, Dest, ReuseBB);
408 Dest->removePredecessor(TIBB);
409 TI->setSuccessor(SuccNum, ReuseBB);
413 SplitCriticalEdge(TI, SuccNum, P, true);
417 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
418 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
419 /// sink it into user blocks to reduce the number of virtual
420 /// registers that must be created and coalesced.
422 /// Return true if any changes are made.
424 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
425 // If this is a noop copy,
426 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
427 EVT DstVT = TLI.getValueType(CI->getType());
429 // This is an fp<->int conversion?
430 if (SrcVT.isInteger() != DstVT.isInteger())
433 // If this is an extension, it will be a zero or sign extension, which
435 if (SrcVT.bitsLT(DstVT)) return false;
437 // If these values will be promoted, find out what they will be promoted
438 // to. This helps us consider truncates on PPC as noop copies when they
440 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
441 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
442 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
443 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
445 // If, after promotion, these are the same types, this is a noop copy.
449 BasicBlock *DefBB = CI->getParent();
451 /// InsertedCasts - Only insert a cast in each block once.
452 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
454 bool MadeChange = false;
455 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
457 Use &TheUse = UI.getUse();
458 Instruction *User = cast<Instruction>(*UI);
460 // Figure out which BB this cast is used in. For PHI's this is the
461 // appropriate predecessor block.
462 BasicBlock *UserBB = User->getParent();
463 if (PHINode *PN = dyn_cast<PHINode>(User)) {
464 UserBB = PN->getIncomingBlock(UI);
467 // Preincrement use iterator so we don't invalidate it.
470 // If this user is in the same block as the cast, don't change the cast.
471 if (UserBB == DefBB) continue;
473 // If we have already inserted a cast into this block, use it.
474 CastInst *&InsertedCast = InsertedCasts[UserBB];
477 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
480 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
485 // Replace a use of the cast with a use of the new cast.
486 TheUse = InsertedCast;
489 // If we removed all uses, nuke the cast.
490 if (CI->use_empty()) {
491 CI->eraseFromParent();
498 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
499 /// the number of virtual registers that must be created and coalesced. This is
500 /// a clear win except on targets with multiple condition code registers
501 /// (PowerPC), where it might lose; some adjustment may be wanted there.
503 /// Return true if any changes are made.
504 static bool OptimizeCmpExpression(CmpInst *CI) {
505 BasicBlock *DefBB = CI->getParent();
507 /// InsertedCmp - Only insert a cmp in each block once.
508 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
510 bool MadeChange = false;
511 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
513 Use &TheUse = UI.getUse();
514 Instruction *User = cast<Instruction>(*UI);
516 // Preincrement use iterator so we don't invalidate it.
519 // Don't bother for PHI nodes.
520 if (isa<PHINode>(User))
523 // Figure out which BB this cmp is used in.
524 BasicBlock *UserBB = User->getParent();
526 // If this user is in the same block as the cmp, don't change the cmp.
527 if (UserBB == DefBB) continue;
529 // If we have already inserted a cmp into this block, use it.
530 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
533 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
536 CmpInst::Create(CI->getOpcode(),
537 CI->getPredicate(), CI->getOperand(0),
538 CI->getOperand(1), "", InsertPt);
542 // Replace a use of the cmp with a use of the new cmp.
543 TheUse = InsertedCmp;
546 // If we removed all uses, nuke the cmp.
548 CI->eraseFromParent();
554 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
556 void replaceCall(Value *With) {
557 CI->replaceAllUsesWith(With);
558 CI->eraseFromParent();
560 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
561 if (ConstantInt *SizeCI =
562 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
563 return SizeCI->isAllOnesValue();
567 } // end anonymous namespace
569 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
570 // Lower all uses of llvm.objectsize.*
571 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
572 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
573 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
574 const Type *ReturnTy = CI->getType();
575 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
576 CI->replaceAllUsesWith(RetVal);
577 CI->eraseFromParent();
581 // From here on out we're working with named functions.
582 if (CI->getCalledFunction() == 0) return false;
584 // We'll need TargetData from here on out.
585 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
586 if (!TD) return false;
588 // Lower all default uses of _chk calls. This is very similar
589 // to what InstCombineCalls does, but here we are only lowering calls
590 // that have the default "don't know" as the objectsize. Anything else
591 // should be left alone.
592 CodeGenPrepareFortifiedLibCalls Simplifier;
593 return Simplifier.fold(CI, TD);
595 //===----------------------------------------------------------------------===//
596 // Memory Optimization
597 //===----------------------------------------------------------------------===//
599 /// IsNonLocalValue - Return true if the specified values are defined in a
600 /// different basic block than BB.
601 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
602 if (Instruction *I = dyn_cast<Instruction>(V))
603 return I->getParent() != BB;
607 /// OptimizeMemoryInst - Load and Store Instructions often have
608 /// addressing modes that can do significant amounts of computation. As such,
609 /// instruction selection will try to get the load or store to do as much
610 /// computation as possible for the program. The problem is that isel can only
611 /// see within a single block. As such, we sink as much legal addressing mode
612 /// stuff into the block as possible.
614 /// This method is used to optimize both load/store and inline asms with memory
616 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
617 const Type *AccessTy,
618 DenseMap<Value*,Value*> &SunkAddrs) {
619 // Figure out what addressing mode will be built up for this operation.
620 SmallVector<Instruction*, 16> AddrModeInsts;
621 ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
622 AddrModeInsts, *TLI);
624 // Check to see if any of the instructions supersumed by this addr mode are
625 // non-local to I's BB.
626 bool AnyNonLocal = false;
627 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
628 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
634 // If all the instructions matched are already in this BB, don't do anything.
636 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
640 // Insert this computation right after this user. Since our caller is
641 // scanning from the top of the BB to the bottom, reuse of the expr are
642 // guaranteed to happen later.
643 BasicBlock::iterator InsertPt = MemoryInst;
645 // Now that we determined the addressing expression we want to use and know
646 // that we have to sink it into this block. Check to see if we have already
647 // done this for some other load/store instr in this block. If so, reuse the
649 Value *&SunkAddr = SunkAddrs[Addr];
651 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
653 if (SunkAddr->getType() != Addr->getType())
654 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
656 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
658 const Type *IntPtrTy =
659 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
663 // Start with the base register. Do this first so that subsequent address
664 // matching finds it last, which will prevent it from trying to match it
665 // as the scaled value in case it happens to be a mul. That would be
666 // problematic if we've sunk a different mul for the scale, because then
667 // we'd end up sinking both muls.
668 if (AddrMode.BaseReg) {
669 Value *V = AddrMode.BaseReg;
670 if (V->getType()->isPointerTy())
671 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
672 if (V->getType() != IntPtrTy)
673 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
674 "sunkaddr", InsertPt);
678 // Add the scale value.
679 if (AddrMode.Scale) {
680 Value *V = AddrMode.ScaledReg;
681 if (V->getType() == IntPtrTy) {
683 } else if (V->getType()->isPointerTy()) {
684 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
685 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
686 cast<IntegerType>(V->getType())->getBitWidth()) {
687 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
689 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
691 if (AddrMode.Scale != 1)
692 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
694 "sunkaddr", InsertPt);
696 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
701 // Add in the BaseGV if present.
702 if (AddrMode.BaseGV) {
703 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
706 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
711 // Add in the Base Offset if present.
712 if (AddrMode.BaseOffs) {
713 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
715 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
721 SunkAddr = Constant::getNullValue(Addr->getType());
723 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
726 MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
728 if (Addr->use_empty()) {
729 RecursivelyDeleteTriviallyDeadInstructions(Addr);
730 // This address is now available for reassignment, so erase the table entry;
731 // we don't want to match some completely different instruction.
737 /// OptimizeInlineAsmInst - If there are any memory operands, use
738 /// OptimizeMemoryInst to sink their address computing into the block when
739 /// possible / profitable.
740 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
741 DenseMap<Value*,Value*> &SunkAddrs) {
742 bool MadeChange = false;
744 std::vector<TargetLowering::AsmOperandInfo> TargetConstraints = TLI->ParseConstraints(CS);
746 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
747 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
749 // Compute the constraint code and ConstraintType to use.
750 TLI->ComputeConstraintToUse(OpInfo, SDValue());
752 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
754 Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
755 MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
756 } else if (OpInfo.Type == InlineAsm::isInput)
763 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
764 /// basic block as the load, unless conditions are unfavorable. This allows
765 /// SelectionDAG to fold the extend into the load.
767 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
768 // Look for a load being extended.
769 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
770 if (!LI) return false;
772 // If they're already in the same block, there's nothing to do.
773 if (LI->getParent() == I->getParent())
776 // If the load has other users and the truncate is not free, this probably
778 if (!LI->hasOneUse() &&
779 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
780 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
781 !TLI->isTruncateFree(I->getType(), LI->getType()))
784 // Check whether the target supports casts folded into loads.
786 if (isa<ZExtInst>(I))
787 LType = ISD::ZEXTLOAD;
789 assert(isa<SExtInst>(I) && "Unexpected ext type!");
790 LType = ISD::SEXTLOAD;
792 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
795 // Move the extend into the same block as the load, so that SelectionDAG
797 I->removeFromParent();
802 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
803 BasicBlock *DefBB = I->getParent();
805 // If the result of a {s|z}ext and its source are both live out, rewrite all
806 // other uses of the source with result of extension.
807 Value *Src = I->getOperand(0);
808 if (Src->hasOneUse())
811 // Only do this xform if truncating is free.
812 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
815 // Only safe to perform the optimization if the source is also defined in
817 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
820 bool DefIsLiveOut = false;
821 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
823 Instruction *User = cast<Instruction>(*UI);
825 // Figure out which BB this ext is used in.
826 BasicBlock *UserBB = User->getParent();
827 if (UserBB == DefBB) continue;
834 // Make sure non of the uses are PHI nodes.
835 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
837 Instruction *User = cast<Instruction>(*UI);
838 BasicBlock *UserBB = User->getParent();
839 if (UserBB == DefBB) continue;
840 // Be conservative. We don't want this xform to end up introducing
841 // reloads just before load / store instructions.
842 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
846 // InsertedTruncs - Only insert one trunc in each block once.
847 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
849 bool MadeChange = false;
850 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
852 Use &TheUse = UI.getUse();
853 Instruction *User = cast<Instruction>(*UI);
855 // Figure out which BB this ext is used in.
856 BasicBlock *UserBB = User->getParent();
857 if (UserBB == DefBB) continue;
859 // Both src and def are live in this block. Rewrite the use.
860 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
862 if (!InsertedTrunc) {
863 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
865 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
868 // Replace a use of the {s|z}ext source with a use of the result.
869 TheUse = InsertedTrunc;
877 // In this pass we look for GEP and cast instructions that are used
878 // across basic blocks and rewrite them to improve basic-block-at-a-time
880 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
881 bool MadeChange = false;
883 // Split all critical edges where the dest block has a PHI.
884 if (CriticalEdgeSplit) {
885 TerminatorInst *BBTI = BB.getTerminator();
886 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
887 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
888 BasicBlock *SuccBB = BBTI->getSuccessor(i);
889 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
890 SplitEdgeNicely(BBTI, i, BackEdges, this);
895 // Keep track of non-local addresses that have been sunk into this block.
896 // This allows us to avoid inserting duplicate code for blocks with multiple
897 // load/stores of the same address.
898 DenseMap<Value*, Value*> SunkAddrs;
900 for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
901 Instruction *I = BBI++;
903 if (CastInst *CI = dyn_cast<CastInst>(I)) {
904 // If the source of the cast is a constant, then this should have
905 // already been constant folded. The only reason NOT to constant fold
906 // it is if something (e.g. LSR) was careful to place the constant
907 // evaluation in a block other than then one that uses it (e.g. to hoist
908 // the address of globals out of a loop). If this is the case, we don't
909 // want to forward-subst the cast.
910 if (isa<Constant>(CI->getOperand(0)))
915 Change = OptimizeNoopCopyExpression(CI, *TLI);
916 MadeChange |= Change;
919 if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
920 MadeChange |= MoveExtToFormExtLoad(I);
921 MadeChange |= OptimizeExtUses(I);
923 } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
924 MadeChange |= OptimizeCmpExpression(CI);
925 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
927 MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
929 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
931 MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
932 SI->getOperand(0)->getType(),
934 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
935 if (GEPI->hasAllZeroIndices()) {
936 /// The GEP operand must be a pointer, so must its result -> BitCast
937 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
938 GEPI->getName(), GEPI);
939 GEPI->replaceAllUsesWith(NC);
940 GEPI->eraseFromParent();
944 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
945 // If we found an inline asm expession, and if the target knows how to
946 // lower it to normal LLVM code, do so now.
947 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
948 if (TLI->ExpandInlineAsm(CI)) {
950 // Avoid processing instructions out of order, which could cause
951 // reuse before a value is defined.
954 // Sink address computing for memory operands into the block.
955 MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
957 // Other CallInst optimizations that don't need to muck with the
958 // enclosing iterator here.
959 MadeChange |= OptimizeCallInst(CI);