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/IRBuilder.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/InstructionSimplify.h"
31 #include "llvm/Analysis/ProfileInfo.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/PatternMatch.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/BuildLibCalls.h"
46 #include "llvm/Transforms/Utils/Local.h"
48 using namespace llvm::PatternMatch;
50 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
51 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
52 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
53 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
55 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
57 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58 "computations were sunk");
59 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
60 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
61 STATISTIC(NumRetsDup, "Number of return instructions duplicated");
62 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
63 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
65 static cl::opt<bool> DisableBranchOpts(
66 "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67 cl::desc("Disable branch optimizations in CodeGenPrepare"));
69 // FIXME: Remove this abomination once all of the tests pass without it!
70 static cl::opt<bool> DisableDeleteDeadBlocks(
71 "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
72 cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
74 static cl::opt<bool> DisableSelectToBranch(
75 "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76 cl::desc("Disable select to branch conversion."));
79 class CodeGenPrepare : public FunctionPass {
80 /// TLI - Keep a pointer of a TargetLowering to consult for determining
81 /// transformation profitability.
82 const TargetLowering *TLI;
83 const TargetLibraryInfo *TLInfo;
87 /// CurInstIterator - As we scan instructions optimizing them, this is the
88 /// next instruction to optimize. Xforms that can invalidate this should
90 BasicBlock::iterator CurInstIterator;
92 /// Keeps track of non-local addresses that have been sunk into a block.
93 /// This allows us to avoid inserting duplicate code for blocks with
94 /// multiple load/stores of the same address.
95 DenseMap<Value*, Value*> SunkAddrs;
97 /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
101 /// OptSize - True if optimizing for size.
105 static char ID; // Pass identification, replacement for typeid
106 explicit CodeGenPrepare(const TargetLowering *tli = 0)
107 : FunctionPass(ID), TLI(tli) {
108 initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
110 bool runOnFunction(Function &F);
112 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113 AU.addPreserved<DominatorTree>();
114 AU.addPreserved<ProfileInfo>();
115 AU.addRequired<TargetLibraryInfo>();
119 bool EliminateMostlyEmptyBlocks(Function &F);
120 bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
121 void EliminateMostlyEmptyBlock(BasicBlock *BB);
122 bool OptimizeBlock(BasicBlock &BB);
123 bool OptimizeInst(Instruction *I);
124 bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
125 bool OptimizeInlineAsmInst(CallInst *CS);
126 bool OptimizeCallInst(CallInst *CI);
127 bool MoveExtToFormExtLoad(Instruction *I);
128 bool OptimizeExtUses(Instruction *I);
129 bool OptimizeSelectInst(SelectInst *SI);
130 bool DupRetToEnableTailCallOpts(ReturnInst *RI);
131 bool PlaceDbgValues(Function &F);
135 char CodeGenPrepare::ID = 0;
136 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
137 "Optimize for code generation", false, false)
138 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
139 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
140 "Optimize for code generation", false, false)
142 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
143 return new CodeGenPrepare(TLI);
146 bool CodeGenPrepare::runOnFunction(Function &F) {
147 bool EverMadeChange = false;
150 TLInfo = &getAnalysis<TargetLibraryInfo>();
151 DT = getAnalysisIfAvailable<DominatorTree>();
152 PFI = getAnalysisIfAvailable<ProfileInfo>();
153 OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
155 // First pass, eliminate blocks that contain only PHI nodes and an
156 // unconditional branch.
157 EverMadeChange |= EliminateMostlyEmptyBlocks(F);
159 // llvm.dbg.value is far away from the value then iSel may not be able
160 // handle it properly. iSel will drop llvm.dbg.value if it can not
161 // find a node corresponding to the value.
162 EverMadeChange |= PlaceDbgValues(F);
164 bool MadeChange = true;
167 for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
168 BasicBlock *BB = I++;
169 MadeChange |= OptimizeBlock(*BB);
171 EverMadeChange |= MadeChange;
176 if (!DisableBranchOpts) {
178 SmallPtrSet<BasicBlock*, 8> WorkList;
179 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
180 SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
181 MadeChange |= ConstantFoldTerminator(BB, true);
182 if (!MadeChange) continue;
184 for (SmallVectorImpl<BasicBlock*>::iterator
185 II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
186 if (pred_begin(*II) == pred_end(*II))
187 WorkList.insert(*II);
190 if (!DisableDeleteDeadBlocks)
191 for (SmallPtrSet<BasicBlock*, 8>::iterator
192 I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
197 EverMadeChange |= MadeChange;
200 if (ModifiedDT && DT)
201 DT->DT->recalculate(F);
203 return EverMadeChange;
206 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
207 /// debug info directives, and an unconditional branch. Passes before isel
208 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
209 /// isel. Start by eliminating these blocks so we can split them the way we
211 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
212 bool MadeChange = false;
213 // Note that this intentionally skips the entry block.
214 for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
215 BasicBlock *BB = I++;
217 // If this block doesn't end with an uncond branch, ignore it.
218 BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
219 if (!BI || !BI->isUnconditional())
222 // If the instruction before the branch (skipping debug info) isn't a phi
223 // node, then other stuff is happening here.
224 BasicBlock::iterator BBI = BI;
225 if (BBI != BB->begin()) {
227 while (isa<DbgInfoIntrinsic>(BBI)) {
228 if (BBI == BB->begin())
232 if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
236 // Do not break infinite loops.
237 BasicBlock *DestBB = BI->getSuccessor(0);
241 if (!CanMergeBlocks(BB, DestBB))
244 EliminateMostlyEmptyBlock(BB);
250 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
251 /// single uncond branch between them, and BB contains no other non-phi
253 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
254 const BasicBlock *DestBB) const {
255 // We only want to eliminate blocks whose phi nodes are used by phi nodes in
256 // the successor. If there are more complex condition (e.g. preheaders),
257 // don't mess around with them.
258 BasicBlock::const_iterator BBI = BB->begin();
259 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
260 for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
262 const Instruction *User = cast<Instruction>(*UI);
263 if (User->getParent() != DestBB || !isa<PHINode>(User))
265 // If User is inside DestBB block and it is a PHINode then check
266 // incoming value. If incoming value is not from BB then this is
267 // a complex condition (e.g. preheaders) we want to avoid here.
268 if (User->getParent() == DestBB) {
269 if (const PHINode *UPN = dyn_cast<PHINode>(User))
270 for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
271 Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
272 if (Insn && Insn->getParent() == BB &&
273 Insn->getParent() != UPN->getIncomingBlock(I))
280 // If BB and DestBB contain any common predecessors, then the phi nodes in BB
281 // and DestBB may have conflicting incoming values for the block. If so, we
282 // can't merge the block.
283 const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
284 if (!DestBBPN) return true; // no conflict.
286 // Collect the preds of BB.
287 SmallPtrSet<const BasicBlock*, 16> BBPreds;
288 if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
289 // It is faster to get preds from a PHI than with pred_iterator.
290 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
291 BBPreds.insert(BBPN->getIncomingBlock(i));
293 BBPreds.insert(pred_begin(BB), pred_end(BB));
296 // Walk the preds of DestBB.
297 for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
298 BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
299 if (BBPreds.count(Pred)) { // Common predecessor?
300 BBI = DestBB->begin();
301 while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
302 const Value *V1 = PN->getIncomingValueForBlock(Pred);
303 const Value *V2 = PN->getIncomingValueForBlock(BB);
305 // If V2 is a phi node in BB, look up what the mapped value will be.
306 if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
307 if (V2PN->getParent() == BB)
308 V2 = V2PN->getIncomingValueForBlock(Pred);
310 // If there is a conflict, bail out.
311 if (V1 != V2) return false;
320 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
321 /// an unconditional branch in it.
322 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
323 BranchInst *BI = cast<BranchInst>(BB->getTerminator());
324 BasicBlock *DestBB = BI->getSuccessor(0);
326 DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
328 // If the destination block has a single pred, then this is a trivial edge,
330 if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
331 if (SinglePred != DestBB) {
332 // Remember if SinglePred was the entry block of the function. If so, we
333 // will need to move BB back to the entry position.
334 bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
335 MergeBasicBlockIntoOnlyPred(DestBB, this);
337 if (isEntry && BB != &BB->getParent()->getEntryBlock())
338 BB->moveBefore(&BB->getParent()->getEntryBlock());
340 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
345 // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
346 // to handle the new incoming edges it is about to have.
348 for (BasicBlock::iterator BBI = DestBB->begin();
349 (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
350 // Remove the incoming value for BB, and remember it.
351 Value *InVal = PN->removeIncomingValue(BB, false);
353 // Two options: either the InVal is a phi node defined in BB or it is some
354 // value that dominates BB.
355 PHINode *InValPhi = dyn_cast<PHINode>(InVal);
356 if (InValPhi && InValPhi->getParent() == BB) {
357 // Add all of the input values of the input PHI as inputs of this phi.
358 for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
359 PN->addIncoming(InValPhi->getIncomingValue(i),
360 InValPhi->getIncomingBlock(i));
362 // Otherwise, add one instance of the dominating value for each edge that
363 // we will be adding.
364 if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
365 for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
366 PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
368 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
369 PN->addIncoming(InVal, *PI);
374 // The PHIs are now updated, change everything that refers to BB to use
375 // DestBB and remove BB.
376 BB->replaceAllUsesWith(DestBB);
377 if (DT && !ModifiedDT) {
378 BasicBlock *BBIDom = DT->getNode(BB)->getIDom()->getBlock();
379 BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
380 BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
381 DT->changeImmediateDominator(DestBB, NewIDom);
385 PFI->replaceAllUses(BB, DestBB);
386 PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
388 BB->eraseFromParent();
391 DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
394 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
395 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
396 /// sink it into user blocks to reduce the number of virtual
397 /// registers that must be created and coalesced.
399 /// Return true if any changes are made.
401 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
402 // If this is a noop copy,
403 EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
404 EVT DstVT = TLI.getValueType(CI->getType());
406 // This is an fp<->int conversion?
407 if (SrcVT.isInteger() != DstVT.isInteger())
410 // If this is an extension, it will be a zero or sign extension, which
412 if (SrcVT.bitsLT(DstVT)) return false;
414 // If these values will be promoted, find out what they will be promoted
415 // to. This helps us consider truncates on PPC as noop copies when they
417 if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
418 TargetLowering::TypePromoteInteger)
419 SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
420 if (TLI.getTypeAction(CI->getContext(), DstVT) ==
421 TargetLowering::TypePromoteInteger)
422 DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
424 // If, after promotion, these are the same types, this is a noop copy.
428 BasicBlock *DefBB = CI->getParent();
430 /// InsertedCasts - Only insert a cast in each block once.
431 DenseMap<BasicBlock*, CastInst*> InsertedCasts;
433 bool MadeChange = false;
434 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
436 Use &TheUse = UI.getUse();
437 Instruction *User = cast<Instruction>(*UI);
439 // Figure out which BB this cast is used in. For PHI's this is the
440 // appropriate predecessor block.
441 BasicBlock *UserBB = User->getParent();
442 if (PHINode *PN = dyn_cast<PHINode>(User)) {
443 UserBB = PN->getIncomingBlock(UI);
446 // Preincrement use iterator so we don't invalidate it.
449 // If this user is in the same block as the cast, don't change the cast.
450 if (UserBB == DefBB) continue;
452 // If we have already inserted a cast into this block, use it.
453 CastInst *&InsertedCast = InsertedCasts[UserBB];
456 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
458 CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
463 // Replace a use of the cast with a use of the new cast.
464 TheUse = InsertedCast;
468 // If we removed all uses, nuke the cast.
469 if (CI->use_empty()) {
470 CI->eraseFromParent();
477 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
478 /// the number of virtual registers that must be created and coalesced. This is
479 /// a clear win except on targets with multiple condition code registers
480 /// (PowerPC), where it might lose; some adjustment may be wanted there.
482 /// Return true if any changes are made.
483 static bool OptimizeCmpExpression(CmpInst *CI) {
484 BasicBlock *DefBB = CI->getParent();
486 /// InsertedCmp - Only insert a cmp in each block once.
487 DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
489 bool MadeChange = false;
490 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
492 Use &TheUse = UI.getUse();
493 Instruction *User = cast<Instruction>(*UI);
495 // Preincrement use iterator so we don't invalidate it.
498 // Don't bother for PHI nodes.
499 if (isa<PHINode>(User))
502 // Figure out which BB this cmp is used in.
503 BasicBlock *UserBB = User->getParent();
505 // If this user is in the same block as the cmp, don't change the cmp.
506 if (UserBB == DefBB) continue;
508 // If we have already inserted a cmp into this block, use it.
509 CmpInst *&InsertedCmp = InsertedCmps[UserBB];
512 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
514 CmpInst::Create(CI->getOpcode(),
515 CI->getPredicate(), CI->getOperand(0),
516 CI->getOperand(1), "", InsertPt);
520 // Replace a use of the cmp with a use of the new cmp.
521 TheUse = InsertedCmp;
525 // If we removed all uses, nuke the cmp.
527 CI->eraseFromParent();
533 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
535 void replaceCall(Value *With) {
536 CI->replaceAllUsesWith(With);
537 CI->eraseFromParent();
539 bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
540 if (ConstantInt *SizeCI =
541 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
542 return SizeCI->isAllOnesValue();
546 } // end anonymous namespace
548 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
549 BasicBlock *BB = CI->getParent();
551 // Lower inline assembly if we can.
552 // If we found an inline asm expession, and if the target knows how to
553 // lower it to normal LLVM code, do so now.
554 if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
555 if (TLI->ExpandInlineAsm(CI)) {
556 // Avoid invalidating the iterator.
557 CurInstIterator = BB->begin();
558 // Avoid processing instructions out of order, which could cause
559 // reuse before a value is defined.
563 // Sink address computing for memory operands into the block.
564 if (OptimizeInlineAsmInst(CI))
568 // Lower all uses of llvm.objectsize.*
569 IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
570 if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
571 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
572 Type *ReturnTy = CI->getType();
573 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
575 // Substituting this can cause recursive simplifications, which can
576 // invalidate our iterator. Use a WeakVH to hold onto it in case this
578 WeakVH IterHandle(CurInstIterator);
580 replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
581 TLInfo, ModifiedDT ? 0 : DT);
583 // If the iterator instruction was recursively deleted, start over at the
584 // start of the block.
585 if (IterHandle != CurInstIterator) {
586 CurInstIterator = BB->begin();
593 SmallVector<Value*, 2> PtrOps;
595 if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
596 while (!PtrOps.empty())
597 if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
601 // From here on out we're working with named functions.
602 if (CI->getCalledFunction() == 0) return false;
604 // We'll need TargetData from here on out.
605 const TargetData *TD = TLI ? TLI->getTargetData() : 0;
606 if (!TD) return false;
608 // Lower all default uses of _chk calls. This is very similar
609 // to what InstCombineCalls does, but here we are only lowering calls
610 // that have the default "don't know" as the objectsize. Anything else
611 // should be left alone.
612 CodeGenPrepareFortifiedLibCalls Simplifier;
613 return Simplifier.fold(CI, TD);
616 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
617 /// instructions to the predecessor to enable tail call optimizations. The
618 /// case it is currently looking for is:
620 /// %tmp0 = tail call i32 @f0()
623 /// %tmp1 = tail call i32 @f1()
626 /// %tmp2 = tail call i32 @f2()
629 /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
635 /// %tmp0 = tail call i32 @f0()
638 /// %tmp1 = tail call i32 @f1()
641 /// %tmp2 = tail call i32 @f2()
644 bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
648 Value *V = RI->getReturnValue();
649 PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
653 BasicBlock *BB = RI->getParent();
654 if (PN && PN->getParent() != BB)
657 // It's not safe to eliminate the sign / zero extension of the return value.
658 // See llvm::isInTailCallPosition().
659 const Function *F = BB->getParent();
660 Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
661 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
664 // Make sure there are no instructions between the PHI and return, or that the
665 // return is the first instruction in the block.
667 BasicBlock::iterator BI = BB->begin();
668 do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
672 BasicBlock::iterator BI = BB->begin();
673 while (isa<DbgInfoIntrinsic>(BI)) ++BI;
678 /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
680 SmallVector<CallInst*, 4> TailCalls;
682 for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
683 CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
684 // Make sure the phi value is indeed produced by the tail call.
685 if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
686 TLI->mayBeEmittedAsTailCall(CI))
687 TailCalls.push_back(CI);
690 SmallPtrSet<BasicBlock*, 4> VisitedBBs;
691 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
692 if (!VisitedBBs.insert(*PI))
695 BasicBlock::InstListType &InstList = (*PI)->getInstList();
696 BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
697 BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
698 do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
702 CallInst *CI = dyn_cast<CallInst>(&*RI);
703 if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
704 TailCalls.push_back(CI);
708 bool Changed = false;
709 for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
710 CallInst *CI = TailCalls[i];
713 // Conservatively require the attributes of the call to match those of the
714 // return. Ignore noalias because it doesn't affect the call sequence.
715 Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
716 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
719 // Make sure the call instruction is followed by an unconditional branch to
721 BasicBlock *CallBB = CI->getParent();
722 BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
723 if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
726 // Duplicate the return into CallBB.
727 (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
728 ModifiedDT = Changed = true;
732 // If we eliminated all predecessors of the block, delete the block now.
733 if (Changed && pred_begin(BB) == pred_end(BB))
734 BB->eraseFromParent();
739 //===----------------------------------------------------------------------===//
740 // Memory Optimization
741 //===----------------------------------------------------------------------===//
743 /// IsNonLocalValue - Return true if the specified values are defined in a
744 /// different basic block than BB.
745 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
746 if (Instruction *I = dyn_cast<Instruction>(V))
747 return I->getParent() != BB;
751 /// OptimizeMemoryInst - Load and Store Instructions often have
752 /// addressing modes that can do significant amounts of computation. As such,
753 /// instruction selection will try to get the load or store to do as much
754 /// computation as possible for the program. The problem is that isel can only
755 /// see within a single block. As such, we sink as much legal addressing mode
756 /// stuff into the block as possible.
758 /// This method is used to optimize both load/store and inline asms with memory
760 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
764 // Try to collapse single-value PHI nodes. This is necessary to undo
765 // unprofitable PRE transformations.
766 SmallVector<Value*, 8> worklist;
767 SmallPtrSet<Value*, 16> Visited;
768 worklist.push_back(Addr);
770 // Use a worklist to iteratively look through PHI nodes, and ensure that
771 // the addressing mode obtained from the non-PHI roots of the graph
773 Value *Consensus = 0;
774 unsigned NumUsesConsensus = 0;
775 bool IsNumUsesConsensusValid = false;
776 SmallVector<Instruction*, 16> AddrModeInsts;
777 ExtAddrMode AddrMode;
778 while (!worklist.empty()) {
779 Value *V = worklist.back();
782 // Break use-def graph loops.
783 if (!Visited.insert(V)) {
788 // For a PHI node, push all of its incoming values.
789 if (PHINode *P = dyn_cast<PHINode>(V)) {
790 for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
791 worklist.push_back(P->getIncomingValue(i));
795 // For non-PHIs, determine the addressing mode being computed.
796 SmallVector<Instruction*, 16> NewAddrModeInsts;
797 ExtAddrMode NewAddrMode =
798 AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
799 NewAddrModeInsts, *TLI);
801 // This check is broken into two cases with very similar code to avoid using
802 // getNumUses() as much as possible. Some values have a lot of uses, so
803 // calling getNumUses() unconditionally caused a significant compile-time
807 AddrMode = NewAddrMode;
808 AddrModeInsts = NewAddrModeInsts;
810 } else if (NewAddrMode == AddrMode) {
811 if (!IsNumUsesConsensusValid) {
812 NumUsesConsensus = Consensus->getNumUses();
813 IsNumUsesConsensusValid = true;
816 // Ensure that the obtained addressing mode is equivalent to that obtained
817 // for all other roots of the PHI traversal. Also, when choosing one
818 // such root as representative, select the one with the most uses in order
819 // to keep the cost modeling heuristics in AddressingModeMatcher
821 unsigned NumUses = V->getNumUses();
822 if (NumUses > NumUsesConsensus) {
824 NumUsesConsensus = NumUses;
825 AddrModeInsts = NewAddrModeInsts;
834 // If the addressing mode couldn't be determined, or if multiple different
835 // ones were determined, bail out now.
836 if (!Consensus) return false;
838 // Check to see if any of the instructions supersumed by this addr mode are
839 // non-local to I's BB.
840 bool AnyNonLocal = false;
841 for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
842 if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
848 // If all the instructions matched are already in this BB, don't do anything.
850 DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
854 // Insert this computation right after this user. Since our caller is
855 // scanning from the top of the BB to the bottom, reuse of the expr are
856 // guaranteed to happen later.
857 IRBuilder<> Builder(MemoryInst);
859 // Now that we determined the addressing expression we want to use and know
860 // that we have to sink it into this block. Check to see if we have already
861 // done this for some other load/store instr in this block. If so, reuse the
863 Value *&SunkAddr = SunkAddrs[Addr];
865 DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
867 if (SunkAddr->getType() != Addr->getType())
868 SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
870 DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
873 TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
877 // Start with the base register. Do this first so that subsequent address
878 // matching finds it last, which will prevent it from trying to match it
879 // as the scaled value in case it happens to be a mul. That would be
880 // problematic if we've sunk a different mul for the scale, because then
881 // we'd end up sinking both muls.
882 if (AddrMode.BaseReg) {
883 Value *V = AddrMode.BaseReg;
884 if (V->getType()->isPointerTy())
885 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
886 if (V->getType() != IntPtrTy)
887 V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
891 // Add the scale value.
892 if (AddrMode.Scale) {
893 Value *V = AddrMode.ScaledReg;
894 if (V->getType() == IntPtrTy) {
896 } else if (V->getType()->isPointerTy()) {
897 V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
898 } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
899 cast<IntegerType>(V->getType())->getBitWidth()) {
900 V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
902 V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
904 if (AddrMode.Scale != 1)
905 V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
908 Result = Builder.CreateAdd(Result, V, "sunkaddr");
913 // Add in the BaseGV if present.
914 if (AddrMode.BaseGV) {
915 Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
917 Result = Builder.CreateAdd(Result, V, "sunkaddr");
922 // Add in the Base Offset if present.
923 if (AddrMode.BaseOffs) {
924 Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
926 Result = Builder.CreateAdd(Result, V, "sunkaddr");
932 SunkAddr = Constant::getNullValue(Addr->getType());
934 SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
937 MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
939 // If we have no uses, recursively delete the value and all dead instructions
941 if (Repl->use_empty()) {
942 // This can cause recursive deletion, which can invalidate our iterator.
943 // Use a WeakVH to hold onto it in case this happens.
944 WeakVH IterHandle(CurInstIterator);
945 BasicBlock *BB = CurInstIterator->getParent();
947 RecursivelyDeleteTriviallyDeadInstructions(Repl);
949 if (IterHandle != CurInstIterator) {
950 // If the iterator instruction was recursively deleted, start over at the
951 // start of the block.
952 CurInstIterator = BB->begin();
955 // This address is now available for reassignment, so erase the table
956 // entry; we don't want to match some completely different instruction.
964 /// OptimizeInlineAsmInst - If there are any memory operands, use
965 /// OptimizeMemoryInst to sink their address computing into the block when
966 /// possible / profitable.
967 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
968 bool MadeChange = false;
970 TargetLowering::AsmOperandInfoVector
971 TargetConstraints = TLI->ParseConstraints(CS);
973 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
974 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
976 // Compute the constraint code and ConstraintType to use.
977 TLI->ComputeConstraintToUse(OpInfo, SDValue());
979 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
981 Value *OpVal = CS->getArgOperand(ArgNo++);
982 MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
983 } else if (OpInfo.Type == InlineAsm::isInput)
990 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
991 /// basic block as the load, unless conditions are unfavorable. This allows
992 /// SelectionDAG to fold the extend into the load.
994 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
995 // Look for a load being extended.
996 LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
997 if (!LI) return false;
999 // If they're already in the same block, there's nothing to do.
1000 if (LI->getParent() == I->getParent())
1003 // If the load has other users and the truncate is not free, this probably
1004 // isn't worthwhile.
1005 if (!LI->hasOneUse() &&
1006 TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1007 !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1008 !TLI->isTruncateFree(I->getType(), LI->getType()))
1011 // Check whether the target supports casts folded into loads.
1013 if (isa<ZExtInst>(I))
1014 LType = ISD::ZEXTLOAD;
1016 assert(isa<SExtInst>(I) && "Unexpected ext type!");
1017 LType = ISD::SEXTLOAD;
1019 if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1022 // Move the extend into the same block as the load, so that SelectionDAG
1024 I->removeFromParent();
1030 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1031 BasicBlock *DefBB = I->getParent();
1033 // If the result of a {s|z}ext and its source are both live out, rewrite all
1034 // other uses of the source with result of extension.
1035 Value *Src = I->getOperand(0);
1036 if (Src->hasOneUse())
1039 // Only do this xform if truncating is free.
1040 if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1043 // Only safe to perform the optimization if the source is also defined in
1045 if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1048 bool DefIsLiveOut = false;
1049 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1051 Instruction *User = cast<Instruction>(*UI);
1053 // Figure out which BB this ext is used in.
1054 BasicBlock *UserBB = User->getParent();
1055 if (UserBB == DefBB) continue;
1056 DefIsLiveOut = true;
1062 // Make sure non of the uses are PHI nodes.
1063 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1065 Instruction *User = cast<Instruction>(*UI);
1066 BasicBlock *UserBB = User->getParent();
1067 if (UserBB == DefBB) continue;
1068 // Be conservative. We don't want this xform to end up introducing
1069 // reloads just before load / store instructions.
1070 if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1074 // InsertedTruncs - Only insert one trunc in each block once.
1075 DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1077 bool MadeChange = false;
1078 for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1080 Use &TheUse = UI.getUse();
1081 Instruction *User = cast<Instruction>(*UI);
1083 // Figure out which BB this ext is used in.
1084 BasicBlock *UserBB = User->getParent();
1085 if (UserBB == DefBB) continue;
1087 // Both src and def are live in this block. Rewrite the use.
1088 Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1090 if (!InsertedTrunc) {
1091 BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1092 InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1095 // Replace a use of the {s|z}ext source with a use of the result.
1096 TheUse = InsertedTrunc;
1104 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1105 /// turned into an explicit branch.
1106 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1107 // FIXME: This should use the same heuristics as IfConversion to determine
1108 // whether a select is better represented as a branch. This requires that
1109 // branch probability metadata is preserved for the select, which is not the
1112 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1114 // If the branch is predicted right, an out of order CPU can avoid blocking on
1115 // the compare. Emit cmovs on compares with a memory operand as branches to
1116 // avoid stalls on the load from memory. If the compare has more than one use
1117 // there's probably another cmov or setcc around so it's not worth emitting a
1122 Value *CmpOp0 = Cmp->getOperand(0);
1123 Value *CmpOp1 = Cmp->getOperand(1);
1125 // We check that the memory operand has one use to avoid uses of the loaded
1126 // value directly after the compare, making branches unprofitable.
1127 return Cmp->hasOneUse() &&
1128 ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1129 (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1133 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1134 // If we have a SelectInst that will likely profit from branch prediction,
1135 // turn it into a branch.
1136 if (DisableSelectToBranch || OptSize || !TLI ||
1137 !TLI->isPredictableSelectExpensive())
1140 if (!SI->getCondition()->getType()->isIntegerTy(1) ||
1141 !isFormingBranchFromSelectProfitable(SI))
1146 // First, we split the block containing the select into 2 blocks.
1147 BasicBlock *StartBlock = SI->getParent();
1148 BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1149 BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1151 // Create a new block serving as the landing pad for the branch.
1152 BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1153 NextBlock->getParent(), NextBlock);
1155 // Move the unconditional branch from the block with the select in it into our
1156 // landing pad block.
1157 StartBlock->getTerminator()->eraseFromParent();
1158 BranchInst::Create(NextBlock, SmallBlock);
1160 // Insert the real conditional branch based on the original condition.
1161 BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1163 // The select itself is replaced with a PHI Node.
1164 PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1166 PN->addIncoming(SI->getTrueValue(), StartBlock);
1167 PN->addIncoming(SI->getFalseValue(), SmallBlock);
1168 SI->replaceAllUsesWith(PN);
1169 SI->eraseFromParent();
1171 // Instruct OptimizeBlock to skip to the next block.
1172 CurInstIterator = StartBlock->end();
1173 ++NumSelectsExpanded;
1177 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1178 if (PHINode *P = dyn_cast<PHINode>(I)) {
1179 // It is possible for very late stage optimizations (such as SimplifyCFG)
1180 // to introduce PHI nodes too late to be cleaned up. If we detect such a
1181 // trivial PHI, go ahead and zap it here.
1182 if (Value *V = SimplifyInstruction(P)) {
1183 P->replaceAllUsesWith(V);
1184 P->eraseFromParent();
1191 if (CastInst *CI = dyn_cast<CastInst>(I)) {
1192 // If the source of the cast is a constant, then this should have
1193 // already been constant folded. The only reason NOT to constant fold
1194 // it is if something (e.g. LSR) was careful to place the constant
1195 // evaluation in a block other than then one that uses it (e.g. to hoist
1196 // the address of globals out of a loop). If this is the case, we don't
1197 // want to forward-subst the cast.
1198 if (isa<Constant>(CI->getOperand(0)))
1201 if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1204 if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1205 bool MadeChange = MoveExtToFormExtLoad(I);
1206 return MadeChange | OptimizeExtUses(I);
1211 if (CmpInst *CI = dyn_cast<CmpInst>(I))
1212 return OptimizeCmpExpression(CI);
1214 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1216 return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1220 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1222 return OptimizeMemoryInst(I, SI->getOperand(1),
1223 SI->getOperand(0)->getType());
1227 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1228 if (GEPI->hasAllZeroIndices()) {
1229 /// The GEP operand must be a pointer, so must its result -> BitCast
1230 Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1231 GEPI->getName(), GEPI);
1232 GEPI->replaceAllUsesWith(NC);
1233 GEPI->eraseFromParent();
1241 if (CallInst *CI = dyn_cast<CallInst>(I))
1242 return OptimizeCallInst(CI);
1244 if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1245 return DupRetToEnableTailCallOpts(RI);
1247 if (SelectInst *SI = dyn_cast<SelectInst>(I))
1248 return OptimizeSelectInst(SI);
1253 // In this pass we look for GEP and cast instructions that are used
1254 // across basic blocks and rewrite them to improve basic-block-at-a-time
1256 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1258 bool MadeChange = false;
1260 CurInstIterator = BB.begin();
1261 for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1262 MadeChange |= OptimizeInst(CurInstIterator++);
1267 // llvm.dbg.value is far away from the value then iSel may not be able
1268 // handle it properly. iSel will drop llvm.dbg.value if it can not
1269 // find a node corresponding to the value.
1270 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1271 bool MadeChange = false;
1272 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1273 Instruction *PrevNonDbgInst = NULL;
1274 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1275 Instruction *Insn = BI; ++BI;
1276 DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1278 PrevNonDbgInst = Insn;
1282 Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1283 if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1284 DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1285 DVI->removeFromParent();
1286 if (isa<PHINode>(VI))
1287 DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1289 DVI->insertAfter(VI);