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/Dominators.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/ProfileInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/Transforms/Utils/BuildLibCalls.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Assembly/Writer.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/GetElementPtrTypeIterator.h"
42 #include "llvm/Support/PatternMatch.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/IRBuilder.h"
45 #include "llvm/Support/ValueHandle.h"
47 using namespace llvm::PatternMatch;
49 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
50 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
51 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
52 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
57 "computations were sunk");
58 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
62 CriticalEdgeSplit("cgp-critical-edge-splitting",
63 cl::desc("Split critical edges during codegen prepare"),
64 cl::init(false), cl::Hidden);
67 class CodeGenPrepare : public FunctionPass {
68 /// TLI - Keep a pointer of a TargetLowering to consult for determining
69 /// transformation profitability.
70 const TargetLowering *TLI;
74 /// CurInstIterator - As we scan instructions optimizing them, this is the
75 /// next instruction to optimize. Xforms that can invalidate this should
77 BasicBlock::iterator CurInstIterator;
79 /// BackEdges - Keep a set of all the loop back edges.
81 SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
83 // Keeps track of non-local addresses that have been sunk into a block. This
84 // allows us to avoid inserting duplicate code for blocks with multiple
85 // load/stores of the same address.
86 DenseMap<Value*, Value*> SunkAddrs;
89 static char ID; // Pass identification, replacement for typeid
90 explicit CodeGenPrepare(const TargetLowering *tli = 0)
91 : FunctionPass(ID), TLI(tli) {
92 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
94 bool runOnFunction(Function &F);
96 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addPreserved<DominatorTree>();
98 AU.addPreserved<ProfileInfo>();
101 virtual void releaseMemory() {
106 bool EliminateMostlyEmptyBlocks(Function &F);
107 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
108 void EliminateMostlyEmptyBlock(BasicBlock *BB);
109 bool OptimizeBlock(BasicBlock &BB);
110 bool OptimizeInst(Instruction *I);
111 bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy);
112 bool OptimizeInlineAsmInst(CallInst *CS);
113 bool OptimizeCallInst(CallInst *CI);
114 bool MoveExtToFormExtLoad(Instruction *I);
115 bool OptimizeExtUses(Instruction *I);
116 void findLoopBackEdges(const Function &F);
120 char CodeGenPrepare::ID = 0;
121 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
122 "Optimize for code generation", false, false)
124 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
125 return new CodeGenPrepare(TLI);
128 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
130 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
131 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
132 FindFunctionBackedges(F, Edges);
134 BackEdges.insert(Edges.begin(), Edges.end());
138 bool CodeGenPrepare::runOnFunction(Function &F) {
139 bool EverMadeChange = false;
141 DT = getAnalysisIfAvailable<DominatorTree>();
142 PFI = getAnalysisIfAvailable<ProfileInfo>();
143 // First pass, eliminate blocks that contain only PHI nodes and an
144 // unconditional branch.
145 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
147 // Now find loop back edges, but only if they are being used to decide which
148 // critical edges to split.
149 if (CriticalEdgeSplit)
150 findLoopBackEdges(F);
152 bool MadeChange = true;
155 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
156 MadeChange |= OptimizeBlock(*BB);
157 EverMadeChange |= MadeChange;
162 return EverMadeChange;
165 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
166 /// debug info directives, and an unconditional branch. Passes before isel
167 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
168 /// isel. Start by eliminating these blocks so we can split them the way we
170 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
171 bool MadeChange = false;
172 // Note that this intentionally skips the entry block.
173 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
174 BasicBlock *BB = I++;
176 // If this block doesn't end with an uncond branch, ignore it.
177 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
178 if (!BI || !BI->isUnconditional())
181 // If the instruction before the branch (skipping debug info) isn't a phi
182 // node, then other stuff is happening here.
183 BasicBlock::iterator BBI = BI;
184 if (BBI != BB->begin()) {
186 while (isa<DbgInfoIntrinsic>(BBI)) {
187 if (BBI == BB->begin())
191 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
195 // Do not break infinite loops.
196 BasicBlock *DestBB = BI->getSuccessor(0);
200 if (!CanMergeBlocks(BB, DestBB))
203 EliminateMostlyEmptyBlock(BB);
209 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
210 /// single uncond branch between them, and BB contains no other non-phi
212 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
213 const BasicBlock *DestBB) const {
214 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
215 // the successor. If there are more complex condition (e.g. preheaders),
216 // don't mess around with them.
217 BasicBlock::const_iterator BBI = BB->begin();
218 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
219 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
221 const Instruction *User = cast<Instruction>(*UI);
222 if (User->getParent() != DestBB || !isa<PHINode>(User))
224 // If User is inside DestBB block and it is a PHINode then check
225 // incoming value. If incoming value is not from BB then this is
226 // a complex condition (e.g. preheaders) we want to avoid here.
227 if (User->getParent() == DestBB) {
228 if (const PHINode *UPN = dyn_cast<PHINode>(User))
229 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
230 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
231 if (Insn && Insn->getParent() == BB &&
232 Insn->getParent() != UPN->getIncomingBlock(I))
239 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
240 // and DestBB may have conflicting incoming values for the block. If so, we
241 // can't merge the block.
242 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
243 if (!DestBBPN) return true; // no conflict.
245 // Collect the preds of BB.
246 SmallPtrSet<const BasicBlock*, 16> BBPreds;
247 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
248 // It is faster to get preds from a PHI than with pred_iterator.
249 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
250 BBPreds.insert(BBPN->getIncomingBlock(i));
252 BBPreds.insert(pred_begin(BB), pred_end(BB));
255 // Walk the preds of DestBB.
256 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
257 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
258 if (BBPreds.count(Pred)) { // Common predecessor?
259 BBI = DestBB->begin();
260 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
261 const Value *V1 = PN->getIncomingValueForBlock(Pred);
262 const Value *V2 = PN->getIncomingValueForBlock(BB);
264 // If V2 is a phi node in BB, look up what the mapped value will be.
265 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
266 if (V2PN->getParent() == BB)
267 V2 = V2PN->getIncomingValueForBlock(Pred);
269 // If there is a conflict, bail out.
270 if (V1 != V2) return false;
279 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
280 /// an unconditional branch in it.
281 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
282 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
283 BasicBlock *DestBB = BI->getSuccessor(0);
285 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
287 // If the destination block has a single pred, then this is a trivial edge,
289 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
290 if (SinglePred != DestBB) {
291 // Remember if SinglePred was the entry block of the function. If so, we
292 // will need to move BB back to the entry position.
293 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
294 MergeBasicBlockIntoOnlyPred(DestBB, this);
296 if (isEntry && BB != &BB->getParent()->getEntryBlock())
297 BB->moveBefore(&BB->getParent()->getEntryBlock());
299 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
304 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
305 // to handle the new incoming edges it is about to have.
307 for (BasicBlock::iterator BBI = DestBB->begin();
308 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
309 // Remove the incoming value for BB, and remember it.
310 Value *InVal = PN->removeIncomingValue(BB, false);
312 // Two options: either the InVal is a phi node defined in BB or it is some
313 // value that dominates BB.
314 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
315 if (InValPhi && InValPhi->getParent() == BB) {
316 // Add all of the input values of the input PHI as inputs of this phi.
317 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
318 PN->addIncoming(InValPhi->getIncomingValue(i),
319 InValPhi->getIncomingBlock(i));
321 // Otherwise, add one instance of the dominating value for each edge that
322 // we will be adding.
323 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
324 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
325 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
327 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
328 PN->addIncoming(InVal, *PI);
333 // The PHIs are now updated, change everything that refers to BB to use
334 // DestBB and remove BB.
335 BB->replaceAllUsesWith(DestBB);
337 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
338 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
339 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
340 DT->changeImmediateDominator(DestBB, NewIDom);
344 PFI->replaceAllUses(BB, DestBB);
345 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
347 BB->eraseFromParent();
350 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
353 /// FindReusablePredBB - Check all of the predecessors of the block DestPHI
354 /// lives in to see if there is a block that we can reuse as a critical edge
356 static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
357 BasicBlock *Dest = DestPHI->getParent();
359 /// TIPHIValues - This array is lazily computed to determine the values of
360 /// PHIs in Dest that TI would provide.
361 SmallVector<Value*, 32> TIPHIValues;
363 /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
364 unsigned TIBBEntryNo = 0;
366 // Check to see if Dest has any blocks that can be used as a split edge for
368 for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
369 BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
370 // To be usable, the pred has to end with an uncond branch to the dest.
371 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
372 if (!PredBr || !PredBr->isUnconditional())
374 // Must be empty other than the branch and debug info.
375 BasicBlock::iterator I = Pred->begin();
376 while (isa<DbgInfoIntrinsic>(I))
380 // Cannot be the entry block; its label does not get emitted.
381 if (Pred == &Dest->getParent()->getEntryBlock())
384 // Finally, since we know that Dest has phi nodes in it, we have to make
385 // sure that jumping to Pred will have the same effect as going to Dest in
386 // terms of PHI values.
389 unsigned PredEntryNo = pi;
391 bool FoundMatch = true;
392 for (BasicBlock::iterator I = Dest->begin();
393 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
394 if (PHINo == TIPHIValues.size()) {
395 if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
396 TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
397 TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
400 // If the PHI entry doesn't work, we can't use this pred.
401 if (PN->getIncomingBlock(PredEntryNo) != Pred)
402 PredEntryNo = PN->getBasicBlockIndex(Pred);
404 if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
410 // If we found a workable predecessor, change TI to branch to Succ.
418 /// SplitEdgeNicely - Split the critical edge from TI to its specified
419 /// successor if it will improve codegen. We only do this if the successor has
420 /// phi nodes (otherwise critical edges are ok). If there is already another
421 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
422 /// instead of introducing a new block.
423 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
424 SmallSet<std::pair<const BasicBlock*,
425 const BasicBlock*>, 8> &BackEdges,
427 BasicBlock *TIBB = TI->getParent();
428 BasicBlock *Dest = TI->getSuccessor(SuccNum);
429 assert(isa<PHINode>(Dest->begin()) &&
430 "This should only be called if Dest has a PHI!");
431 PHINode *DestPHI = cast<PHINode>(Dest->begin());
433 // Do not split edges to EH landing pads.
434 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
435 if (Invoke->getSuccessor(1) == Dest)
438 // As a hack, never split backedges of loops. Even though the copy for any
439 // PHIs inserted on the backedge would be dead for exits from the loop, we
440 // assume that the cost of *splitting* the backedge would be too high.
441 if (BackEdges.count(std::make_pair(TIBB, Dest)))
444 if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
445 ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
447 PFI->splitEdge(TIBB, Dest, ReuseBB);
448 Dest->removePredecessor(TIBB);
449 TI->setSuccessor(SuccNum, ReuseBB);
453 SplitCriticalEdge(TI, SuccNum, P, true);
457 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
458 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
459 /// sink it into user blocks to reduce the number of virtual
460 /// registers that must be created and coalesced.
462 /// Return true if any changes are made.
464 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
465 // If this is a noop copy,
466 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
467 EVT DstVT = TLI.getValueType(CI->getType());
469 // This is an fp<->int conversion?
470 if (SrcVT.isInteger() != DstVT.isInteger())
473 // If this is an extension, it will be a zero or sign extension, which
475 if (SrcVT.bitsLT(DstVT)) return false;
477 // If these values will be promoted, find out what they will be promoted
478 // to. This helps us consider truncates on PPC as noop copies when they
480 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
481 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
482 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
483 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
485 // If, after promotion, these are the same types, this is a noop copy.
489 BasicBlock *DefBB = CI->getParent();
491 /// InsertedCasts - Only insert a cast in each block once.
492 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
494 bool MadeChange = false;
495 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
497 Use &TheUse = UI.getUse();
498 Instruction *User = cast<Instruction>(*UI);
500 // Figure out which BB this cast is used in. For PHI's this is the
501 // appropriate predecessor block.
502 BasicBlock *UserBB = User->getParent();
503 if (PHINode *PN = dyn_cast<PHINode>(User)) {
504 UserBB = PN->getIncomingBlock(UI);
507 // Preincrement use iterator so we don't invalidate it.
510 // If this user is in the same block as the cast, don't change the cast.
511 if (UserBB == DefBB) continue;
513 // If we have already inserted a cast into this block, use it.
514 CastInst *&InsertedCast = InsertedCasts[UserBB];
517 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
520 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
525 // Replace a use of the cast with a use of the new cast.
526 TheUse = InsertedCast;
530 // If we removed all uses, nuke the cast.
531 if (CI->use_empty()) {
532 CI->eraseFromParent();
539 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
540 /// the number of virtual registers that must be created and coalesced. This is
541 /// a clear win except on targets with multiple condition code registers
542 /// (PowerPC), where it might lose; some adjustment may be wanted there.
544 /// Return true if any changes are made.
545 static bool OptimizeCmpExpression(CmpInst *CI) {
546 BasicBlock *DefBB = CI->getParent();
548 /// InsertedCmp - Only insert a cmp in each block once.
549 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
551 bool MadeChange = false;
552 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
554 Use &TheUse = UI.getUse();
555 Instruction *User = cast<Instruction>(*UI);
557 // Preincrement use iterator so we don't invalidate it.
560 // Don't bother for PHI nodes.
561 if (isa<PHINode>(User))
564 // Figure out which BB this cmp is used in.
565 BasicBlock *UserBB = User->getParent();
567 // If this user is in the same block as the cmp, don't change the cmp.
568 if (UserBB == DefBB) continue;
570 // If we have already inserted a cmp into this block, use it.
571 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
574 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
577 CmpInst::Create(CI->getOpcode(),
578 CI->getPredicate(), CI->getOperand(0),
579 CI->getOperand(1), "", InsertPt);
583 // Replace a use of the cmp with a use of the new cmp.
584 TheUse = InsertedCmp;
588 // If we removed all uses, nuke the cmp.
590 CI->eraseFromParent();
596 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
598 void replaceCall(Value *With) {
599 CI->replaceAllUsesWith(With);
600 CI->eraseFromParent();
602 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
603 if (ConstantInt *SizeCI =
604 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
605 return SizeCI->isAllOnesValue();
609 } // end anonymous namespace
611 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
612 BasicBlock *BB = CI->getParent();
614 // Lower inline assembly if we can.
615 // If we found an inline asm expession, and if the target knows how to
616 // lower it to normal LLVM code, do so now.
617 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
618 if (TLI->ExpandInlineAsm(CI)) {
619 // Avoid invalidating the iterator.
620 CurInstIterator = BB->begin();
621 // Avoid processing instructions out of order, which could cause
622 // reuse before a value is defined.
626 // Sink address computing for memory operands into the block.
627 if (OptimizeInlineAsmInst(CI))
631 // Lower all uses of llvm.objectsize.*
632 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
633 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
634 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
635 const Type *ReturnTy = CI->getType();
636 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
638 // Substituting this can cause recursive simplifications, which can
639 // invalidate our iterator. Use a WeakVH to hold onto it in case this
641 WeakVH IterHandle(CurInstIterator);
643 ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0, DT);
645 // If the iterator instruction was recursively deleted, start over at the
646 // start of the block.
647 if (IterHandle != CurInstIterator) {
648 CurInstIterator = BB->begin();
654 // From here on out we're working with named functions.
655 if (CI->getCalledFunction() == 0) return false;
657 // We'll need TargetData from here on out.
658 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
659 if (!TD) return false;
661 // Lower all default uses of _chk calls. This is very similar
662 // to what InstCombineCalls does, but here we are only lowering calls
663 // that have the default "don't know" as the objectsize. Anything else
664 // should be left alone.
665 CodeGenPrepareFortifiedLibCalls Simplifier;
666 return Simplifier.fold(CI, TD);
669 //===----------------------------------------------------------------------===//
670 // Memory Optimization
671 //===----------------------------------------------------------------------===//
673 /// IsNonLocalValue - Return true if the specified values are defined in a
674 /// different basic block than BB.
675 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
676 if (Instruction *I = dyn_cast<Instruction>(V))
677 return I->getParent() != BB;
681 /// OptimizeMemoryInst - Load and Store Instructions often have
682 /// addressing modes that can do significant amounts of computation. As such,
683 /// instruction selection will try to get the load or store to do as much
684 /// computation as possible for the program. The problem is that isel can only
685 /// see within a single block. As such, we sink as much legal addressing mode
686 /// stuff into the block as possible.
688 /// This method is used to optimize both load/store and inline asms with memory
690 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
691 const Type *AccessTy) {
694 // Try to collapse single-value PHI nodes. This is necessary to undo
695 // unprofitable PRE transformations.
696 SmallVector<Value*, 8> worklist;
697 SmallPtrSet<Value*, 16> Visited;
698 worklist.push_back(Addr);
700 // Use a worklist to iteratively look through PHI nodes, and ensure that
701 // the addressing mode obtained from the non-PHI roots of the graph
703 Value *Consensus = 0;
704 unsigned NumUsesConsensus = 0;
705 SmallVector<Instruction*, 16> AddrModeInsts;
706 ExtAddrMode AddrMode;
707 while (!worklist.empty()) {
708 Value *V = worklist.back();
711 // Break use-def graph loops.
712 if (Visited.count(V)) {
719 // For a PHI node, push all of its incoming values.
720 if (PHINode *P = dyn_cast<PHINode>(V)) {
721 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
722 worklist.push_back(P->getIncomingValue(i));
726 // For non-PHIs, determine the addressing mode being computed.
727 SmallVector<Instruction*, 16> NewAddrModeInsts;
728 ExtAddrMode NewAddrMode =
729 AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
730 NewAddrModeInsts, *TLI);
732 // Ensure that the obtained addressing mode is equivalent to that obtained
733 // for all other roots of the PHI traversal. Also, when choosing one
734 // such root as representative, select the one with the most uses in order
735 // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
736 if (!Consensus || NewAddrMode == AddrMode) {
737 unsigned NumUses = V->getNumUses();
738 if (NumUses > NumUsesConsensus) {
740 NumUsesConsensus = NumUses;
741 AddrMode = NewAddrMode;
742 AddrModeInsts = NewAddrModeInsts;
751 // If the addressing mode couldn't be determined, or if multiple different
752 // ones were determined, bail out now.
753 if (!Consensus) return false;
755 // Check to see if any of the instructions supersumed by this addr mode are
756 // non-local to I's BB.
757 bool AnyNonLocal = false;
758 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
759 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
765 // If all the instructions matched are already in this BB, don't do anything.
767 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
771 // Insert this computation right after this user. Since our caller is
772 // scanning from the top of the BB to the bottom, reuse of the expr are
773 // guaranteed to happen later.
774 BasicBlock::iterator InsertPt = MemoryInst;
776 // Now that we determined the addressing expression we want to use and know
777 // that we have to sink it into this block. Check to see if we have already
778 // done this for some other load/store instr in this block. If so, reuse the
780 Value *&SunkAddr = SunkAddrs[Addr];
782 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
784 if (SunkAddr->getType() != Addr->getType())
785 SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
787 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
789 const Type *IntPtrTy =
790 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
794 // Start with the base register. Do this first so that subsequent address
795 // matching finds it last, which will prevent it from trying to match it
796 // as the scaled value in case it happens to be a mul. That would be
797 // problematic if we've sunk a different mul for the scale, because then
798 // we'd end up sinking both muls.
799 if (AddrMode.BaseReg) {
800 Value *V = AddrMode.BaseReg;
801 if (V->getType()->isPointerTy())
802 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
803 if (V->getType() != IntPtrTy)
804 V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
805 "sunkaddr", InsertPt);
809 // Add the scale value.
810 if (AddrMode.Scale) {
811 Value *V = AddrMode.ScaledReg;
812 if (V->getType() == IntPtrTy) {
814 } else if (V->getType()->isPointerTy()) {
815 V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
816 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
817 cast<IntegerType>(V->getType())->getBitWidth()) {
818 V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
820 V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
822 if (AddrMode.Scale != 1)
823 V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
825 "sunkaddr", InsertPt);
827 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
832 // Add in the BaseGV if present.
833 if (AddrMode.BaseGV) {
834 Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
837 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
842 // Add in the Base Offset if present.
843 if (AddrMode.BaseOffs) {
844 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
846 Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
852 SunkAddr = Constant::getNullValue(Addr->getType());
854 SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
857 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
859 if (Repl->use_empty()) {
860 RecursivelyDeleteTriviallyDeadInstructions(Repl);
861 // This address is now available for reassignment, so erase the table entry;
862 // we don't want to match some completely different instruction.
869 /// OptimizeInlineAsmInst - If there are any memory operands, use
870 /// OptimizeMemoryInst to sink their address computing into the block when
871 /// possible / profitable.
872 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
873 bool MadeChange = false;
875 TargetLowering::AsmOperandInfoVector
876 TargetConstraints = TLI->ParseConstraints(CS);
878 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
879 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
881 // Compute the constraint code and ConstraintType to use.
882 TLI->ComputeConstraintToUse(OpInfo, SDValue());
884 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
886 Value *OpVal = CS->getArgOperand(ArgNo++);
887 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
888 } else if (OpInfo.Type == InlineAsm::isInput)
895 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
896 /// basic block as the load, unless conditions are unfavorable. This allows
897 /// SelectionDAG to fold the extend into the load.
899 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
900 // Look for a load being extended.
901 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
902 if (!LI) return false;
904 // If they're already in the same block, there's nothing to do.
905 if (LI->getParent() == I->getParent())
908 // If the load has other users and the truncate is not free, this probably
910 if (!LI->hasOneUse() &&
911 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
912 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
913 !TLI->isTruncateFree(I->getType(), LI->getType()))
916 // Check whether the target supports casts folded into loads.
918 if (isa<ZExtInst>(I))
919 LType = ISD::ZEXTLOAD;
921 assert(isa<SExtInst>(I) && "Unexpected ext type!");
922 LType = ISD::SEXTLOAD;
924 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
927 // Move the extend into the same block as the load, so that SelectionDAG
929 I->removeFromParent();
935 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
936 BasicBlock *DefBB = I->getParent();
938 // If the result of a {s|z}ext and its source are both live out, rewrite all
939 // other uses of the source with result of extension.
940 Value *Src = I->getOperand(0);
941 if (Src->hasOneUse())
944 // Only do this xform if truncating is free.
945 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
948 // Only safe to perform the optimization if the source is also defined in
950 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
953 bool DefIsLiveOut = false;
954 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
956 Instruction *User = cast<Instruction>(*UI);
958 // Figure out which BB this ext is used in.
959 BasicBlock *UserBB = User->getParent();
960 if (UserBB == DefBB) continue;
967 // Make sure non of the uses are PHI nodes.
968 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
970 Instruction *User = cast<Instruction>(*UI);
971 BasicBlock *UserBB = User->getParent();
972 if (UserBB == DefBB) continue;
973 // Be conservative. We don't want this xform to end up introducing
974 // reloads just before load / store instructions.
975 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
979 // InsertedTruncs - Only insert one trunc in each block once.
980 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
982 bool MadeChange = false;
983 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
985 Use &TheUse = UI.getUse();
986 Instruction *User = cast<Instruction>(*UI);
988 // Figure out which BB this ext is used in.
989 BasicBlock *UserBB = User->getParent();
990 if (UserBB == DefBB) continue;
992 // Both src and def are live in this block. Rewrite the use.
993 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
995 if (!InsertedTrunc) {
996 BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
998 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1001 // Replace a use of the {s|z}ext source with a use of the result.
1002 TheUse = InsertedTrunc;
1010 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1011 if (PHINode *P = dyn_cast<PHINode>(I)) {
1012 // It is possible for very late stage optimizations (such as SimplifyCFG)
1013 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1014 // trivial PHI, go ahead and zap it here.
1015 if (Value *V = SimplifyInstruction(P)) {
1016 P->replaceAllUsesWith(V);
1017 P->eraseFromParent();
1024 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1025 // If the source of the cast is a constant, then this should have
1026 // already been constant folded. The only reason NOT to constant fold
1027 // it is if something (e.g. LSR) was careful to place the constant
1028 // evaluation in a block other than then one that uses it (e.g. to hoist
1029 // the address of globals out of a loop). If this is the case, we don't
1030 // want to forward-subst the cast.
1031 if (isa<Constant>(CI->getOperand(0)))
1034 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1037 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1038 bool MadeChange = MoveExtToFormExtLoad(I);
1039 return MadeChange | OptimizeExtUses(I);
1044 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1045 return OptimizeCmpExpression(CI);
1047 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1049 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1053 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1055 return OptimizeMemoryInst(I, SI->getOperand(1),
1056 SI->getOperand(0)->getType());
1060 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1061 if (GEPI->hasAllZeroIndices()) {
1062 /// The GEP operand must be a pointer, so must its result -> BitCast
1063 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1064 GEPI->getName(), GEPI);
1065 GEPI->replaceAllUsesWith(NC);
1066 GEPI->eraseFromParent();
1074 if (CallInst *CI = dyn_cast<CallInst>(I))
1075 return OptimizeCallInst(CI);
1080 // In this pass we look for GEP and cast instructions that are used
1081 // across basic blocks and rewrite them to improve basic-block-at-a-time
1083 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1084 bool MadeChange = false;
1086 // Split all critical edges where the dest block has a PHI.
1087 if (CriticalEdgeSplit) {
1088 TerminatorInst *BBTI = BB.getTerminator();
1089 if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
1090 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1091 BasicBlock *SuccBB = BBTI->getSuccessor(i);
1092 if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1093 SplitEdgeNicely(BBTI, i, BackEdges, this);
1100 CurInstIterator = BB.begin();
1101 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1102 MadeChange |= OptimizeInst(CurInstIterator++);